Skip to main content

workshop_rs/frontend/
parser.rs

1//! Native localized Workshop parser.
2//!
3//! Parses vanilla Workshop text directly into validated, locale-independent
4//! the canonical public [`Program`]. Localized actions, values, events, enums, and structural
5//! keywords resolve through the canonical catalog; malformed input,
6//! unknown spellings, and recognized-but-unsupported constructs are reported
7//! as distinct structured diagnostics with source spans.
8
9pub(crate) use std::collections::HashMap;
10use std::sync::OnceLock;
11
12pub(crate) use crate::core::signatures::ExpectedDomain;
13pub(crate) use crate::core::source::{Position, SourceFile, Span};
14use crate::program::Program;
15pub(crate) use crate::settings::table::KeyKind;
16pub(crate) use crate::settings::{PathPart, table};
17pub(crate) use crate::settings::{Settings, SettingsListElement, SettingsNode};
18pub(crate) use crate::wir::{
19    self, Action, Event, EventTarget, EventTeam, ModifyOp, PlayerEventKind, Value, ValueNode,
20};
21
22pub(crate) use super::lexer::{Token, TokenKind, tokenize};
23pub(crate) use crate::catalog::{Catalog, Kind, Locale};
24pub(crate) use crate::core::error::{Result, WorkshopError};
25
26/// Where action parsing stopped.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub(crate) enum Stop {
29    /// The enclosing `}` was consumed.
30    SectionClosed,
31    /// The `End` keyword is next (not consumed).
32    End,
33    /// The `Else If` keyword is next (not consumed).
34    ElseIf,
35    /// The `Else` keyword is next (not consumed).
36    Else,
37}
38
39pub(crate) enum AssignmentOperator {
40    Set,
41    Modify(ModifyOp),
42}
43
44/// Parse localized Workshop text into Workshop IR using the catalog's
45/// canonical call-signature context. Ambiguous bare enum members resolve when
46/// their enclosing call pins one matching domain; unpinned ambiguity remains a
47/// structured canonical value. See [`parse_with_context`] when a
48/// consumer needs to provide additional signature context.
49pub fn parse(input: &str, catalog: &Catalog, locale: &Locale) -> Result<Program> {
50    parse_with_context(input, catalog, locale, catalog)
51}
52
53#[cfg(test)]
54pub(crate) fn parse_wir(input: &str, catalog: &Catalog, locale: &Locale) -> Result<wir::Program> {
55    parse_wir_with_context(input, catalog, locale, catalog)
56}
57
58/// Compatibility entry point for crate-internal storage tests and migration
59/// checks. Ordinary consumers should use [`parse`], which returns [`Program`].
60/// Parse localized Workshop text into Workshop IR, resolving ambiguous bare
61/// enum members from the enclosing call's canonical signature context (#111).
62///
63/// When a bare member spelling matches several enum domains, the parser asks
64/// [`ExpectedDomain::expected_domain`] for the domain the enclosing call's
65/// signature expects at that argument position; the member resolves only when
66/// that expected domain is one of the matching domains (i.e. the signature
67/// pins exactly one). Without a pin all matching candidates are preserved.
68pub fn parse_with_context(
69    input: &str,
70    catalog: &Catalog,
71    locale: &Locale,
72    context: &dyn ExpectedDomain,
73) -> Result<Program> {
74    parse_wir_with_context(input, catalog, locale, context).and_then(Program::from_wir)
75}
76
77pub(crate) fn parse_wir_with_context(
78    input: &str,
79    catalog: &Catalog,
80    locale: &Locale,
81    context: &dyn ExpectedDomain,
82) -> Result<wir::Program> {
83    let tokens = tokenize(input).map_err(|error| WorkshopError::Malformed {
84        message: error.message,
85        span: Some(synthetic_span(error.position)),
86    })?;
87    ParseContext {
88        tokens,
89        pos: 0,
90        source: input,
91        catalog,
92        locale: locale.clone(),
93        context,
94        expected_domain: None,
95        call_stack: Vec::new(),
96        target: wir::Program::default(),
97        globals: HashMap::new(),
98        players: HashMap::new(),
99        subroutines: HashMap::new(),
100        next_global_index: 0,
101        next_player_index: 0,
102    }
103    .program()
104}
105
106/// A synthetic single-position span (used before a file registry exists).
107pub(crate) fn synthetic_span(position: Position) -> Span {
108    Span::new(crate::core::ids::Id::from_index(0), position, position)
109}
110
111pub(crate) struct ParseContext<'a> {
112    pub(crate) tokens: Vec<Token>,
113    pub(crate) pos: usize,
114    pub(crate) source: &'a str,
115    pub(crate) catalog: &'a Catalog,
116    pub(crate) locale: Locale,
117    /// Canonical signature context (#111): supplies the expected enum domain
118    /// for the call argument currently being parsed.
119    pub(crate) context: &'a dyn ExpectedDomain,
120    /// The expected enum domain for the value currently being parsed, set by
121    /// [`ParseContext::value_args`] from the enclosing call's signature.
122    pub(crate) expected_domain: Option<&'a str>,
123    pub(crate) call_stack: Vec<String>,
124    pub(crate) target: wir::Program,
125    pub(crate) globals: HashMap<String, wir::GlobalVarId>,
126    pub(crate) players: HashMap<String, wir::PlayerVarId>,
127    pub(crate) subroutines: HashMap<String, wir::SubroutineId>,
128    pub(crate) next_global_index: u32,
129    pub(crate) next_player_index: u32,
130}
131
132impl<'a> ParseContext<'a> {
133    pub(crate) fn resolve_entry(
134        &self,
135        kind: Kind,
136        spelling: &str,
137    ) -> Option<&'a crate::catalog::CatalogEntry> {
138        self.catalog
139            .resolve(kind, &self.locale, spelling)
140            .or_else(|| {
141                if self.locale != *self.catalog.primary_locale() {
142                    self.catalog
143                        .resolve(kind, self.catalog.primary_locale(), spelling)
144                } else {
145                    None
146                }
147            })
148    }
149
150    pub(crate) fn canonical_keyword(&self, spelling: &str) -> String {
151        self.catalog
152            .resolve(Kind::Structural, &self.locale, spelling)
153            .or_else(|| {
154                (self.locale != *self.catalog.primary_locale()).then(|| {
155                    self.catalog
156                        .resolve(Kind::Structural, self.catalog.primary_locale(), spelling)
157                })?
158            })
159            .map(|entry| entry.id.clone())
160            .unwrap_or_else(|| canonical_keyword(spelling).to_string())
161    }
162
163    pub(crate) fn line_has_assignment(&self) -> bool {
164        let tokens: Vec<_> = self.tokens[self.pos..]
165            .iter()
166            .take_while(|token| !matches!(token.kind, TokenKind::Semi | TokenKind::RBrace))
167            .collect();
168        tokens.iter().any(|token| {
169            matches!(&token.kind, TokenKind::Op(op) if matches!(op.as_str(), "=" | "+=" | "-=" | "*=" | "/=" | "%="))
170        }) || tokens.windows(2).any(|window| {
171            matches!(&window[0].kind, TokenKind::Word(_))
172                && matches!(&window[1].kind, TokenKind::Op(op) if op == "=")
173        })
174    }
175
176    /// Read the maximal phrase of consecutive words (space-joined). Phrases
177    /// may span lines because long Workshop action arguments wrap mid-phrase.
178    pub(crate) fn phrase(&mut self) -> Result<(String, Position, Position)> {
179        let mut words = Vec::new();
180        let (start, mut end) = match self.peek() {
181            Some(Token {
182                kind: TokenKind::Word(word),
183                start,
184                end,
185            }) => {
186                words.push(word.clone());
187                (start, end)
188            }
189            Some(Token {
190                kind: TokenKind::Number { text, .. },
191                start,
192                end,
193            }) => {
194                words.push(text.clone());
195                (start, end)
196            }
197            Some(token) => return Err(self.malformed("expected an identifier", &token)),
198            None => return Err(self.malformed("expected an identifier", self.eof())),
199        };
200        self.pos += 1;
201        while let Some(token) = self.peek() {
202            match token {
203                Token {
204                    kind: TokenKind::Word(word),
205                    end: word_end,
206                    ..
207                } => {
208                    if matches!(
209                        self.peek_at(1).map(|token| token.kind),
210                        Some(TokenKind::Op(equal)) if equal == "="
211                    ) {
212                        break;
213                    }
214                    words.push(word.clone());
215                    end = word_end;
216                    self.pos += 1;
217                }
218                // Enum members embed numbers (`Team 2`, `Ability 2`); the
219                // lexer splits them from the word, so phrases join Number
220                // tokens too (#119 reference evidence).
221                Token {
222                    kind: TokenKind::Number { text, .. },
223                    end: number_end,
224                    ..
225                } => {
226                    words.push(text.clone());
227                    end = number_end;
228                    self.pos += 1;
229                }
230                _ => break,
231            }
232        }
233        Ok((words.join(" "), start, end))
234    }
235
236    /// Read a single-line phrase (stops at a line boundary). Used for names
237    /// that are structurally one per line, such as variable declarations.
238    pub(crate) fn phrase_on_line(&mut self) -> Result<(String, Position, Position)> {
239        let mut words = Vec::new();
240        let (start, mut end, line) = match self.peek() {
241            Some(Token {
242                kind: TokenKind::Word(word),
243                start,
244                end,
245            }) => {
246                words.push(word.clone());
247                (start, end, start.line)
248            }
249            Some(Token {
250                kind: TokenKind::Number { text, .. },
251                start,
252                end,
253            }) => {
254                words.push(text.clone());
255                (start, end, start.line)
256            }
257            Some(token) => return Err(self.malformed("expected an identifier", &token)),
258            None => return Err(self.malformed("expected an identifier", self.eof())),
259        };
260        self.pos += 1;
261        while let Some(token) = self.peek() {
262            let (word, word_start, word_end) = match token {
263                Token {
264                    kind: TokenKind::Word(word),
265                    start,
266                    end,
267                } => (word, start, end),
268                Token {
269                    kind: TokenKind::Number { text, .. },
270                    start,
271                    end,
272                } => (text, start, end),
273                Token {
274                    kind: TokenKind::Dot,
275                    start,
276                    end,
277                } => (".".to_string(), start, end),
278                Token {
279                    kind: TokenKind::Op(op),
280                    start,
281                    end,
282                } if matches!(op.as_str(), "-" | "%") => (op.clone(), start, end),
283                _ => break,
284            };
285            if word_start.line != line {
286                break;
287            }
288            words.push(word);
289            end = word_end;
290            self.pos += 1;
291        }
292        Ok((
293            words
294                .join(" ")
295                .replace(" .", ".")
296                .replace(". ", ".")
297                .replace(" : ", ":")
298                .replace(" %", "%"),
299            start,
300            end,
301        ))
302    }
303
304    pub(crate) fn phrase_on_line_with_colon(&mut self) -> Result<(String, Position, Position)> {
305        let (mut phrase, start, mut end) = self.phrase_on_line()?;
306        if matches!(
307            self.peek(),
308            Some(Token {
309                kind: TokenKind::Colon,
310                ..
311            })
312        ) {
313            let colon_pos = self.pos;
314            self.next();
315            let (rest, _, rest_end) = self.phrase_on_line()?;
316            if matches!(
317                self.peek(),
318                Some(Token {
319                    kind: TokenKind::LBrace,
320                    ..
321                })
322            ) {
323                phrase.push(':');
324                phrase.push(' ');
325                phrase.push_str(&rest);
326                end = rest_end;
327            } else {
328                self.pos = colon_pos;
329            }
330        }
331        Ok((phrase, start, end))
332    }
333
334    pub(crate) fn enum_member_phrase(&mut self) -> Result<(String, Position, Position)> {
335        let first = self
336            .peek()
337            .ok_or_else(|| self.malformed("expected an enum member", self.eof()))?;
338        let start = first.start;
339        let line = first.start.line;
340        let mut end = first.end;
341        let mut parts = Vec::new();
342        while let Some(token) = self.peek() {
343            if token.start.line != line
344                || matches!(token.kind, TokenKind::RParen | TokenKind::Comma)
345            {
346                break;
347            }
348            self.pos += 1;
349            end = token.end;
350            parts.push(raw_token_text(&token.kind));
351        }
352        if parts.is_empty() {
353            return Err(self.malformed("expected an enum member", &first));
354        }
355        Ok((
356            parts
357                .join(" ")
358                .replace(" : ", ":")
359                .replace(" .", ".")
360                .replace(". ", "."),
361            start,
362            end,
363        ))
364    }
365
366    /// Read a text line (tokens until `;`), joining words and dashes into
367    /// the literal text, and consume the terminating `;`. Returns the text
368    /// and the span covering the line's content tokens.
369    pub(crate) fn line_text(&mut self) -> Result<(String, Option<Span>)> {
370        let mut parts = Vec::new();
371        let mut start = None;
372        let mut end = None;
373        loop {
374            match self.peek() {
375                Some(Token {
376                    kind: TokenKind::Semi,
377                    ..
378                }) => {
379                    self.pos += 1;
380                    break;
381                }
382                Some(token) => {
383                    start.get_or_insert(token.start);
384                    end = Some(token.end);
385                    match &token.kind {
386                        TokenKind::Word(word) => parts.push(word.clone()),
387                        TokenKind::Op(op) if op == "-" => parts.push("-".to_string()),
388                        TokenKind::Number { value, .. } => parts.push(value.to_string()),
389                        TokenKind::Dot => parts.push(".".to_string()),
390                        TokenKind::Colon => parts.push(":".to_string()),
391                        _ => return Err(self.malformed("expected a text line", &token)),
392                    }
393                    self.pos += 1;
394                }
395                None => {
396                    return Err(self.malformed("unexpected end of input in line", self.eof()));
397                }
398            }
399        }
400        Ok((
401            parts
402                .join(" ")
403                .replace(" .", ".")
404                .replace(". ", ".")
405                .replace(" : ", ":"),
406            start
407                .zip(end)
408                .map(|(start, end)| Span::new(self.file(), start, end)),
409        ))
410    }
411
412    /// Consume a known keyword phrase, verifying its spelling.
413    pub(crate) fn consume_phrase(&mut self, expected: &str) -> Result<()> {
414        let (phrase, _, _) = self.phrase()?;
415        if phrase != expected {
416            return Err(self.malformed(&format!("expected '{expected}'"), self.previous()));
417        }
418        Ok(())
419    }
420
421    pub(crate) fn expect_keyword(&mut self, expected: &str) -> Result<Position> {
422        match self.next() {
423            Some(Token {
424                kind: TokenKind::Word(word),
425                start,
426                ..
427            }) if self.canonical_keyword(&word) == expected => Ok(start),
428            Some(token) => Err(self.malformed(&format!("expected '{expected}'"), &token)),
429            None => Err(self.malformed(&format!("expected '{expected}'"), self.eof())),
430        }
431    }
432
433    pub(crate) fn expect(&mut self, kind: TokenKind, message: &str) -> Result<()> {
434        match self.next() {
435            Some(token) if token.kind == kind => Ok(()),
436            Some(token) => Err(self.malformed(message, &token)),
437            None => Err(self.malformed(message, self.eof())),
438        }
439    }
440
441    pub(crate) fn expect_string(&mut self, message: &str) -> Result<String> {
442        match self.next() {
443            Some(Token {
444                kind: TokenKind::String(content),
445                ..
446            }) => Ok(content),
447            Some(token) => Err(self.malformed(message, &token)),
448            None => Err(self.malformed(message, self.eof())),
449        }
450    }
451
452    pub(crate) fn malformed(&self, message: &str, token: &Token) -> WorkshopError {
453        WorkshopError::Malformed {
454            message: message.to_string(),
455            span: Some(Span::new(self.file(), token.start, token.end)),
456        }
457    }
458
459    pub(crate) fn unknown(&self, kind: &'static str, spelling: &str) -> WorkshopError {
460        WorkshopError::Unknown {
461            kind,
462            spelling: spelling.to_string(),
463            locale: self.locale.clone(),
464            span: None,
465        }
466    }
467
468    pub(crate) fn peek(&self) -> Option<Token> {
469        self.tokens.get(self.pos).cloned()
470    }
471
472    pub(crate) fn peek_at(&self, offset: usize) -> Option<Token> {
473        self.tokens.get(self.pos + offset).cloned()
474    }
475
476    pub(crate) fn next(&mut self) -> Option<Token> {
477        let token = self.tokens.get(self.pos).cloned();
478        if token.is_some() {
479            self.pos += 1;
480        }
481        token
482    }
483
484    pub(crate) fn previous(&self) -> &Token {
485        self.tokens
486            .get(self.pos.saturating_sub(1))
487            .unwrap_or_else(|| self.tokens.last().unwrap())
488    }
489
490    pub(crate) fn previous_span(&self) -> (Position, Position) {
491        let token = self.previous();
492        (token.start, token.end)
493    }
494
495    pub(crate) fn span_here(&self) -> (Position, Position) {
496        let token = self
497            .peek()
498            .unwrap_or_else(|| self.tokens.last().unwrap().clone());
499        (token.start, token.end)
500    }
501
502    pub(crate) fn eof(&self) -> &Token {
503        self.tokens.last().unwrap()
504    }
505
506    pub(crate) fn file(&self) -> crate::core::ids::Id<SourceFile> {
507        crate::core::ids::Id::from_index(0)
508    }
509}
510
511pub(crate) fn is_comparison(op: &str) -> bool {
512    matches!(op, "==" | "!=" | "<" | "<=" | ">" | ">=")
513}
514
515pub(crate) fn canonical_keyword(keyword: &str) -> &str {
516    static KEYWORDS: OnceLock<HashMap<String, String>> = OnceLock::new();
517    KEYWORDS
518        .get_or_init(|| {
519            serde_json::from_str(include_str!("structural_keywords.json"))
520                .expect("structural keyword data is valid JSON")
521        })
522        .get(keyword)
523        .map(String::as_str)
524        .unwrap_or(keyword)
525}
526
527pub(crate) fn raw_token_text(kind: &TokenKind) -> String {
528    match kind {
529        TokenKind::Word(value) => value.clone(),
530        TokenKind::Number { text, .. } => text.clone(),
531        TokenKind::String(value) => format!("\"{}\"", value.replace('"', "\\\"")),
532        TokenKind::Op(value) => value.clone(),
533        TokenKind::LParen => "(".to_string(),
534        TokenKind::RParen => ")".to_string(),
535        TokenKind::Comma => ",".to_string(),
536        TokenKind::Semi => ";".to_string(),
537        TokenKind::LBrace => "{".to_string(),
538        TokenKind::RBrace => "}".to_string(),
539        TokenKind::Colon => ":".to_string(),
540        TokenKind::Dot => ".".to_string(),
541        TokenKind::LBracket => "[".to_string(),
542        TokenKind::RBracket => "]".to_string(),
543        TokenKind::Eof => String::new(),
544    }
545}