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