1use 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
70pub 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 let canonical_helper = matches!(
219 name.as_str(),
220 crate::wir::AMBIGUOUS_ENUM_CALL
221 | "memberAccess"
222 | "+"
223 | "-"
224 | "*"
225 | "/"
226 | "%"
227 | "add"
228 | "subtract"
229 | "multiply"
230 | "divide"
231 | "modulo"
232 | "min"
233 | "max"
234 | "raiseToPower"
235 | "appendToArray"
236 | "removeFromArray"
237 | "removeFromArrayByValue"
238 | "removeFromArrayByIndex"
239 ) && (args.is_empty()
240 || matches!(
241 name.as_str(),
242 crate::wir::AMBIGUOUS_ENUM_CALL | "memberAccess" | "+" | "-" | "*" | "/" | "%"
243 ));
244 if canonical_helper {
245 return;
246 }
247 if catalog.entry(Kind::Value, name).is_none()
248 && catalog.entry(Kind::Operator, name).is_none()
249 {
250 issues.push(SemanticIssue {
251 kind: IncompletenessKind::UnknownValue,
252 name: name.clone(),
253 span: node.span,
254 classification: if program
255 .global_variables
256 .iter()
257 .any(|variable| variable.name == *name)
258 || program
259 .player_variables
260 .iter()
261 .any(|variable| variable.name == *name)
262 {
263 ResidualClassification::SourceDeclaredVariable
264 } else {
265 ResidualClassification::UnresolvedIdentifier
266 },
267 });
268 }
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use super::*;
275 use crate::settings::{Settings, SettingsNode};
276
277 #[test]
278 fn reports_preserved_and_unknown_nodes() {
279 let catalog = Catalog::builtin().expect("builtin catalog");
280 let mut program = Program {
281 settings: Some(Settings {
282 span: None,
283 children: vec![SettingsNode::Raw {
284 name: "Future Setting".to_string(),
285 value: "opaque".to_string(),
286 span: None,
287 }],
288 }),
289 ..Program::default()
290 };
291 program.actions.push(Action::Call {
292 name: "rawWorkshopAction".to_string(),
293 args: Vec::new(),
294 span: None,
295 });
296 program.actions.push(Action::Call {
297 name: "futureAction".to_string(),
298 args: Vec::new(),
299 span: None,
300 });
301 program.values.push(crate::wir::ValueNode::new(
302 Value::Call {
303 name: "futureValue".to_string(),
304 args: Vec::new(),
305 },
306 None,
307 ));
308
309 let issues = inspect_wir(&program, &catalog);
310 assert!(
311 issues
312 .iter()
313 .any(|issue| issue.kind == IncompletenessKind::RawSetting)
314 );
315 assert!(
316 issues
317 .iter()
318 .any(|issue| issue.kind == IncompletenessKind::OpaqueAction)
319 );
320 assert!(
321 issues
322 .iter()
323 .any(|issue| issue.kind == IncompletenessKind::UnknownAction)
324 );
325 assert!(
326 issues
327 .iter()
328 .any(|issue| issue.kind == IncompletenessKind::UnknownValue)
329 );
330 assert!(issues.iter().any(|issue| {
331 issue.kind == IncompletenessKind::RawSetting
332 && issue.classification == ResidualClassification::ProjectDefinedConstruct
333 }));
334 assert!(issues.iter().any(|issue| {
335 issue.kind == IncompletenessKind::OpaqueAction
336 && issue.classification == ResidualClassification::LegacyOpaque
337 }));
338 assert!(issues.iter().any(|issue| {
339 issue.kind == IncompletenessKind::UnknownValue
340 && issue.classification == ResidualClassification::UnresolvedIdentifier
341 }));
342 }
343}