Skip to main content

workshop_rs/analysis/
semantic.rs

1//! Semantic-completeness inspection for permissive raw Workshop parsing.
2//!
3//! Structural WIR validation deliberately remains separate from this report:
4//! a preserved node can be structurally valid while still being unsuitable
5//! for definitive analysis.
6
7use crate::catalog::{Catalog, Kind};
8use crate::core::source::Span;
9use crate::settings::SettingsNode;
10use crate::settings::table;
11use crate::wir::{Action, Program, Value};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum IncompletenessKind {
15    RawSetting,
16    UnknownAction,
17    UnknownValue,
18    OpaqueAction,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum ResidualClassification {
23    ProjectDefinedConstruct,
24    SourceDeclaredVariable,
25    ProducerExtension,
26    LegacyOpaque,
27    UnresolvedIdentifier,
28}
29
30impl ResidualClassification {
31    pub fn as_str(self) -> &'static str {
32        match self {
33            Self::ProjectDefinedConstruct => "project-defined-construct",
34            Self::SourceDeclaredVariable => "source-declared-variable",
35            Self::ProducerExtension => "producer-extension",
36            Self::LegacyOpaque => "legacy-opaque-construct",
37            Self::UnresolvedIdentifier => "truly-unresolved-identifier",
38        }
39    }
40
41    pub fn evidence(self) -> &'static str {
42        match self {
43            Self::ProjectDefinedConstruct => {
44                "source settings or construct was preserved without a canonical catalog identity"
45            }
46            Self::SourceDeclaredVariable => {
47                "the identifier matches a variable declaration in the parsed source program"
48            }
49            Self::ProducerExtension => {
50                "the source uses an action-shaped identity outside the canonical catalog and no declaration resolves it"
51            }
52            Self::LegacyOpaque => {
53                "the parser preserved a legacy raw construct without a canonical contract"
54            }
55            Self::UnresolvedIdentifier => {
56                "the identifier matches neither a source declaration nor a canonical catalog identity"
57            }
58        }
59    }
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct SemanticIssue {
64    pub kind: IncompletenessKind,
65    pub name: String,
66    pub span: Option<Span>,
67    pub classification: ResidualClassification,
68}
69
70/// Report preserved or catalog-unknown constructs that must not be treated as
71/// fully understood by downstream analysis.
72pub fn inspect(program: &crate::Program, catalog: &Catalog) -> Vec<SemanticIssue> {
73    let Ok(storage) = program.to_wir() else {
74        return Vec::new();
75    };
76    inspect_wir(&storage, catalog)
77}
78
79#[doc(hidden)]
80pub fn inspect_wir(program: &Program, catalog: &Catalog) -> Vec<SemanticIssue> {
81    let mut issues = Vec::new();
82    if let Some(settings) = &program.settings {
83        for node in &settings.children {
84            inspect_setting(node, &mut issues);
85        }
86    }
87    for action in program.actions.iter() {
88        inspect_action(action, program, catalog, &mut issues);
89    }
90    for value in program.values.iter() {
91        inspect_value(value, program, catalog, &mut issues);
92    }
93    issues
94}
95
96fn inspect_setting(node: &SettingsNode, issues: &mut Vec<SemanticIssue>) {
97    match node {
98        SettingsNode::Workshop { .. } => {}
99        SettingsNode::Group { children, .. } => {
100            for child in children {
101                inspect_setting(child, issues);
102            }
103        }
104        SettingsNode::Raw { name, span, .. } => issues.push(SemanticIssue {
105            kind: IncompletenessKind::RawSetting,
106            name: name.clone(),
107            span: *span,
108            classification: ResidualClassification::ProjectDefinedConstruct,
109        }),
110        SettingsNode::List {
111            name,
112            elements,
113            span,
114        } => {
115            let known = match name.as_str() {
116                "enabledMaps" | "disabledMaps" => elements
117                    .iter()
118                    .all(|element| table::map_name(&element.value).is_some()),
119                "enabledHeroes" | "disabledHeroes" => elements
120                    .iter()
121                    .all(|element| table::hero_name(&element.value).is_some()),
122                _ => true,
123            };
124            if !known {
125                issues.push(SemanticIssue {
126                    kind: IncompletenessKind::RawSetting,
127                    name: name.clone(),
128                    span: *span,
129                    classification: ResidualClassification::ProjectDefinedConstruct,
130                });
131            }
132        }
133        SettingsNode::Number { .. }
134        | SettingsNode::Bool { .. }
135        | SettingsNode::Flag { .. }
136        | SettingsNode::String { .. } => {}
137    }
138}
139
140fn inspect_action(
141    action: &Action,
142    program: &Program,
143    catalog: &Catalog,
144    issues: &mut Vec<SemanticIssue>,
145) {
146    match action {
147        Action::Call { name, span, .. } => {
148            let kind = if name == "rawWorkshopAction" {
149                Some(IncompletenessKind::OpaqueAction)
150            } else if catalog.entry(Kind::Action, name).is_none() {
151                Some(IncompletenessKind::UnknownAction)
152            } else {
153                None
154            };
155            if let Some(kind) = kind {
156                let classification = if kind == IncompletenessKind::OpaqueAction {
157                    ResidualClassification::LegacyOpaque
158                } else {
159                    ResidualClassification::ProducerExtension
160                };
161                issues.push(SemanticIssue {
162                    kind,
163                    name: name.clone(),
164                    span: *span,
165                    classification,
166                });
167            }
168        }
169        Action::If {
170            branches,
171            else_body,
172            ..
173        } => {
174            for branch in branches {
175                inspect_action_id(branch.body.as_slice(), program, catalog, issues);
176            }
177            if let Some(body) = else_body {
178                inspect_action_id(body.as_slice(), program, catalog, issues);
179            }
180        }
181        Action::While { body, .. }
182        | Action::ForGlobalVariable { body, .. }
183        | Action::ForPlayerVariable { body, .. } => {
184            inspect_action_id(body.as_slice(), program, catalog, issues);
185        }
186        Action::SetGlobalVariable { .. }
187        | Action::ModifyGlobalVariable { .. }
188        | Action::SetPlayerVariable { .. }
189        | Action::ModifyPlayerVariable { .. }
190        | Action::AssignMember { .. }
191        | Action::CallSubroutine { .. } => {}
192    }
193}
194
195fn inspect_action_id(
196    ids: &[crate::wir::ActionId],
197    program: &Program,
198    catalog: &Catalog,
199    issues: &mut Vec<SemanticIssue>,
200) {
201    for id in ids {
202        if let Some(action) = program.actions.get(*id) {
203            inspect_action(action, program, catalog, issues);
204        }
205    }
206}
207
208fn inspect_value(
209    node: &crate::wir::ValueNode,
210    program: &Program,
211    catalog: &Catalog,
212    issues: &mut Vec<SemanticIssue>,
213) {
214    if let Value::Call { name, args } = &node.value {
215        // These names are canonical WIR helpers rather than Workshop
216        // builtins: memberAccess preserves dynamic receiver properties, and
217        // infix operators are lowered to their source spelling for emission.
218        let canonical_helper = matches!(
219            name.as_str(),
220            "memberAccess"
221                | "+"
222                | "-"
223                | "*"
224                | "/"
225                | "%"
226                | "add"
227                | "subtract"
228                | "multiply"
229                | "divide"
230                | "modulo"
231                | "min"
232                | "max"
233                | "raiseToPower"
234                | "appendToArray"
235                | "removeFromArray"
236                | "removeFromArrayByIndex"
237        ) && (args.is_empty()
238            || matches!(name.as_str(), "memberAccess" | "+" | "-" | "*" | "/" | "%"));
239        if canonical_helper {
240            return;
241        }
242        if catalog.entry(Kind::Value, name).is_none()
243            && catalog.entry(Kind::Operator, name).is_none()
244        {
245            issues.push(SemanticIssue {
246                kind: IncompletenessKind::UnknownValue,
247                name: name.clone(),
248                span: node.span,
249                classification: if program
250                    .global_variables
251                    .iter()
252                    .any(|variable| variable.name == *name)
253                    || program
254                        .player_variables
255                        .iter()
256                        .any(|variable| variable.name == *name)
257                {
258                    ResidualClassification::SourceDeclaredVariable
259                } else {
260                    ResidualClassification::UnresolvedIdentifier
261                },
262            });
263        }
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270    use crate::settings::{Settings, SettingsNode};
271
272    #[test]
273    fn reports_preserved_and_unknown_nodes() {
274        let catalog = Catalog::builtin().expect("builtin catalog");
275        let mut program = Program {
276            settings: Some(Settings {
277                span: None,
278                children: vec![SettingsNode::Raw {
279                    name: "Future Setting".to_string(),
280                    value: "opaque".to_string(),
281                    span: None,
282                }],
283            }),
284            ..Program::default()
285        };
286        program.actions.push(Action::Call {
287            name: "rawWorkshopAction".to_string(),
288            args: Vec::new(),
289            span: None,
290        });
291        program.actions.push(Action::Call {
292            name: "futureAction".to_string(),
293            args: Vec::new(),
294            span: None,
295        });
296        program.values.push(crate::wir::ValueNode::new(
297            Value::Call {
298                name: "futureValue".to_string(),
299                args: Vec::new(),
300            },
301            None,
302        ));
303
304        let issues = inspect_wir(&program, &catalog);
305        assert!(
306            issues
307                .iter()
308                .any(|issue| issue.kind == IncompletenessKind::RawSetting)
309        );
310        assert!(
311            issues
312                .iter()
313                .any(|issue| issue.kind == IncompletenessKind::OpaqueAction)
314        );
315        assert!(
316            issues
317                .iter()
318                .any(|issue| issue.kind == IncompletenessKind::UnknownAction)
319        );
320        assert!(
321            issues
322                .iter()
323                .any(|issue| issue.kind == IncompletenessKind::UnknownValue)
324        );
325        assert!(issues.iter().any(|issue| {
326            issue.kind == IncompletenessKind::RawSetting
327                && issue.classification == ResidualClassification::ProjectDefinedConstruct
328        }));
329        assert!(issues.iter().any(|issue| {
330            issue.kind == IncompletenessKind::OpaqueAction
331                && issue.classification == ResidualClassification::LegacyOpaque
332        }));
333        assert!(issues.iter().any(|issue| {
334            issue.kind == IncompletenessKind::UnknownValue
335                && issue.classification == ResidualClassification::UnresolvedIdentifier
336        }));
337    }
338}