workshop-rs 0.1.16

Canonical multi-locale Overwatch Workshop semantic core: catalog, parser, WIR, validation, emitter.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! The Workshop IR model.
//!
//! Workshop IR models the lower-level workshop program structure: variables
//! with indexes, subroutines with indexes, and rules with events, conditions,
//! actions, and values. It is locale-independent (canonical catalog ids only,
//! never localized spellings) and protocol-agnostic.
//!
//! Name policy: call/value `name` fields keep the canonical catalog ids
//! (`countOf`, `wait`, `createBeamEffect`); mapping those to localized
//! Workshop presentation spellings is an emission concern.
//!
//! Extracted from the Wright-authored `wright-ir` crate (the `wir`,
//! `settings`, and `source` modules); see
//! [`docs/provenance.md`](https://github.com/wrightkit/workshop-rs/blob/main/docs/provenance.md).

mod dump;
mod validate;

pub mod error;

/// The WIR-owned capability surface used by the canonical census. Providers
/// do not contribute source-language inventories to this registry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CensusCapabilityKind {
    Variable,
    PlayerVariable,
    Subroutine,
    ControlFlow,
    String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CensusCapability {
    pub kind: CensusCapabilityKind,
    pub name: &'static str,
}

pub const CENSUS_CAPABILITIES: &[CensusCapability] = &[
    CensusCapability {
        kind: CensusCapabilityKind::Variable,
        name: "global",
    },
    CensusCapability {
        kind: CensusCapabilityKind::PlayerVariable,
        name: "player",
    },
    CensusCapability {
        kind: CensusCapabilityKind::Subroutine,
        name: "declaration-and-call",
    },
    CensusCapability {
        kind: CensusCapabilityKind::ControlFlow,
        name: "if",
    },
    CensusCapability {
        kind: CensusCapabilityKind::ControlFlow,
        name: "else-if",
    },
    CensusCapability {
        kind: CensusCapabilityKind::ControlFlow,
        name: "else",
    },
    CensusCapability {
        kind: CensusCapabilityKind::ControlFlow,
        name: "while",
    },
    CensusCapability {
        kind: CensusCapabilityKind::ControlFlow,
        name: "for-global-variable",
    },
    CensusCapability {
        kind: CensusCapabilityKind::String,
        name: "custom-string",
    },
];

use crate::arena::Arena;
use crate::ids::Id;
use crate::source::{SourceFile, Span};

/// A typed ID referencing a [`WorkshopVariable`] in the global table.
pub type GlobalVarId = Id<WorkshopVariable>;
/// A typed ID referencing a [`WorkshopVariable`] in the player table.
pub type PlayerVarId = Id<WorkshopVariable>;
/// A typed ID referencing a [`WorkshopSubroutine`].
pub type SubroutineId = Id<WorkshopSubroutine>;
/// A typed ID referencing a [`Rule`].
pub type RuleId = Id<Rule>;
/// A typed ID referencing an [`Action`] in the action arena.
pub type ActionId = Id<Action>;
/// A typed ID referencing a [`ValueNode`] in the value arena.
pub type ValueId = Id<ValueNode>;

/// The Workshop IR program: tables and arenas produced by lowering.
#[derive(Debug, Clone)]
pub struct Program {
    /// The source-file registry, copied from the source HIR so spans remain
    /// resolvable for diagnostics.
    pub files: Arena<SourceFile>,
    /// The custom-game-settings carrier, copied inertly from the source HIR
    /// (emitted verbatim, never lowered, #86).
    pub settings: Option<crate::settings::Settings>,
    pub global_variables: Arena<WorkshopVariable>,
    pub player_variables: Arena<WorkshopVariable>,
    pub subroutines: Arena<WorkshopSubroutine>,
    pub rules: Arena<Rule>,
    pub values: Arena<ValueNode>,
    pub actions: Arena<Action>,
}

impl Default for Program {
    fn default() -> Self {
        Program {
            files: Arena::new(),
            settings: None,
            global_variables: Arena::new(),
            player_variables: Arena::new(),
            subroutines: Arena::new(),
            rules: Arena::new(),
            values: Arena::new(),
            actions: Arena::new(),
        }
    }
}

impl Program {
    /// Validate structural invariants: every ID resolves and every span is
    /// valid. Returns the first violation as a structured [`IrError`].
    ///
    /// [`IrError`]: crate::wir::error::IrError
    pub fn validate(&self) -> Result<(), error::IrError> {
        validate::validate(self)
    }

    /// Report preserved or unknown constructs separately from structural
    /// validation so consumers cannot present analysis as definitive.
    pub fn semantic_issues(
        &self,
        catalog: &crate::catalog::Catalog,
    ) -> Vec<crate::semantic::SemanticIssue> {
        crate::semantic::inspect(self, catalog)
    }

    /// Render a deterministic debug dump of the workshop program.
    pub fn dump(&self) -> String {
        dump::dump(self)
    }
}

