workshop-rs 1.5.0

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
//! Semantic-completeness inspection for permissive raw Workshop parsing.
//!
//! Inspection is defined over the public canonical `Program` model and is
//! independent from structural validation: residuals observable in the public
//! model are reported even when the program cannot be materialized to
//! internal WIR. Structural validity deliberately remains separate from this
//! report: a preserved node can be structurally valid while still being
//! unsuitable for definitive analysis, and a structurally invalid program can
//! still carry inspectable semantic residuals.

use crate::catalog::{Catalog, Kind};
use crate::core::source::Span;
use crate::program::{action_argument_values, value_children};
use crate::settings::SettingsNode;
use crate::settings::table;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IncompletenessKind {
    RawSetting,
    UnknownAction,
    UnknownValue,
    OpaqueAction,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResidualClassification {
    ProjectDefinedConstruct,
    SourceDeclaredVariable,
    ProducerExtension,
    LegacyOpaque,
    UnresolvedIdentifier,
}

impl ResidualClassification {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ProjectDefinedConstruct => "project-defined-construct",
            Self::SourceDeclaredVariable => "source-declared-variable",
            Self::ProducerExtension => "producer-extension",
            Self::LegacyOpaque => "legacy-opaque-construct",
            Self::UnresolvedIdentifier => "truly-unresolved-identifier",
        }
    }

    pub fn evidence(self) -> &'static str {
        match self {
            Self::ProjectDefinedConstruct => {
                "source settings or construct was preserved without a canonical catalog identity"
            }
            Self::SourceDeclaredVariable => {
                "the identifier matches a variable declaration in the parsed source program"
            }
            Self::ProducerExtension => {
                "the source uses an action-shaped identity outside the canonical catalog and no declaration resolves it"
            }
            Self::LegacyOpaque => {
                "the parser preserved a legacy raw construct without a canonical contract"
            }
            Self::UnresolvedIdentifier => {
                "the identifier matches neither a source declaration nor a canonical catalog identity"
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SemanticIssue {
    pub kind: IncompletenessKind,
    pub name: String,
    pub span: Option<Span>,
    pub classification: ResidualClassification,
}

/// Report preserved or catalog-unknown constructs that must not be treated as
/// fully understood by downstream analysis.
///
/// Residual inspection is defined over the public canonical
/// [`crate::Program`] model and is independent from structural validation: it
/// may be used on `Program` values that [`Program::validate`] rejects, and an
/// internal WIR materialization failure never projects to an empty inventory.
/// Callers that also require structural validity call
/// [`Program::validate`](crate::Program::validate) separately; inspection
/// does not report validation errors.
///
/// [`Program::validate`]: crate::Program::validate
pub fn inspect(program: &crate::Program, catalog: &Catalog) -> Vec<SemanticIssue> {
    let mut issues = Vec::new();
    if let Some(settings) = &program.settings {
        for node in &settings.children {
            inspect_setting(node, &mut issues);
        }
    }
    for (rule, rule_data) in program.rules.iter().enumerate() {
        for (position, action) in rule_data.actions.iter().enumerate() {
            inspect_action(action, program, rule, position, catalog, &mut issues);
        }
    }
    for (rule, rule_data) in program.rules.iter().enumerate() {
        for (condition, condition_data) in rule_data.conditions.iter().enumerate() {
            inspect_value_tree(
                &condition_data.value,
                &mut Vec::new(),
                &|path| program.condition_value_node_span(rule, condition, path),
                program,
                catalog,
                &mut issues,
            );
        }
        let mut position = 0;
        inspect_action_values(
            &rule_data.actions,
            &mut position,
            false,
            rule,
            program,
            catalog,
            &mut issues,
        );
    }
    issues
}

#[cfg(test)]
pub(crate) fn inspect_wir(program: &crate::wir::Program, catalog: &Catalog) -> Vec<SemanticIssue> {
    let program = crate::Program::from_wir(program.clone())
        .expect("test WIR materializes as a public program");
    inspect(&program, catalog)
}

fn inspect_setting(node: &SettingsNode, issues: &mut Vec<SemanticIssue>) {
    match node {
        SettingsNode::Workshop { .. } => {}
        SettingsNode::Group { children, .. } => {
            for child in children {
                inspect_setting(child, issues);
            }
        }
        SettingsNode::Raw { name, span, .. } => issues.push(SemanticIssue {
            kind: IncompletenessKind::RawSetting,
            name: name.clone(),
            span: *span,
            classification: ResidualClassification::ProjectDefinedConstruct,
        }),
        SettingsNode::List { name, elements, .. } => {
            let element_known: fn(&crate::settings::SettingsListElement) -> bool =
                match name.as_str() {
                    "enabledMaps" | "disabledMaps" => {
                        |element: &crate::settings::SettingsListElement| {
                            table::map_name(&element.value).is_some()
                        }
                    }
                    "enabledHeroes" | "disabledHeroes" => {
                        |element: &crate::settings::SettingsListElement| {
                            table::hero_name(&element.value).is_some()
                        }
                    }
                    _ => |_| true,
                };
            for element in elements {
                if !element_known(element) {
                    issues.push(SemanticIssue {
                        kind: IncompletenessKind::RawSetting,
                        name: element.value.clone(),
                        span: element.span,
                        classification: ResidualClassification::ProjectDefinedConstruct,
                    });
                }
            }
        }
        SettingsNode::Number { .. }
        | SettingsNode::Bool { .. }
        | SettingsNode::Flag { .. }
        | SettingsNode::String { .. } => {}
    }
}

fn inspect_action(
    action: &crate::Action,
    program: &crate::Program,
    rule: usize,
    position: usize,
    catalog: &Catalog,
    issues: &mut Vec<SemanticIssue>,
) {
    match action {
        crate::Action::Call { name, .. } => {
            let kind = if name == "rawWorkshopAction" {
                Some(IncompletenessKind::OpaqueAction)
            } else if catalog.entry(Kind::Action, name).is_none() {
                Some(IncompletenessKind::UnknownAction)
            } else {
                None
            };
            if let Some(kind) = kind {
                let classification = if kind == IncompletenessKind::OpaqueAction {
                    ResidualClassification::LegacyOpaque
                } else {
                    ResidualClassification::ProducerExtension
                };
                issues.push(SemanticIssue {
                    kind,
                    name: name.clone(),
                    span: program.action_span(rule, position),
                    classification,
                });
            }
        }
        crate::Action::Disabled { action } => {
            inspect_action(action, program, rule, position, catalog, issues);
        }
        _ => {}
    }
}

/// Visit every action value argument in the order internal materialization
/// pushes value nodes: an `If` header precedes its body, while `While`,
/// `For`, and `Else If` headers follow their bodies. Control-flow terminators
/// stop a body scan without being consumed; a stray terminator at stream top
/// level is visited like any other action, so malformed rules still expose
/// every observable value. `stop_at_terminator` distinguishes the two scans.
fn inspect_action_values(
    actions: &[crate::Action],
    position: &mut usize,
    stop_at_terminator: bool,
    rule: usize,
    program: &crate::Program,
    catalog: &Catalog,
    issues: &mut Vec<SemanticIssue>,
) {
    while *position < actions.len() {
        let index = *position;
        let current = match &actions[index] {
            crate::Action::Disabled { action } => action.as_ref(),
            action => action,
        };
        match current {
            crate::Action::ElseIf { .. } | crate::Action::Else | crate::Action::End
                if stop_at_terminator =>
            {
                return;
            }
            crate::Action::If { .. } => {
                inspect_action_arguments(rule, index, &actions[index], program, catalog, issues);
                *position += 1;
                inspect_action_values(actions, position, true, rule, program, catalog, issues);
                while matches!(actions.get(*position), Some(crate::Action::ElseIf { .. })) {
                    let elseif = *position;
                    *position += 1;
                    inspect_action_values(actions, position, true, rule, program, catalog, issues);
                    inspect_action_arguments(
                        rule,
                        elseif,
                        &actions[elseif],
                        program,
                        catalog,
                        issues,
                    );
                }
                if matches!(actions.get(*position), Some(crate::Action::Else)) {
                    *position += 1;
                    inspect_action_values(actions, position, true, rule, program, catalog, issues);
                }
                if matches!(actions.get(*position), Some(crate::Action::End)) {
                    *position += 1;
                }
            }
            crate::Action::While { .. }
            | crate::Action::ForGlobalVariable { .. }
            | crate::Action::ForPlayerVariable { .. } => {
                *position += 1;
                inspect_action_values(actions, position, true, rule, program, catalog, issues);
                if matches!(actions.get(*position), Some(crate::Action::End)) {
                    *position += 1;
                }
                inspect_action_arguments(rule, index, &actions[index], program, catalog, issues);
            }
            _ => {
                inspect_action_arguments(rule, index, &actions[index], program, catalog, issues);
                *position += 1;
            }
        }
    }
}

/// Inspect the direct value arguments of one public action in their mapped
/// order.
fn inspect_action_arguments(
    rule: usize,
    action: usize,
    action_data: &crate::Action,
    program: &crate::Program,
    catalog: &Catalog,
    issues: &mut Vec<SemanticIssue>,
) {
    for (argument, value) in action_argument_values(action_data).iter().enumerate() {
        inspect_value_tree(
            value,
            &mut Vec::new(),
            &|path| program.action_argument_value_node_span(rule, action, argument, path),
            program,
            catalog,
            issues,
        );
    }
}

/// Walk a public value tree in post-order — children before their node, the
/// order value nodes take when materialized to the internal arena — flagging
/// every `Value::Call` identity the catalog does not resolve.
fn inspect_value_tree(
    value: &crate::Value,
    path: &mut Vec<usize>,
    span_at: &impl Fn(&[usize]) -> Option<Span>,
    program: &crate::Program,
    catalog: &Catalog,
    issues: &mut Vec<SemanticIssue>,
) {
    for (index, child) in value_children(value).into_iter().enumerate() {
        path.push(index);
        inspect_value_tree(child, path, span_at, program, catalog, issues);
        path.pop();
    }
    if let crate::Value::Call { name, args } = value {
        // These names are canonical helpers rather than Workshop
        // builtins: memberAccess preserves dynamic receiver properties, and
        // infix operators are lowered to their source spelling for emission.
        let canonical_helper = name == crate::wir::AMBIGUOUS_ENUM_CALL
            || crate::wir::is_canonical_helper_call(name, args.len());
        if canonical_helper {
            return;
        }
        if catalog.entry(Kind::Value, name).is_none()
            && catalog.entry(Kind::Operator, name).is_none()
        {
            issues.push(SemanticIssue {
                kind: IncompletenessKind::UnknownValue,
                name: name.clone(),
                span: span_at(path),
                classification: if program
                    .global_variables
                    .iter()
                    .any(|variable| variable.name == *name)
                    || program
                        .player_variables
                        .iter()
                        .any(|variable| variable.name == *name)
                {
                    ResidualClassification::SourceDeclaredVariable
                } else {
                    ResidualClassification::UnresolvedIdentifier
                },
            });
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::settings::{Settings, SettingsNode};
    use crate::{Action, Condition, Event, Program, Rule, Value};

    #[test]
    fn reports_preserved_and_unknown_nodes() {
        let catalog = Catalog::builtin().expect("builtin catalog");
        let mut program = Program::new();
        program.settings = Some(Settings {
            span: None,
            children: vec![SettingsNode::Raw {
                name: "Future Setting".to_string(),
                value: "opaque".to_string(),
                span: None,
            }],
        });
        program.rule(
            Rule::new("residuals", Event::Global)
                .condition(Condition::new(Value::call("futureValue", [])))
                .action(Action::call("rawWorkshopAction", []))
                .action(Action::call("futureAction", [])),
        );

        let issues = inspect(&program, &catalog);
        assert!(
            issues
                .iter()
                .any(|issue| issue.kind == IncompletenessKind::RawSetting)
        );
        assert!(
            issues
                .iter()
                .any(|issue| issue.kind == IncompletenessKind::OpaqueAction)
        );
        assert!(
            issues
                .iter()
                .any(|issue| issue.kind == IncompletenessKind::UnknownAction)
        );
        assert!(
            issues
                .iter()
                .any(|issue| issue.kind == IncompletenessKind::UnknownValue)
        );
        assert!(issues.iter().any(|issue| {
            issue.kind == IncompletenessKind::RawSetting
                && issue.classification == ResidualClassification::ProjectDefinedConstruct
        }));
        assert!(issues.iter().any(|issue| {
            issue.kind == IncompletenessKind::OpaqueAction
                && issue.classification == ResidualClassification::LegacyOpaque
        }));
        assert!(issues.iter().any(|issue| {
            issue.kind == IncompletenessKind::UnknownValue
                && issue.classification == ResidualClassification::UnresolvedIdentifier
        }));
    }
}