Skip to main content

lemma/parsing/
parser.rs

1use crate::error::Error;
2use crate::limits::ResourceLimits;
3use crate::parsing::ast::{try_parse_type_constraint_command, *};
4use crate::parsing::lexer::{
5    can_be_label, can_be_spec_name_spelling, can_be_unit_name, is_boolean_keyword, is_keyword,
6    is_math_function, is_prefix_rounding, is_reserved_repository_name, is_spec_body_keyword,
7    token_is_calendar_period_marker, token_kind_to_boolean_value,
8    token_kind_to_conversion_type_kind, token_kind_to_primitive, Lexer, LexerCheckpoint, Token,
9    TokenKind,
10};
11use crate::parsing::source::Source;
12use indexmap::IndexMap;
13use rust_decimal::Decimal;
14use std::sync::Arc;
15
16#[derive(Debug)]
17pub struct ParseResult {
18    pub repositories: IndexMap<Arc<LemmaRepository>, Vec<LemmaSpec>>,
19    pub expression_count: usize,
20}
21
22impl ParseResult {
23    /// Specs in parse order: repository groups follow declaration order; specs within each group follow source order.
24    #[must_use]
25    pub fn flatten_specs(&self) -> Vec<&LemmaSpec> {
26        self.repositories
27            .values()
28            .flat_map(|specs| specs.iter())
29            .collect()
30    }
31
32    #[must_use]
33    pub fn into_flattened_specs(self) -> Vec<LemmaSpec> {
34        self.repositories.into_values().flatten().collect()
35    }
36}
37
38/// Parse a standalone repository qualifier string (trimmed). Requires EOF after
39/// the qualifier so callers can reject URL/path injection in install ids.
40pub fn parse_repository_qualifier_str(
41    input: &str,
42) -> Result<crate::parsing::ast::RepositoryQualifier, Error> {
43    let limits = ResourceLimits::default();
44    let mut parser = Parser::new(
45        input.trim(),
46        crate::parsing::source::SourceType::Volatile,
47        &limits,
48    );
49    let (qualifier, _) = parser.parse_repository_qualifier()?;
50    if !parser.at(&TokenKind::Eof)? {
51        let tok = *parser.peek()?;
52        return Err(parser.error_at_token(
53            &tok,
54            format!(
55                "Unexpected {} after repository qualifier '{}'",
56                tok.kind, qualifier.name
57            ),
58        ));
59    }
60    Ok(qualifier)
61}
62
63pub fn parse(
64    content: &str,
65    source_type: crate::parsing::source::SourceType,
66    limits: &ResourceLimits,
67) -> Result<ParseResult, Error> {
68    if content.len() > limits.max_source_size_bytes {
69        return Err(Error::resource_limit_exceeded(
70            "max_source_size_bytes",
71            format!(
72                "{} bytes ({} MB)",
73                limits.max_source_size_bytes,
74                limits.max_source_size_bytes / (1024 * 1024)
75            ),
76            format!(
77                "{} bytes ({:.2} MB)",
78                content.len(),
79                content.len() as f64 / (1024.0 * 1024.0)
80            ),
81            "Reduce source size or split into multiple specs",
82            None,
83            None,
84            None,
85        ));
86    }
87
88    let mut parser = Parser::new(content, source_type, limits);
89    let repositories = parser.parse_file()?;
90    let mut result = ParseResult {
91        repositories,
92        expression_count: parser.expression_count,
93    };
94    canonicalize_parse_result(&mut result);
95    Ok(result)
96}
97
98fn canonicalize_parse_result(result: &mut ParseResult) {
99    let old = std::mem::take(&mut result.repositories);
100    let mut new_map: IndexMap<Arc<LemmaRepository>, Vec<LemmaSpec>> = IndexMap::new();
101    for (repo, mut specs) in old {
102        let mut canonical_repo = (*repo).clone();
103        canonicalize_repository(&mut canonical_repo);
104        for spec in &mut specs {
105            canonicalize_lemma_spec(spec);
106        }
107        new_map
108            .entry(Arc::new(canonical_repo))
109            .or_default()
110            .extend(specs);
111    }
112    result.repositories = new_map;
113}
114
115/// Parser position to rewind to after a speculative parse.
116struct ParserCheckpoint {
117    lexer: LexerCheckpoint,
118    expression_count: usize,
119    table_len: usize,
120}
121
122struct Parser {
123    lexer: Lexer,
124    source: Arc<str>,
125    source_type: crate::parsing::source::SourceType,
126    depth_tracker: DepthTracker,
127    expression_count: usize,
128    max_expression_count: usize,
129    max_spec_name_length: usize,
130    max_data_name_length: usize,
131    max_rule_name_length: usize,
132    last_span: Span,
133    /// Nesting depth of comma-separated call arguments (`find(a, b)`).
134    call_argument_depth: usize,
135    /// Operand starts of the bound chain that last completed without `...`.
136    bound_chain_starts: Vec<usize>,
137    /// Operand starts whose bound chain is known to end without `...`, under the flags
138    /// they were parsed with. Such an operand is a suffix of an already-scanned chain.
139    no_range_at: std::collections::HashMap<usize, ExprFlags>,
140    table: ExprTable<ExpressionKind>,
141    /// Continuation stack of the expression machine, kept for its capacity. Empty between
142    /// runs; a run nested in another starts from a fresh stack.
143    expr_frames: Vec<ExprCont>,
144}
145
146impl Parser {
147    fn new(
148        content: &str,
149        source_type: crate::parsing::source::SourceType,
150        limits: &ResourceLimits,
151    ) -> Self {
152        let source: Arc<str> = Arc::from(content);
153        Parser {
154            lexer: Lexer::new(Arc::clone(&source), &source_type),
155            source,
156            source_type,
157            depth_tracker: DepthTracker::with_max_depth(limits.max_expression_depth),
158            expression_count: 0,
159            max_expression_count: limits.max_expression_count,
160            max_spec_name_length: crate::limits::MAX_SPEC_NAME_LENGTH,
161            max_data_name_length: crate::limits::MAX_DATA_NAME_LENGTH,
162            max_rule_name_length: crate::limits::MAX_RULE_NAME_LENGTH,
163            last_span: Span {
164                start: 0,
165                end: 0,
166                line: 1,
167                col: 0,
168            },
169            call_argument_depth: 0,
170            bound_chain_starts: Vec::new(),
171            no_range_at: std::collections::HashMap::new(),
172            expr_frames: Vec::new(),
173            table: ExprTable::default(),
174        }
175    }
176
177    fn source_type(&self) -> crate::parsing::source::SourceType {
178        self.source_type.clone()
179    }
180
181    fn peek(&mut self) -> Result<&Token, Error> {
182        self.lexer.peek()
183    }
184
185    fn next(&mut self) -> Result<Token, Error> {
186        let token = self.lexer.next_token()?;
187        self.last_span = token.span;
188        Ok(token)
189    }
190
191    fn at(&mut self, kind: &TokenKind) -> Result<bool, Error> {
192        Ok(&self.peek()?.kind == kind)
193    }
194
195    fn at_any(&mut self, kinds: &[TokenKind]) -> Result<bool, Error> {
196        let current = &self.peek()?.kind;
197        Ok(kinds.contains(current))
198    }
199
200    fn checkpoint(&self) -> ParserCheckpoint {
201        ParserCheckpoint {
202            lexer: self.lexer.checkpoint(),
203            expression_count: self.expression_count,
204            table_len: self.table.len(),
205        }
206    }
207
208    /// Rewinds to `checkpoint`, dropping every expression node parsed since.
209    fn restore(&mut self, checkpoint: ParserCheckpoint) {
210        self.lexer.restore(checkpoint.lexer);
211        self.expression_count = checkpoint.expression_count;
212        self.table.truncate(checkpoint.table_len);
213    }
214
215    fn expect(&mut self, kind: &TokenKind) -> Result<Token, Error> {
216        let token = self.next()?;
217        if &token.kind == kind {
218            Ok(token)
219        } else {
220            Err(self.error_at_token(&token, format!("Expected {}, found {}", kind, token.kind)))
221        }
222    }
223
224    fn at_calendar_period_marker(&mut self) -> Result<bool, Error> {
225        let peeked = *self.peek()?;
226        Ok(token_is_calendar_period_marker(&self.source, &peeked))
227    }
228
229    fn expect_calendar_period_marker(&mut self) -> Result<Token, Error> {
230        let token = self.next()?;
231        if token_is_calendar_period_marker(&self.source, &token) {
232            Ok(token)
233        } else {
234            Err(self.error_at_token(&token, "Expected 'calendar' (date-period predicate marker)"))
235        }
236    }
237
238    fn next_calendar_period_marker(&mut self) -> Result<Token, Error> {
239        self.expect_calendar_period_marker()
240    }
241
242    fn error_at_token(&self, token: &Token, message: impl Into<String>) -> Error {
243        Error::parsing(
244            message,
245            Source::new(self.source_type(), token.span),
246            None::<String>,
247        )
248    }
249
250    fn error_at_token_with_suggestion(
251        &self,
252        token: &Token,
253        message: impl Into<String>,
254        suggestion: impl Into<String>,
255    ) -> Error {
256        Error::parsing(
257            message,
258            Source::new(self.source_type(), token.span),
259            Some(suggestion),
260        )
261    }
262
263    fn parse_spec_ref_trailing_effective(&mut self) -> Result<Option<DateTimeValue>, Error> {
264        let mut effective = None;
265        if self.at(&TokenKind::NumberLit)? {
266            let peeked = *self.peek()?;
267            let peeked_text = peeked.text.of(&self.source);
268            if peeked_text.len() == 4 && peeked_text.chars().all(|c| c.is_ascii_digit()) {
269                effective = self.try_parse_effective_from()?;
270            }
271        }
272        Ok(effective)
273    }
274
275    fn make_source(&self, span: Span) -> Source {
276        Source::new(self.source_type(), span)
277    }
278
279    fn span_from(&self, start: &Span) -> Span {
280        // Create a span from start to the current lexer position.
281        // We peek to get the current position.
282        Span {
283            start: start.start,
284            end: start.end.max(start.start),
285            line: start.line,
286            col: start.col,
287        }
288    }
289
290    fn span_covering(&self, start: &Span, end: &Span) -> Span {
291        Span {
292            start: start.start,
293            end: end.end,
294            line: start.line,
295            col: start.col,
296        }
297    }
298
299    // ========================================================================
300    // Top-level: file and spec
301    // ========================================================================
302
303    fn parse_file(&mut self) -> Result<IndexMap<Arc<LemmaRepository>, Vec<LemmaSpec>>, Error> {
304        let mut map: IndexMap<Arc<LemmaRepository>, Vec<LemmaSpec>> = IndexMap::new();
305        let mut current_repo = Arc::new(LemmaRepository::new(None));
306
307        loop {
308            if self.at(&TokenKind::Eof)? {
309                break;
310            }
311
312            if self.at(&TokenKind::Repo)? {
313                let repo_token = self.expect(&TokenKind::Repo)?;
314                let start_line = repo_token.span.line;
315                let (qualifier, _) = self.parse_repository_qualifier()?;
316                crate::limits::check_max_length(
317                    &qualifier.name,
318                    self.max_spec_name_length,
319                    "repository name",
320                    Some(Source::new(self.source_type(), repo_token.span)),
321                )?;
322                current_repo = Arc::new(
323                    LemmaRepository::new(Some(qualifier.name)).with_start_line(start_line),
324                );
325                map.entry(Arc::clone(&current_repo)).or_default();
326                continue;
327            }
328
329            if self.at(&TokenKind::Spec)? {
330                let spec = self.parse_spec()?;
331                map.entry(Arc::clone(&current_repo)).or_default().push(spec);
332                continue;
333            }
334
335            let token = self.next()?;
336            return Err(self.error_at_token_with_suggestion(
337                &token,
338                format!(
339                    "Expected a top-level `repo` or `spec` declaration, found {}",
340                    token.kind
341                ),
342                "Each Lemma file is a sequence of optional `repo <name>` sections followed by `spec <name>` blocks",
343            ));
344        }
345
346        Ok(map)
347    }
348
349    fn parse_spec(&mut self) -> Result<LemmaSpec, Error> {
350        let spec_token = self.expect(&TokenKind::Spec)?;
351        let start_line = spec_token.span.line;
352
353        let (name, name_span) = self.parse_spec_name()?;
354        self.reject_dotted_name("spec", &name, name_span)?;
355        crate::limits::check_max_length(
356            &name,
357            self.max_spec_name_length,
358            "spec",
359            Some(Source::new(self.source_type(), name_span)),
360        )?;
361
362        let effective_from = self.try_parse_effective_from()?;
363
364        let commentary = self.try_parse_commentary()?;
365
366        let mut spec = LemmaSpec::new(name.clone())
367            .with_source_type(self.source_type())
368            .with_start_line(start_line);
369        spec.effective_from = crate::parsing::ast::EffectiveDate::from_option(effective_from);
370
371        if let Some(commentary_text) = commentary {
372            spec = spec.set_commentary(commentary_text);
373        }
374
375        // First pass: collect type definitions
376        // We need to peek and handle type definitions first, but since we consume tokens
377        // linearly, we'll collect all items in one pass.
378        let mut data = Vec::new();
379        let mut rules = Vec::new();
380        let mut meta_fields = Vec::new();
381
382        loop {
383            let peek_kind = self.peek()?.kind;
384            match peek_kind {
385                TokenKind::Data => {
386                    let datum = self.parse_data()?;
387                    data.push(datum);
388                }
389                TokenKind::Rule => {
390                    let rule = self.parse_rule()?;
391                    rules.push(rule);
392                }
393                TokenKind::Meta => {
394                    let meta = self.parse_meta()?;
395                    meta_fields.push(meta);
396                }
397                TokenKind::Uses => {
398                    let uses_data = self.parse_uses_statement()?;
399                    data.push(uses_data);
400                }
401                TokenKind::Spec | TokenKind::Repo | TokenKind::Eof => break,
402                TokenKind::With => {
403                    let token = self.next()?;
404                    return Err(self.error_at_token_with_suggestion(
405                        &token,
406                        "Standalone `with alias.field: value` is not allowed".to_string(),
407                        "Use `uses alias: spec -> with field: value`",
408                    ));
409                }
410                _ => {
411                    let token = self.next()?;
412                    return Err(self.error_at_token_with_suggestion(
413                        &token,
414                        format!(
415                            "Expected 'data', 'rule', 'meta', 'uses', or a new 'spec', found '{}'",
416                            token.text.of(&self.source)
417                        ),
418                        "Check the spelling or add the appropriate keyword",
419                    ));
420                }
421            }
422        }
423
424        let has_own_list = data.iter().any(|row| {
425            matches!(
426                &row.value,
427                DataValue::Definition {
428                    base: Some(ParentType::List { inner }),
429                    ..
430                } if matches!(
431                    inner.as_ref(),
432                    ParentType::Custom { name: element } if element.eq_ignore_ascii_case(&name)
433                )
434            )
435        });
436        for mut data in data {
437            if has_own_list {
438                data.value = own_rows_value(&name, &data.reference, data.value);
439            }
440            spec = spec.add_data(data);
441        }
442        for rule in rules {
443            spec = spec.add_rule(rule);
444        }
445        for meta in meta_fields {
446            spec = spec.add_meta_field(meta);
447        }
448
449        Ok(spec)
450    }
451
452    fn next_logical_name(&mut self) -> Result<Token, Error> {
453        let token = self.lexer.next_logical_name()?;
454        self.last_span = token.span;
455        Ok(token)
456    }
457
458    fn parse_spec_name(&mut self) -> Result<(String, Span), Error> {
459        let tok = self.next_logical_name()?;
460        if tok.text.of(&self.source).starts_with('@') {
461            return Err(Error::parsing(
462                "'@' is not allowed in spec names; it is valid for repository names (`repo @org/name`) and qualifiers (`uses @org/name`)",
463                self.make_source(tok.span),
464                Some(
465                    "Write `spec my_spec`, then reference registry specs as `uses alias: @org/repo spec_name` or `data x: alias.TypeName` after importing with `uses`.",
466                ),
467            ));
468        }
469        if !can_be_spec_name_spelling(tok.text.of(&self.source)) {
470            return Err(self.error_at_token(
471                &tok,
472                format!(
473                    "Expected a spec name, found '{}'",
474                    tok.text.of(&self.source)
475                ),
476            ));
477        }
478        Ok((tok.text.of(&self.source).to_string(), tok.span))
479    }
480
481    /// A spec or repository name has no `.`: `.` separates path segments (`alias.Type`,
482    /// `global.x.field`, `<repo> global.x.field`), so a dotted name would make those paths
483    /// ambiguous. `kind` is `spec` or `repository`.
484    fn reject_dotted_name(&self, kind: &str, name: &str, span: Span) -> Result<(), Error> {
485        if !name.contains('.') {
486            return Ok(());
487        }
488        Err(Error::parsing(
489            format!("'.' is not allowed in {kind} names: '{name}'"),
490            self.make_source(span),
491            Some(format!(
492                "Separate the parts with '/' or '_' instead: `{}`",
493                name.replace('.', "/")
494            )),
495        ))
496    }
497
498    /// Parse a repository qualifier as one opaque [`TokenKind::LogicalName`].
499    fn parse_repository_qualifier(&mut self) -> Result<(RepositoryQualifier, Span), Error> {
500        let tok = self.next_logical_name()?;
501        if !tok.text.of(&self.source).starts_with('@')
502            && is_reserved_repository_name(tok.text.of(&self.source))
503        {
504            return Err(self.error_at_token(
505                &tok,
506                format!(
507                    "'{}' is a reserved keyword and cannot be used as a repository name",
508                    tok.text.of(&self.source).to_ascii_lowercase()
509                ),
510            ));
511        }
512        self.reject_dotted_name("repository", tok.text.of(&self.source), tok.span)?;
513        Ok((
514            RepositoryQualifier {
515                name: tok.text.of(&self.source).to_string(),
516            },
517            tok.span,
518        ))
519    }
520
521    /// Parses `[<repository_qualifier>] <spec> [<effective>]`
522    pub fn parse_spec_ref_target(&mut self) -> Result<SpecRef, Error> {
523        let first = self.next_logical_name()?;
524        let mut repository = None;
525        let mut repository_span = None;
526        let (spec_name, spec_name_span) = if first.text.of(&self.source).starts_with('@') {
527            self.reject_dotted_name("repository", first.text.of(&self.source), first.span)?;
528            repository = Some(RepositoryQualifier {
529                name: first.text.of(&self.source).to_string(),
530            });
531            repository_span = Some(first.span);
532            self.parse_spec_name()?
533        } else if can_be_label(&self.peek()?.kind) {
534            if is_reserved_repository_name(first.text.of(&self.source)) {
535                return Err(self.error_at_token(
536                    &first,
537                    format!(
538                        "'{}' is a reserved keyword and cannot be used as a repository name",
539                        first.text.of(&self.source).to_ascii_lowercase()
540                    ),
541                ));
542            }
543            self.reject_dotted_name("repository", first.text.of(&self.source), first.span)?;
544            repository = Some(RepositoryQualifier {
545                name: first.text.of(&self.source).to_string(),
546            });
547            repository_span = Some(first.span);
548            self.parse_spec_name()?
549        } else {
550            (first.text.of(&self.source).to_string(), first.span)
551        };
552        self.reject_dotted_name("spec", &spec_name, spec_name_span)?;
553        let effective = self.parse_spec_ref_trailing_effective()?;
554        let target_span = self.span_covering(&spec_name_span, &self.last_span);
555
556        let has_repository = repository.is_some();
557        Ok(SpecRef {
558            name: spec_name,
559            repository,
560            effective,
561            repository_span: if has_repository {
562                repository_span
563            } else {
564                None
565            },
566            target_span: Some(target_span),
567        })
568    }
569
570    fn try_parse_effective_from(&mut self) -> Result<Option<DateTimeValue>, Error> {
571        // effective_from is a date/time token right after the spec name.
572        // It's tricky because it looks like a number (e.g. 2026-03-04).
573        // In the old grammar it was a special atomic rule.
574        // We'll check if the next token is a NumberLit that looks like a year.
575        if !self.at(&TokenKind::NumberLit)? {
576            return Ok(None);
577        }
578
579        let peeked = *self.peek()?;
580        let peeked_text = peeked.text.of(&self.source).to_string();
581        let peeked_span = peeked.span;
582
583        // Check if it could be a date: 4-digit number followed by -
584        if peeked_text.len() == 4 && peeked_text.chars().all(|c| c.is_ascii_digit()) {
585            // Collect the full datetime string by consuming tokens
586            let mut dt_str = String::new();
587            let num_tok = self.next()?; // consume the year number
588            dt_str.push_str(num_tok.text.of(&self.source));
589
590            // Try to consume -MM-DD and optional T... parts
591            while self.at(&TokenKind::Minus)? {
592                self.next()?; // consume -
593                dt_str.push('-');
594                let part = self.next()?;
595                dt_str.push_str(part.text.of(&self.source));
596            }
597
598            // Check for T (time part)
599            if self.at(&TokenKind::Identifier)? {
600                let peeked = *self.peek()?;
601                let time_marker = peeked.text.of(&self.source).starts_with(['T', 't']);
602                if time_marker {
603                    let time_part = self.next()?;
604                    dt_str.push_str(time_part.text.of(&self.source));
605                    // Consume any : separated parts
606                    while self.at(&TokenKind::Colon)? {
607                        self.next()?;
608                        dt_str.push(':');
609                        let part = self.next()?;
610                        dt_str.push_str(part.text.of(&self.source));
611                    }
612                    // Check for timezone (+ or Z)
613                    if self.at(&TokenKind::Plus)? {
614                        self.next()?;
615                        dt_str.push('+');
616                        let tz_part = self.next()?;
617                        dt_str.push_str(tz_part.text.of(&self.source));
618                        if self.at(&TokenKind::Colon)? {
619                            self.next()?;
620                            dt_str.push(':');
621                            let tz_min = self.next()?;
622                            dt_str.push_str(tz_min.text.of(&self.source));
623                        }
624                    }
625                }
626            }
627
628            // Try to parse as datetime
629            if let Ok(dtv) = dt_str.parse::<DateTimeValue>() {
630                return Ok(Some(dtv));
631            }
632
633            return Err(Error::parsing(
634                format!("Invalid date/time in spec declaration: '{}'", dt_str),
635                self.make_source(peeked_span),
636                None::<String>,
637            ));
638        }
639
640        Ok(None)
641    }
642
643    fn try_parse_commentary(&mut self) -> Result<Option<String>, Error> {
644        if !self.at(&TokenKind::Commentary)? {
645            return Ok(None);
646        }
647        let token = self.next()?;
648        let trimmed = token.text.of(&self.source).trim().to_string();
649        if trimmed.is_empty() {
650            Ok(None)
651        } else {
652            Ok(Some(trimmed))
653        }
654    }
655
656    // ========================================================================
657    // Data parsing
658    // ========================================================================
659
660    fn parse_data(&mut self) -> Result<LemmaData, Error> {
661        let data_token = self.expect(&TokenKind::Data)?;
662        let start_span = data_token.span;
663
664        let reference = self.parse_reference()?;
665        for segment in reference
666            .segments
667            .iter()
668            .chain(std::iter::once(&reference.name))
669        {
670            crate::limits::check_max_length(
671                segment,
672                self.max_data_name_length,
673                "data",
674                Some(Source::new(self.source_type(), start_span)),
675            )?;
676        }
677
678        self.expect(&TokenKind::Colon)?;
679
680        if !reference.segments.is_empty() {
681            let tok = *self.peek()?;
682            return Err(self.error_at_token_with_suggestion(
683                &tok,
684                "Dotted paths require `uses` with `-> with`; `data` declares types and values on local names only.",
685                "Use `uses alias: spec` with `  -> with path.to.slot: <value or reference>`.",
686            ));
687        }
688
689        let value = self.parse_data_value(&reference.name)?;
690
691        let span = self.span_covering(&start_span, &self.last_span);
692        let source = self.make_source(span);
693
694        Ok(LemmaData::new(reference, value, source))
695    }
696
697    fn with_rhs_starts_as_literal(kind: &TokenKind) -> bool {
698        matches!(
699            kind,
700            TokenKind::StringLit | TokenKind::NumberLit | TokenKind::Minus | TokenKind::Plus
701        ) || is_boolean_keyword(kind)
702    }
703
704    fn parse_with_rhs(&mut self) -> Result<WithRhs, Error> {
705        let peek_kind = self.peek()?.kind;
706
707        if Self::with_rhs_starts_as_literal(&peek_kind) {
708            let value = self.parse_literal_value()?;
709            return Ok(WithRhs::Literal(value));
710        }
711
712        if can_be_label(&peek_kind) {
713            let target = self.parse_reference()?;
714            if self.at(&TokenKind::Arrow)? && self.lexer.peek_second()?.kind != TokenKind::With {
715                let tok = *self.peek()?;
716                return Err(self.error_at_token_with_suggestion(
717                    &tok,
718                    "Constraint chains (`-> ...`) are not allowed on a `uses` binding reference.",
719                    "Use `data name: <type> -> ...` for type constraints on local slots.",
720                ));
721            }
722            return Ok(WithRhs::Reference { target });
723        }
724
725        let tok = *self.peek()?;
726        Err(self.error_at_token(
727            &tok,
728            format!(
729                "Expected a reference or literal after `-> with ...:`, found {}",
730                tok.kind
731            ),
732        ))
733    }
734
735    fn parse_reference(&mut self) -> Result<Reference, Error> {
736        self.parse_path(false)
737    }
738
739    /// A dotted path of names. With `row_numbers`, a segment after a name may also be
740    /// the number of a list row (`stappen.2.bedrag`).
741    fn parse_path(&mut self, row_numbers: bool) -> Result<Reference, Error> {
742        let mut segments = Vec::new();
743
744        let first = self.next()?;
745        // Keywords cannot be used as names
746        if is_keyword(&first.kind) {
747            return Err(self.error_at_token_with_suggestion(
748                &first,
749                format!(
750                    "'{}' is a reserved keyword and cannot be used as a name",
751                    first.text.of(&self.source).to_ascii_lowercase()
752                ),
753                "Choose a different name that is not a reserved keyword",
754            ));
755        }
756
757        if !can_be_label(&first.kind) {
758            return Err(self.error_at_token(
759                &first,
760                format!("Expected an identifier, found {}", first.kind),
761            ));
762        }
763
764        segments.push(first.text.of(&self.source).to_string());
765
766        // Consume . separated segments
767        while self.at(&TokenKind::Dot)? {
768            self.next()?; // consume .
769            let seg = self.next()?;
770            let is_row_number = row_numbers && self.is_row_number(&seg);
771            if !can_be_label(&seg.kind) && !is_row_number {
772                return Err(self.error_at_token(
773                    &seg,
774                    format!("Expected an identifier after '.', found {}", seg.kind),
775                ));
776            }
777            segments.push(seg.text.of(&self.source).to_string());
778        }
779
780        Ok(Reference::from_path(segments))
781    }
782
783    fn parse_data_value(&mut self, data_name: &str) -> Result<DataValue, Error> {
784        if self.at(&TokenKind::Spec)? {
785            let token = self.next()?;
786            return Err(self.error_at_token_with_suggestion(
787                &token,
788                "Cannot import a spec with `data`; use `uses`",
789                "Use `uses <spec_name>` or `uses <alias>: <spec_name>`",
790            ));
791        }
792
793        let peek = *self.peek()?;
794        let starts_parent_type = token_kind_to_primitive(&peek.kind).is_some()
795            || can_be_label(&peek.kind)
796            || (peek.kind == TokenKind::LogicalName && peek.text.of(&self.source).starts_with('@'));
797
798        if starts_parent_type {
799            let base = self.parse_parent_type()?;
800            if matches!(base, ParentType::List { .. }) {
801                let (constraints, list) = self.parse_list_suffix(data_name)?;
802                return Ok(DataValue::Definition {
803                    base: Some(base),
804                    constraints,
805                    value: None,
806                    list,
807                });
808            }
809            let constraints = self.parse_trailing_constraints()?;
810            return Ok(DataValue::Definition {
811                base: Some(base),
812                constraints,
813                value: None,
814                list: None,
815            });
816        }
817
818        // Otherwise, it's a literal value
819        let value = self.parse_literal_value()?;
820        Ok(DataValue::Definition {
821            base: None,
822            constraints: None,
823            value: Some(value),
824            list: None,
825        })
826    }
827
828    /// True when the next arrows are instance-list `-> key` or `-> with` field/named-instance rows.
829    fn data_instance_list_body_ahead(&mut self) -> Result<bool, Error> {
830        if !self.at(&TokenKind::Arrow)? {
831            return Ok(false);
832        }
833        match self.lexer.peek_second()?.kind {
834            TokenKind::Key => Ok(true),
835            TokenKind::With => {
836                let checkpoint = self.checkpoint();
837                self.next()?; // ->
838                self.next()?; // with
839                let instance = if self.at_uses_field_pair()? {
840                    true
841                } else {
842                    let kind = self.peek()?.kind;
843                    can_be_label(&kind) && !Self::with_rhs_starts_as_literal(&kind)
844                };
845                self.restore(checkpoint);
846                Ok(instance)
847            }
848            _ => Ok(false),
849        }
850    }
851
852    fn list_query_ahead(&mut self) -> Result<bool, Error> {
853        if !self.at(&TokenKind::Arrow)? {
854            return Ok(false);
855        }
856        Ok(matches!(
857            self.lexer.peek_second()?.kind,
858            TokenKind::Find
859                | TokenKind::First
860                | TokenKind::Last
861                | TokenKind::Sum
862                | TokenKind::Avg
863                | TokenKind::Product
864                | TokenKind::Count
865                | TokenKind::Min
866                | TokenKind::Max
867                | TokenKind::Any
868                | TokenKind::All
869                | TokenKind::Where
870                | TokenKind::Sort
871                | TokenKind::Top
872        ))
873    }
874
875    fn option_field_row_ahead(&mut self) -> Result<bool, Error> {
876        if !self.at(&TokenKind::Arrow)? {
877            return Ok(false);
878        }
879        let second = *self.lexer.peek_second()?;
880        if !second.text.of(&self.source).eq_ignore_ascii_case("option") {
881            return Ok(false);
882        }
883        let checkpoint = self.checkpoint();
884        self.next()?;
885        self.next()?;
886        let field = self.at_uses_field_pair()?;
887        self.restore(checkpoint);
888        Ok(field)
889    }
890
891    fn parse_option_field_row(
892        &mut self,
893        alias: &str,
894        list: &mut InstanceListBody,
895    ) -> Result<(), Error> {
896        let arrow = self.next()?;
897        let name_tok = self.next()?;
898        let bindings = self.parse_row_field_pairs(alias, &name_tok)?;
899        let span = self.span_covering(&arrow.span, &self.last_span);
900        list.option_rows.push(InstanceListRow::Fields {
901            bindings,
902            source_location: self.make_source(span),
903        });
904        Ok(())
905    }
906
907    /// Parse a single `uses` item after `uses` and an optional `global`: `[alias ':']` then
908    /// [`Self::parse_spec_ref_target`] (optional repository qualifier, spec name, optional
909    /// effective date pin).
910    fn parse_uses_item(&mut self, start_span: &Span, global: bool) -> Result<LemmaData, Error> {
911        let explicit_alias = if self.lexer.peek_second()?.kind == TokenKind::Colon {
912            let peek = *self.peek()?;
913            if is_keyword(&peek.kind) {
914                return Err(self.error_at_token_with_suggestion(
915                    &peek,
916                    format!(
917                        "'{}' is a reserved keyword and cannot be used as a name",
918                        peek.text.of(&self.source).to_ascii_lowercase()
919                    ),
920                    "Choose a different name that is not a reserved keyword",
921                ));
922            }
923            if can_be_label(&peek.kind) {
924                let alias_tok = self.next()?;
925                self.expect(&TokenKind::Colon)?;
926                Some(alias_tok)
927            } else {
928                None
929            }
930        } else {
931            None
932        };
933
934        let spec_ref = self.parse_spec_ref_target()?;
935
936        let spec_name_source = spec_ref
937            .target_span
938            .as_ref()
939            .map(|sp| Source::new(self.source_type(), *sp));
940
941        crate::limits::check_max_length(
942            &spec_ref.name,
943            self.max_spec_name_length,
944            "spec",
945            spec_name_source.clone(),
946        )?;
947
948        let alias = if let Some(ref alias_tok) = explicit_alias {
949            crate::limits::check_max_length(
950                alias_tok.text.of(&self.source),
951                self.max_data_name_length,
952                "data",
953                Some(Source::new(self.source_type(), alias_tok.span)),
954            )?;
955            alias_tok.text.of(&self.source).to_string()
956        } else {
957            let implicit = spec_ref.name.clone();
958            crate::limits::check_max_length(
959                &implicit,
960                self.max_data_name_length,
961                "data",
962                spec_name_source,
963            )?;
964            implicit
965        };
966
967        if self.at(&TokenKind::List)? {
968            let list_tok = *self.peek()?;
969            return Err(self.error_at_token_with_suggestion(
970                &list_tok,
971                format!(
972                    "`uses {alias}: {spec_ref} list` is not valid; `uses` imports one sealed item"
973                ),
974                format!(
975                    "Write `uses {alias}: {spec_ref}` for one item, or `data {alias}: {spec_ref} list` for a caller-owned list, or a list-valued rule for a sealed catalog"
976                ),
977            ));
978        }
979
980        let mut bindings = Vec::new();
981        let mut effective_ref = None;
982        while self.at(&TokenKind::Arrow)? {
983            let command = self.lexer.peek_second()?.kind;
984            match command {
985                TokenKind::With => {
986                    self.next()?; // ->
987                    let with_token = self.expect(&TokenKind::With)?;
988                    bindings.extend(self.parse_uses_field_pairs(&alias, &with_token)?);
989                }
990                TokenKind::Effective => {
991                    self.next()?; // ->
992                    let effective_token = self.expect(&TokenKind::Effective)?;
993                    if effective_ref.is_some() {
994                        return Err(self.error_at_token_with_suggestion(
995                            &effective_token,
996                            "A `uses` block may have at most one `-> effective`.",
997                            "Remove the extra `-> effective` line.",
998                        ));
999                    }
1000                    if spec_ref.effective.is_some() {
1001                        return Err(self.error_at_token_with_suggestion(
1002                            &effective_token,
1003                            "Cannot combine a literal effective pin on the `uses` target with `-> effective`.",
1004                            "Remove the date after the spec name, or remove `-> effective`.",
1005                        ));
1006                    }
1007                    effective_ref = Some(self.parse_reference()?);
1008                }
1009                _ => {
1010                    let tok = *self.peek()?;
1011                    return Err(self.error_at_token_with_suggestion(
1012                        &tok,
1013                        "Expected `with` or `effective` after `->` in a `uses` block.",
1014                        "Write `  -> with path.to.slot: <value or reference>` or `  -> effective <date>` under the `uses` line.",
1015                    ));
1016                }
1017            }
1018        }
1019
1020        let span = self.span_covering(start_span, &self.last_span);
1021        Ok(LemmaData::new(
1022            Reference::local(alias),
1023            DataValue::Import {
1024                spec_ref,
1025                bindings,
1026                effective_ref,
1027                global,
1028            },
1029            self.make_source(span),
1030        ))
1031    }
1032
1033    /// Constraints and instance-list rows under `data name: T list`.
1034    ///
1035    /// `-> key` and instance `-> with` stay on the list body. `-> options`, `-> help`,
1036    /// and a value-list `-> with` stay constraints. A list can carry both.
1037    fn parse_list_suffix(
1038        &mut self,
1039        alias: &str,
1040    ) -> Result<(Option<Vec<Constraint>>, Option<InstanceListBody>), Error> {
1041        let mut commands = Vec::new();
1042        let mut list = InstanceListBody {
1043            key: None,
1044            rows: Vec::new(),
1045            option_rows: Vec::new(),
1046        };
1047        let mut saw_instance = false;
1048        while self.at(&TokenKind::Arrow)? {
1049            if self.option_field_row_ahead()? {
1050                saw_instance = true;
1051                self.parse_option_field_row(alias, &mut list)?;
1052            } else if self.data_instance_list_body_ahead()? {
1053                saw_instance = true;
1054                self.parse_instance_list_command(alias, &mut list)?;
1055            } else if self.list_query_ahead()? {
1056                let arrow = self.next()?;
1057                let name_tok = self.next()?;
1058                let command = self.parse_list_command_body(name_tok)?;
1059                let command = display_list_command(&self.table, &command);
1060                return Err(self.error_at_token(
1061                    &arrow,
1062                    format!(
1063                        "data supplies values; `-> {command}` is a query on `{alias}`, write it in a rule"
1064                    ),
1065                ));
1066            } else {
1067                commands.push(self.parse_one_constraint()?);
1068            }
1069        }
1070        let constraints = if commands.is_empty() {
1071            None
1072        } else {
1073            Some(commands)
1074        };
1075        let list = if saw_instance { Some(list) } else { None };
1076        Ok((constraints, list))
1077    }
1078
1079    /// `-> key`, `-> with` rows under `data name: Spec list`.
1080    fn parse_instance_list_command(
1081        &mut self,
1082        alias: &str,
1083        list: &mut InstanceListBody,
1084    ) -> Result<(), Error> {
1085        let arrow = self.next()?;
1086        let name_tok = self.next()?;
1087        match name_tok.kind {
1088            TokenKind::Key => {
1089                if list.key.is_some() {
1090                    return Err(self.error_at_token(
1091                            &name_tok,
1092                            format!("`{alias}` declares `-> key` twice; list every key field in one `-> key`"),
1093                        ));
1094                }
1095                if !list.rows.is_empty() {
1096                    return Err(self.error_at_token(
1097                        &name_tok,
1098                        format!("`-> key` on `{alias}` must come before the first `-> with`"),
1099                    ));
1100                }
1101                let mut fields = vec![self.parse_reference()?];
1102                while self.at(&TokenKind::Comma)? {
1103                    self.next()?;
1104                    fields.push(self.parse_reference()?);
1105                }
1106                let span = self.span_covering(&arrow.span, &self.last_span);
1107                list.key = Some(InstanceListKey {
1108                    fields,
1109                    source_location: self.make_source(span),
1110                });
1111            }
1112            TokenKind::With => {
1113                let row = if self.at_uses_field_pair()? {
1114                    let bindings = self.parse_row_field_pairs(alias, &name_tok)?;
1115                    let span = self.span_covering(&arrow.span, &self.last_span);
1116                    InstanceListRow::Fields {
1117                        bindings,
1118                        source_location: self.make_source(span),
1119                    }
1120                } else {
1121                    let values = self.parse_instance_list_values()?;
1122                    let span = self.span_covering(&arrow.span, &self.last_span);
1123                    InstanceListRow::Values {
1124                        values,
1125                        source_location: self.make_source(span),
1126                    }
1127                };
1128                list.rows.push(row);
1129            }
1130            other => {
1131                unreachable!("BUG: instance-list command ahead was not key or with, got {other:?}")
1132            }
1133        }
1134        Ok(())
1135    }
1136
1137    /// `-> with ada, grace` under `data name: Spec list`: references to instances (literals are
1138    /// rejected at planning with the row spec's name).
1139    fn parse_instance_list_values(&mut self) -> Result<Vec<WithRhs>, Error> {
1140        let mut values = Vec::new();
1141        loop {
1142            values.push(self.parse_with_rhs()?);
1143            if !self.at(&TokenKind::Comma)? {
1144                break;
1145            }
1146            self.next()?;
1147            if self.at_command_terminator()? || self.at(&TokenKind::Comma)? {
1148                let tok = *self.peek()?;
1149                return Err(self.error_at_token_with_suggestion(
1150                    &tok,
1151                    "Trailing or empty comma in list".to_string(),
1152                    "Remove the extra comma, or add the missing row",
1153                ));
1154            }
1155        }
1156        if self.at_uses_field_pair()? {
1157            let tok = *self.peek()?;
1158            return Err(self.error_at_token_with_suggestion(
1159                &tok,
1160                "A `-> with` line holds either references or field pairs, not both".to_string(),
1161                "Put the field pairs on their own `-> with` line",
1162            ));
1163        }
1164        Ok(values)
1165    }
1166
1167    fn parse_row_field_pairs(
1168        &mut self,
1169        alias: &str,
1170        with_token: &Token,
1171    ) -> Result<Vec<RowBinding>, Error> {
1172        let mut bindings = Vec::new();
1173        let mut binding_start_span = with_token.span;
1174        loop {
1175            let path = self.parse_reference()?;
1176            for segment in path.segments.iter().chain(std::iter::once(&path.name)) {
1177                crate::limits::check_max_length(
1178                    segment,
1179                    self.max_data_name_length,
1180                    "row binding",
1181                    Some(Source::new(self.source_type(), binding_start_span)),
1182                )?;
1183            }
1184            if path
1185                .segments
1186                .first()
1187                .is_some_and(|segment| segment == alias)
1188            {
1189                return Err(self.error_at_token_with_suggestion(
1190                    with_token,
1191                    format!("Row path must be relative, not prefixed with `{alias}`."),
1192                    format!(
1193                        "Use `-> with {}: …` without the `{alias}.` prefix.",
1194                        path.name
1195                    ),
1196                ));
1197            }
1198            let (rhs, _) =
1199                self.parse_assignment_after_key(|parser| parser.parse_with_rhs(), "with", false)?;
1200            let binding_span = self.span_covering(&binding_start_span, &self.last_span);
1201            bindings.push(RowBinding {
1202                path,
1203                rhs,
1204                source_location: self.make_source(binding_span),
1205            });
1206            if self.at(&TokenKind::Comma)? {
1207                self.next()?;
1208                if self.at_command_terminator()? || self.at(&TokenKind::Comma)? {
1209                    let tok = *self.peek()?;
1210                    return Err(self.error_at_token_with_suggestion(
1211                        &tok,
1212                        "Trailing or empty comma in list".to_string(),
1213                        "Remove the extra comma, or add the missing field pair",
1214                    ));
1215                }
1216                if !self.at_uses_field_pair()? {
1217                    let tok = *self.peek()?;
1218                    return Err(self.error_at_token_with_suggestion(
1219                        &tok,
1220                        "Expected a field pair after comma".to_string(),
1221                        "Remove the extra comma, or add `path: value`",
1222                    ));
1223                }
1224                binding_start_span = self.peek()?.span;
1225                continue;
1226            }
1227            if self.at_uses_field_pair()? {
1228                let tok = *self.peek()?;
1229                return Err(self.error_at_token_with_suggestion(
1230                    &tok,
1231                    "Expected a comma between field pairs".to_string(),
1232                    "Separate field pairs with commas",
1233                ));
1234            }
1235            return Ok(bindings);
1236        }
1237    }
1238
1239    /// Comma-separated `path: value` pairs after `-> with` in a `uses` block.
1240    fn parse_uses_field_pairs(
1241        &mut self,
1242        alias: &str,
1243        with_token: &Token,
1244    ) -> Result<Vec<UsesBinding>, Error> {
1245        let mut bindings = Vec::new();
1246        let mut binding_start_span = with_token.span;
1247        loop {
1248            let path = self.parse_path(true)?;
1249            for segment in path.segments.iter().chain(std::iter::once(&path.name)) {
1250                crate::limits::check_max_length(
1251                    segment,
1252                    self.max_data_name_length,
1253                    "uses binding",
1254                    Some(Source::new(self.source_type(), binding_start_span)),
1255                )?;
1256            }
1257            if path
1258                .segments
1259                .first()
1260                .is_some_and(|segment| segment == alias)
1261            {
1262                return Err(self.error_at_token_with_suggestion(
1263                    with_token,
1264                    format!(
1265                        "Binding path must be relative to the imported spec, not prefixed with import alias `{alias}`."
1266                    ),
1267                    format!(
1268                        "Use `-> with {}: …` without the `{alias}.` prefix.",
1269                        path.name
1270                    ),
1271                ));
1272            }
1273
1274            let (first_rhs, _) =
1275                self.parse_assignment_after_key(|parser| parser.parse_with_rhs(), "with", false)?;
1276            let mut next_field_pair = false;
1277            let rhs = match first_rhs {
1278                WithRhs::Literal(value) => UsesBindingRhs::Literal(value),
1279                WithRhs::Reference { target } => {
1280                    let mut targets = vec![target];
1281                    while self.at(&TokenKind::Comma)? {
1282                        self.next()?;
1283                        if self.at_command_terminator()? || self.at(&TokenKind::Comma)? {
1284                            let tok = *self.peek()?;
1285                            return Err(self.error_at_token_with_suggestion(
1286                                &tok,
1287                                "Trailing or empty comma in list".to_string(),
1288                                "Remove the extra comma, or add the missing reference",
1289                            ));
1290                        }
1291                        if self.at_uses_field_pair()? {
1292                            next_field_pair = true;
1293                            break;
1294                        }
1295                        let rhs_token = *self.peek()?;
1296                        match self.parse_with_rhs()? {
1297                            WithRhs::Reference { target } => targets.push(target),
1298                            WithRhs::Literal(_) => {
1299                                return Err(self.error_at_token_with_suggestion(
1300                                    &rhs_token,
1301                                    "A `uses -> with` reference sequence cannot contain literals"
1302                                        .to_string(),
1303                                    "Use only `uses` aliases in the sequence",
1304                                ));
1305                            }
1306                        }
1307                    }
1308                    UsesBindingRhs::References { targets }
1309                }
1310            };
1311
1312            let binding_span = self.span_covering(&binding_start_span, &self.last_span);
1313            bindings.push(UsesBinding {
1314                path,
1315                rhs,
1316                source_location: self.make_source(binding_span),
1317            });
1318
1319            if next_field_pair {
1320                binding_start_span = self.peek()?.span;
1321                continue;
1322            }
1323
1324            if self.at(&TokenKind::Comma)? {
1325                self.next()?;
1326                if self.at_command_terminator()? || self.at(&TokenKind::Comma)? {
1327                    let tok = *self.peek()?;
1328                    return Err(self.error_at_token_with_suggestion(
1329                        &tok,
1330                        "Trailing or empty comma in list".to_string(),
1331                        "Remove the extra comma, or add the missing field pair",
1332                    ));
1333                }
1334                if !self.at_uses_field_pair()? {
1335                    let tok = *self.peek()?;
1336                    return Err(self.error_at_token_with_suggestion(
1337                        &tok,
1338                        "Expected a field pair after comma".to_string(),
1339                        "Remove the extra comma, or add `path: value`",
1340                    ));
1341                }
1342                binding_start_span = self.peek()?.span;
1343                continue;
1344            }
1345
1346            if self.at_uses_field_pair()? {
1347                let tok = *self.peek()?;
1348                return Err(self.error_at_token_with_suggestion(
1349                    &tok,
1350                    "Expected a comma between field pairs".to_string(),
1351                    "Separate field pairs with commas, for example `-> with qty: 3, sku: \"latte\"`",
1352                ));
1353            }
1354            return Ok(bindings);
1355        }
1356    }
1357
1358    fn at_uses_field_pair(&mut self) -> Result<bool, Error> {
1359        if self.at_command_terminator()? {
1360            return Ok(false);
1361        }
1362        self.at_path_then_colon_with(true)
1363    }
1364
1365    /// Whether `token` is digits only, as a list row is numbered in a path.
1366    fn is_row_number(&self, token: &Token) -> bool {
1367        token.kind == TokenKind::NumberLit
1368            && token
1369                .text
1370                .of(&self.source)
1371                .chars()
1372                .all(|ch| ch.is_ascii_digit())
1373    }
1374
1375    /// True when the next tokens are `label (. label)* :`, the start of a field pair.
1376    /// Does not consume input.
1377    fn at_path_then_colon(&mut self) -> Result<bool, Error> {
1378        self.at_path_then_colon_with(false)
1379    }
1380
1381    /// [`Self::at_path_then_colon`]; with `row_numbers`, of a path as
1382    /// [`Self::parse_path`] reads it.
1383    fn at_path_then_colon_with(&mut self, row_numbers: bool) -> Result<bool, Error> {
1384        if !can_be_label(&self.peek()?.kind) {
1385            return Ok(false);
1386        }
1387        let checkpoint = self.checkpoint();
1388        let result = self.scan_path_then_colon(row_numbers);
1389        self.restore(checkpoint);
1390        result
1391    }
1392
1393    fn scan_path_then_colon(&mut self, row_numbers: bool) -> Result<bool, Error> {
1394        self.next()?;
1395        loop {
1396            match self.peek()?.kind {
1397                TokenKind::Colon => return Ok(true),
1398                TokenKind::Dot => {
1399                    self.next()?;
1400                    let segment = *self.peek()?;
1401                    if !(can_be_label(&segment.kind) || row_numbers && self.is_row_number(&segment))
1402                    {
1403                        return Ok(false);
1404                    }
1405                    self.next()?;
1406                }
1407                _ => return Ok(false),
1408            }
1409        }
1410    }
1411
1412    fn parse_uses_statement(&mut self) -> Result<LemmaData, Error> {
1413        let uses_token = self.expect(&TokenKind::Uses)?;
1414        let start_span = uses_token.span;
1415        let global = if self.at(&TokenKind::Global)? {
1416            let global_token = self.next()?;
1417            if self.at(&TokenKind::Colon)? {
1418                return Err(self.error_at_token_with_suggestion(
1419                    &global_token,
1420                    "'global' is a reserved keyword and cannot be used as a name",
1421                    "Choose a different name that is not a reserved keyword",
1422                ));
1423            }
1424            true
1425        } else {
1426            false
1427        };
1428        self.parse_uses_item(&start_span, global)
1429    }
1430
1431    // ========================================================================
1432    // Rule parsing
1433    // ========================================================================
1434
1435    fn parse_rule(&mut self) -> Result<LemmaRule, Error> {
1436        let rule_token = self.expect(&TokenKind::Rule)?;
1437        let start_span = rule_token.span;
1438
1439        let name_tok = self.next()?;
1440        if is_keyword(&name_tok.kind) {
1441            return Err(self.error_at_token_with_suggestion(
1442                &name_tok,
1443                format!(
1444                    "'{}' is a reserved keyword and cannot be used as a rule name",
1445                    name_tok.text.of(&self.source).to_ascii_lowercase()
1446                ),
1447                "Choose a different name that is not a reserved keyword",
1448            ));
1449        }
1450        if !can_be_label(&name_tok.kind) {
1451            return Err(self.error_at_token(
1452                &name_tok,
1453                format!("Expected a rule name, found {}", name_tok.kind),
1454            ));
1455        }
1456        let rule_name = name_tok.text.of(&self.source).to_string();
1457        crate::limits::check_max_length(
1458            &rule_name,
1459            self.max_rule_name_length,
1460            "rule",
1461            Some(Source::new(self.source_type(), name_tok.span)),
1462        )?;
1463
1464        self.expect(&TokenKind::Colon)?;
1465
1466        // Parse the base expression or veto result (`veto "msg"`). `veto is …` is an expression.
1467        let root = if self.at(&TokenKind::Veto)? && !self.at_bare_veto_followed_by_is()? {
1468            self.parse_veto_expression()?
1469        } else {
1470            self.parse_expression()?
1471        };
1472
1473        let expression = self.finish_expression(root);
1474
1475        // Parse unless clauses
1476        let mut unless_clauses = Vec::new();
1477        while self.at(&TokenKind::Unless)? {
1478            unless_clauses.push(self.parse_unless_clause()?);
1479        }
1480
1481        let end_span = if let Some(last_unless) = unless_clauses.last() {
1482            last_unless.source_location.span
1483        } else if let Some(loc) = expression.root_source() {
1484            loc.span
1485        } else {
1486            start_span
1487        };
1488
1489        let span = self.span_covering(&start_span, &end_span);
1490        Ok(LemmaRule {
1491            name: rule_name,
1492            expression,
1493            unless_clauses,
1494            source_location: self.make_source(span),
1495        })
1496    }
1497
1498    fn parse_veto_expression(&mut self) -> Result<ExprId, Error> {
1499        let veto_tok = self.expect(&TokenKind::Veto)?;
1500        let start_span = veto_tok.span;
1501
1502        let message = if self.at(&TokenKind::StringLit)? {
1503            let str_tok = self.next()?;
1504            Some(str_tok.text.of(&self.source).to_string())
1505        } else {
1506            None
1507        };
1508
1509        let span = self.span_from(&start_span);
1510        self.new_expression(
1511            ExpressionKind::Veto(VetoExpression { message }),
1512            self.make_source(span),
1513        )
1514    }
1515
1516    fn parse_unless_clause(&mut self) -> Result<UnlessClause, Error> {
1517        let unless_tok = self.expect(&TokenKind::Unless)?;
1518        let start_span = unless_tok.span;
1519
1520        let condition_root = self.parse_expression()?;
1521        let condition = self.finish_expression(condition_root);
1522
1523        self.expect(&TokenKind::Then)?;
1524
1525        let result_root = if self.at(&TokenKind::Veto)? {
1526            self.parse_veto_expression()?
1527        } else {
1528            self.parse_expression()?
1529        };
1530
1531        let end_span = self.expr_span(result_root).unwrap_or(start_span);
1532        let span = self.span_covering(&start_span, &end_span);
1533        let result = self.finish_expression(result_root);
1534
1535        Ok(UnlessClause {
1536            condition,
1537            result,
1538            source_location: self.make_source(span),
1539        })
1540    }
1541
1542    /// Parse a parent type, including optional `range` / `list` suffixes.
1543    ///
1544    /// List and type parents are bare names. Pin and `@repo` belong on `uses`.
1545    fn parse_parent_type(&mut self) -> Result<ParentType, Error> {
1546        let peek = *self.peek()?;
1547        let base = if let Some(primitive) = token_kind_to_primitive(&peek.kind) {
1548            self.next()?;
1549            if self.at(&TokenKind::Dot)? {
1550                let dot_tok = *self.peek()?;
1551                return Err(self.error_at_token_with_suggestion(
1552                    &dot_tok,
1553                    "A primitive type cannot be the left segment of a qualified parent path",
1554                    "Use `data name: alias.typename` where `alias` is the `uses` import name and `typename` is the parent type.",
1555                ));
1556            }
1557            ParentType::Primitive { primitive }
1558        } else {
1559            self.parse_custom_or_spec_element_parent()?
1560        };
1561
1562        let base = if self.at(&TokenKind::Identifier)? && {
1563            let peeked = *self.peek()?;
1564            peeked.text.of(&self.source) == "range"
1565        } {
1566            self.next()?;
1567            ParentType::Ranged {
1568                inner: Box::new(base),
1569            }
1570        } else {
1571            base
1572        };
1573
1574        if self.at(&TokenKind::List)? {
1575            self.next()?;
1576            Ok(ParentType::List {
1577                inner: Box::new(base),
1578            })
1579        } else {
1580            Ok(base)
1581        }
1582    }
1583
1584    /// Custom or qualified type name. `@repo` and a trailing pin are parse Errors.
1585    fn parse_custom_or_spec_element_parent(&mut self) -> Result<ParentType, Error> {
1586        let peek = *self.peek()?;
1587        if peek.text.of(&self.source).starts_with('@') {
1588            return Err(self.error_at_token_with_suggestion(
1589                &peek,
1590                "A repository qualifier is not valid on a type or list element",
1591                "Write `uses @repo Spec [pin]`, then `data name: Spec list` or `rule name: Spec list`.",
1592            ));
1593        }
1594        let (name, span) = self.parse_spec_name()?;
1595        if name.split('.').any(str::is_empty) {
1596            return Err(Error::parsing(
1597                format!("Expected a name on both sides of '.', found '{name}'"),
1598                self.make_source(span),
1599                Some("Write `alias.typename`, where `alias` is the `uses` import name."),
1600            ));
1601        }
1602        if let Some((alias, type_name)) = name.rsplit_once('.') {
1603            return Ok(ParentType::Qualified {
1604                spec_alias: alias.to_string(),
1605                inner: Box::new(ParentType::custom(type_name.to_string())),
1606            });
1607        }
1608        if self.at(&TokenKind::NumberLit)? {
1609            let year = *self.peek()?;
1610            if year.text.of(&self.source).len() == 4
1611                && year
1612                    .text
1613                    .of(&self.source)
1614                    .chars()
1615                    .all(|c| c.is_ascii_digit())
1616            {
1617                return Err(self.error_at_token_with_suggestion(
1618                    &year,
1619                    "An effective pin is not valid on a type or list element",
1620                    "Write `uses Spec <pin>`, then `data name: Spec list` or `rule name: Spec list`.",
1621                ));
1622            }
1623        }
1624        Ok(ParentType::custom(name))
1625    }
1626
1627    fn parse_trailing_constraints(&mut self) -> Result<Option<Vec<Constraint>>, Error> {
1628        let mut commands = Vec::new();
1629        while self.at(&TokenKind::Arrow)? {
1630            commands.push(self.parse_one_constraint()?);
1631        }
1632        let constraints = if commands.is_empty() {
1633            None
1634        } else {
1635            Some(commands)
1636        };
1637        Ok(constraints)
1638    }
1639
1640    fn parse_one_constraint(&mut self) -> Result<Constraint, Error> {
1641        let arrow_token = self.next()?;
1642        let constraint_start_span = arrow_token.span;
1643        let (cmd, cmd_args, deprecated_without_colon) = self.parse_constraint_command()?;
1644        let constraint_span = self.span_covering(&constraint_start_span, &self.last_span);
1645        Ok(Constraint {
1646            command: cmd,
1647            args: cmd_args,
1648            source_location: self.make_source(constraint_span),
1649            deprecated_without_colon,
1650        })
1651    }
1652
1653    fn parse_constraint_command(
1654        &mut self,
1655    ) -> Result<(TypeConstraintCommand, Vec<CommandArg>, bool), Error> {
1656        let name_tok = self.next()?;
1657        if matches!(name_tok.kind, TokenKind::Key) {
1658            return Err(self.error_at_token(
1659                &name_tok,
1660                "value lists are numbered; `-> key` is for instance lists".to_string(),
1661            ));
1662        }
1663        if matches!(
1664            name_tok.kind,
1665            TokenKind::Find
1666                | TokenKind::First
1667                | TokenKind::Last
1668                | TokenKind::Sum
1669                | TokenKind::Avg
1670                | TokenKind::Product
1671                | TokenKind::Count
1672                | TokenKind::Min
1673                | TokenKind::Max
1674                | TokenKind::Any
1675                | TokenKind::All
1676                | TokenKind::Where
1677                | TokenKind::Sort
1678                | TokenKind::Top
1679        ) {
1680            return Err(self.error_at_token(
1681                &name_tok,
1682                "data supplies values; query commands belong on rules, not data declarations"
1683                    .to_string(),
1684            ));
1685        }
1686        if !can_be_label(&name_tok.kind)
1687            && !matches!(
1688                name_tok.kind,
1689                TokenKind::Lower | TokenKind::Upper | TokenKind::With
1690            )
1691        {
1692            return Err(self.error_at_token(
1693                &name_tok,
1694                format!("Expected a command name, found {}", name_tok.kind),
1695            ));
1696        }
1697        let cmd = try_parse_type_constraint_command(name_tok.text.of(&self.source)).ok_or_else(|| {
1698            self.error_at_token(
1699                &name_tok,
1700                format!(
1701                    "Unknown constraint command '{}'. Valid commands: help, suggest, with, unit, trait, minimum, maximum, lower, upper, decimals, option, options, length",
1702                    name_tok.text.of(&self.source)
1703                ),
1704            )
1705        })?;
1706
1707        match cmd.continuation_shape() {
1708            ContinuationShape::Assignment => {
1709                let (args, deprecated_without_colon) = self.parse_unit_as_assignment()?;
1710                Ok((cmd, args, deprecated_without_colon))
1711            }
1712            ContinuationShape::Single => Ok((cmd, self.parse_single_command_arg(cmd)?, false)),
1713            ContinuationShape::CommaSeparated => {
1714                Ok((cmd, self.parse_comma_separated_command_args()?, false))
1715            }
1716        }
1717    }
1718
1719    /// Shared spine for assignment continuations (`with`, `unit`): `key: value` or deprecated space.
1720    fn parse_assignment_after_key<T>(
1721        &mut self,
1722        parse_value: impl FnOnce(&mut Self) -> Result<T, Error>,
1723        assignment_context: &str,
1724        allow_deprecated_without_colon: bool,
1725    ) -> Result<(T, bool), Error> {
1726        if self.at(&TokenKind::Colon)? {
1727            self.next()?;
1728            let value = parse_value(self)?;
1729            return Ok((value, false));
1730        }
1731        if allow_deprecated_without_colon {
1732            let value = parse_value(self)?;
1733            return Ok((value, true));
1734        }
1735        let tok = *self.peek()?;
1736        Err(self.error_at_token_with_suggestion(
1737            &tok,
1738            format!("Expected `:` after `{assignment_context}` key."),
1739            format!("Use `-> {assignment_context} <key>: <value>`."),
1740        ))
1741    }
1742
1743    fn parse_unit_as_assignment(&mut self) -> Result<(Vec<CommandArg>, bool), Error> {
1744        if self.at_command_terminator()? {
1745            return Ok((Vec::new(), false));
1746        }
1747
1748        let peek_kind = self.peek()?.kind;
1749        if is_keyword(&peek_kind) {
1750            let tok = *self.peek()?;
1751            return Err(self.error_at_token_with_suggestion(
1752                &tok,
1753                format!(
1754                    "'{}' is a reserved keyword and cannot be used as a unit name",
1755                    tok.text.of(&self.source).to_ascii_lowercase()
1756                ),
1757                "Choose a different name that is not a reserved keyword",
1758            ));
1759        }
1760        if !can_be_label(&peek_kind) {
1761            return Ok((Vec::new(), false));
1762        }
1763
1764        let unit_name_tok = self.next()?;
1765        let unit_name_arg = CommandArg::Label(unit_name_tok.text.of(&self.source).to_string());
1766
1767        let (unit_arg, deprecated_without_colon) =
1768            self.parse_assignment_after_key(|parser| parser.parse_unit_payload(), "unit", true)?;
1769
1770        Ok((
1771            vec![unit_name_arg, CommandArg::UnitExpr(unit_arg)],
1772            deprecated_without_colon,
1773        ))
1774    }
1775
1776    /// Value side of `-> unit <name>: <payload>` (factor, compound, or prefix + compound).
1777    fn parse_unit_payload(&mut self) -> Result<UnitArg, Error> {
1778        if self.at_command_terminator()? {
1779            let tok = *self.peek()?;
1780            return Err(self.error_at_token_with_suggestion(
1781                &tok,
1782                "Expected a unit conversion factor or compound unit expression after `:`.",
1783                "Use `-> unit <name>: <factor>` or `-> unit <name>: <compound>` (e.g. `unit eur: 1.00`, `unit eur_per_hour: eur/hour`).",
1784            ));
1785        }
1786
1787        let numeric_prefix: Option<Decimal> = if self.at(&TokenKind::NumberLit)? {
1788            let num_tok = self.next()?;
1789            Some(parse_decimal_string(
1790                num_tok.text.of(&self.source),
1791                &num_tok.span,
1792                self,
1793            )?)
1794        } else {
1795            None
1796        };
1797
1798        let peek_kind_after_prefix = self.peek()?.kind;
1799        let has_compound_expr =
1800            can_be_unit_name(&peek_kind_after_prefix) && !self.at_command_terminator()?;
1801
1802        if has_compound_expr {
1803            // When no numeric prefix leads, a bare or dotted identifier is a dynamic
1804            // scale reference (`-> unit gbp: rate`, `-> unit gbp: fx.rate`) unless a
1805            // compound operator (`*`, `/`, `^`) follows, in which case it is the
1806            // first factor of a compound unit expression (`-> unit mps: meter/second`).
1807            match numeric_prefix {
1808                None => {
1809                    let checkpoint = self.checkpoint();
1810                    let reference = self.parse_reference()?;
1811                    let next_kind = self.peek()?.kind;
1812                    if matches!(
1813                        next_kind,
1814                        TokenKind::Star | TokenKind::Slash | TokenKind::Caret
1815                    ) {
1816                        self.restore(checkpoint);
1817                        let factors = self.parse_unit_factors()?;
1818                        let prefix = Decimal::ONE;
1819                        Ok(UnitArg::Expr(prefix, factors))
1820                    } else {
1821                        Ok(UnitArg::Reference(reference))
1822                    }
1823                }
1824                Some(prefix) => {
1825                    let factors = self.parse_unit_factors()?;
1826                    Ok(UnitArg::Expr(prefix, factors))
1827                }
1828            }
1829        } else if let Some(factor) = numeric_prefix {
1830            Ok(UnitArg::Factor(factor))
1831        } else {
1832            let tok = *self.peek()?;
1833            Err(self.error_at_token_with_suggestion(
1834                &tok,
1835                "Expected a unit conversion factor or compound unit expression after `:`.",
1836                "Use `-> unit <name>: <factor>` or `-> unit <name>: <compound>` (e.g. `unit eur: 1.00`, `unit eur_per_hour: eur/hour`).",
1837            ))
1838        }
1839    }
1840
1841    fn parse_single_command_arg(
1842        &mut self,
1843        cmd: TypeConstraintCommand,
1844    ) -> Result<Vec<CommandArg>, Error> {
1845        let Some(arg) = self.try_parse_one_command_arg()? else {
1846            return Ok(Vec::new());
1847        };
1848        if self.at(&TokenKind::Comma)? || self.command_arg_starts_without_comma()? {
1849            let tok = *self.peek()?;
1850            return Err(self.error_at_token_with_suggestion(
1851                &tok,
1852                format!("`-> {cmd}` takes one value"),
1853                format!("Write `-> {cmd}` with a single argument"),
1854            ));
1855        }
1856        Ok(vec![arg])
1857    }
1858
1859    fn try_parse_one_command_arg(&mut self) -> Result<Option<CommandArg>, Error> {
1860        if self.at(&TokenKind::Arrow)?
1861            || self.at(&TokenKind::Eof)?
1862            || is_spec_body_keyword(&self.peek()?.kind)
1863            || self.at(&TokenKind::Spec)?
1864            || self.at(&TokenKind::Comma)?
1865        {
1866            return Ok(None);
1867        }
1868
1869        let peek_kind = self.peek()?.kind;
1870        match peek_kind {
1871            TokenKind::NumberLit | TokenKind::Minus | TokenKind::Plus | TokenKind::StringLit => {
1872                let value = self.parse_literal_value()?;
1873                Ok(Some(CommandArg::Literal(value)))
1874            }
1875            ref k if is_boolean_keyword(k) => {
1876                let value = self.parse_literal_value()?;
1877                Ok(Some(CommandArg::Literal(value)))
1878            }
1879            ref k if can_be_label(k) => {
1880                let tok = self.next()?;
1881                Ok(Some(CommandArg::Label(
1882                    tok.text.of(&self.source).to_string(),
1883                )))
1884            }
1885            _ => Ok(None),
1886        }
1887    }
1888
1889    fn parse_comma_separated_command_args(&mut self) -> Result<Vec<CommandArg>, Error> {
1890        let mut args = Vec::new();
1891        if self.at_command_terminator()? {
1892            return Ok(args);
1893        }
1894        if self.at(&TokenKind::Comma)? {
1895            let tok = self.next()?;
1896            return Err(self.error_at_token_with_suggestion(
1897                &tok,
1898                "Unexpected comma".to_string(),
1899                "Remove the extra comma, or put a value before it",
1900            ));
1901        }
1902
1903        loop {
1904            let Some(arg) = self.try_parse_one_command_arg()? else {
1905                let tok = *self.peek()?;
1906                return Err(self.error_at_token_with_suggestion(
1907                    &tok,
1908                    "Expected a value after comma".to_string(),
1909                    "Remove the extra comma, or add the missing value",
1910                ));
1911            };
1912            args.push(arg);
1913
1914            if self.at(&TokenKind::Comma)? {
1915                self.next()?;
1916                if self.at_command_terminator()? || self.at(&TokenKind::Comma)? {
1917                    let tok = *self.peek()?;
1918                    return Err(self.error_at_token_with_suggestion(
1919                        &tok,
1920                        "Trailing or empty comma in list".to_string(),
1921                        "Remove the extra comma, or add the missing value",
1922                    ));
1923                }
1924                continue;
1925            }
1926
1927            if self.command_arg_starts_without_comma()? {
1928                let tok = *self.peek()?;
1929                return Err(self.error_at_token_with_suggestion(
1930                    &tok,
1931                    "Expected a comma between items".to_string(),
1932                    "Separate items with commas, for example `-> options \"a\", \"b\"`",
1933                ));
1934            }
1935            break;
1936        }
1937        Ok(args)
1938    }
1939
1940    fn command_arg_starts_without_comma(&mut self) -> Result<bool, Error> {
1941        if self.at_command_terminator()? || self.at(&TokenKind::Comma)? {
1942            return Ok(false);
1943        }
1944        let peek_kind = self.peek()?.kind;
1945        Ok(matches!(
1946            peek_kind,
1947            TokenKind::NumberLit | TokenKind::Minus | TokenKind::Plus | TokenKind::StringLit
1948        ) || is_boolean_keyword(&peek_kind)
1949            || can_be_label(&peek_kind))
1950    }
1951
1952    fn parse_scalar_literal_value(&mut self) -> Result<Value, Error> {
1953        self.parse_scalar_literal_value_with_context("value (number, text, boolean, date, etc.)")
1954    }
1955
1956    fn parse_scalar_literal_value_with_context(&mut self, expected: &str) -> Result<Value, Error> {
1957        let peeked = self.peek()?;
1958        match &peeked.kind {
1959            TokenKind::StringLit => {
1960                let tok = self.next()?;
1961                Ok(Value::Text(tok.text.of(&self.source).to_string()))
1962            }
1963            k if is_boolean_keyword(k) => {
1964                let tok = self.next()?;
1965                Ok(Value::Boolean(token_kind_to_boolean_value(&tok.kind)))
1966            }
1967            TokenKind::NumberLit => self.parse_number_literal(),
1968            TokenKind::Minus | TokenKind::Plus => self.parse_signed_number_literal(),
1969            _ => {
1970                let tok = self.next()?;
1971                Err(self.error_at_token(
1972                    &tok,
1973                    format!(
1974                        "Expected a {expected}, found '{}'",
1975                        tok.text.of(&self.source)
1976                    ),
1977                ))
1978            }
1979        }
1980    }
1981
1982    /// Returns true when the current token ends the current command argument list.
1983    fn at_command_terminator(&mut self) -> Result<bool, Error> {
1984        if self.at(&TokenKind::Arrow)? || self.at(&TokenKind::Eof)? || self.at(&TokenKind::Spec)? {
1985            return Ok(true);
1986        }
1987        Ok(is_spec_body_keyword(&self.peek()?.kind))
1988    }
1989
1990    /// Parse a sequence of `<measure_ref>[^[-]<integer>]` terms joined by `*` or `/`.
1991    ///
1992    /// `*` is explicit multiplication and resets to numerator mode.
1993    /// `/` switches to denominator mode for all subsequent factors until the next `*`.
1994    /// Exponents in denominator mode are negated.
1995    /// An explicit `^<integer>` overrides the default (±1), still relative to the current mode.
1996    ///
1997    /// Space has no meaning in Lemma — `kg * m / s^2` and `kg*m/s^2` are identical.
1998    /// Space-adjacent labels without an intervening `*` or `/` end the expression;
1999    /// the bare label belongs to the next syntactic element.
2000    ///
2001    /// Examples:
2002    /// - `meter/second`            → `[{meter, +1}, {second, -1}]`
2003    /// - `meter/second^2`          → `[{meter, +1}, {second, -2}]`
2004    /// - `kg * meter / second^2`   → `[{kg, +1}, {meter, +1}, {second, -2}]`
2005    /// - `meter / second * kg`     → `[{meter, +1}, {second, -1}, {kg, +1}]`
2006    fn parse_unit_factors(&mut self) -> Result<Vec<UnitFactor>, Error> {
2007        let mut factors: Vec<UnitFactor> = Vec::new();
2008        let mut summed_exponents: std::collections::BTreeMap<String, i32> =
2009            std::collections::BTreeMap::new();
2010        let mut denominator_mode = false;
2011        // Tracks whether the loop is sitting immediately after an operator (* or /).
2012        // On the first iteration there is an implicit "we just started", so we allow
2013        // the first label without a preceding operator.
2014        let mut operator_just_consumed = true;
2015
2016        loop {
2017            if self.at_command_terminator()? {
2018                if !operator_just_consumed {
2019                    break;
2020                }
2021                // An operator was consumed but no label followed — that is a parse error
2022                // only if we already emitted at least one factor (dangling operator).
2023                // If factors is empty the caller will handle the missing expression.
2024                break;
2025            }
2026
2027            // `*` — explicit multiplication; reset to numerator mode.
2028            if self.at(&TokenKind::Star)? {
2029                if operator_just_consumed && !factors.is_empty() {
2030                    let bad_tok = self.next()?;
2031                    return Err(self.error_at_token(
2032                        &bad_tok,
2033                        "Unexpected '*' in unit expression: two consecutive operators".to_string(),
2034                    ));
2035                }
2036                self.next()?;
2037                denominator_mode = false;
2038                operator_just_consumed = true;
2039                continue;
2040            }
2041
2042            // `/` — switch to denominator mode.
2043            if self.at(&TokenKind::Slash)? {
2044                if operator_just_consumed && !factors.is_empty() {
2045                    let bad_tok = self.next()?;
2046                    return Err(self.error_at_token(
2047                        &bad_tok,
2048                        "Unexpected '/' in unit expression: two consecutive operators".to_string(),
2049                    ));
2050                }
2051                self.next()?;
2052                denominator_mode = true;
2053                operator_just_consumed = true;
2054                continue;
2055            }
2056
2057            // A label is a measure reference.
2058            let peek_kind = self.peek()?.kind;
2059            if !can_be_unit_name(&peek_kind) {
2060                break;
2061            }
2062
2063            // A label without a preceding operator ends the expression.
2064            // The first factor is permitted without an operator (operator_just_consumed starts true).
2065            if !operator_just_consumed {
2066                break;
2067            }
2068            operator_just_consumed = false;
2069
2070            let (measure_ref, measure_span) = self.parse_unit_path()?;
2071
2072            // Optional exponent: `^` followed by an optional `-` and an integer.
2073            let explicit_exp: Option<i32> = if self.at(&TokenKind::Caret)? {
2074                self.next()?; // consume `^`
2075
2076                let negative = if self.at(&TokenKind::Minus)? {
2077                    self.next()?; // consume `-`
2078                    true
2079                } else {
2080                    false
2081                };
2082
2083                if !self.at(&TokenKind::NumberLit)? {
2084                    let bad_tok = self.next()?;
2085                    return Err(self.error_at_token(
2086                        &bad_tok,
2087                        format!(
2088                            "Expected an integer exponent after '^' in unit expression, found {}",
2089                            bad_tok.kind
2090                        ),
2091                    ));
2092                }
2093
2094                let exp_tok = self.next()?;
2095                let raw: i32 = exp_tok.text.of(&self.source).parse::<i32>().map_err(|_| {
2096                    self.error_at_token(
2097                        &exp_tok,
2098                        format!(
2099                            "Exponent '{}' is not a valid integer in unit expression",
2100                            exp_tok.text.of(&self.source)
2101                        ),
2102                    )
2103                })?;
2104
2105                if raw == 0 {
2106                    return Err(self.error_at_token(
2107                        &exp_tok,
2108                        "Exponent cannot be zero in a unit expression".to_string(),
2109                    ));
2110                }
2111
2112                Some(if negative { -raw } else { raw })
2113            } else {
2114                None
2115            };
2116
2117            // Apply denominator mode: negate the exponent (or its default) when in denominator.
2118            let final_exp = match (explicit_exp, denominator_mode) {
2119                (Some(exponent), true) => -exponent,
2120                (Some(exponent), false) => exponent,
2121                (None, true) => -1,
2122                (None, false) => 1,
2123            };
2124
2125            let summed = summed_exponents
2126                .entry(crate::parsing::ast::canonical_logical_name(&measure_ref).into_owned())
2127                .or_insert(0i32);
2128            *summed = summed
2129                .checked_add(final_exp)
2130                .filter(|sum| sum.unsigned_abs() <= crate::limits::MAX_UNIT_EXPONENT.unsigned_abs())
2131                .ok_or_else(|| {
2132                    Error::parsing(
2133                        format!(
2134                            "Unit '{}' exceeds the maximum unit exponent of {} in this unit expression",
2135                            measure_ref,
2136                            crate::limits::MAX_UNIT_EXPONENT
2137                        ),
2138                        Source::new(self.source_type(), measure_span),
2139                        None::<String>,
2140                    )
2141                })?;
2142
2143            factors.push(UnitFactor {
2144                measure_ref,
2145                exp: final_exp,
2146            });
2147        }
2148
2149        Ok(factors)
2150    }
2151
2152    // ========================================================================
2153    // Meta parsing
2154    // ========================================================================
2155
2156    fn parse_meta(&mut self) -> Result<MetaField, Error> {
2157        let meta_tok = self.expect(&TokenKind::Meta)?;
2158        let start_span = meta_tok.span;
2159
2160        let key_tok = self.next()?;
2161        let key = key_tok.text.of(&self.source).to_string();
2162
2163        self.expect(&TokenKind::Colon)?;
2164
2165        let value = self.parse_meta_literal_value()?;
2166
2167        let span = self.span_covering(&start_span, &self.last_span);
2168
2169        Ok(MetaField {
2170            key,
2171            value,
2172            source_location: self.make_source(span),
2173        })
2174    }
2175
2176    // ========================================================================
2177    // Literal value parsing
2178    // ========================================================================
2179
2180    fn parse_meta_literal_value(&mut self) -> Result<Value, Error> {
2181        if self.at(&TokenKind::Ellipsis)? {
2182            let tok = *self.peek()?;
2183            return Err(self.error_at_token(&tok, "Expected a meta literal, found a range"));
2184        }
2185        self.parse_scalar_literal_value_with_context("meta literal")
2186    }
2187
2188    fn parse_literal_value(&mut self) -> Result<Value, Error> {
2189        let left = self.parse_scalar_literal_value()?;
2190        if self.at(&TokenKind::Ellipsis)? {
2191            self.next()?;
2192            let right = self.parse_scalar_literal_value()?;
2193            Ok(Value::Range(Box::new(left), Box::new(right)))
2194        } else {
2195            Ok(left)
2196        }
2197    }
2198
2199    fn parse_signed_number_literal(&mut self) -> Result<Value, Error> {
2200        let sign_tok = self.next()?;
2201        let sign_span = sign_tok.span;
2202        let is_negative = sign_tok.kind == TokenKind::Minus;
2203
2204        if !self.at(&TokenKind::NumberLit)? {
2205            let tok = *self.peek()?;
2206            return Err(self.error_at_token(
2207                &tok,
2208                format!(
2209                    "Expected a number after '{}', found '{}'",
2210                    sign_tok.text.of(&self.source),
2211                    tok.text.of(&self.source)
2212                ),
2213            ));
2214        }
2215
2216        let value = self.parse_number_literal()?;
2217        if !is_negative {
2218            return Ok(value);
2219        }
2220        match try_negate_numeric_literal(value) {
2221            Ok(negated) => Ok(negated),
2222            Err(other) => Err(Error::parsing(
2223                format!("Cannot negate this value: {}", other),
2224                self.make_source(sign_span),
2225                None::<String>,
2226            )),
2227        }
2228    }
2229
2230    fn parse_number_literal(&mut self) -> Result<Value, Error> {
2231        let num_tok = self.next()?;
2232        let source = Arc::clone(&self.source);
2233        let num_text = num_tok.text.of(&source);
2234        let num_span = num_tok.span;
2235
2236        if self.at(&TokenKind::Comma)? {
2237            let comma = *self.peek()?;
2238            let next = *self.lexer.peek_second()?;
2239            let digits_grouped = next.kind == TokenKind::NumberLit
2240                && comma.span.start == num_span.end
2241                && next.span.start == comma.span.end;
2242            if digits_grouped {
2243                let grouped = format!("{}_{}", num_text, next.text.of(&self.source));
2244                return Err(self.error_at_token_with_suggestion(
2245                    &comma,
2246                    format!(
2247                        "`,` is a list separator, not a digit separator. Write `{grouped}` instead of `{num_text},{}`",
2248                        next.text.of(&self.source)
2249                    ),
2250                    format!("Use `{grouped}`"),
2251                ));
2252            }
2253        }
2254
2255        // Check if followed by - which could make it a date (YYYY-MM-DD)
2256        if num_text.len() == 4
2257            && num_text.chars().all(|c| c.is_ascii_digit())
2258            && self.at(&TokenKind::Minus)?
2259        {
2260            return self.parse_date_literal(num_text, num_span);
2261        }
2262
2263        // Check what follows the number
2264        let peeked = self.peek()?;
2265
2266        // Number followed by : could be a time literal (HH:MM:SS)
2267        if num_text.len() == 2
2268            && num_text.chars().all(|c| c.is_ascii_digit())
2269            && peeked.kind == TokenKind::Colon
2270        {
2271            // Only if we're in a data value context... this is ambiguous.
2272            // Time literals look like: 14:30:00 or 14:30
2273            // But we might also have "rule x: expr" where : is assignment.
2274            // The grammar handles this at the grammar level. For us,
2275            // we need to check if the context is right.
2276            // Let's try to parse as time if the following pattern matches.
2277            return self.try_parse_time_literal(num_text, num_span);
2278        }
2279
2280        // Check for %% (permille) - must be before %
2281        if peeked.kind == TokenKind::PercentPercent {
2282            let pp_tok = self.next()?;
2283            // Check it's not followed by a digit
2284            if let Ok(next_peek) = self.peek() {
2285                if next_peek.kind == TokenKind::NumberLit {
2286                    return Err(self.error_at_token(
2287                        &pp_tok,
2288                        "Permille literal cannot be followed by a digit",
2289                    ));
2290                }
2291            }
2292            let decimal = parse_decimal_string(num_text, &num_span, self)?;
2293            return Ok(Value::NumberWithUnit(decimal, "permille".to_string()));
2294        }
2295
2296        // Check for % (percent)
2297        if peeked.kind == TokenKind::Percent {
2298            let pct_tok = self.next()?;
2299            // Check it's not followed by a digit or another %
2300            if let Ok(next_peek) = self.peek() {
2301                if next_peek.kind == TokenKind::NumberLit || next_peek.kind == TokenKind::Percent {
2302                    return Err(self.error_at_token(
2303                        &pct_tok,
2304                        "Percent literal cannot be followed by a digit",
2305                    ));
2306                }
2307            }
2308            let decimal = parse_decimal_string(num_text, &num_span, self)?;
2309            return Ok(Value::NumberWithUnit(decimal, "percent".to_string()));
2310        }
2311
2312        // Check for "permille" keyword
2313        if peeked.kind == TokenKind::Permille {
2314            self.next()?; // consume "permille"
2315            let decimal = parse_decimal_string(num_text, &num_span, self)?;
2316            return Ok(Value::NumberWithUnit(decimal, "permille".to_string()));
2317        }
2318
2319        let starts_unit = can_be_unit_name(&peeked.kind);
2320        if starts_unit && !self.at_path_then_colon()? {
2321            let (unit_path, _) = self.parse_unit_path()?;
2322            let decimal = parse_decimal_string(num_text, &num_span, self)?;
2323            return Ok(Value::NumberWithUnit(decimal, unit_path));
2324        }
2325
2326        // Plain number
2327        let decimal = parse_decimal_string(num_text, &num_span, self)?;
2328        Ok(Value::Number(decimal))
2329    }
2330
2331    /// One or more labels separated by `.` (bare unit or qualified unit path).
2332    fn parse_unit_path(&mut self) -> Result<(String, Span), Error> {
2333        let first = self.next()?;
2334        if !can_be_unit_name(&first.kind) {
2335            return Err(self.error_at_token(
2336                &first,
2337                format!("Expected a unit name, found {}", first.kind),
2338            ));
2339        }
2340        let mut path = first.text.of(&self.source).to_string();
2341        let mut end_span = first.span;
2342        while self.at(&TokenKind::Dot)? {
2343            self.next()?;
2344            let seg = self.next()?;
2345            if !can_be_unit_name(&seg.kind) {
2346                return Err(self.error_at_token(
2347                    &seg,
2348                    format!("Expected a unit path segment after '.', found {}", seg.kind),
2349                ));
2350            }
2351            path.push('.');
2352            path.push_str(seg.text.of(&self.source));
2353            end_span = seg.span;
2354        }
2355        Ok((path, end_span))
2356    }
2357
2358    fn parse_date_literal(&mut self, year_text: &str, start_span: Span) -> Result<Value, Error> {
2359        let mut dt_str = year_text.to_string();
2360
2361        // Consume -MM
2362        self.expect(&TokenKind::Minus)?;
2363        dt_str.push('-');
2364        let month_tok = self.expect(&TokenKind::NumberLit)?;
2365        dt_str.push_str(month_tok.text.of(&self.source));
2366
2367        // Consume -DD
2368        self.expect(&TokenKind::Minus)?;
2369        dt_str.push('-');
2370        let day_tok = self.expect(&TokenKind::NumberLit)?;
2371        dt_str.push_str(day_tok.text.of(&self.source));
2372
2373        // Check for T (time component)
2374        if self.at(&TokenKind::Identifier)? {
2375            let peeked = *self.peek()?;
2376            if peeked.text.of(&self.source).len() >= 2
2377                && (peeked.text.of(&self.source).starts_with('T')
2378                    || peeked.text.of(&self.source).starts_with('t'))
2379            {
2380                // The lexer may have tokenized T14 as a single identifier
2381                let t_tok = self.next()?;
2382                dt_str.push_str(t_tok.text.of(&self.source));
2383
2384                // Consume :MM
2385                if self.at(&TokenKind::Colon)? {
2386                    self.next()?;
2387                    dt_str.push(':');
2388                    let min_tok = self.next()?;
2389                    dt_str.push_str(min_tok.text.of(&self.source));
2390
2391                    // Consume :SS and optional fractional second
2392                    if self.at(&TokenKind::Colon)? {
2393                        self.next()?;
2394                        dt_str.push(':');
2395                        let sec_tok = self.next()?;
2396                        dt_str.push_str(sec_tok.text.of(&self.source));
2397
2398                        // Check for fractional second .NNNNNN
2399                        if self.at(&TokenKind::Dot)? {
2400                            self.next()?;
2401                            dt_str.push('.');
2402                            let frac_tok = self.expect(&TokenKind::NumberLit)?;
2403                            dt_str.push_str(frac_tok.text.of(&self.source));
2404                        }
2405                    }
2406                }
2407
2408                // Check for timezone
2409                self.try_consume_timezone(&mut dt_str)?;
2410            }
2411        }
2412
2413        if let Ok(dtv) = dt_str.parse::<crate::literals::DateTimeValue>() {
2414            return Ok(Value::Date(dtv));
2415        }
2416
2417        Err(Error::parsing(
2418            format!("Invalid date/time format: '{}'", dt_str),
2419            self.make_source(start_span),
2420            None::<String>,
2421        ))
2422    }
2423
2424    fn try_consume_timezone(&mut self, dt_str: &mut String) -> Result<(), Error> {
2425        // Z timezone
2426        if self.at(&TokenKind::Identifier)? {
2427            let peeked = *self.peek()?;
2428            if (peeked.text.of(&self.source) == "Z" || peeked.text.of(&self.source) == "z")
2429                && peeked.span.start == self.last_span.end
2430            {
2431                let z_tok = self.next()?;
2432                dt_str.push_str(z_tok.text.of(&self.source));
2433                return Ok(());
2434            }
2435        }
2436
2437        // +HH:MM or -HH:MM, only when attached directly to the preceding token.
2438        if self.at(&TokenKind::Plus)? || self.at(&TokenKind::Minus)? {
2439            let checkpoint = self.lexer.checkpoint();
2440            let sign_tok = self.lexer.next_token()?;
2441            let hour_tok = self.lexer.next_token()?;
2442            let colon_tok = self.lexer.next_token()?;
2443            let minute_tok = self.lexer.next_token()?;
2444
2445            let attached = sign_tok.span.start == self.last_span.end;
2446            let is_timezone_shape = hour_tok.kind == TokenKind::NumberLit
2447                && colon_tok.kind == TokenKind::Colon
2448                && minute_tok.kind == TokenKind::NumberLit;
2449
2450            self.lexer.restore(checkpoint);
2451
2452            if attached && is_timezone_shape {
2453                let sign_tok = self.next()?;
2454                dt_str.push_str(sign_tok.text.of(&self.source));
2455                let hour_tok = self.expect(&TokenKind::NumberLit)?;
2456                dt_str.push_str(hour_tok.text.of(&self.source));
2457                self.expect(&TokenKind::Colon)?;
2458                dt_str.push(':');
2459                let min_tok = self.expect(&TokenKind::NumberLit)?;
2460                dt_str.push_str(min_tok.text.of(&self.source));
2461            }
2462        }
2463
2464        Ok(())
2465    }
2466
2467    fn try_parse_time_literal(
2468        &mut self,
2469        hour_text: &str,
2470        start_span: Span,
2471    ) -> Result<Value, Error> {
2472        let mut time_str = hour_text.to_string();
2473
2474        // Consume :MM
2475        self.expect(&TokenKind::Colon)?;
2476        time_str.push(':');
2477        let min_tok = self.expect(&TokenKind::NumberLit)?;
2478        time_str.push_str(min_tok.text.of(&self.source));
2479
2480        // Optional :SS
2481        if self.at(&TokenKind::Colon)? {
2482            self.next()?;
2483            time_str.push(':');
2484            let sec_tok = self.expect(&TokenKind::NumberLit)?;
2485            time_str.push_str(sec_tok.text.of(&self.source));
2486
2487            // Optional fractional second .NNNNNN
2488            if self.at(&TokenKind::Dot)? {
2489                self.next()?;
2490                time_str.push('.');
2491                let frac_tok = self.expect(&TokenKind::NumberLit)?;
2492                time_str.push_str(frac_tok.text.of(&self.source));
2493            }
2494        }
2495
2496        // Try timezone
2497        self.try_consume_timezone(&mut time_str)?;
2498
2499        if let Ok(t) = time_str.parse::<TimeValue>() {
2500            return Ok(Value::Time(TimeValue {
2501                hour: t.hour,
2502                minute: t.minute,
2503                second: t.second,
2504                microsecond: t.microsecond,
2505                timezone: t.timezone,
2506            }));
2507        }
2508
2509        Err(Error::parsing(
2510            format!("Invalid time format: '{}'", time_str),
2511            self.make_source(start_span),
2512            None::<String>,
2513        ))
2514    }
2515
2516    // ========================================================================
2517    // Expression grammar
2518    // ========================================================================
2519
2520    fn expr_span(&self, id: ExprId) -> Option<Span> {
2521        self.table.source(id).map(|source| source.span)
2522    }
2523
2524    fn expr_source(&self, id: ExprId) -> Option<Source> {
2525        self.table.source(id).cloned()
2526    }
2527
2528    /// Ends one top-level expression: its nodes move into a fresh table owned by the result.
2529    fn finish_expression(&mut self, root: ExprId) -> Expression {
2530        ExprTree::new(self.table.take_compact(), root)
2531    }
2532
2533    fn new_expression(&mut self, kind: ExpressionKind, source: Source) -> Result<ExprId, Error> {
2534        self.expression_count += 1;
2535        if self.expression_count > self.max_expression_count {
2536            return Err(Error::resource_limit_exceeded(
2537                "max_expression_count",
2538                self.max_expression_count.to_string(),
2539                self.expression_count.to_string(),
2540                "Split logic into multiple rules to reduce expression count",
2541                Some(source),
2542                None,
2543                None,
2544            ));
2545        }
2546        Ok(self.table.push(kind, Some(source)))
2547    }
2548
2549    fn check_depth(&mut self) -> Result<(), Error> {
2550        if let Err(actual) = self.depth_tracker.push_depth() {
2551            let span = self.peek()?.span;
2552            self.depth_tracker.pop_depth();
2553            return Err(Error::resource_limit_exceeded(
2554                "max_expression_depth",
2555                self.depth_tracker.max_depth().to_string(),
2556                actual.to_string(),
2557                "Simplify nested expressions or break into separate rules",
2558                Some(self.make_source(span)),
2559                None,
2560                None,
2561            ));
2562        }
2563        Ok(())
2564    }
2565
2566    fn at_bare_veto_token(&mut self) -> Result<bool, Error> {
2567        if !self.at(&TokenKind::Veto)? {
2568            return Ok(false);
2569        }
2570        let checkpoint = self.checkpoint();
2571        self.next()?;
2572        let bare = !self.at(&TokenKind::StringLit)?;
2573        self.restore(checkpoint);
2574        Ok(bare)
2575    }
2576
2577    fn at_bare_veto_followed_by_is(&mut self) -> Result<bool, Error> {
2578        if !self.at_bare_veto_token()? {
2579            return Ok(false);
2580        }
2581        let checkpoint = self.checkpoint();
2582        self.next()?;
2583        let followed = self.at(&TokenKind::Is)?;
2584        self.restore(checkpoint);
2585        Ok(followed)
2586    }
2587
2588    fn at_not_bare_veto_followed_by_is(&mut self) -> Result<bool, Error> {
2589        if !self.at(&TokenKind::Not)? {
2590            return Ok(false);
2591        }
2592        let checkpoint = self.checkpoint();
2593        self.next()?;
2594        if !self.at(&TokenKind::Veto)? {
2595            self.restore(checkpoint);
2596            return Ok(false);
2597        }
2598        self.next()?;
2599        if self.at(&TokenKind::StringLit)? {
2600            self.restore(checkpoint);
2601            return Ok(false);
2602        }
2603        let followed = self.at(&TokenKind::Is)?;
2604        self.restore(checkpoint);
2605        Ok(followed)
2606    }
2607
2608    fn wrap_result_is_veto_expression(
2609        &mut self,
2610        operand: ExprId,
2611        operator_is_not: bool,
2612        keyword_was_negated: bool,
2613        start_span: Span,
2614    ) -> Result<ExprId, Error> {
2615        let negate = operator_is_not ^ keyword_was_negated;
2616        let end_span = self.expr_span(operand).unwrap_or(start_span);
2617        let span = self.span_covering(&start_span, &end_span);
2618        let core = self.new_expression(
2619            ExpressionKind::ResultIsVeto(operand),
2620            self.make_source(span),
2621        )?;
2622        if negate {
2623            self.new_expression(
2624                ExpressionKind::LogicalNegation(core, NegationType::Not),
2625                self.make_source(span),
2626            )
2627        } else {
2628            Ok(core)
2629        }
2630    }
2631
2632    fn next_is_list_type_suffix(&mut self) -> Result<bool, Error> {
2633        let checkpoint = self.checkpoint();
2634        self.next()?;
2635        let list_after_range = if self.at(&TokenKind::Identifier)? && {
2636            let peeked = *self.peek()?;
2637            peeked.text.of(&self.source) == "range"
2638        } {
2639            self.next()?;
2640            self.at(&TokenKind::List)?
2641        } else {
2642            self.at(&TokenKind::List)?
2643        };
2644        self.restore(checkpoint);
2645        Ok(list_after_range)
2646    }
2647
2648    fn wrap_list_type_suffix(&mut self, expr: ExprId, start_span: Span) -> Result<ExprId, Error> {
2649        if self.pin_before_list_ahead()? {
2650            let tok = *self.peek()?;
2651            return Err(self.error_at_token_with_suggestion(
2652                &tok,
2653                "An effective pin is not valid on a type or list element",
2654                "Write `uses Spec <pin>`, then `data name: Spec list` or `rule name: Spec list`.",
2655            ));
2656        }
2657        if !self.at_list_type_suffix()? {
2658            return Ok(expr);
2659        }
2660        let ExpressionKind::Reference(reference) = self.table.kind(expr).clone() else {
2661            return Ok(expr);
2662        };
2663        let mut parent = parent_type_from_reference(&reference);
2664        if self.at(&TokenKind::Identifier)? && {
2665            let peeked = *self.peek()?;
2666            peeked.text.of(&self.source) == "range"
2667        } {
2668            self.next()?;
2669            parent = ParentType::Ranged {
2670                inner: Box::new(parent),
2671            };
2672        }
2673        self.expect(&TokenKind::List)?;
2674        parent = ParentType::List {
2675            inner: Box::new(parent),
2676        };
2677        let span = self.span_covering(&start_span, &self.last_span);
2678        *self.table.kind_mut(expr) = ExpressionKind::ListType { element: parent };
2679        self.table.set_source(expr, self.make_source(span));
2680        Ok(expr)
2681    }
2682
2683    fn pin_before_list_ahead(&mut self) -> Result<bool, Error> {
2684        if !self.at(&TokenKind::NumberLit)? {
2685            return Ok(false);
2686        }
2687        let year = *self.peek()?;
2688        if year.text.of(&self.source).len() != 4
2689            || !year
2690                .text
2691                .of(&self.source)
2692                .chars()
2693                .all(|c| c.is_ascii_digit())
2694        {
2695            return Ok(false);
2696        }
2697        let checkpoint = self.checkpoint();
2698        self.next()?;
2699        let list = self.at(&TokenKind::List)?;
2700        self.restore(checkpoint);
2701        Ok(list)
2702    }
2703
2704    fn at_list_type_suffix(&mut self) -> Result<bool, Error> {
2705        if self.at(&TokenKind::List)? {
2706            return Ok(true);
2707        }
2708        if self.at(&TokenKind::Identifier)? && {
2709            let peeked = *self.peek()?;
2710            peeked.text.of(&self.source) == "range"
2711        } {
2712            let checkpoint = self.checkpoint();
2713            self.next()?;
2714            let list = self.at(&TokenKind::List)?;
2715            self.restore(checkpoint);
2716            return Ok(list);
2717        }
2718        Ok(false)
2719    }
2720
2721    fn parse_expression_parent_type(&mut self) -> Result<ParentType, Error> {
2722        let peek = *self.peek()?;
2723        let base = if let Some(primitive) = token_kind_to_primitive(&peek.kind) {
2724            self.next()?;
2725            ParentType::Primitive { primitive }
2726        } else {
2727            self.parse_custom_or_spec_element_parent()?
2728        };
2729        let base = if self.at(&TokenKind::Identifier)? && {
2730            let peeked = *self.peek()?;
2731            peeked.text.of(&self.source) == "range"
2732        } {
2733            self.next()?;
2734            ParentType::Ranged {
2735                inner: Box::new(base),
2736            }
2737        } else {
2738            base
2739        };
2740        self.expect(&TokenKind::List)?;
2741        Ok(ParentType::List {
2742            inner: Box::new(base),
2743        })
2744    }
2745
2746    /// A token that starts a bare (unparenthesised) command argument. Never a sign:
2747    /// after a command, `+` / `-` is the binary operator. Never `is`: `items -> count is 0`.
2748    fn at_bare_operand_start(&mut self) -> Result<bool, Error> {
2749        let kind = self.peek()?.kind;
2750        if kind == TokenKind::Is {
2751            return Ok(false);
2752        }
2753        Ok(matches!(
2754            kind,
2755            TokenKind::NumberLit
2756                | TokenKind::StringLit
2757                | TokenKind::Now
2758                | TokenKind::Past
2759                | TokenKind::Future
2760                | TokenKind::Lower
2761                | TokenKind::Upper
2762        ) || is_boolean_keyword(&kind)
2763            || is_math_function(&kind)
2764            || can_be_label(&kind)
2765            || token_kind_to_primitive(&kind).is_some())
2766    }
2767
2768    fn at_command_argument_start(&mut self) -> Result<bool, Error> {
2769        Ok(self.at(&TokenKind::LParen)? || self.at_bare_operand_start()?)
2770    }
2771
2772    /// Tokens that may follow a bare argument. Anything else (an operator) is ambiguous.
2773    fn at_bare_argument_end(&mut self) -> Result<bool, Error> {
2774        Ok(self.at_any(&[
2775            TokenKind::Arrow,
2776            TokenKind::Then,
2777            TokenKind::Unless,
2778            TokenKind::RParen,
2779            TokenKind::Comma,
2780            TokenKind::Eof,
2781            TokenKind::Spec,
2782            TokenKind::Repo,
2783            TokenKind::Uses,
2784        ])? || is_spec_body_keyword(&self.peek()?.kind))
2785    }
2786
2787    fn bare_argument_error(&mut self, command: &str) -> Error {
2788        let tok = match self.peek() {
2789            Ok(tok) => *tok,
2790            Err(error) => return error,
2791        };
2792        self.error_at_token(
2793            &tok,
2794            format!(
2795                "`{command}` without parentheses takes one operand, found '{}' after it; \
2796                 write `{command}(...)` around the whole argument, or `(... -> {command} ...)` \
2797                 to use the result",
2798                tok.text.of(&self.source)
2799            ),
2800        )
2801    }
2802
2803    fn reject_comma_after_call(&mut self, command: &str) -> Result<(), Error> {
2804        if self.call_argument_depth == 0 && self.at(&TokenKind::Comma)? {
2805            let tok = *self.peek()?;
2806            return Err(self.error_at_token(
2807                &tok,
2808                format!(
2809                    "`,` after `{command}(...)`: put all arguments inside the parentheses, \
2810                     `{command}(a, b)`"
2811                ),
2812            ));
2813        }
2814        Ok(())
2815    }
2816
2817    fn reject_command_argument(&mut self, command: &str) -> Result<(), Error> {
2818        if self.at_command_argument_start()? {
2819            let tok = *self.peek()?;
2820            return Err(self.error_at_token(&tok, format!("`{command}` takes no argument")));
2821        }
2822        Ok(())
2823    }
2824
2825    fn at_row_condition_operator(&mut self) -> Result<bool, Error> {
2826        Ok(is_comparison_operator(&self.peek()?.kind) || self.at(&TokenKind::In)?)
2827    }
2828
2829    fn parse_row_condition_operator(&mut self) -> Result<RowCondition, Error> {
2830        if self.at(&TokenKind::In)? {
2831            self.next()?;
2832            return Ok(RowCondition::In);
2833        }
2834        Ok(RowCondition::Compare(self.parse_comparison_operator()?))
2835    }
2836
2837    fn condition_error(&mut self, command: &str) -> Error {
2838        let tok = match self.peek() {
2839            Ok(tok) => *tok,
2840            Err(error) => return error,
2841        };
2842        self.error_at_token(
2843            &tok,
2844            format!(
2845                "`{command}` condition without parentheses is one comparison between single \
2846                 operands, found '{}'; write `{command}(...)` around the whole condition, \
2847                 for example `{command}(> 5 or is 3)`",
2848                tok.text.of(&self.source)
2849            ),
2850        )
2851    }
2852
2853    /// `asc` when omitted.
2854    fn parse_sort_direction(&mut self) -> Result<bool, Error> {
2855        if self.at(&TokenKind::Desc)? {
2856            self.next()?;
2857            return Ok(true);
2858        }
2859        if self.at(&TokenKind::Asc)? {
2860            self.next()?;
2861        }
2862        Ok(false)
2863    }
2864
2865    fn parse_comparison_operator(&mut self) -> Result<ComparisonComputation, Error> {
2866        let tok = self.next()?;
2867        match tok.kind {
2868            TokenKind::Gt => Ok(ComparisonComputation::GreaterThan),
2869            TokenKind::Lt => Ok(ComparisonComputation::LessThan),
2870            TokenKind::Gte => Ok(ComparisonComputation::GreaterThanOrEqual),
2871            TokenKind::Lte => Ok(ComparisonComputation::LessThanOrEqual),
2872            TokenKind::Is => {
2873                // Check for "is not"
2874                if self.at(&TokenKind::Not)? {
2875                    self.next()?; // consume 'not'
2876                    Ok(ComparisonComputation::IsNot)
2877                } else {
2878                    Ok(ComparisonComputation::Is)
2879                }
2880            }
2881            _ => Err(self.error_at_token(
2882                &tok,
2883                format!("Expected a comparison operator, found {}", tok.kind),
2884            )),
2885        }
2886    }
2887
2888    fn parse_not_in_calendar_suffix(
2889        &mut self,
2890        repository: ExprId,
2891        start_span: Span,
2892    ) -> Result<ExprId, Error> {
2893        self.expect(&TokenKind::Not)?;
2894        self.expect(&TokenKind::In)?;
2895        self.expect_calendar_period_marker()?;
2896        let unit = self.parse_calendar_unit()?;
2897        let end = self.peek()?.span;
2898        let span = self.span_covering(&start_span, &end);
2899        self.new_expression(
2900            ExpressionKind::DateCalendar(DateCalendarKind::NotIn, unit, repository),
2901            self.make_source(span),
2902        )
2903    }
2904
2905    fn parse_as_chain(&mut self, mut expr: ExprId, start_span: Span) -> Result<ExprId, Error> {
2906        while self.at(&TokenKind::As)? {
2907            self.expect(&TokenKind::As)?;
2908            let target_tok = self.next()?;
2909            let target = if matches!(target_tok.kind, TokenKind::Permille) {
2910                ConversionTarget::Unit {
2911                    unit_name: "permille".to_string(),
2912                }
2913            } else if matches!(target_tok.kind, TokenKind::TextKw) {
2914                return Err(self.error_at_token_with_suggestion(
2915                    &target_tok,
2916                    "'text' is not a valid conversion target.".to_string(),
2917                    "Use `as number`, `as boolean`, `as date`, `as time`, `as measure`, `as ratio`, or a unit name (e.g. `as eur`).".to_string(),
2918                ));
2919            } else if let Some(kind) = token_kind_to_conversion_type_kind(&target_tok.kind) {
2920                ConversionTarget::Type(kind)
2921            } else if can_be_label(&target_tok.kind) {
2922                let mut unit_path = target_tok.text.of(&self.source).to_string();
2923                let mut end_span = target_tok.span;
2924                while self.at(&TokenKind::Dot)? {
2925                    self.next()?;
2926                    let seg = self.next()?;
2927                    if !can_be_label(&seg.kind) {
2928                        return Err(self.error_at_token(
2929                            &seg,
2930                            format!("Expected a unit path segment after '.', found {}", seg.kind),
2931                        ));
2932                    }
2933                    unit_path.push('.');
2934                    unit_path.push_str(seg.text.of(&self.source));
2935                    end_span = seg.span;
2936                }
2937                let target = ConversionTarget::Unit {
2938                    unit_name: unit_path,
2939                };
2940                expr = self.new_expression(
2941                    ExpressionKind::UnitConversion(expr, target),
2942                    self.make_source(self.span_covering(&start_span, &end_span)),
2943                )?;
2944                continue;
2945            } else {
2946                return Err(self.error_at_token(
2947                    &target_tok,
2948                    format!(
2949                        "Expected a type keyword or unit name after 'as', found {}",
2950                        target_tok.kind
2951                    ),
2952                ));
2953            };
2954            expr = self.new_expression(
2955                ExpressionKind::UnitConversion(expr, target),
2956                self.make_source(self.span_covering(&start_span, &target_tok.span)),
2957            )?;
2958        }
2959        Ok(expr)
2960    }
2961
2962    fn is_plain_number_literal(&self, id: ExprId) -> bool {
2963        matches!(
2964            self.table.kind(id),
2965            ExpressionKind::Literal(Value::Number(_))
2966        )
2967    }
2968
2969    fn is_unit_conversion(&self, id: ExprId) -> bool {
2970        matches!(self.table.kind(id), ExpressionKind::UnitConversion(..))
2971    }
2972
2973    /// True when the next token can follow a completed suffix expression (no further operands).
2974    ///
2975    /// Must include every token that can start the next spec-body item, a new `spec`/`repo`,
2976    /// or end the file. See `parse_unit_conversion_before_expression_boundaries` in `parsing/mod.rs`.
2977    fn at_expression_suffix_end(&mut self) -> Result<bool, Error> {
2978        Ok(self.at_any(&[TokenKind::And, TokenKind::Or])?
2979            || self.at(&TokenKind::Unless)?
2980            || self.at(&TokenKind::Then)?
2981            || self.at(&TokenKind::RParen)?
2982            || self.at(&TokenKind::Eof)?
2983            || self.at(&TokenKind::Arrow)?
2984            || self.at(&TokenKind::Comma)?
2985            || self.at(&TokenKind::Spec)?
2986            || self.at(&TokenKind::Repo)?
2987            || self.at(&TokenKind::Uses)?
2988            || is_spec_body_keyword(&self.peek()?.kind))
2989    }
2990
2991    fn parse_calendar_unit(&mut self) -> Result<CalendarPeriodUnit, Error> {
2992        let tok = self.next()?;
2993        if let Some(unit) = CalendarPeriodUnit::from_keyword(tok.text.of(&self.source)) {
2994            return Ok(unit);
2995        }
2996        Err(self.error_at_token(
2997            &tok,
2998            format!(
2999                "Expected 'year', 'month', or 'week', found '{}'",
3000                tok.text.of(&self.source)
3001            ),
3002        ))
3003    }
3004
3005    // ========================================================================
3006    // Arithmetic and range operands
3007    // ========================================================================
3008
3009    /// One left fold over `steps`. Without steps the operand itself is the result.
3010    fn arithmetic_chain(
3011        &mut self,
3012        first: ExprId,
3013        steps: Vec<ChainStep<ArithmeticComputation>>,
3014    ) -> Result<ExprId, Error> {
3015        let source = match steps.last() {
3016            None => return Ok(first),
3017            Some(last) => last.source_location.clone(),
3018        };
3019        self.new_expression(ExpressionKind::Arithmetic { first, steps }, source)
3020    }
3021
3022    fn parse_number_expression(&mut self) -> Result<ExprId, Error> {
3023        let num_tok = self.next()?;
3024        let source = Arc::clone(&self.source);
3025        let num_text = num_tok.text.of(&source);
3026        let start_span = num_tok.span;
3027
3028        // Check if this is a date literal (YYYY-MM-DD)
3029        if num_text.len() == 4
3030            && num_text.chars().all(|c| c.is_ascii_digit())
3031            && self.at(&TokenKind::Minus)?
3032        {
3033            // Peek further: if next-next is a number, this is likely a date
3034            // We need to be careful: "2024 - 5" is arithmetic, "2024-01-15" is a date
3035            // Date format requires: YYYY-MM-DD where MM and DD are 2 digits
3036            // This is ambiguous at the token level. Let's check if the pattern matches.
3037            // Since dates use -NN- pattern and arithmetic uses - N pattern (with spaces),
3038            // we can use the span positions to disambiguate.
3039            let minus_span = self.peek()?.span;
3040            // If minus is immediately adjacent to the number (no space), it's a date
3041            if minus_span.start == start_span.end {
3042                let value = self.parse_date_literal(num_text, start_span)?;
3043                return self
3044                    .new_expression(ExpressionKind::Literal(value), self.make_source(start_span));
3045            }
3046        }
3047
3048        // Check for time literal (HH:MM:SS)
3049        if num_text.len() == 2
3050            && num_text.chars().all(|c| c.is_ascii_digit())
3051            && self.at(&TokenKind::Colon)?
3052        {
3053            let colon_span = self.peek()?.span;
3054            if colon_span.start == start_span.end {
3055                let value = self.try_parse_time_literal(num_text, start_span)?;
3056                return self
3057                    .new_expression(ExpressionKind::Literal(value), self.make_source(start_span));
3058            }
3059        }
3060
3061        // Check for %% (permille)
3062        if self.at(&TokenKind::PercentPercent)? {
3063            let pp_tok = self.next()?;
3064            if let Ok(next_peek) = self.peek() {
3065                if next_peek.kind == TokenKind::NumberLit {
3066                    return Err(self.error_at_token(
3067                        &pp_tok,
3068                        "Permille literal cannot be followed by a digit",
3069                    ));
3070                }
3071            }
3072            let decimal = parse_decimal_string(num_text, &start_span, self)?;
3073            return self.new_expression(
3074                ExpressionKind::Literal(Value::NumberWithUnit(decimal, "permille".to_string())),
3075                self.make_source(start_span),
3076            );
3077        }
3078
3079        // Check for % (percent)
3080        if self.at(&TokenKind::Percent)? {
3081            let pct_span = self.peek()?.span;
3082            // Only consume % if it's directly adjacent (no space) for the shorthand syntax
3083            // Or if it's "50 %" (space separated is also valid per the grammar)
3084            let pct_tok = self.next()?;
3085            if let Ok(next_peek) = self.peek() {
3086                if next_peek.kind == TokenKind::NumberLit || next_peek.kind == TokenKind::Percent {
3087                    return Err(self.error_at_token(
3088                        &pct_tok,
3089                        "Percent literal cannot be followed by a digit (use 'mod' for remainder)",
3090                    ));
3091                }
3092            }
3093            let decimal = parse_decimal_string(num_text, &start_span, self)?;
3094            return self.new_expression(
3095                ExpressionKind::Literal(Value::NumberWithUnit(decimal, "percent".to_string())),
3096                self.make_source(self.span_covering(&start_span, &pct_span)),
3097            );
3098        }
3099
3100        // Check for "permille" keyword
3101        if self.at(&TokenKind::Permille)? {
3102            self.next()?;
3103            let decimal = parse_decimal_string(num_text, &start_span, self)?;
3104            return self.new_expression(
3105                ExpressionKind::Literal(Value::NumberWithUnit(decimal, "permille".to_string())),
3106                self.make_source(start_span),
3107            );
3108        }
3109
3110        if can_be_unit_name(&self.peek()?.kind) {
3111            let (unit_path, end_span) = self.parse_unit_path()?;
3112            let decimal = parse_decimal_string(num_text, &start_span, self)?;
3113            return self.new_expression(
3114                ExpressionKind::Literal(Value::NumberWithUnit(decimal, unit_path)),
3115                self.make_source(self.span_covering(&start_span, &end_span)),
3116            );
3117        }
3118
3119        // Plain number
3120        let decimal = parse_decimal_string(num_text, &start_span, self)?;
3121        self.new_expression(
3122            ExpressionKind::Literal(Value::Number(decimal)),
3123            self.make_source(start_span),
3124        )
3125    }
3126
3127    fn parse_expression_reference(&mut self) -> Result<Reference, Error> {
3128        let mut segments = Vec::new();
3129
3130        let first = self.next()?;
3131        segments.push(first.text.of(&self.source).to_string());
3132
3133        while self.at(&TokenKind::Dot)? {
3134            self.next()?; // consume .
3135            let seg = self.next()?;
3136            if !can_be_label(&seg.kind) {
3137                return Err(self.error_at_token(
3138                    &seg,
3139                    format!("Expected an identifier after '.', found {}", seg.kind),
3140                ));
3141            }
3142            segments.push(seg.text.of(&self.source).to_string());
3143        }
3144
3145        Ok(Reference::from_path(segments))
3146    }
3147    fn parse_expression(&mut self) -> Result<ExprId, Error> {
3148        Ok(expr_of(self.run_expression_machine(ExprTask::Expression)?))
3149    }
3150
3151    fn parse_list_command_body(&mut self, name_tok: Token) -> Result<ListCommand, Error> {
3152        Ok(command_of(self.run_expression_machine(
3153            ExprTask::ListCommandBody { name: name_tok },
3154        )?))
3155    }
3156
3157    fn save_flags(&self) -> ExprFlags {
3158        ExprFlags {
3159            call_argument_depth: self.call_argument_depth,
3160        }
3161    }
3162
3163    fn run_expression_machine(&mut self, root: ExprTask) -> Result<ExprVal, Error> {
3164        let mut frames = std::mem::take(&mut self.expr_frames);
3165        let result = self.drive_expression_machine(root, &mut frames);
3166        self.expr_frames = frames;
3167        result
3168    }
3169
3170    fn drive_expression_machine(
3171        &mut self,
3172        root: ExprTask,
3173        frames: &mut Vec<ExprCont>,
3174    ) -> Result<ExprVal, Error> {
3175        let mut step = ExprStep::Enter(root);
3176        loop {
3177            let next = match step {
3178                ExprStep::Enter(task) => self.enter_expression(task, frames),
3179                ExprStep::Yield(value) => match frames.pop() {
3180                    None => return Ok(value),
3181                    Some(cont) => self.resume_expression(cont, value, frames),
3182                },
3183            };
3184            match next {
3185                Ok(next_step) => step = next_step,
3186                Err(error) => {
3187                    self.unwind_expression(frames);
3188                    return Err(error);
3189                }
3190            }
3191        }
3192    }
3193
3194    fn unwind_expression(&mut self, frames: &mut Vec<ExprCont>) {
3195        while let Some(cont) = frames.pop() {
3196            match cont {
3197                ExprCont::Restore(flags) => {
3198                    self.call_argument_depth = flags.call_argument_depth;
3199                }
3200                ExprCont::PopDepth => self.depth_tracker.pop_depth(),
3201                _ => {}
3202            }
3203        }
3204    }
3205
3206    fn enter_expression(
3207        &mut self,
3208        task: ExprTask,
3209        frames: &mut Vec<ExprCont>,
3210    ) -> Result<ExprStep, Error> {
3211        match task {
3212            ExprTask::Expression => {
3213                self.check_depth()?;
3214                frames.push(ExprCont::PopDepth);
3215                Ok(ExprStep::Enter(ExprTask::LogicalExpression {
3216                    connective: LogicalConnective::Or,
3217                }))
3218            }
3219            ExprTask::LogicalExpression { connective } => {
3220                let start_span = self.peek()?.span;
3221                let kind = LogicalChainKind::Expression;
3222                frames.push(ExprCont::LogicalFirst {
3223                    connective,
3224                    start_span,
3225                    kind,
3226                });
3227                Ok(ExprStep::Enter(logical_operand_task(connective, kind)))
3228            }
3229            ExprTask::LogicalOperand => {
3230                if self.at_not_bare_veto_followed_by_is()? || self.at_bare_veto_followed_by_is()? {
3231                    Ok(ExprStep::Enter(ExprTask::VetoStatus))
3232                } else if self.at(&TokenKind::Not)? {
3233                    Ok(ExprStep::Enter(ExprTask::NotExpression))
3234                } else {
3235                    Ok(ExprStep::Enter(ExprTask::RepositoryWithSuffix))
3236                }
3237            }
3238            ExprTask::VetoStatus => {
3239                let start_span = self.peek()?.span;
3240                let keyword_was_negated = if self.at(&TokenKind::Not)? {
3241                    self.next()?;
3242                    true
3243                } else {
3244                    false
3245                };
3246                self.expect(&TokenKind::Veto)?;
3247                if self.at(&TokenKind::StringLit)? {
3248                    let tok = *self.peek()?;
3249                    return Err(self.error_at_token(
3250                        &tok,
3251                        "veto with a message is only valid as a rule or unless result, not in `is veto` comparisons",
3252                    ));
3253                }
3254                let operator = self.parse_comparison_operator()?;
3255                let operator_is_not = matches!(operator, ComparisonComputation::IsNot);
3256                if !matches!(
3257                    operator,
3258                    ComparisonComputation::Is | ComparisonComputation::IsNot
3259                ) {
3260                    let tok = *self.peek()?;
3261                    return Err(self.error_at_token(
3262                        &tok,
3263                        "Expected `is` or `is not` after `veto` in a veto-status comparison",
3264                    ));
3265                }
3266                frames.push(ExprCont::VetoStatus {
3267                    operator_is_not,
3268                    keyword_was_negated,
3269                    start_span,
3270                });
3271                Ok(ExprStep::Enter(ExprTask::Pipe))
3272            }
3273            ExprTask::NotExpression => {
3274                let not_tok = self.expect(&TokenKind::Not)?;
3275                frames.push(ExprCont::Negation {
3276                    start_span: not_tok.span,
3277                });
3278                Ok(ExprStep::Enter(ExprTask::PrefixArgument {
3279                    keyword: "not".to_string(),
3280                }))
3281            }
3282            ExprTask::RepositoryWithSuffix => {
3283                let start_span = self.peek()?.span;
3284                frames.push(ExprCont::RepositorySuffix { start_span });
3285                Ok(ExprStep::Enter(ExprTask::Pipe))
3286            }
3287            ExprTask::Pipe => {
3288                let start_span = self.peek()?.span;
3289                frames.push(ExprCont::PipeFirst { start_span });
3290                Ok(ExprStep::Enter(ExprTask::RepositoryExpression))
3291            }
3292            ExprTask::ComparisonSuffix { left, start_span } => {
3293                self.enter_comparison_suffix(left, start_span, frames)
3294            }
3295            ExprTask::InSuffix {
3296                repository,
3297                start_span,
3298            } => self.enter_in_suffix(repository, start_span, frames),
3299            ExprTask::RepositoryExpression => {
3300                let start_span = self.peek()?.span;
3301                frames.push(ExprCont::RepositoryFirst { start_span });
3302                Ok(ExprStep::Enter(ExprTask::Term { allow_as: true }))
3303            }
3304            ExprTask::Term { allow_as } => {
3305                let start_span = self.peek()?.span;
3306                frames.push(ExprCont::TermFirst {
3307                    allow_as,
3308                    start_span,
3309                });
3310                Ok(ExprStep::Enter(ExprTask::Power))
3311            }
3312            ExprTask::Power => {
3313                let start_span = self.peek()?.span;
3314                frames.push(ExprCont::PowerLeft {
3315                    start_span,
3316                    range_bound: false,
3317                });
3318                Ok(ExprStep::Enter(ExprTask::RangeOperand))
3319            }
3320            ExprTask::RangeOperand => {
3321                let start_span = self.peek()?.span;
3322                let flags = self.save_flags();
3323                if self.no_range_at.get(&start_span.start) == Some(&flags) {
3324                    return Ok(ExprStep::Enter(ExprTask::Factor));
3325                }
3326                frames.push(ExprCont::RangeFactor { start_span, flags });
3327                Ok(ExprStep::Enter(ExprTask::Factor))
3328            }
3329            ExprTask::RangeEllipsisBound => {
3330                let start_span = self.peek()?.span;
3331                frames.push(ExprCont::EllipsisFirst { start_span });
3332                Ok(ExprStep::Enter(ExprTask::PowerForRangeBound))
3333            }
3334            ExprTask::PowerForRangeBound => {
3335                let start_span = self.peek()?.span;
3336                frames.push(ExprCont::PowerLeft {
3337                    start_span,
3338                    range_bound: true,
3339                });
3340                Ok(ExprStep::Enter(ExprTask::Factor))
3341            }
3342            ExprTask::Factor => {
3343                let peeked = self.peek()?;
3344                let start_span = peeked.span;
3345                let kind = peeked.kind;
3346                if kind == TokenKind::Minus {
3347                    self.next()?;
3348                    frames.push(ExprCont::FactorNegate { start_span });
3349                    return Ok(ExprStep::Enter(ExprTask::PrimaryOrMath));
3350                }
3351                if kind == TokenKind::Plus {
3352                    self.next()?;
3353                }
3354                Ok(ExprStep::Enter(ExprTask::PrimaryOrMath))
3355            }
3356            ExprTask::PrimaryOrMath => {
3357                let kind = self.peek()?.kind;
3358                if is_prefix_rounding(&kind) {
3359                    return Ok(ExprStep::Enter(ExprTask::PrefixRoundingRejected));
3360                }
3361                if is_math_function(&kind) {
3362                    return Ok(ExprStep::Enter(ExprTask::MathFunction));
3363                }
3364                if matches!(kind, TokenKind::Lower | TokenKind::Upper) {
3365                    return Ok(ExprStep::Enter(ExprTask::LowerUpper));
3366                }
3367                Ok(ExprStep::Enter(ExprTask::Primary))
3368            }
3369            ExprTask::PrefixRoundingRejected => {
3370                let tok = self.next()?;
3371                let keyword = tok.text.of(&self.source).to_string();
3372                frames.push(ExprCont::PrefixRoundingRejected {
3373                    keyword: keyword.clone(),
3374                    keyword_span: tok.span,
3375                });
3376                Ok(ExprStep::Enter(ExprTask::PrefixArgument { keyword }))
3377            }
3378            ExprTask::MathFunction => {
3379                let func_tok = self.next()?;
3380                let start_span = func_tok.span;
3381                let operator = match func_tok.kind {
3382                    TokenKind::Sqrt => MathematicalComputation::Sqrt,
3383                    TokenKind::Sin => MathematicalComputation::Sin,
3384                    TokenKind::Cos => MathematicalComputation::Cos,
3385                    TokenKind::Tan => MathematicalComputation::Tan,
3386                    TokenKind::Asin => MathematicalComputation::Asin,
3387                    TokenKind::Acos => MathematicalComputation::Acos,
3388                    TokenKind::Atan => MathematicalComputation::Atan,
3389                    TokenKind::Log => MathematicalComputation::Log,
3390                    TokenKind::Exp => MathematicalComputation::Exp,
3391                    TokenKind::Abs => MathematicalComputation::Abs,
3392                    _ => unreachable!("BUG: only math functions should reach here"),
3393                };
3394                frames.push(ExprCont::Math {
3395                    operator,
3396                    start_span,
3397                });
3398                Ok(ExprStep::Enter(ExprTask::PrefixArgument {
3399                    keyword: func_tok.text.of(&self.source).to_string(),
3400                }))
3401            }
3402            ExprTask::LowerUpper => {
3403                let bound_tok = self.next()?;
3404                let start_span = bound_tok.span;
3405                let bound = match bound_tok.kind {
3406                    TokenKind::Lower => RangeBound::Lower,
3407                    TokenKind::Upper => RangeBound::Upper,
3408                    _ => unreachable!("BUG: only lower and upper should reach parse_range_bound"),
3409                };
3410                frames.push(ExprCont::LowerUpperEnd { bound, start_span });
3411                Ok(ExprStep::Enter(ExprTask::PrefixArgument {
3412                    keyword: bound_tok.text.of(&self.source).to_string(),
3413                }))
3414            }
3415            ExprTask::PrefixArgument { keyword } => self.enter_prefix_argument(keyword, frames),
3416            ExprTask::Primary => self.enter_primary(frames),
3417            ExprTask::ListCommandSuffix { list, start_span } => {
3418                self.expect(&TokenKind::Arrow)?;
3419                let name = self.next()?;
3420                frames.push(ExprCont::ListCommandDone { list, start_span });
3421                Ok(ExprStep::Enter(ExprTask::ListCommandBody { name }))
3422            }
3423            ExprTask::ListCommandBody { name } => self.enter_list_command_body(name, frames),
3424            ExprTask::FindKeys => {
3425                if self.at(&TokenKind::LParen)? {
3426                    return Ok(ExprStep::Enter(ExprTask::CallArguments { command: "find" }));
3427                }
3428                if !self.at_bare_operand_start()? {
3429                    let tok = *self.peek()?;
3430                    return Err(self.error_at_token(&tok, "`find` needs a key"));
3431                }
3432                frames.push(ExprCont::FindKey { keys: Vec::new() });
3433                Ok(ExprStep::Enter(ExprTask::BareArgument { command: "find" }))
3434            }
3435            ExprTask::CallArguments { command } => {
3436                self.expect(&TokenKind::LParen)?;
3437                let saved = self.save_flags();
3438                self.call_argument_depth += 1;
3439                frames.push(ExprCont::CallArgumentsEnd { command });
3440                frames.push(ExprCont::Restore(saved));
3441                frames.push(ExprCont::CallArgumentItems {
3442                    arguments: Vec::new(),
3443                });
3444                Ok(ExprStep::Enter(ExprTask::Expression))
3445            }
3446            ExprTask::SingleCallArgument { command } => {
3447                frames.push(ExprCont::SingleCallArgumentCheck { command });
3448                Ok(ExprStep::Enter(ExprTask::CallArguments { command }))
3449            }
3450            ExprTask::OptionalArgument { command } => {
3451                if self.at(&TokenKind::LParen)? {
3452                    frames.push(ExprCont::WrapSome);
3453                    return Ok(ExprStep::Enter(ExprTask::SingleCallArgument { command }));
3454                }
3455                if self.at_bare_operand_start()? {
3456                    frames.push(ExprCont::WrapSome);
3457                    return Ok(ExprStep::Enter(ExprTask::BareArgument { command }));
3458                }
3459                Ok(ExprStep::Yield(ExprVal::Optional(None)))
3460            }
3461            ExprTask::RequiredArgument { command } => {
3462                if self.at(&TokenKind::LParen)? {
3463                    return Ok(ExprStep::Enter(ExprTask::SingleCallArgument { command }));
3464                }
3465                if self.at_bare_operand_start()? {
3466                    return Ok(ExprStep::Enter(ExprTask::BareArgument { command }));
3467                }
3468                let tok = *self.peek()?;
3469                Err(self.error_at_token(&tok, format!("`{command}` needs an argument")))
3470            }
3471            ExprTask::BareArgument { command } => {
3472                frames.push(ExprCont::BareArgumentEnd { command });
3473                Ok(ExprStep::Enter(ExprTask::BareOperand))
3474            }
3475            ExprTask::BareOperand => Ok(ExprStep::Enter(ExprTask::RangeOperand)),
3476            ExprTask::ListPredicate { command } => self.enter_list_predicate(command, frames),
3477            ExprTask::CallListPredicate { command } => {
3478                let checkpoint = self.checkpoint();
3479                self.expect(&TokenKind::LParen)?;
3480                if !self.starts_value_predicate()? {
3481                    self.restore(checkpoint);
3482                    frames.push(ExprCont::WrapInstance);
3483                    return Ok(ExprStep::Enter(ExprTask::SingleCallArgument { command }));
3484                }
3485                frames.push(ExprCont::ValuePredicateCallEnd { command });
3486                Ok(ExprStep::Enter(ExprTask::ValuePredicate {
3487                    command,
3488                    connective: LogicalConnective::Or,
3489                }))
3490            }
3491            ExprTask::ValuePredicate {
3492                command,
3493                connective,
3494            } => {
3495                let start_span = self.peek()?.span;
3496                let kind = LogicalChainKind::ValuePredicate { command };
3497                frames.push(ExprCont::LogicalFirst {
3498                    connective,
3499                    start_span,
3500                    kind,
3501                });
3502                Ok(ExprStep::Enter(logical_operand_task(connective, kind)))
3503            }
3504            ExprTask::ValuePredicateFactor { command } => {
3505                self.enter_value_predicate_factor(command, frames)
3506            }
3507            ExprTask::SortCommand => {
3508                if self.at(&TokenKind::LParen)? {
3509                    frames.push(ExprCont::SortArgument { check_bare: false });
3510                    return Ok(ExprStep::Enter(ExprTask::SingleCallArgument {
3511                        command: "sort",
3512                    }));
3513                }
3514                if self.at_bare_operand_start()? {
3515                    frames.push(ExprCont::SortArgument { check_bare: true });
3516                    return Ok(ExprStep::Enter(ExprTask::BareOperand));
3517                }
3518                let descending = self.parse_sort_direction()?;
3519                Ok(ExprStep::Yield(ExprVal::Command(ListCommand::Sort {
3520                    descending,
3521                    argument: None,
3522                })))
3523            }
3524            ExprTask::ListWithCommand => {
3525                if !self.at(&TokenKind::LParen)? {
3526                    return Ok(ExprStep::Enter(ExprTask::ListWithRows));
3527                }
3528                self.next()?;
3529                let saved = self.save_flags();
3530                self.call_argument_depth += 1;
3531                frames.push(ExprCont::ListWithEnd);
3532                frames.push(ExprCont::Restore(saved));
3533                Ok(ExprStep::Enter(ExprTask::ListWithRows))
3534            }
3535            ExprTask::ListWithRows => {
3536                if self.at_path_then_colon()? {
3537                    return self.enter_pair_field(Vec::new(), frames);
3538                }
3539                frames.push(ExprCont::ValueItem { values: Vec::new() });
3540                Ok(ExprStep::Enter(ExprTask::BareArgument { command: "with" }))
3541            }
3542        }
3543    }
3544
3545    fn resume_expression(
3546        &mut self,
3547        cont: ExprCont,
3548        value: ExprVal,
3549        frames: &mut Vec<ExprCont>,
3550    ) -> Result<ExprStep, Error> {
3551        match cont {
3552            ExprCont::Restore(flags) => {
3553                self.call_argument_depth = flags.call_argument_depth;
3554                Ok(ExprStep::Yield(value))
3555            }
3556            ExprCont::PopDepth => {
3557                self.depth_tracker.pop_depth();
3558                Ok(ExprStep::Yield(value))
3559            }
3560            ExprCont::LogicalFirst {
3561                connective,
3562                start_span,
3563                kind,
3564            } => self.logical_chain(
3565                connective,
3566                expr_of(value),
3567                Vec::new(),
3568                start_span,
3569                kind,
3570                frames,
3571            ),
3572            ExprCont::LogicalOperand {
3573                connective,
3574                first,
3575                mut steps,
3576                start_span,
3577                kind,
3578            } => {
3579                let operand = expr_of(value);
3580                let end_span = self.expr_span(operand).unwrap_or(start_span);
3581                let span = self.span_covering(&start_span, &end_span);
3582                steps.push(ChainStep {
3583                    op: (),
3584                    operand,
3585                    source_location: self.make_source(span),
3586                });
3587                self.logical_chain(connective, first, steps, start_span, kind, frames)
3588            }
3589            ExprCont::VetoStatus {
3590                operator_is_not,
3591                keyword_was_negated,
3592                start_span,
3593            } => expr_step(self.wrap_result_is_veto_expression(
3594                expr_of(value),
3595                operator_is_not,
3596                keyword_was_negated,
3597                start_span,
3598            )),
3599            ExprCont::Negation { start_span } => {
3600                let operand = expr_of(value);
3601                if self.at(&TokenKind::Arrow)? {
3602                    let tok = *self.peek()?;
3603                    let operand_text = display_expression(&self.table, operand);
3604                    return Err(self.error_at_token(
3605                        &tok,
3606                        format!(
3607                            "`not` without parentheses takes one operand, found '->' after it; \
3608                             write `not ({operand_text} -> ...)` to negate the command's result"
3609                        ),
3610                    ));
3611                }
3612                let end_span = self.expr_span(operand).unwrap_or(start_span);
3613                let span = self.span_covering(&start_span, &end_span);
3614                expr_step(self.new_expression(
3615                    ExpressionKind::LogicalNegation(operand, NegationType::Not),
3616                    self.make_source(span),
3617                ))
3618            }
3619            ExprCont::RepositorySuffix { start_span } => {
3620                self.continue_repository(expr_of(value), start_span, frames)
3621            }
3622            ExprCont::ContinueRepository { start_span } => {
3623                self.continue_repository(expr_of(value), start_span, frames)
3624            }
3625            ExprCont::ComparisonRight {
3626                left,
3627                operator,
3628                start_span,
3629            } => {
3630                let right = expr_of(value);
3631                let end_span = self.expr_span(right).unwrap_or(start_span);
3632                let span = self.span_covering(&start_span, &end_span);
3633                expr_step(self.new_expression(
3634                    ExpressionKind::Comparison(left, operator, right),
3635                    self.make_source(span),
3636                ))
3637            }
3638            ExprCont::InOffset {
3639                direction,
3640                rel_kind,
3641                repository,
3642                start_span,
3643            } => {
3644                let offset = expr_of(value);
3645                let offset_end_span = self.expr_span(offset).unwrap_or(start_span);
3646                let range = self.new_expression(
3647                    ExpressionKind::PastFutureRange(rel_kind, offset),
3648                    self.make_source(self.span_covering(&direction, &offset_end_span)),
3649                )?;
3650                let span = self.span_covering(&start_span, &offset_end_span);
3651                expr_step(self.new_expression(
3652                    ExpressionKind::RangeContainment(repository, range),
3653                    self.make_source(span),
3654                ))
3655            }
3656            ExprCont::InRange {
3657                repository,
3658                start_span,
3659            } => {
3660                let range = expr_of(value);
3661                let end_span = self.expr_span(range).unwrap_or(start_span);
3662                let span = self.span_covering(&start_span, &end_span);
3663                expr_step(self.new_expression(
3664                    ExpressionKind::RangeContainment(repository, range),
3665                    self.make_source(span),
3666                ))
3667            }
3668            ExprCont::RepositoryFirst { start_span } => {
3669                self.repository_chain(expr_of(value), Vec::new(), start_span, frames)
3670            }
3671            ExprCont::RepositoryOperand {
3672                first,
3673                mut steps,
3674                start_span,
3675                operation,
3676            } => {
3677                let operand = expr_of(value);
3678                if steps.is_empty()
3679                    && self.is_plain_number_literal(first)
3680                    && self.is_unit_conversion(operand)
3681                {
3682                    let source = self
3683                        .expr_source(operand)
3684                        .unwrap_or_else(|| self.make_source(start_span));
3685                    return Err(Error::parsing(
3686                        "Cannot add a plain number to a converted value; convert each operand before \
3687                         '+' (e.g. '5 as usd + c as usd')",
3688                        source,
3689                        None::<String>,
3690                    ));
3691                }
3692                let end_span = self.expr_span(operand).unwrap_or(start_span);
3693                let span = self.span_covering(&start_span, &end_span);
3694                steps.push(ChainStep {
3695                    op: operation,
3696                    operand,
3697                    source_location: self.make_source(span),
3698                });
3699                self.repository_chain(first, steps, start_span, frames)
3700            }
3701            ExprCont::TermFirst {
3702                allow_as,
3703                start_span,
3704            } => {
3705                let mut first = expr_of(value);
3706                if allow_as {
3707                    first = self.parse_as_chain(first, start_span)?;
3708                }
3709                self.term_chain(first, Vec::new(), allow_as, start_span, frames)
3710            }
3711            ExprCont::TermOperand {
3712                first,
3713                mut steps,
3714                allow_as,
3715                start_span,
3716                operation,
3717                right_start_span,
3718            } => {
3719                let mut operand = expr_of(value);
3720                if allow_as {
3721                    operand = self.parse_as_chain(operand, right_start_span)?;
3722                }
3723                let end_span = self.expr_span(operand).unwrap_or(start_span);
3724                let span = self.span_covering(&start_span, &end_span);
3725                steps.push(ChainStep {
3726                    op: operation,
3727                    operand,
3728                    source_location: self.make_source(span),
3729                });
3730                self.term_chain(first, steps, allow_as, start_span, frames)
3731            }
3732            ExprCont::PowerLeft {
3733                start_span,
3734                range_bound,
3735            } => self.power_tail(expr_of(value), start_span, range_bound, frames),
3736            ExprCont::PowerRight { left, start_span } => {
3737                let right = expr_of(value);
3738                let end_span = self.expr_span(right).unwrap_or(start_span);
3739                let span = self.span_covering(&start_span, &end_span);
3740                let step = ChainStep {
3741                    op: ArithmeticComputation::Power,
3742                    operand: right,
3743                    source_location: self.make_source(span),
3744                };
3745                expr_step(self.arithmetic_chain(left, vec![step]))
3746            }
3747            ExprCont::RangeFactor { start_span, flags } => {
3748                let factor = expr_of(value);
3749                if self.at(&TokenKind::Ellipsis)? {
3750                    self.next()?;
3751                    frames.push(ExprCont::RangeRight {
3752                        left: factor,
3753                        start_span,
3754                    });
3755                    return Ok(ExprStep::Enter(ExprTask::RangeEllipsisBound));
3756                }
3757                if !self.at_any(&[TokenKind::Caret, TokenKind::Plus, TokenKind::Minus])? {
3758                    return Ok(ExprStep::Yield(ExprVal::Expr(factor)));
3759                }
3760                frames.push(ExprCont::RangeLeft {
3761                    factor,
3762                    start_span,
3763                    checkpoint: Box::new(self.checkpoint()),
3764                    flags,
3765                });
3766                frames.push(ExprCont::EllipsisFirst { start_span });
3767                self.power_tail(factor, start_span, true, frames)
3768            }
3769            ExprCont::RangeLeft {
3770                factor,
3771                start_span,
3772                checkpoint,
3773                flags,
3774            } => {
3775                let left = expr_of(value);
3776                let starts = std::mem::take(&mut self.bound_chain_starts);
3777                if !self.at(&TokenKind::Ellipsis)? {
3778                    for start in starts {
3779                        self.no_range_at.insert(start, flags);
3780                    }
3781                    self.restore(*checkpoint);
3782                    return Ok(ExprStep::Yield(ExprVal::Expr(factor)));
3783                }
3784                self.next()?;
3785                frames.push(ExprCont::RangeRight { left, start_span });
3786                Ok(ExprStep::Enter(ExprTask::RangeEllipsisBound))
3787            }
3788            ExprCont::RangeRight { left, start_span } => {
3789                let right = expr_of(value);
3790                let end_span = self.expr_span(right).unwrap_or(start_span);
3791                let span = self.span_covering(&start_span, &end_span);
3792                expr_step(self.new_expression(
3793                    ExpressionKind::RangeLiteral(left, right),
3794                    self.make_source(span),
3795                ))
3796            }
3797            ExprCont::EllipsisFirst { start_span } => {
3798                let starts = vec![start_span.start];
3799                self.ellipsis_chain(expr_of(value), Vec::new(), start_span, starts, frames)
3800            }
3801            ExprCont::EllipsisOperand {
3802                first,
3803                mut steps,
3804                start_span,
3805                operation,
3806                starts,
3807            } => {
3808                let operand = expr_of(value);
3809                let end_span = self.expr_span(operand).unwrap_or(start_span);
3810                let span = self.span_covering(&start_span, &end_span);
3811                steps.push(ChainStep {
3812                    op: operation,
3813                    operand,
3814                    source_location: self.make_source(span),
3815                });
3816                self.ellipsis_chain(first, steps, start_span, starts, frames)
3817            }
3818            ExprCont::FactorNegate { start_span } => {
3819                let operand = expr_of(value);
3820                let end_span = self.expr_span(operand).unwrap_or(start_span);
3821                let span = self.span_covering(&start_span, &end_span);
3822                if let ExpressionKind::Literal(literal) = self.table.kind(operand) {
3823                    if let Ok(negated) = try_negate_numeric_literal(literal.clone()) {
3824                        return expr_step(self.new_expression(
3825                            ExpressionKind::Literal(negated),
3826                            self.make_source(span),
3827                        ));
3828                    }
3829                }
3830                let zero = self.new_expression(
3831                    ExpressionKind::Literal(Value::Number(Decimal::ZERO)),
3832                    self.make_source(start_span),
3833                )?;
3834                let step = ChainStep {
3835                    op: ArithmeticComputation::Subtract,
3836                    operand,
3837                    source_location: self.make_source(span),
3838                };
3839                expr_step(self.arithmetic_chain(zero, vec![step]))
3840            }
3841            ExprCont::PipeFirst { start_span } => {
3842                self.pipe_chain(expr_of(value), start_span, false, frames)
3843            }
3844            ExprCont::PipeCommand { start_span } => {
3845                self.pipe_chain(expr_of(value), start_span, true, frames)
3846            }
3847            ExprCont::StepRoundingDone {
3848                operand,
3849                mode,
3850                start_span,
3851            } => {
3852                let step = optional_of(value);
3853                let span = self.span_covering(&start_span, &self.last_span);
3854                let rounded = self.new_expression(
3855                    ExpressionKind::StepRounding {
3856                        operand,
3857                        mode,
3858                        step,
3859                    },
3860                    self.make_source(span),
3861                )?;
3862                self.pipe_chain(rounded, start_span, true, frames)
3863            }
3864            ExprCont::PrefixRoundingRejected {
3865                keyword,
3866                keyword_span,
3867            } => {
3868                let operand = expr_of(value);
3869                let operand_text = display_expression(&self.table, operand);
3870                Err(Error::parsing(
3871                    format!(
3872                        "`{keyword}` is written after `->`; write `{operand_text} -> {keyword}`"
3873                    ),
3874                    Source::new(self.source_type(), keyword_span),
3875                    None::<String>,
3876                ))
3877            }
3878            ExprCont::ListCommandDone { list, start_span } => {
3879                let command = command_of(value);
3880                let span = self.span_covering(&start_span, &self.last_span);
3881                expr_step(self.new_expression(
3882                    ExpressionKind::ListCommand { list, command },
3883                    self.make_source(span),
3884                ))
3885            }
3886            ExprCont::Command(builder) => Ok(ExprStep::Yield(ExprVal::Command(build_command(
3887                builder, value,
3888            )))),
3889            ExprCont::FindKey { mut keys } => {
3890                keys.push(expr_of(value));
3891                self.find_key_next(keys, frames)
3892            }
3893            ExprCont::CallArgumentsEnd { command } => {
3894                self.expect(&TokenKind::RParen)?;
3895                self.reject_comma_after_call(command)?;
3896                Ok(ExprStep::Yield(value))
3897            }
3898            ExprCont::CallArgumentItems { mut arguments } => {
3899                arguments.push(expr_of(value));
3900                self.call_argument_items(arguments, frames)
3901            }
3902            ExprCont::SingleCallArgumentCheck { command } => {
3903                let mut arguments = exprs_of(value);
3904                if arguments.len() != 1 {
3905                    let tok = *self.peek()?;
3906                    return Err(self.error_at_token(
3907                        &tok,
3908                        format!("`{command}` takes one argument, got {}", arguments.len()),
3909                    ));
3910                }
3911                Ok(ExprStep::Yield(ExprVal::Expr(arguments.remove(0))))
3912            }
3913            ExprCont::WrapSome => Ok(ExprStep::Yield(ExprVal::Optional(Some(expr_of(value))))),
3914            ExprCont::BareArgumentEnd { command } => {
3915                let argument = expr_of(value);
3916                if !self.at_bare_argument_end()? {
3917                    return Err(self.bare_argument_error(command));
3918                }
3919                Ok(ExprStep::Yield(ExprVal::Expr(argument)))
3920            }
3921            ExprCont::ParenEnd { start_span } => {
3922                let mut inner = expr_of(value);
3923                self.expect(&TokenKind::RParen)?;
3924                if self.at(&TokenKind::Dot)? {
3925                    self.next()?;
3926                    let path = self.parse_reference()?;
3927                    let span = self.span_covering(&start_span, &self.last_span);
3928                    inner = self.new_expression(
3929                        ExpressionKind::Member { base: inner, path },
3930                        self.make_source(span),
3931                    )?;
3932                }
3933                Ok(ExprStep::Yield(ExprVal::Expr(inner)))
3934            }
3935            ExprCont::PastFuture { kind, start_span } => {
3936                let offset = expr_of(value);
3937                let offset_span = self.expr_span(offset).unwrap_or(start_span);
3938                let span = self.span_covering(&start_span, &offset_span);
3939                expr_step(self.new_expression(
3940                    ExpressionKind::PastFutureRange(kind, offset),
3941                    self.make_source(span),
3942                ))
3943            }
3944            ExprCont::Math {
3945                operator,
3946                start_span,
3947            } => {
3948                let operand = expr_of(value);
3949                let end_span = self.expr_span(operand).unwrap_or(start_span);
3950                let span = self.span_covering(&start_span, &end_span);
3951                expr_step(self.new_expression(
3952                    ExpressionKind::MathematicalComputation(operator, operand),
3953                    self.make_source(span),
3954                ))
3955            }
3956            ExprCont::LowerUpperEnd { bound, start_span } => {
3957                let operand = expr_of(value);
3958                let end_span = self.expr_span(operand).unwrap_or(start_span);
3959                let span = self.span_covering(&start_span, &end_span);
3960                expr_step(self.new_expression(
3961                    ExpressionKind::RangeBound(bound, operand),
3962                    self.make_source(span),
3963                ))
3964            }
3965            ExprCont::PrefixArgumentEnd { keyword } => {
3966                let argument = expr_of(value);
3967                if !self.at_bare_argument_end()? {
3968                    let tok = *self.peek()?;
3969                    return Err(self.error_at_token(
3970                        &tok,
3971                        format!(
3972                            "`{keyword}` without parentheses takes one operand, found '{op}' after it; \
3973                             write `{keyword}(a {op} b)` or `{keyword}(a) {op} b`",
3974                            op = tok.text.of(&self.source)
3975                        ),
3976                    ));
3977                }
3978                Ok(ExprStep::Yield(ExprVal::Expr(argument)))
3979            }
3980            ExprCont::PredicateValueRight { op, command } => {
3981                let right = expr_of(value);
3982                if !self.at_bare_argument_end()? {
3983                    return Err(self.condition_error(command));
3984                }
3985                let left = self.new_expression(
3986                    ExpressionKind::ImplicitRowValue,
3987                    self.table
3988                        .source(right)
3989                        .cloned()
3990                        .expect("BUG: parsed predicate operand has source"),
3991                )?;
3992                let kind = match op {
3993                    RowCondition::Compare(op) => ExpressionKind::Comparison(left, op, right),
3994                    RowCondition::In => ExpressionKind::RangeContainment(left, right),
3995                };
3996                let expr = self.new_expression(
3997                    kind,
3998                    self.table
3999                        .source(right)
4000                        .cloned()
4001                        .expect("BUG: parsed predicate operand has source"),
4002                )?;
4003                Ok(ExprStep::Yield(ExprVal::Predicate(ListPredicate::Value {
4004                    expr,
4005                })))
4006            }
4007            ExprCont::PredicateLeft {
4008                start_span,
4009                command,
4010            } => {
4011                let left = expr_of(value);
4012                if self.at_row_condition_operator()? {
4013                    let op = self.parse_row_condition_operator()?;
4014                    frames.push(ExprCont::PredicateRight {
4015                        left,
4016                        op,
4017                        start_span,
4018                        command,
4019                    });
4020                    return Ok(ExprStep::Enter(ExprTask::BareOperand));
4021                }
4022                self.predicate_instance_end(left, command)
4023            }
4024            ExprCont::PredicateRight {
4025                left,
4026                op,
4027                start_span,
4028                command,
4029            } => {
4030                let right = expr_of(value);
4031                let span = self.span_covering(&start_span, &self.last_span);
4032                let kind = match op {
4033                    RowCondition::Compare(op) => ExpressionKind::Comparison(left, op, right),
4034                    RowCondition::In => ExpressionKind::RangeContainment(left, right),
4035                };
4036                let expr = self.new_expression(kind, self.make_source(span))?;
4037                self.predicate_instance_end(expr, command)
4038            }
4039            ExprCont::WrapInstance => Ok(ExprStep::Yield(ExprVal::Predicate(
4040                ListPredicate::Instance {
4041                    expr: expr_of(value),
4042                },
4043            ))),
4044            ExprCont::SortArgument { check_bare } => {
4045                let argument = expr_of(value);
4046                if check_bare
4047                    && !self.at_any(&[TokenKind::Asc, TokenKind::Desc])?
4048                    && !self.at_bare_argument_end()?
4049                {
4050                    return Err(self.bare_argument_error("sort"));
4051                }
4052                let descending = self.parse_sort_direction()?;
4053                Ok(ExprStep::Yield(ExprVal::Command(ListCommand::Sort {
4054                    descending,
4055                    argument: Some(argument),
4056                })))
4057            }
4058            ExprCont::ListWithEnd => {
4059                let rows = rows_of(value);
4060                self.expect(&TokenKind::RParen)?;
4061                self.reject_comma_after_call("with")?;
4062                Ok(ExprStep::Yield(ExprVal::Rows(rows)))
4063            }
4064            ExprCont::PairValue { path, mut pairs } => {
4065                pairs.push((path, expr_of(value)));
4066                self.pair_value_next(pairs, frames)
4067            }
4068            ExprCont::ValueItem { mut values } => {
4069                values.push(expr_of(value));
4070                self.value_item_next(values, frames)
4071            }
4072            ExprCont::ValuePredicateCallEnd { command } => {
4073                self.expect(&TokenKind::RParen)?;
4074                self.reject_comma_after_call(command)?;
4075                Ok(ExprStep::Yield(ExprVal::Predicate(ListPredicate::Value {
4076                    expr: expr_of(value),
4077                })))
4078            }
4079            ExprCont::ValuePredicateGroupEnd => {
4080                self.expect(&TokenKind::RParen)?;
4081                Ok(ExprStep::Yield(value))
4082            }
4083            ExprCont::ValuePredicateLeaf { op, start } => {
4084                let right = expr_of(value);
4085                let left =
4086                    self.new_expression(ExpressionKind::ImplicitRowValue, self.make_source(start))?;
4087                let kind = match op {
4088                    RowCondition::Compare(op) => ExpressionKind::Comparison(left, op, right),
4089                    RowCondition::In => ExpressionKind::RangeContainment(left, right),
4090                };
4091                expr_step(self.new_expression(
4092                    kind,
4093                    self.make_source(self.span_covering(&start, &self.last_span.clone())),
4094                ))
4095            }
4096        }
4097    }
4098
4099    fn logical_chain(
4100        &mut self,
4101        connective: LogicalConnective,
4102        first: ExprId,
4103        steps: Vec<ChainStep<()>>,
4104        start_span: Span,
4105        kind: LogicalChainKind,
4106        frames: &mut Vec<ExprCont>,
4107    ) -> Result<ExprStep, Error> {
4108        let token = match connective {
4109            LogicalConnective::And => TokenKind::And,
4110            LogicalConnective::Or => TokenKind::Or,
4111        };
4112        if !self.at(&token)? {
4113            return match steps.last() {
4114                None => Ok(ExprStep::Yield(ExprVal::Expr(first))),
4115                Some(last) => {
4116                    let source = last.source_location.clone();
4117                    expr_step(self.new_expression(
4118                        ExpressionKind::Logical {
4119                            connective,
4120                            first,
4121                            steps,
4122                        },
4123                        source,
4124                    ))
4125                }
4126            };
4127        }
4128        self.next()?;
4129        frames.push(ExprCont::LogicalOperand {
4130            connective,
4131            first,
4132            steps,
4133            start_span,
4134            kind,
4135        });
4136        Ok(ExprStep::Enter(logical_operand_task(connective, kind)))
4137    }
4138
4139    /// `operand -> command -> ...`. Each `->` applies to everything on its left up to the
4140    /// nearest comparison or logic operator. `piped` is true once a command was applied:
4141    /// an arithmetic operator may not follow it.
4142    fn pipe_chain(
4143        &mut self,
4144        operand: ExprId,
4145        start_span: Span,
4146        piped: bool,
4147        frames: &mut Vec<ExprCont>,
4148    ) -> Result<ExprStep, Error> {
4149        if self.at(&TokenKind::Arrow)? {
4150            let mode = match self.lexer.peek_second()?.kind {
4151                TokenKind::Round => Some(RoundingMode::Round),
4152                TokenKind::Floor => Some(RoundingMode::Floor),
4153                TokenKind::Ceil => Some(RoundingMode::Ceil),
4154                _ => None,
4155            };
4156            let Some(mode) = mode else {
4157                frames.push(ExprCont::PipeCommand { start_span });
4158                return Ok(ExprStep::Enter(ExprTask::ListCommandSuffix {
4159                    list: operand,
4160                    start_span,
4161                }));
4162            };
4163            self.next()?;
4164            self.next()?;
4165            frames.push(ExprCont::StepRoundingDone {
4166                operand,
4167                mode,
4168                start_span,
4169            });
4170            return Ok(ExprStep::Enter(ExprTask::OptionalArgument {
4171                command: mode.keyword(),
4172            }));
4173        }
4174        if piped
4175            && self.at_any(&[
4176                TokenKind::Plus,
4177                TokenKind::Minus,
4178                TokenKind::Star,
4179                TokenKind::Slash,
4180                TokenKind::Mod,
4181                TokenKind::Caret,
4182                TokenKind::As,
4183            ])?
4184        {
4185            let tok = *self.peek()?;
4186            let op = tok.text.of(&self.source);
4187            let command = display_pipe_command(&self.table, operand);
4188            return Err(self.error_at_token(
4189                &tok,
4190                format!(
4191                    "found '{op}' after `-> {command}`; `->` applies to everything on its left, \
4192                     so put parentheses around the command to use its result: \
4193                     `(... -> {command}) {op} ...`"
4194                ),
4195            ));
4196        }
4197        expr_step(Ok(operand))
4198    }
4199
4200    fn continue_repository(
4201        &mut self,
4202        mut expr: ExprId,
4203        start_span: Span,
4204        frames: &mut Vec<ExprCont>,
4205    ) -> Result<ExprStep, Error> {
4206        loop {
4207            let kind = self.peek()?.kind;
4208            if is_comparison_operator(&kind) {
4209                return Ok(ExprStep::Enter(ExprTask::ComparisonSuffix {
4210                    left: expr,
4211                    start_span,
4212                }));
4213            }
4214            if kind == TokenKind::Not {
4215                expr = self.parse_not_in_calendar_suffix(expr, start_span)?;
4216                continue;
4217            }
4218            if kind == TokenKind::In {
4219                frames.push(ExprCont::ContinueRepository { start_span });
4220                return Ok(ExprStep::Enter(ExprTask::InSuffix {
4221                    repository: expr,
4222                    start_span,
4223                }));
4224            }
4225            if kind == TokenKind::As {
4226                expr = self.parse_as_chain(expr, start_span)?;
4227                continue;
4228            }
4229            break;
4230        }
4231
4232        if self.at(&TokenKind::Arrow)? {
4233            let tok = *self.peek()?;
4234            let message = match self.table.kind(expr) {
4235                ExpressionKind::RangeContainment(value, range)
4236                    if !matches!(self.table.kind(*range), ExpressionKind::PastFutureRange(..)) =>
4237                {
4238                    let value_text = display_expression(&self.table, *value);
4239                    let range_text = display_expression(&self.table, *range);
4240                    format!(
4241                        "found '->' after `{value_text} in {range_text}`; `in` takes one range operand, \
4242                         so put parentheses around the command: `{value_text} in ({range_text} -> ...)`"
4243                    )
4244                }
4245                _ => {
4246                    let expr_text = display_expression(&self.table, expr);
4247                    format!(
4248                        "found '->' after `{expr_text}`; put parentheses around what `->` applies to: \
4249                         `({expr_text}) -> ...`"
4250                    )
4251                }
4252            };
4253            return Err(self.error_at_token(&tok, message));
4254        }
4255
4256        if self.at_expression_suffix_end()? {
4257            return expr_step(Ok(expr));
4258        }
4259
4260        let tok = *self.peek()?;
4261        Err(self.error_at_token(
4262            &tok,
4263            format!(
4264                "Unexpected token '{}' after expression",
4265                tok.text.of(&self.source)
4266            ),
4267        ))
4268    }
4269
4270    fn enter_comparison_suffix(
4271        &mut self,
4272        left: ExprId,
4273        start_span: Span,
4274        frames: &mut Vec<ExprCont>,
4275    ) -> Result<ExprStep, Error> {
4276        let operator = self.parse_comparison_operator()?;
4277        let operator_is_not = matches!(operator, ComparisonComputation::IsNot);
4278
4279        if matches!(
4280            operator,
4281            ComparisonComputation::Is | ComparisonComputation::IsNot
4282        ) && self.at_bare_veto_token()?
4283        {
4284            self.expect(&TokenKind::Veto)?;
4285            if self.at(&TokenKind::StringLit)? {
4286                let tok = *self.peek()?;
4287                return Err(self.error_at_token(
4288                    &tok,
4289                    "veto with a message is only valid as a rule or unless result, not in `is veto` comparisons",
4290                ));
4291            }
4292            return expr_step(self.wrap_result_is_veto_expression(
4293                left,
4294                operator_is_not,
4295                false,
4296                start_span,
4297            ));
4298        }
4299
4300        let right = if self.at(&TokenKind::Not)? {
4301            ExprTask::NotExpression
4302        } else {
4303            ExprTask::Pipe
4304        };
4305        frames.push(ExprCont::ComparisonRight {
4306            left,
4307            operator,
4308            start_span,
4309        });
4310        Ok(ExprStep::Enter(right))
4311    }
4312
4313    fn enter_in_suffix(
4314        &mut self,
4315        repository: ExprId,
4316        start_span: Span,
4317        frames: &mut Vec<ExprCont>,
4318    ) -> Result<ExprStep, Error> {
4319        self.expect(&TokenKind::In)?;
4320
4321        let peeked = *self.peek()?;
4322        if peeked.kind == TokenKind::Past || peeked.kind == TokenKind::Future {
4323            let direction = self.next()?;
4324            let rel_kind = if direction.kind == TokenKind::Past {
4325                DateRelativeKind::InPast
4326            } else {
4327                DateRelativeKind::InFuture
4328            };
4329
4330            if self.at_calendar_period_marker()? {
4331                self.next_calendar_period_marker()?;
4332                let cal_kind = if direction.kind == TokenKind::Past {
4333                    DateCalendarKind::Past
4334                } else {
4335                    DateCalendarKind::Future
4336                };
4337                let unit = self.parse_calendar_unit()?;
4338                let end = self.peek()?.span;
4339                let span = self.span_covering(&start_span, &end);
4340                return expr_step(self.new_expression(
4341                    ExpressionKind::DateCalendar(cal_kind, unit, repository),
4342                    self.make_source(span),
4343                ));
4344            }
4345
4346            if self.at_any(&[TokenKind::And, TokenKind::Or])?
4347                || self.at(&TokenKind::Unless)?
4348                || self.at(&TokenKind::Then)?
4349                || self.at(&TokenKind::RParen)?
4350                || self.at(&TokenKind::Eof)?
4351                || self.at(&TokenKind::Spec)?
4352                || is_spec_body_keyword(&self.peek()?.kind)
4353                || is_comparison_operator(&self.peek()?.kind)
4354            {
4355                let end = self.peek()?.span;
4356                let span = self.span_covering(&start_span, &end);
4357                return expr_step(self.new_expression(
4358                    ExpressionKind::DateRelative(rel_kind, repository),
4359                    self.make_source(span),
4360                ));
4361            }
4362
4363            frames.push(ExprCont::InOffset {
4364                direction: direction.span,
4365                rel_kind,
4366                repository,
4367                start_span,
4368            });
4369            return Ok(ExprStep::Enter(ExprTask::RepositoryExpression));
4370        }
4371
4372        if token_is_calendar_period_marker(&self.source, &peeked) {
4373            self.next_calendar_period_marker()?;
4374            let unit = self.parse_calendar_unit()?;
4375            let end = self.peek()?.span;
4376            let span = self.span_covering(&start_span, &end);
4377            return expr_step(self.new_expression(
4378                ExpressionKind::DateCalendar(DateCalendarKind::Current, unit, repository),
4379                self.make_source(span),
4380            ));
4381        }
4382
4383        frames.push(ExprCont::InRange {
4384            repository,
4385            start_span,
4386        });
4387        Ok(ExprStep::Enter(ExprTask::RepositoryExpression))
4388    }
4389
4390    fn enter_prefix_argument(
4391        &mut self,
4392        keyword: String,
4393        frames: &mut Vec<ExprCont>,
4394    ) -> Result<ExprStep, Error> {
4395        if self.at(&TokenKind::LParen)? {
4396            return Ok(ExprStep::Enter(ExprTask::Primary));
4397        }
4398        if !self.at_bare_operand_start()? {
4399            let tok = *self.peek()?;
4400            return Err(self.error_at_token(
4401                &tok,
4402                format!(
4403                    "`{keyword}` takes one operand or `{keyword}(...)`, found '{}'",
4404                    tok.text.of(&self.source)
4405                ),
4406            ));
4407        }
4408        self.check_depth()?;
4409        frames.push(ExprCont::PrefixArgumentEnd { keyword });
4410        frames.push(ExprCont::PopDepth);
4411        Ok(ExprStep::Enter(ExprTask::RangeOperand))
4412    }
4413
4414    fn enter_primary(&mut self, frames: &mut Vec<ExprCont>) -> Result<ExprStep, Error> {
4415        let start_span = self.peek()?.span;
4416        let kind = self.peek()?.kind;
4417        match &kind {
4418            TokenKind::LParen => {
4419                self.next()?;
4420                let saved = self.save_flags();
4421                self.call_argument_depth = 0;
4422                frames.push(ExprCont::ParenEnd { start_span });
4423                frames.push(ExprCont::Restore(saved));
4424                Ok(ExprStep::Enter(ExprTask::Expression))
4425            }
4426            TokenKind::Now => {
4427                let tok = self.next()?;
4428                expr_step(self.new_expression(ExpressionKind::Now, self.make_source(tok.span)))
4429            }
4430            TokenKind::Past | TokenKind::Future => {
4431                let tok = self.next()?;
4432                let rel_kind = if tok.kind == TokenKind::Past {
4433                    DateRelativeKind::InPast
4434                } else {
4435                    DateRelativeKind::InFuture
4436                };
4437                frames.push(ExprCont::PastFuture {
4438                    kind: rel_kind,
4439                    start_span,
4440                });
4441                Ok(ExprStep::Enter(ExprTask::RepositoryExpression))
4442            }
4443            TokenKind::StringLit => {
4444                let tok = self.next()?;
4445                expr_step(self.new_expression(
4446                    ExpressionKind::Literal(Value::Text(tok.text.of(&self.source).to_string())),
4447                    self.make_source(tok.span),
4448                ))
4449            }
4450            k if is_boolean_keyword(k) => {
4451                let tok = self.next()?;
4452                expr_step(self.new_expression(
4453                    ExpressionKind::Literal(Value::Boolean(token_kind_to_boolean_value(&tok.kind))),
4454                    self.make_source(tok.span),
4455                ))
4456            }
4457            TokenKind::NumberLit => expr_step(self.parse_number_expression()),
4458            k if can_be_label(k) => {
4459                let reference = self.parse_expression_reference()?;
4460                let span = self.span_covering(&start_span, &self.last_span);
4461                let expr = self
4462                    .new_expression(ExpressionKind::Reference(reference), self.make_source(span))?;
4463                expr_step(self.wrap_list_type_suffix(expr, start_span))
4464            }
4465            k if token_kind_to_primitive(k).is_some() => {
4466                if !self.next_is_list_type_suffix()? {
4467                    let tok = self.next()?;
4468                    return Err(self.error_at_token(
4469                        &tok,
4470                        format!(
4471                            "Expected an expression, found '{}'",
4472                            tok.text.of(&self.source)
4473                        ),
4474                    ));
4475                }
4476                let parent = self.parse_expression_parent_type()?;
4477                let span = self.span_covering(&start_span, &self.last_span);
4478                expr_step(self.new_expression(
4479                    ExpressionKind::ListType { element: parent },
4480                    self.make_source(span),
4481                ))
4482            }
4483            _ => {
4484                let tok = *self.peek()?;
4485                if tok.text.of(&self.source).starts_with('@') {
4486                    return Err(self.error_at_token_with_suggestion(
4487                        &tok,
4488                        "A repository qualifier is not valid on a type or list element",
4489                        "Write `uses @repo Spec [pin]`, then `data name: Spec list` or `rule name: Spec list`.",
4490                    ));
4491                }
4492                let tok = self.next()?;
4493                Err(self.error_at_token(
4494                    &tok,
4495                    format!(
4496                        "Expected an expression, found '{}'",
4497                        tok.text.of(&self.source)
4498                    ),
4499                ))
4500            }
4501        }
4502    }
4503
4504    fn enter_list_command_body(
4505        &mut self,
4506        name: Token,
4507        frames: &mut Vec<ExprCont>,
4508    ) -> Result<ExprStep, Error> {
4509        match name.kind {
4510            TokenKind::Find => {
4511                frames.push(ExprCont::Command(CommandBuild::Find));
4512                Ok(ExprStep::Enter(ExprTask::FindKeys))
4513            }
4514            TokenKind::First => {
4515                self.reject_command_argument("first")?;
4516                Ok(ExprStep::Yield(ExprVal::Command(ListCommand::First)))
4517            }
4518            TokenKind::Last => {
4519                self.reject_command_argument("last")?;
4520                Ok(ExprStep::Yield(ExprVal::Command(ListCommand::Last)))
4521            }
4522            TokenKind::Count => {
4523                self.reject_command_argument("count")?;
4524                Ok(ExprStep::Yield(ExprVal::Command(ListCommand::Count)))
4525            }
4526            TokenKind::Sum => {
4527                frames.push(ExprCont::Command(CommandBuild::Sum));
4528                Ok(ExprStep::Enter(ExprTask::OptionalArgument {
4529                    command: "sum",
4530                }))
4531            }
4532            TokenKind::Avg => {
4533                frames.push(ExprCont::Command(CommandBuild::Avg));
4534                Ok(ExprStep::Enter(ExprTask::OptionalArgument {
4535                    command: "avg",
4536                }))
4537            }
4538            TokenKind::Product => {
4539                frames.push(ExprCont::Command(CommandBuild::Product));
4540                Ok(ExprStep::Enter(ExprTask::OptionalArgument {
4541                    command: "product",
4542                }))
4543            }
4544            TokenKind::Min => {
4545                frames.push(ExprCont::Command(CommandBuild::Min));
4546                Ok(ExprStep::Enter(ExprTask::OptionalArgument {
4547                    command: "min",
4548                }))
4549            }
4550            TokenKind::Max => {
4551                frames.push(ExprCont::Command(CommandBuild::Max));
4552                Ok(ExprStep::Enter(ExprTask::OptionalArgument {
4553                    command: "max",
4554                }))
4555            }
4556            TokenKind::Any => {
4557                frames.push(ExprCont::Command(CommandBuild::Any));
4558                Ok(ExprStep::Enter(ExprTask::ListPredicate { command: "any" }))
4559            }
4560            TokenKind::All => {
4561                frames.push(ExprCont::Command(CommandBuild::All));
4562                Ok(ExprStep::Enter(ExprTask::ListPredicate { command: "all" }))
4563            }
4564            TokenKind::Where => {
4565                frames.push(ExprCont::Command(CommandBuild::Where));
4566                Ok(ExprStep::Enter(ExprTask::ListPredicate {
4567                    command: "where",
4568                }))
4569            }
4570            TokenKind::Sort => Ok(ExprStep::Enter(ExprTask::SortCommand)),
4571            TokenKind::Top => {
4572                frames.push(ExprCont::Command(CommandBuild::Top));
4573                Ok(ExprStep::Enter(ExprTask::RequiredArgument {
4574                    command: "top",
4575                }))
4576            }
4577            TokenKind::With => {
4578                frames.push(ExprCont::Command(CommandBuild::With));
4579                Ok(ExprStep::Enter(ExprTask::ListWithCommand))
4580            }
4581            TokenKind::Key => {
4582                let mut fields = vec![self.parse_reference()?];
4583                while self.at(&TokenKind::Comma)? {
4584                    self.next()?;
4585                    fields.push(self.parse_reference()?);
4586                }
4587                Ok(ExprStep::Yield(ExprVal::Command(ListCommand::Key {
4588                    fields,
4589                })))
4590            }
4591            _ => Err(self.error_at_token(
4592                &name,
4593                format!("Unknown list command '{}'", name.text.of(&self.source)),
4594            )),
4595        }
4596    }
4597
4598    fn enter_list_predicate(
4599        &mut self,
4600        command: &'static str,
4601        frames: &mut Vec<ExprCont>,
4602    ) -> Result<ExprStep, Error> {
4603        if self.at(&TokenKind::LParen)? {
4604            return Ok(ExprStep::Enter(ExprTask::CallListPredicate { command }));
4605        }
4606        if self.at_row_condition_operator()? {
4607            let op = self.parse_row_condition_operator()?;
4608            frames.push(ExprCont::PredicateValueRight { op, command });
4609            return Ok(ExprStep::Enter(ExprTask::BareOperand));
4610        }
4611        if !self.at_bare_operand_start()? {
4612            let tok = *self.peek()?;
4613            return Err(self.error_at_token(
4614                &tok,
4615                format!("`{command}` needs a condition; write `{command}(...)`"),
4616            ));
4617        }
4618        let start_span = self.peek()?.span;
4619        frames.push(ExprCont::PredicateLeft {
4620            start_span,
4621            command,
4622        });
4623        Ok(ExprStep::Enter(ExprTask::BareOperand))
4624    }
4625
4626    fn starts_value_predicate(&mut self) -> Result<bool, Error> {
4627        let checkpoint = self.checkpoint();
4628        while self.at(&TokenKind::LParen)? {
4629            self.next()?;
4630        }
4631        let result = self.at_row_condition_operator();
4632        self.restore(checkpoint);
4633        result
4634    }
4635
4636    fn enter_value_predicate_factor(
4637        &mut self,
4638        command: &'static str,
4639        frames: &mut Vec<ExprCont>,
4640    ) -> Result<ExprStep, Error> {
4641        if self.at(&TokenKind::LParen)? {
4642            self.next()?;
4643            self.check_depth()?;
4644            frames.push(ExprCont::ValuePredicateGroupEnd);
4645            frames.push(ExprCont::PopDepth);
4646            return Ok(ExprStep::Enter(ExprTask::ValuePredicate {
4647                command,
4648                connective: LogicalConnective::Or,
4649            }));
4650        }
4651        if !self.at_row_condition_operator()? {
4652            let token = *self.peek()?;
4653            return Err(self.error_at_token(
4654                &token,
4655                format!(
4656                    "value-list `{command}` predicates require a headless comparison, found '{}'",
4657                    token.text.of(&self.source)
4658                ),
4659            ));
4660        }
4661        let start = self.peek()?.span;
4662        let op = self.parse_row_condition_operator()?;
4663        frames.push(ExprCont::ValuePredicateLeaf { op, start });
4664        Ok(ExprStep::Enter(ExprTask::RepositoryExpression))
4665    }
4666
4667    fn predicate_instance_end(
4668        &mut self,
4669        expr: ExprId,
4670        command: &'static str,
4671    ) -> Result<ExprStep, Error> {
4672        if !self.at_bare_argument_end()? {
4673            return Err(self.condition_error(command));
4674        }
4675        Ok(ExprStep::Yield(ExprVal::Predicate(
4676            ListPredicate::Instance { expr },
4677        )))
4678    }
4679
4680    fn enter_pair_field(
4681        &mut self,
4682        pairs: Vec<(Reference, ExprId)>,
4683        frames: &mut Vec<ExprCont>,
4684    ) -> Result<ExprStep, Error> {
4685        let path = self.parse_reference()?;
4686        self.expect(&TokenKind::Colon)?;
4687        frames.push(ExprCont::PairValue { path, pairs });
4688        Ok(ExprStep::Enter(ExprTask::BareArgument { command: "with" }))
4689    }
4690
4691    fn pair_value_next(
4692        &mut self,
4693        pairs: Vec<(Reference, ExprId)>,
4694        frames: &mut Vec<ExprCont>,
4695    ) -> Result<ExprStep, Error> {
4696        if !self.at(&TokenKind::Comma)? {
4697            return Ok(ExprStep::Yield(ExprVal::Rows(ListWithRows::FieldPairs(
4698                pairs,
4699            ))));
4700        }
4701        self.next()?;
4702        if !self.at_path_then_colon()? {
4703            let tok = *self.peek()?;
4704            return Err(self.error_at_token_with_suggestion(
4705                &tok,
4706                "Expected a field pair after comma".to_string(),
4707                "Remove the extra comma, or add `field: value`",
4708            ));
4709        }
4710        self.enter_pair_field(pairs, frames)
4711    }
4712
4713    fn value_item_next(
4714        &mut self,
4715        values: Vec<ExprId>,
4716        frames: &mut Vec<ExprCont>,
4717    ) -> Result<ExprStep, Error> {
4718        if !self.at(&TokenKind::Comma)? {
4719            return Ok(ExprStep::Yield(ExprVal::Rows(ListWithRows::Values(values))));
4720        }
4721        self.next()?;
4722        if self.at_expression_suffix_end()? || self.at(&TokenKind::Comma)? {
4723            let tok = *self.peek()?;
4724            return Err(self.error_at_token_with_suggestion(
4725                &tok,
4726                "Trailing or empty comma in list".to_string(),
4727                "Remove the extra comma, or add the missing value",
4728            ));
4729        }
4730        frames.push(ExprCont::ValueItem { values });
4731        Ok(ExprStep::Enter(ExprTask::BareArgument { command: "with" }))
4732    }
4733
4734    fn find_key_next(
4735        &mut self,
4736        keys: Vec<ExprId>,
4737        frames: &mut Vec<ExprCont>,
4738    ) -> Result<ExprStep, Error> {
4739        if self.at(&TokenKind::Comma)? && self.call_argument_depth == 0 {
4740            self.next()?;
4741            frames.push(ExprCont::FindKey { keys });
4742            return Ok(ExprStep::Enter(ExprTask::BareArgument { command: "find" }));
4743        }
4744        Ok(ExprStep::Yield(ExprVal::Exprs(keys)))
4745    }
4746
4747    fn call_argument_items(
4748        &mut self,
4749        arguments: Vec<ExprId>,
4750        frames: &mut Vec<ExprCont>,
4751    ) -> Result<ExprStep, Error> {
4752        if self.at(&TokenKind::Comma)? {
4753            self.next()?;
4754            frames.push(ExprCont::CallArgumentItems { arguments });
4755            return Ok(ExprStep::Enter(ExprTask::Expression));
4756        }
4757        Ok(ExprStep::Yield(ExprVal::Exprs(arguments)))
4758    }
4759
4760    fn repository_chain(
4761        &mut self,
4762        first: ExprId,
4763        steps: Vec<ChainStep<ArithmeticComputation>>,
4764        start_span: Span,
4765        frames: &mut Vec<ExprCont>,
4766    ) -> Result<ExprStep, Error> {
4767        if !self.at_any(&[TokenKind::Plus, TokenKind::Minus])? {
4768            return expr_step(self.arithmetic_chain(first, steps));
4769        }
4770        let op_tok = self.next()?;
4771        let operation = match op_tok.kind {
4772            TokenKind::Plus => ArithmeticComputation::Add,
4773            TokenKind::Minus => ArithmeticComputation::Subtract,
4774            _ => unreachable!("BUG: only + and - should reach here"),
4775        };
4776        frames.push(ExprCont::RepositoryOperand {
4777            first,
4778            steps,
4779            start_span,
4780            operation,
4781        });
4782        Ok(ExprStep::Enter(ExprTask::Term { allow_as: true }))
4783    }
4784
4785    fn term_chain(
4786        &mut self,
4787        first: ExprId,
4788        steps: Vec<ChainStep<ArithmeticComputation>>,
4789        allow_as: bool,
4790        start_span: Span,
4791        frames: &mut Vec<ExprCont>,
4792    ) -> Result<ExprStep, Error> {
4793        if self.at(&TokenKind::Percent)? {
4794            let pct_tok = self.next()?;
4795            return Err(self.error_at_token(
4796                &pct_tok,
4797                "'%' is percent only; use 'mod' for remainder (e.g. 'value mod 7')",
4798            ));
4799        }
4800        if !self.at_any(&[TokenKind::Star, TokenKind::Slash, TokenKind::Mod])? {
4801            return expr_step(self.arithmetic_chain(first, steps));
4802        }
4803        let op_tok = self.next()?;
4804        let operation = match op_tok.kind {
4805            TokenKind::Star => ArithmeticComputation::Multiply,
4806            TokenKind::Slash => ArithmeticComputation::Divide,
4807            TokenKind::Mod => ArithmeticComputation::Modulo,
4808            _ => unreachable!("BUG: only *, /, mod should reach here"),
4809        };
4810        let right_start_span = self.peek()?.span;
4811        frames.push(ExprCont::TermOperand {
4812            first,
4813            steps,
4814            allow_as,
4815            start_span,
4816            operation,
4817            right_start_span,
4818        });
4819        Ok(ExprStep::Enter(ExprTask::Power))
4820    }
4821
4822    fn power_tail(
4823        &mut self,
4824        left: ExprId,
4825        start_span: Span,
4826        range_bound: bool,
4827        frames: &mut Vec<ExprCont>,
4828    ) -> Result<ExprStep, Error> {
4829        if !self.at(&TokenKind::Caret)? {
4830            return Ok(ExprStep::Yield(ExprVal::Expr(left)));
4831        }
4832        self.next()?;
4833        self.check_depth()?;
4834        frames.push(ExprCont::PowerRight { left, start_span });
4835        frames.push(ExprCont::PopDepth);
4836        Ok(ExprStep::Enter(if range_bound {
4837            ExprTask::PowerForRangeBound
4838        } else {
4839            ExprTask::Power
4840        }))
4841    }
4842
4843    fn ellipsis_chain(
4844        &mut self,
4845        first: ExprId,
4846        steps: Vec<ChainStep<ArithmeticComputation>>,
4847        start_span: Span,
4848        mut starts: Vec<usize>,
4849        frames: &mut Vec<ExprCont>,
4850    ) -> Result<ExprStep, Error> {
4851        if !self.at_any(&[TokenKind::Plus, TokenKind::Minus])? {
4852            self.bound_chain_starts = starts;
4853            return expr_step(self.arithmetic_chain(first, steps));
4854        }
4855        let op_tok = self.next()?;
4856        let operation = match op_tok.kind {
4857            TokenKind::Plus => ArithmeticComputation::Add,
4858            TokenKind::Minus => ArithmeticComputation::Subtract,
4859            _ => unreachable!("BUG: only + and - should reach here"),
4860        };
4861        starts.push(self.peek()?.span.start);
4862        frames.push(ExprCont::EllipsisOperand {
4863            first,
4864            steps,
4865            start_span,
4866            operation,
4867            starts,
4868        });
4869        Ok(ExprStep::Enter(ExprTask::PowerForRangeBound))
4870    }
4871}
4872
4873/// Expression grammar state saved and restored around nested parses.
4874#[derive(Clone, Copy, PartialEq, Eq)]
4875struct ExprFlags {
4876    call_argument_depth: usize,
4877}
4878
4879/// Which operand grammar a logical chain continues with.
4880#[derive(Clone, Copy)]
4881enum LogicalChainKind {
4882    Expression,
4883    ValuePredicate { command: &'static str },
4884}
4885
4886fn logical_operand_task(connective: LogicalConnective, kind: LogicalChainKind) -> ExprTask {
4887    match kind {
4888        LogicalChainKind::Expression => match connective {
4889            LogicalConnective::And => ExprTask::LogicalOperand,
4890            LogicalConnective::Or => ExprTask::LogicalExpression {
4891                connective: LogicalConnective::And,
4892            },
4893        },
4894        LogicalChainKind::ValuePredicate { command } => match connective {
4895            LogicalConnective::And => ExprTask::ValuePredicateFactor { command },
4896            LogicalConnective::Or => ExprTask::ValuePredicate {
4897                command,
4898                connective: LogicalConnective::And,
4899            },
4900        },
4901    }
4902}
4903
4904/// A grammar nonterminal the expression machine can enter.
4905enum ExprTask {
4906    Expression,
4907    LogicalExpression {
4908        connective: LogicalConnective,
4909    },
4910    LogicalOperand,
4911    VetoStatus,
4912    NotExpression,
4913    RepositoryWithSuffix,
4914    ComparisonSuffix {
4915        left: ExprId,
4916        start_span: Span,
4917    },
4918    InSuffix {
4919        repository: ExprId,
4920        start_span: Span,
4921    },
4922    /// Comparison operand: an arithmetic expression followed by any `->` commands.
4923    Pipe,
4924    RepositoryExpression,
4925    Term {
4926        allow_as: bool,
4927    },
4928    Power,
4929    RangeOperand,
4930    RangeEllipsisBound,
4931    PowerForRangeBound,
4932    Factor,
4933    PrimaryOrMath,
4934    /// Prefix `round` / `floor` / `ceil`: parse the operand, then reject with a rewrite.
4935    PrefixRoundingRejected,
4936    MathFunction,
4937    LowerUpper,
4938    PrefixArgument {
4939        keyword: String,
4940    },
4941    Primary,
4942    ListCommandSuffix {
4943        list: ExprId,
4944        start_span: Span,
4945    },
4946    ListCommandBody {
4947        name: Token,
4948    },
4949    FindKeys,
4950    CallArguments {
4951        command: &'static str,
4952    },
4953    SingleCallArgument {
4954        command: &'static str,
4955    },
4956    OptionalArgument {
4957        command: &'static str,
4958    },
4959    RequiredArgument {
4960        command: &'static str,
4961    },
4962    BareArgument {
4963        command: &'static str,
4964    },
4965    BareOperand,
4966    ListPredicate {
4967        command: &'static str,
4968    },
4969    CallListPredicate {
4970        command: &'static str,
4971    },
4972    ValuePredicate {
4973        command: &'static str,
4974        connective: LogicalConnective,
4975    },
4976    ValuePredicateFactor {
4977        command: &'static str,
4978    },
4979    SortCommand,
4980    ListWithCommand,
4981    ListWithRows,
4982}
4983
4984/// Command whose argument values are collected before the `ListCommand` is built.
4985#[derive(Clone, Copy)]
4986enum CommandBuild {
4987    Find,
4988    Sum,
4989    Avg,
4990    Product,
4991    Min,
4992    Max,
4993    Any,
4994    All,
4995    Where,
4996    Top,
4997    With,
4998}
4999
5000/// Continuation: what to do with the value a nested nonterminal yields.
5001enum ExprCont {
5002    Restore(ExprFlags),
5003    PopDepth,
5004    LogicalFirst {
5005        connective: LogicalConnective,
5006        start_span: Span,
5007        kind: LogicalChainKind,
5008    },
5009    LogicalOperand {
5010        connective: LogicalConnective,
5011        first: ExprId,
5012        steps: Vec<ChainStep<()>>,
5013        start_span: Span,
5014        kind: LogicalChainKind,
5015    },
5016    VetoStatus {
5017        operator_is_not: bool,
5018        keyword_was_negated: bool,
5019        start_span: Span,
5020    },
5021    Negation {
5022        start_span: Span,
5023    },
5024    RepositorySuffix {
5025        start_span: Span,
5026    },
5027    ContinueRepository {
5028        start_span: Span,
5029    },
5030    ComparisonRight {
5031        left: ExprId,
5032        operator: ComparisonComputation,
5033        start_span: Span,
5034    },
5035    InOffset {
5036        direction: Span,
5037        rel_kind: DateRelativeKind,
5038        repository: ExprId,
5039        start_span: Span,
5040    },
5041    InRange {
5042        repository: ExprId,
5043        start_span: Span,
5044    },
5045    RepositoryFirst {
5046        start_span: Span,
5047    },
5048    RepositoryOperand {
5049        first: ExprId,
5050        steps: Vec<ChainStep<ArithmeticComputation>>,
5051        start_span: Span,
5052        operation: ArithmeticComputation,
5053    },
5054    TermFirst {
5055        allow_as: bool,
5056        start_span: Span,
5057    },
5058    TermOperand {
5059        first: ExprId,
5060        steps: Vec<ChainStep<ArithmeticComputation>>,
5061        allow_as: bool,
5062        start_span: Span,
5063        operation: ArithmeticComputation,
5064        right_start_span: Span,
5065    },
5066    PowerLeft {
5067        start_span: Span,
5068        range_bound: bool,
5069    },
5070    PowerRight {
5071        left: ExprId,
5072        start_span: Span,
5073    },
5074    /// Factor of a range operand is parsed; a range bound may continue it.
5075    RangeFactor {
5076        start_span: Span,
5077        flags: ExprFlags,
5078    },
5079    /// Bound continuing `factor` is parsed speculatively from `checkpoint`, taken right after
5080    /// `factor`. Without a following `...` the parser rewinds there and yields `factor`.
5081    RangeLeft {
5082        factor: ExprId,
5083        start_span: Span,
5084        checkpoint: Box<ParserCheckpoint>,
5085        flags: ExprFlags,
5086    },
5087    RangeRight {
5088        left: ExprId,
5089        start_span: Span,
5090    },
5091    EllipsisFirst {
5092        start_span: Span,
5093    },
5094    EllipsisOperand {
5095        first: ExprId,
5096        steps: Vec<ChainStep<ArithmeticComputation>>,
5097        start_span: Span,
5098        operation: ArithmeticComputation,
5099        starts: Vec<usize>,
5100    },
5101    FactorNegate {
5102        start_span: Span,
5103    },
5104    /// Arithmetic operand of a `->` chain is parsed; commands may follow.
5105    PipeFirst {
5106        start_span: Span,
5107    },
5108    /// A list command was applied; more commands may follow.
5109    PipeCommand {
5110        start_span: Span,
5111    },
5112    StepRoundingDone {
5113        operand: ExprId,
5114        mode: RoundingMode,
5115        start_span: Span,
5116    },
5117    ListCommandDone {
5118        list: ExprId,
5119        start_span: Span,
5120    },
5121    Command(CommandBuild),
5122    FindKey {
5123        keys: Vec<ExprId>,
5124    },
5125    CallArgumentsEnd {
5126        command: &'static str,
5127    },
5128    CallArgumentItems {
5129        arguments: Vec<ExprId>,
5130    },
5131    SingleCallArgumentCheck {
5132        command: &'static str,
5133    },
5134    WrapSome,
5135    BareArgumentEnd {
5136        command: &'static str,
5137    },
5138    ParenEnd {
5139        start_span: Span,
5140    },
5141    PastFuture {
5142        kind: DateRelativeKind,
5143        start_span: Span,
5144    },
5145    Math {
5146        operator: MathematicalComputation,
5147        start_span: Span,
5148    },
5149    PrefixRoundingRejected {
5150        keyword: String,
5151        keyword_span: Span,
5152    },
5153    LowerUpperEnd {
5154        bound: RangeBound,
5155        start_span: Span,
5156    },
5157    PrefixArgumentEnd {
5158        keyword: String,
5159    },
5160    PredicateValueRight {
5161        op: RowCondition,
5162        command: &'static str,
5163    },
5164    PredicateLeft {
5165        start_span: Span,
5166        command: &'static str,
5167    },
5168    PredicateRight {
5169        left: ExprId,
5170        op: RowCondition,
5171        start_span: Span,
5172        command: &'static str,
5173    },
5174    ValuePredicateCallEnd {
5175        command: &'static str,
5176    },
5177    ValuePredicateGroupEnd,
5178    ValuePredicateLeaf {
5179        op: RowCondition,
5180        start: Span,
5181    },
5182    WrapInstance,
5183    SortArgument {
5184        check_bare: bool,
5185    },
5186    ListWithEnd,
5187    PairValue {
5188        path: Reference,
5189        pairs: Vec<(Reference, ExprId)>,
5190    },
5191    ValueItem {
5192        values: Vec<ExprId>,
5193    },
5194}
5195
5196/// Value a finished nonterminal yields to its continuation.
5197enum ExprVal {
5198    Expr(ExprId),
5199    Optional(Option<ExprId>),
5200    Exprs(Vec<ExprId>),
5201    Command(ListCommand),
5202    Predicate(ListPredicate),
5203    Rows(ListWithRows),
5204}
5205
5206enum ExprStep {
5207    Enter(ExprTask),
5208    Yield(ExprVal),
5209}
5210
5211fn expr_of(value: ExprVal) -> ExprId {
5212    match value {
5213        ExprVal::Expr(expr) => expr,
5214        _ => panic!("BUG: expression machine expected an expression value"),
5215    }
5216}
5217
5218fn optional_of(value: ExprVal) -> Option<ExprId> {
5219    match value {
5220        ExprVal::Optional(argument) => argument,
5221        _ => panic!("BUG: expression machine expected an optional argument"),
5222    }
5223}
5224
5225fn exprs_of(value: ExprVal) -> Vec<ExprId> {
5226    match value {
5227        ExprVal::Exprs(exprs) => exprs,
5228        _ => panic!("BUG: expression machine expected an argument list"),
5229    }
5230}
5231
5232fn predicate_of(value: ExprVal) -> ListPredicate {
5233    match value {
5234        ExprVal::Predicate(predicate) => predicate,
5235        _ => panic!("BUG: expression machine expected a list predicate"),
5236    }
5237}
5238
5239fn rows_of(value: ExprVal) -> ListWithRows {
5240    match value {
5241        ExprVal::Rows(rows) => rows,
5242        _ => panic!("BUG: expression machine expected list rows"),
5243    }
5244}
5245
5246fn command_of(value: ExprVal) -> ListCommand {
5247    match value {
5248        ExprVal::Command(command) => command,
5249        _ => panic!("BUG: expression machine expected a list command"),
5250    }
5251}
5252
5253fn expr_step(result: Result<ExprId, Error>) -> Result<ExprStep, Error> {
5254    result.map(|expr| ExprStep::Yield(ExprVal::Expr(expr)))
5255}
5256
5257fn build_command(builder: CommandBuild, value: ExprVal) -> ListCommand {
5258    match builder {
5259        CommandBuild::Find => ListCommand::Find {
5260            keys: exprs_of(value),
5261        },
5262        CommandBuild::Sum => ListCommand::Sum {
5263            argument: optional_of(value),
5264        },
5265        CommandBuild::Avg => ListCommand::Avg {
5266            argument: optional_of(value),
5267        },
5268        CommandBuild::Product => ListCommand::Product {
5269            argument: optional_of(value),
5270        },
5271        CommandBuild::Min => ListCommand::Min {
5272            argument: optional_of(value),
5273        },
5274        CommandBuild::Max => ListCommand::Max {
5275            argument: optional_of(value),
5276        },
5277        CommandBuild::Any => ListCommand::Any {
5278            form: predicate_of(value),
5279        },
5280        CommandBuild::All => ListCommand::All {
5281            form: predicate_of(value),
5282        },
5283        CommandBuild::Where => ListCommand::Where {
5284            form: predicate_of(value),
5285        },
5286        CommandBuild::Top => ListCommand::Top { n: expr_of(value) },
5287        CommandBuild::With => ListCommand::With {
5288            rows: rows_of(value),
5289        },
5290    }
5291}
5292
5293/// `uses x -> with f: v` inside `spec x` is what `x` writes on its own rows
5294/// ([`DataValue::OwnRows`]); any other value is itself.
5295fn own_rows_value(spec: &str, reference: &Reference, value: DataValue) -> DataValue {
5296    match value {
5297        DataValue::Import {
5298            spec_ref,
5299            bindings,
5300            effective_ref: None,
5301            global: false,
5302        } if !bindings.is_empty()
5303            && spec_ref.repository.is_none()
5304            && spec_ref.effective.is_none()
5305            && spec_ref.name.eq_ignore_ascii_case(spec)
5306            && reference.is_local()
5307            && reference.name.eq_ignore_ascii_case(spec) =>
5308        {
5309            DataValue::OwnRows { spec_ref, bindings }
5310        }
5311        other => other,
5312    }
5313}
5314
5315fn parent_type_from_reference(reference: &Reference) -> ParentType {
5316    if reference.segments.is_empty() {
5317        return ParentType::custom(reference.name.clone());
5318    }
5319    if reference.segments.len() == 1 {
5320        return ParentType::Qualified {
5321            spec_alias: reference.segments[0].clone(),
5322            inner: Box::new(ParentType::custom(reference.name.clone())),
5323        };
5324    }
5325    ParentType::Qualified {
5326        spec_alias: reference.segments[0].clone(),
5327        inner: Box::new(ParentType::custom(reference.name.clone())),
5328    }
5329}
5330
5331// ============================================================================
5332// Helper functions
5333// ============================================================================
5334
5335fn parse_decimal_string(text: &str, span: &Span, parser: &Parser) -> Result<Decimal, Error> {
5336    text.parse::<crate::literals::NumberLiteral>()
5337        .map(|parsed| parsed.0)
5338        .map_err(|message| Error::parsing(message, parser.make_source(*span), None::<String>))
5339}
5340
5341/// Negate a numeric literal value. Returns `Err(value)` when the value is not a number.
5342fn try_negate_numeric_literal(value: Value) -> Result<Value, Value> {
5343    match value {
5344        Value::Number(d) => Ok(Value::Number(-d)),
5345        Value::NumberWithUnit(d, unit) => Ok(Value::NumberWithUnit(-d, unit)),
5346        other => Err(other),
5347    }
5348}
5349
5350fn is_comparison_operator(kind: &TokenKind) -> bool {
5351    matches!(
5352        kind,
5353        TokenKind::Gt | TokenKind::Lt | TokenKind::Gte | TokenKind::Lte | TokenKind::Is
5354    )
5355}