/// A workshop variable (global or player) with its assigned index.
///
/// Declaration initializers are lowered into synthetic "Initialize global
/// variables" / "Initialize player variables" rules during HIR → WIR lowering
/// (#112); the variable tables carry no initializer field, so the Initialize
/// rules are the single source of truth.
#[derive(Debug, Clone)]
pub struct WorkshopVariable {
    pub name: String,
    /// The workshop variable index assigned during lowering.
    pub index: u32,
    pub span: Option<Span>,
    /// The exact span of the declared identifier token.
    pub name_span: Option<Span>,
}

/// A workshop subroutine with its assigned index.
#[derive(Debug, Clone)]
pub struct WorkshopSubroutine {
    pub name: String,
    pub index: u32,
    pub span: Option<Span>,
    /// The exact span of the declared identifier token.
    pub name_span: Option<Span>,
}

/// A workshop rule.
#[derive(Debug, Clone)]
pub struct Rule {
    pub name: String,
    pub span: Option<Span>,
    /// The exact span of the rule name inside its string literal.
    pub name_span: Option<Span>,
    pub disabled: bool,
    pub event: Event,
    pub conditions: Vec<ValueId>,
    pub actions: Vec<ActionId>,
}

/// The team filter attached to a player-scoped Workshop event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventTeam {
    All,
    Team1,
    Team2,
}

/// The player filter attached to a player-scoped Workshop event.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventTarget {
    All,
    Slot(u8),
    Hero(String),
}

/// A non-ongoing player event identity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlayerEventKind {
    DealtDamage,
    DealtFinalBlow,
    DealtHealing,
    DealtKnockback,
    Died,
    EarnedElimination,
    Joined,
    Left,
    ReceivedHealing,
    ReceivedKnockback,
    TookDamage,
}

impl PlayerEventKind {
    /// The locale-independent catalog identity for this event.
    pub fn catalog_id(self) -> &'static str {
        match self {
            PlayerEventKind::DealtDamage => "playerDealtDamage",
            PlayerEventKind::DealtFinalBlow => "playerDealtFinalBlow",
            PlayerEventKind::DealtHealing => "playerDealtHealing",
            PlayerEventKind::DealtKnockback => "playerDealtKnockback",
            PlayerEventKind::Died => "playerDied",
            PlayerEventKind::EarnedElimination => "playerEarnedElimination",
            PlayerEventKind::Joined => "playerJoined",
            PlayerEventKind::Left => "playerLeft",
            PlayerEventKind::ReceivedHealing => "playerReceivedHealing",
            PlayerEventKind::ReceivedKnockback => "playerReceivedKnockback",
            PlayerEventKind::TookDamage => "playerTookDamage",
        }
    }
}

/// A workshop event.
#[derive(Debug, Clone)]
pub enum Event {
    /// `Ongoing - Global` (from `@Event global`).
    Global,
    /// `Ongoing - Each Player` (from `@Event eachPlayer`).
    EachPlayer,
    /// `Ongoing - Each Player` with its canonical team/player filters.
    EachPlayerWithFilters {
        team: EventTeam,
        target: EventTarget,
    },
    /// A player-scoped Workshop event with canonical filters.
    Player {
        kind: PlayerEventKind,
        team: EventTeam,
        target: EventTarget,
    },
    /// A subroutine body (`def name():`), referencing the subroutine.
    Subroutine(SubroutineId),
}

/// A workshop value (expression) node with its source span.
#[derive(Debug, Clone)]
pub struct ValueNode {
    pub value: Value,
    pub span: Option<Span>,
}

/// A workshop value (expression).
#[derive(Debug, Clone)]
pub enum Value {
    /// A numeric literal with its source spelling (`5`, `0.0`, `-22.05`);
    /// computed values (constant folding) carry the formatted spelling.
    Number {
        value: f64,
        text: String,
    },
    String(String),
    /// A reviewed localized Workshop preset-string identity.
    LocalizedString(String),
    Bool(bool),
    Null,
    Array(Vec<ValueId>),
    Vector {
        x: ValueId,
        y: ValueId,
        z: ValueId,
    },
    /// A built-in enumerated value, e.g. `Team.ALL`.
    Enum {
        value_type: String,
        value: String,
    },
    GlobalVariable(GlobalVarId),
    PlayerVariable {
        player: ValueId,
        variable: PlayerVarId,
    },
    /// A declared Workshop subroutine referenced by a generic action such as
    /// `Start Rule`. The identity is source-owned, not a catalog builtin.
    Subroutine(SubroutineId),
    EventPlayer,
    /// A function call over workshop values.
    Call {
        name: String,
        args: Vec<ValueId>,
    },
}

impl ValueNode {
    /// Build a value node with a source span.
    pub fn new(value: Value, span: Option<Span>) -> Self {
        ValueNode { value, span }
    }
}

/// A workshop action.
#[derive(Debug, Clone)]
pub enum Action {
    SetGlobalVariable {
        variable: GlobalVarId,
        value: ValueId,
        span: Option<Span>,
        /// The exact span of the assigned variable identifier.
        target_span: Option<Span>,
    },
    ModifyGlobalVariable {
        variable: GlobalVarId,
        op: ModifyOp,
        value: ValueId,
        span: Option<Span>,
        /// The exact span of the modified variable identifier.
        target_span: Option<Span>,
    },
    SetPlayerVariable {
        player: ValueId,
        variable: PlayerVarId,
        value: ValueId,
        span: Option<Span>,
        /// The exact span of the assigned variable identifier.
        target_span: Option<Span>,
    },
    ModifyPlayerVariable {
        player: ValueId,
        variable: PlayerVarId,
        op: ModifyOp,
        value: ValueId,
        span: Option<Span>,
        /// The exact span of the modified variable identifier.
        target_span: Option<Span>,
    },
    /// Assignment to a canonical Workshop member-access target, optionally
    /// indexed. This is not a builtin catalog action; the emitter preserves
    /// the native member-assignment syntax.
    AssignMember {
        target: ValueId,
        op: Option<ModifyOp>,
        value: ValueId,
        span: Option<Span>,
    },
    CallSubroutine {
        subroutine: SubroutineId,
        span: Option<Span>,
        /// The exact span of the callee identifier occurrence.
        callee_span: Option<Span>,
    },
    If {
        branches: Vec<IfBranch>,
        else_body: Option<Vec<ActionId>>,
        span: Option<Span>,
    },
    While {
        condition: ValueId,
        body: Vec<ActionId>,
        span: Option<Span>,
    },
    ForGlobalVariable {
        variable: GlobalVarId,
        start: ValueId,
        stop: ValueId,
        step: ValueId,
        body: Vec<ActionId>,
        span: Option<Span>,
        /// The exact span of the loop variable identifier.
        target_span: Option<Span>,
    },
    /// `For Player Variable(player, name, start, stop, step)`: the
    /// per-player loop form (frontend-neutral; parsed from reference
    /// evidence, not emitted by Wright's own lowering, which models
    /// foreach counters as globals under the declared #119 contract).
    ForPlayerVariable {
        player: ValueId,
        variable: PlayerVarId,
        start: ValueId,
        stop: ValueId,
        step: ValueId,
        body: Vec<ActionId>,
        span: Option<Span>,
    },
    /// Any other action call with side effects.
    Call {
        name: String,
        args: Vec<ValueId>,
        span: Option<Span>,
    },
}

impl Action {
    /// The source span of this action, if any.
    pub fn span(&self) -> Option<Span> {
        match self {
            Action::SetGlobalVariable { span, .. }
            | Action::ModifyGlobalVariable { span, .. }
            | Action::SetPlayerVariable { span, .. }
            | Action::ModifyPlayerVariable { span, .. }
            | Action::AssignMember { span, .. }
            | Action::CallSubroutine { span, .. }
            | Action::If { span, .. }
            | Action::While { span, .. }
            | Action::ForGlobalVariable { span, .. }
            | Action::ForPlayerVariable { span, .. }
            | Action::Call { span, .. } => *span,
        }
    }
}

/// One condition/body pair of an `If` action.
#[derive(Debug, Clone)]
pub struct IfBranch {
    pub condition: ValueId,
    pub body: Vec<ActionId>,
}

/// The modify operators of the v0.1 surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModifyOp {
    Add,
    Subtract,
    Multiply,
    Divide,
    Modulo,
    Min,
    Max,
    RaiseToPower,
    AppendToArray,
    RemoveFromArray,
    RemoveFromArrayByIndex,
}

impl ModifyOp {
    /// A short canonical name for dumps and diagnostics.
    pub fn as_str(self) -> &'static str {
        match self {
            ModifyOp::Add => "Add",
            ModifyOp::Subtract => "Subtract",
            ModifyOp::Multiply => "Multiply",
            ModifyOp::Divide => "Divide",
            ModifyOp::Modulo => "Modulo",
            ModifyOp::Min => "Min",
            ModifyOp::Max => "Max",
            ModifyOp::RaiseToPower => "RaiseToPower",
            ModifyOp::AppendToArray => "AppendToArray",
            ModifyOp::RemoveFromArray => "RemoveFromArray",
            ModifyOp::RemoveFromArrayByIndex => "RemoveFromArrayByIndex",
        }
    }

    /// The canonical catalog identity for this modification operation.
    pub fn catalog_id(self) -> &'static str {
        match self {
            ModifyOp::Add => "add",
            ModifyOp::Subtract => "subtract",
            ModifyOp::Multiply => "multiply",
            ModifyOp::Divide => "divide",
            ModifyOp::Modulo => "modulo",
            ModifyOp::Min => "min",
            ModifyOp::Max => "max",
            ModifyOp::RaiseToPower => "raiseToPower",
            ModifyOp::AppendToArray => "appendToArray",
            ModifyOp::RemoveFromArray => "removeFromArray",
            ModifyOp::RemoveFromArrayByIndex => "removeFromArrayByIndex",
        }
    }
}