Skip to main content

ridl_syntax/
parser.rs

1//! The hand-written recursive-descent parser for the typl grammar
2//! (ADR-0004 §2, typl reference Appendix E).
3//!
4//! The parser consumes the flat token stream from [`crate::lex`] and builds a
5//! lossless rowan tree whose nodes match `family.ungram` exactly: every token —
6//! including whitespace and comments — lands in the tree in source order, so
7//! [`Parse::syntax`] round-trips back to the original source for both valid
8//! and broken input. On an unexpected token the parser records a
9//! [`SyntaxError`] and wraps the skipped tokens in an
10//! [`ErrorNode`](SyntaxKind::ErrorNode) rather than dropping them, so recovery
11//! never loses text and never panics.
12//!
13//! Trivia placement: leading trivia — including doc comments — is flushed at
14//! the parent level before a child node starts, so a doc comment sits as a
15//! sibling immediately before the definition it documents
16//! (`ast::HasDocComments` reads it from there).
17//!
18//! # The `[a..b]` bound policy
19//!
20//! `[3..6]` has two legal tree shapes: a pair of scalar `Literal` children
21//! (a value range) or a `Bound` child (a length bound). The parser emits a
22//! `Bound` iff the constraint attaches to a `string`/`bytes` backing and both
23//! endpoints are integer-shaped (no float token); it emits scalar `Literal`s
24//! otherwise — including when a `step` clause follows, which only the scalar
25//! shape can carry. A single literal with no `..` (`[17]`) is always a
26//! `Bound`; a float endpoint is always scalar.
27//!
28//! # Grammar over-approximations
29//!
30//! The grammar deliberately accepts more than the typl reference allows —
31//! constraints on any primitive in field position, arbitrary map key types,
32//! identifier literals in value positions, `step` on open ranges, non-integer
33//! literals in bounds and reserved entries, repeated separator commas with no
34//! member between them (`,,,`), and the `internal`/`error` modifiers on every
35//! definition kind. The checker narrows these later (TYPL-2xx); the parser
36//! must not reject them.
37//!
38//! The interaction grammar follows the same discipline: a `: return_type`
39//! after a command's params parses; timing parses on command, query, and
40//! fixed; an attr block parses on signal, event, and fixed; an init value
41//! parses on event and fixed; a stream `<T>` parses in every type position,
42//! including signal/event payloads and struct fields; a typl definition inside
43//! an interface body whose `}` still lies ahead recovers into one body-local
44//! `ErrorNode` and draws **RIDL-107** here, where the keyword is recognised,
45//! while a body with no `}` ahead reports an unclosed `{` and keeps the
46//! declarations that follow it. The other rejections are checker scope (RIDL-104/-106/-201/-301).
47//!
48//! # Profile boundary
49//!
50//! The parser runs under a [`Profile`] (ADR-0007 decision 10). In a `.typl`
51//! parse, a `Duration` token or a stray `@` anywhere emits **TYPL-302** (typl
52//! reference §2.8) and parsing continues, an interaction keyword at
53//! declaration-start position emits **TYPL-304**, and a `require`/`ensure`
54//! attribute emits **TYPL-303** with the same recovery. In a `.ridl` parse durations and `@` are ordinary tokens,
55//! and a `ReservedWord` at declaration-start position — a word of the
56//! rmdl/rsdl profiles, or a ridl clause word — emits **RIDL-403** (ridl
57//! reference §16.4). In a
58//! `.rsdl` parse a declaration of another profile at declaration-start position
59//! — a typl definition, `interface`, `service`, or any other `ReservedWord` —
60//! emits **RSDL-604** (rsdl reference §2), and an `internal` or `error`
61//! modifier before an rsdl declaration emits FORM-102. The typl and ridl
62//! declaration-start boundaries recover exactly as FORM-105 does; the rsdl one
63//! consumes a `{ … }` body whole. The stream grammar parses under both
64//! profiles: a `<T>` in type position builds a `StreamType` node everywhere,
65//! and in a `.typl` parse it additionally emits **TYPL-301** (`stream type in
66//! typl context`) and parsing continues. Leading zeros in an integer literal
67//! emit **FORM-005**. Every [`SyntaxError`] carries its diagnostic code; the
68//! coded `Diagnostic` model consumes it.
69//!
70//! # Error recovery
71//!
72//! A broken declaration does not derail the rest of the file. When a loop
73//! meets a token it cannot place, it reports one diagnostic and skips forward,
74//! wrapping the skipped run in a single [`ErrorNode`](SyntaxKind::ErrorNode),
75//! until it reaches a resynchronization point: a top-level keyword (`type`,
76//! `const`, `struct`, and the other definition starters) or a closing `}` (a
77//! tuple loop also stops at its `)`). A block body that runs into a top-level
78//! keyword treats its `{` as unclosed (FORM-103) and hands the keyword back to
79//! the top level rather than swallowing the next declaration. A family reserved
80//! word where a declared name is expected is held in an `ErrorNode` and flagged
81//! FORM-105, so the rest of the declaration still parses. Every [`SyntaxError`]
82//! carries the narrowest honest range — the offending token — while the
83//! `ErrorNode` carries the wider skipped span.
84//!
85//! # One diagnostic per source position
86//!
87//! [`Parser::expect`] never consumes on a mismatch, so a stuck cursor could
88//! otherwise re-report at the same offset on every unwind step — a closed
89//! 200-level type nesting once produced over a thousand diagnostics piled on a
90//! single token. The parser records at most one [`SyntaxError`] per token start
91//! offset. Because the cursor only ever moves forward,
92//! [`Parser::error_at_current`] suppressing an error at the offset the previous
93//! error already used is exactly "one diagnostic per source position". A run of
94//! garbage therefore collapses to one diagnostic plus one `ErrorNode`, and the
95//! pathological nesting inputs report a small, constant number of diagnostics
96//! instead of one per unwound level.
97//!
98//! The profile-boundary **TYPL-302** is the one exception: a positional
99//! FORM-101 can land on a duration or `@` token first (`[0..10ms]` fails the
100//! `]` check at `10ms`), and the profile-boundary fact is the higher-value
101//! diagnostic, so both are recorded. A TYPL-302 token is always consumed where
102//! it is raised, so exempting it can never re-introduce a flood.
103
104use rowan::{GreenNode, GreenNodeBuilder, TextRange, TextSize};
105
106use crate::keywords::{self, Profile};
107use crate::lexer::{Token, lex};
108use crate::syntax_kind::{SyntaxKind, SyntaxNode};
109
110/// A parse diagnostic: a message, the stable diagnostic code it will carry in
111/// the coded model (`FORM-…` per ADR-0007 decision 2, `TYPL-302` per typl
112/// reference §16.4), and the source range of the offending token.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct SyntaxError {
115    pub message: String,
116    pub code: &'static str,
117    pub range: TextRange,
118}
119
120/// The result of [`parse`]: the lossless green tree plus any diagnostics.
121///
122/// [`Parse`] compares by the identity of its green tree, which is what the
123/// salsa query graph needs to decide whether a reparse changed
124/// anything downstream.
125#[derive(Debug, Clone)]
126pub struct Parse {
127    green: GreenNode,
128    errors: Vec<SyntaxError>,
129}
130
131impl Parse {
132    /// A fresh red-tree root over the parsed green tree.
133    pub fn syntax(&self) -> SyntaxNode {
134        SyntaxNode::new_root(self.green.clone())
135    }
136
137    /// The diagnostics gathered while parsing, in source order.
138    pub fn errors(&self) -> &[SyntaxError] {
139        &self.errors
140    }
141}
142
143impl PartialEq for Parse {
144    fn eq(&self, other: &Self) -> bool {
145        self.green == other.green
146    }
147}
148
149impl Eq for Parse {}
150
151/// Parses `input` into a lossless [`Parse`] under `profile`.
152pub fn parse(input: &str, profile: Profile) -> Parse {
153    let mut parser = Parser::new(lex(input, profile), profile);
154    parser.source_file();
155    parser.finish()
156}
157
158/// Whether `kind` can be the value token of a `Literal` (`family.ungram` rule
159/// `Literal`, minus the optional leading `-`).
160fn is_value_token(kind: SyntaxKind) -> bool {
161    matches!(
162        kind,
163        SyntaxKind::IntNumber
164            | SyntaxKind::FloatNumber
165            | SyntaxKind::String
166            | SyntaxKind::TrueKw
167            | SyntaxKind::FalseKw
168            | SyntaxKind::Regex
169            | SyntaxKind::Ident
170    )
171}
172
173/// Names the literal shape a `reserved` tombstone refused, for the FORM-102
174/// message. `kind` is a value token other than `IntNumber` — the one shape
175/// typl Appendix E admits after `reserved` alongside a name.
176fn ungrammatical_reserved_noun(kind: SyntaxKind) -> &'static str {
177    match kind {
178        SyntaxKind::FloatNumber => "a floating-point literal",
179        SyntaxKind::String => "a string literal",
180        SyntaxKind::TrueKw | SyntaxKind::FalseKw => "a boolean literal",
181        SyntaxKind::Regex => "a regex literal",
182        SyntaxKind::Ident => "a constant reference",
183        _ => "a literal of that shape",
184    }
185}
186
187/// Whether `kind` starts a top-level construct. These are the
188/// resynchronization points recovery falls back to, both at the file level
189/// and when a block body runs past an unclosed `}` into the next declaration.
190/// `interface` joins the set under the ridl profile; under [`Profile::Typl`] it never
191/// occurs (the word lexes to `ReservedWord` there). The four top-level rsdl
192/// declaration keywords join it with the rsdl grammar; they occur only under
193/// [`Profile::Rsdl`]. `machine` is not among them: a machine is declared only
194/// inside a deployment body (rsdl reference Appendix B).
195fn is_top_level_start(kind: SyntaxKind) -> bool {
196    matches!(
197        kind,
198        SyntaxKind::PackageKw
199            | SyntaxKind::ImportKw
200            | SyntaxKind::InternalKw
201            | SyntaxKind::ErrorKw
202            | SyntaxKind::TypeKw
203            | SyntaxKind::ConstKw
204            | SyntaxKind::StructKw
205            | SyntaxKind::EnumKw
206            | SyntaxKind::EnumsetKw
207            | SyntaxKind::UnionKw
208            | SyntaxKind::InterfaceKw
209            | SyntaxKind::ServiceKw
210            | SyntaxKind::SystemKw
211            | SyntaxKind::ComponentKw
212            | SyntaxKind::DistributionKw
213            | SyntaxKind::DeploymentKw
214    )
215}
216
217/// Whether `kind` starts an rsdl declaration, `machine` included — what an
218/// `internal` or `error` modifier in an `.rsdl` file is refused in front of
219/// (FORM-102, rsdl reference §2).
220fn is_rsdl_declaration_start(kind: SyntaxKind) -> bool {
221    matches!(
222        kind,
223        SyntaxKind::SystemKw
224            | SyntaxKind::ComponentKw
225            | SyntaxKind::DistributionKw
226            | SyntaxKind::DeploymentKw
227            | SyntaxKind::MachineKw
228    )
229}
230
231/// The three body kinds of the rsdl containers (rsdl reference §3, §4): what
232/// starts a line, what parses it, and how the body is named in a diagnostic.
233#[derive(Clone, Copy, PartialEq, Eq)]
234enum RsdlBody {
235    /// A `system`, `distribution` or `machine` body: bare member lines.
236    Members,
237    /// A `component` body: `offers` and `requires` lines.
238    ComponentLines,
239    /// A `deployment` body: `machine` declarations.
240    Machines,
241}
242
243impl RsdlBody {
244    fn starts_line(self, kind: SyntaxKind) -> bool {
245        match self {
246            // A reference starts like a `QualifiedName` ([`Parser::at_path_segment`]).
247            Self::Members => matches!(
248                kind,
249                SyntaxKind::Ident
250                    | SyntaxKind::BooleanKw
251                    | SyntaxKind::IntegerKw
252                    | SyntaxKind::FloatKw
253                    | SyntaxKind::StringKw
254                    | SyntaxKind::BytesKw
255            ),
256            Self::ComponentLines => matches!(kind, SyntaxKind::OffersKw | SyntaxKind::RequiresKw),
257            Self::Machines => kind == SyntaxKind::MachineKw,
258        }
259    }
260}
261
262/// The RSDL-604 message for a declaration of another profile at the top level
263/// of an `.rsdl` file, naming the word that starts it (rsdl reference §2).
264fn rsdl_foreign_declaration_message(word: &str) -> String {
265    format!(
266        "`{word}` starts a declaration of another profile, and an `.rsdl` file declares \
267         `system`, `component`, `distribution` and `deployment` only — a type is declared in \
268         a `.typl` file, an interface or a service in a `.ridl` file (rsdl reference §2)"
269    )
270}
271
272/// Whether `kind` starts an interaction inside an interface body — the five
273/// interaction keywords. They join the recovery sync set inside
274/// interface bodies, so garbage resynchronizes at the next interaction.
275fn is_interaction_start(kind: SyntaxKind) -> bool {
276    matches!(
277        kind,
278        SyntaxKind::SignalKw
279            | SyntaxKind::EventKw
280            | SyntaxKind::CommandKw
281            | SyntaxKind::QueryKw
282            | SyntaxKind::FixedKw
283    )
284}
285
286/// Where recovery from a rejected return type stops: the interface-body sync
287/// set plus `@`, so a timing annotation written after a broken return type is
288/// still parsed into its own node and still draws its own diagnostic.
289fn is_return_sync(kind: SyntaxKind) -> bool {
290    matches!(
291        kind,
292        SyntaxKind::RBrace | SyntaxKind::Comma | SyntaxKind::ReservedKw | SyntaxKind::At
293    ) || is_interaction_start(kind)
294        || is_top_level_start(kind)
295}
296
297/// Whether `kind` is a typl definition keyword. Inside an interface body
298/// whose `}` still lies ahead, these recover into a body-local
299/// [`ErrorNode`](SyntaxKind::ErrorNode) — the ridl reference forbids type
300/// declarations there (§14.1) and reserves RIDL-107 for them (§16.1), which
301/// the body loop raises. In a body with no `}` ahead they signal an unclosed
302/// `{` exactly like the remaining top-level keywords, so a genuinely
303/// unclosed interface keeps the declarations that follow it.
304fn is_typl_definition_start(kind: SyntaxKind) -> bool {
305    matches!(
306        kind,
307        SyntaxKind::TypeKw
308            | SyntaxKind::ConstKw
309            | SyntaxKind::StructKw
310            | SyntaxKind::EnumKw
311            | SyntaxKind::EnumsetKw
312            | SyntaxKind::UnionKw
313    )
314}
315
316/// The deepest field-type, expression, or attribute-value nesting the parser
317/// follows before it stops recursing, and the greatest height of the tree it
318/// builds for one expression — far beyond any real schema, small enough that
319/// a pathological input can overflow neither the parser's stack nor the stack
320/// of a pass that later recurses over the tree.
321const MAX_TYPE_DEPTH: usize = 128;
322
323/// The recursive-descent state: the token stream, a cursor, the tree builder,
324/// and the diagnostics.
325struct Parser<'a> {
326    tokens: Vec<Token<'a>>,
327    /// Byte offset of the start of each token, plus a final entry for the end
328    /// of input; `offsets[i]` is the offset of `tokens[i]`.
329    offsets: Vec<usize>,
330    pos: usize,
331    /// The nesting the cursor is under, bounded by [`MAX_TYPE_DEPTH`].
332    /// Outside an expression it counts the field types and attribute values
333    /// open above the cursor (each `field_type` or `attr_value` call adds
334    /// one). Inside an expression it counts the expression nodes open above
335    /// the cursor — the groups, prefixes and chain wraps the node built next
336    /// will sit under — which is what the height bound is measured against.
337    depth: usize,
338    /// Whether the expression being parsed has already drawn FORM-102. A
339    /// later part of the same expression that does not fit either goes flat
340    /// without a second diagnostic.
341    expr_refused: bool,
342    /// The profile the file parses under — where the profile-boundary
343    /// diagnostics (TYPL-302, TYPL-304, RIDL-403) are drawn.
344    profile: Profile,
345    builder: GreenNodeBuilder<'static>,
346    errors: Vec<SyntaxError>,
347}
348
349impl<'a> Parser<'a> {
350    fn new(tokens: Vec<Token<'a>>, profile: Profile) -> Self {
351        let mut offsets = Vec::with_capacity(tokens.len() + 1);
352        let mut acc = 0;
353        for token in &tokens {
354            offsets.push(acc);
355            acc += token.text.len();
356        }
357        offsets.push(acc);
358        Self {
359            tokens,
360            offsets,
361            pos: 0,
362            depth: 0,
363            expr_refused: false,
364            profile,
365            builder: GreenNodeBuilder::new(),
366            errors: Vec::new(),
367        }
368    }
369
370    fn finish(self) -> Parse {
371        Parse {
372            green: self.builder.finish(),
373            errors: self.errors,
374        }
375    }
376
377    // --- cursor over significant (non-trivia) tokens ---------------------
378
379    /// Index of the next non-trivia token at or after the cursor.
380    fn significant_pos(&self) -> usize {
381        let mut i = self.pos;
382        while self.tokens.get(i).is_some_and(|t| t.kind.is_trivia()) {
383            i += 1;
384        }
385        i
386    }
387
388    /// Kind of the next significant token, or `None` at end of input.
389    fn current(&self) -> Option<SyntaxKind> {
390        self.tokens.get(self.significant_pos()).map(|t| t.kind)
391    }
392
393    /// Kind of the `n`-th significant token ahead (`nth(0)` is [`current`]).
394    fn nth(&self, n: usize) -> Option<SyntaxKind> {
395        let mut i = self.pos;
396        let mut seen = 0;
397        loop {
398            let token = self.tokens.get(i)?;
399            if !token.kind.is_trivia() {
400                if seen == n {
401                    return Some(token.kind);
402                }
403                seen += 1;
404            }
405            i += 1;
406        }
407    }
408
409    fn at(&self, kind: SyntaxKind) -> bool {
410        self.current() == Some(kind)
411    }
412
413    /// Source text of the next significant token, or `""` at end of input —
414    /// for a message that quotes the word the author wrote.
415    fn current_text(&self) -> &'a str {
416        self.tokens
417            .get(self.significant_pos())
418            .map_or("", |token| token.text)
419    }
420
421    // --- token consumption (feeds the tree, keeps losslessness) ----------
422
423    /// Attaches any pending trivia tokens to the current node, in source order.
424    fn eat_trivia(&mut self) {
425        while let Some(token) = self.tokens.get(self.pos) {
426            if token.kind.is_trivia() {
427                self.builder.token(token.kind.into(), token.text);
428                self.pos += 1;
429            } else {
430                break;
431            }
432        }
433    }
434
435    /// Flushes leading trivia to the currently open node, then starts a child
436    /// node — so a definition's doc comment stays a sibling of the definition
437    /// rather than its first child.
438    fn start(&mut self, kind: SyntaxKind) {
439        self.eat_trivia();
440        self.builder.start_node(kind.into());
441    }
442
443    /// Consumes one significant token into the tree, flushing leading trivia
444    /// first. Callers must have confirmed a token is present.
445    fn bump(&mut self) {
446        self.eat_trivia();
447        if let Some(token) = self.tokens.get(self.pos) {
448            self.builder.token(token.kind.into(), token.text);
449            self.pos += 1;
450        }
451    }
452
453    /// Consumes the current token if it is `kind`; reports FORM-101 otherwise.
454    fn expect(&mut self, kind: SyntaxKind) {
455        if self.at(kind) {
456            self.bump();
457        } else {
458            self.error_at_current("FORM-101", format!("expected {kind:?}"));
459        }
460    }
461
462    /// Records an error spanning the current significant token (or the end of
463    /// input), unless a diagnostic already sits at that start offset.
464    ///
465    /// The cursor only ever moves forward, so the start offset here is
466    /// non-decreasing across calls; comparing against the last recorded error
467    /// therefore enforces one diagnostic per source position (see the module
468    /// doc). This is the flood control: on a stuck cursor the repeated,
469    /// no-progress `expect`/`bound` errors during an unwind collapse to the
470    /// first one.
471    ///
472    /// The profile-boundary **TYPL-302** is exempt: it is the higher-value
473    /// diagnostic and must survive a positional FORM-101 that lands on the
474    /// same boundary token first (`[0..10ms]` reports both). A TYPL-302 token
475    /// is always consumed at the site that raises it, so it can never be the
476    /// stuck-cursor flood source the suppression guards against.
477    fn error_at_current(&mut self, code: &'static str, message: String) {
478        let i = self.significant_pos();
479        let start = TextSize::new(self.offsets[i] as u32);
480        if code != "TYPL-302"
481            && self
482                .errors
483                .last()
484                .is_some_and(|last| last.range.start() == start)
485        {
486            return;
487        }
488        let end = self
489            .tokens
490            .get(i)
491            .map_or(start, |t| start + TextSize::of(t.text));
492        self.errors.push(SyntaxError {
493            message,
494            code,
495            range: TextRange::new(start, end),
496        });
497    }
498
499    /// The diagnostic for the current unexpected token: in a `.typl` parse,
500    /// TYPL-302 for the profile-boundary tokens (duration literals and the `@`
501    /// timing sigil, typl reference §2.8); FORM-102 otherwise. Under
502    /// [`Profile::Ridl`] durations and `@` are ordinary tokens, so they draw
503    /// the generic FORM-102 like any other token the grammar cannot place.
504    fn unexpected_token_diag(&self, context: &str) -> (&'static str, String) {
505        if self.profile == Profile::Typl {
506            match self.current() {
507                Some(SyntaxKind::Duration) => {
508                    return ("TYPL-302", "duration literal in typl context".to_string());
509                }
510                Some(SyntaxKind::At) => {
511                    return ("TYPL-302", "timing annotation in typl context".to_string());
512                }
513                _ => {}
514            }
515        }
516        ("FORM-102", format!("unexpected token {context}"))
517    }
518
519    /// Recovery: report the current unexpected token, then skip forward —
520    /// wrapping the skipped run in one [`SyntaxKind::ErrorNode`] — until a
521    /// token `is_sync` accepts (a resynchronization point) or the input ends.
522    /// The first token is always consumed, so the enclosing loop makes
523    /// progress and no text is dropped.
524    fn err_and_recover(&mut self, context: &str, is_sync: impl Fn(SyntaxKind) -> bool) {
525        let (code, message) = self.unexpected_token_diag(context);
526        self.error_at_current(code, message);
527        self.recover(is_sync);
528    }
529
530    /// The recovery half of [`err_and_recover`]: consumes the current token
531    /// and everything up to the next token `is_sync` accepts into one
532    /// [`SyntaxKind::ErrorNode`]. The profile-boundary arms (TYPL-304,
533    /// RIDL-403) share it, so they recover exactly as FORM-102/FORM-105 do.
534    fn recover(&mut self, is_sync: impl Fn(SyntaxKind) -> bool) {
535        self.start(SyntaxKind::ErrorNode);
536        self.bump();
537        while let Some(kind) = self.current() {
538            if is_sync(kind) {
539                break;
540            }
541            self.bump();
542        }
543        self.builder.finish_node();
544    }
545
546    // --- grammar productions --------------------------------------------
547
548    /// `SourceFile = PackageDecl? Import* Definition*`
549    ///
550    /// A missing `package` emits FORM-104 and parsing continues; extra
551    /// `package` declarations parse as further `PackageDecl` nodes (TYPL-001
552    /// is checker scope). Imports and definitions are accepted in any order —
553    /// ordering is surface convention, not tree shape.
554    fn source_file(&mut self) {
555        self.builder.start_node(SyntaxKind::SourceFile.into());
556        self.eat_trivia();
557        if self.at(SyntaxKind::PackageKw) {
558            self.package_decl();
559        } else {
560            self.error_at_current("FORM-104", "missing `package` declaration".to_string());
561        }
562        loop {
563            self.eat_trivia();
564            match self.current() {
565                None => break,
566                Some(SyntaxKind::PackageKw) => self.package_decl(),
567                Some(SyntaxKind::ImportKw) => self.import(),
568                Some(
569                    SyntaxKind::InternalKw
570                    | SyntaxKind::ErrorKw
571                    | SyntaxKind::TypeKw
572                    | SyntaxKind::ConstKw
573                    | SyntaxKind::StructKw
574                    | SyntaxKind::EnumKw
575                    | SyntaxKind::EnumsetKw
576                    | SyntaxKind::UnionKw
577                    | SyntaxKind::InterfaceKw,
578                ) => {
579                    if self.profile == Profile::Rsdl {
580                        self.rsdl_typl_word_at_top_level();
581                    } else {
582                        self.definition();
583                    }
584                }
585                Some(SyntaxKind::ServiceKw) => self.service_def(),
586                Some(SyntaxKind::SystemKw) => {
587                    self.rsdl_container(SyntaxKind::SystemDef, RsdlBody::Members);
588                }
589                Some(SyntaxKind::ComponentKw) => {
590                    self.rsdl_container(SyntaxKind::ComponentDef, RsdlBody::ComponentLines);
591                }
592                Some(SyntaxKind::DistributionKw) => {
593                    self.rsdl_container(SyntaxKind::DistributionDef, RsdlBody::Members);
594                }
595                Some(SyntaxKind::DeploymentKw) => self.deployment_def(),
596                Some(SyntaxKind::ReservedWord) => {
597                    if !self.profile_boundary_at_top_level() {
598                        self.err_and_recover("at top level", is_top_level_start);
599                    }
600                }
601                Some(_) => self.err_and_recover("at top level", is_top_level_start),
602            }
603        }
604        self.builder.finish_node();
605    }
606
607    /// The profile boundary at declaration-start position (ADR-0007 decision
608    /// 10, ridl reference §16.4). Called on a `ReservedWord` at the top level:
609    ///
610    /// - in a `.typl` parse, an interaction keyword (one of the nine ridl
611    ///   words) draws **TYPL-304** instead of the generic FORM-102 — except
612    ///   `require`/`ensure`, which are attributes, not declarations, and
613    ///   draw **TYPL-303** (`require/ensure attribute in typl context`,
614    ///   typl reference §16.4);
615    /// - in a `.ridl` parse, any `ReservedWord` — a behaviour or architecture
616    ///   word of the rmdl/rsdl profiles, or a ridl clause word — draws
617    ///   **RIDL-403**;
618    /// - in a `.rsdl` parse, any `ReservedWord` — `interface` and `service`
619    ///   first of all — draws **RSDL-604** (rsdl reference §2), with the
620    ///   brace-aware recovery of [`Parser::rsdl_foreign_declaration`]. The typl
621    ///   definition keywords are active in an `.rsdl` file and reach
622    ///   [`Parser::rsdl_typl_word_at_top_level`] instead.
623    ///
624    /// All recover exactly as FORM-105 does ([`Parser::recover`]: the run
625    /// lands in one `ErrorNode`, resynchronizing at the next top-level
626    /// keyword). Returns `false` — leaving the token untouched for the
627    /// caller's generic recovery — when neither boundary applies (a
628    /// uxdl/rmdl/rsdl word in a `.typl` parse stays a generic FORM-102).
629    fn profile_boundary_at_top_level(&mut self) -> bool {
630        let text = self.tokens[self.significant_pos()].text;
631        let (code, message) = match self.profile {
632            Profile::Typl => match keywords::ridl_keyword(text) {
633                None => return false,
634                Some(SyntaxKind::RequireKw | SyntaxKind::EnsureKw) => (
635                    "TYPL-303",
636                    "require/ensure attribute in typl context".to_string(),
637                ),
638                Some(_) => (
639                    "TYPL-304",
640                    format!("interaction declaration in typl context: `{text}`"),
641                ),
642            },
643            // The message names neither "behaviour" nor "user-interaction" nor
644            // "architecture": those are the catalogue's words for the three
645            // profiles, and the author wrote one word, not a taxonomy. What is
646            // wrong is that the word is spoken for; what is allowed is the two
647            // declarations a `.ridl` file makes.
648            Profile::Ridl => (
649                "RIDL-403",
650                format!(
651                    "`{text}` is reserved by another profile of the family, so it cannot start a \
652                     declaration here — a `.ridl` file declares `interface` and `service`. Move \
653                     the declaration to the profile that owns the word, or, if `{text}` was meant \
654                     as a name, choose one the family does not reserve (ridl reference §16.4)"
655                ),
656            ),
657            Profile::Rsdl => {
658                self.rsdl_foreign_declaration(0);
659                return true;
660            }
661        };
662        self.error_at_current(code, message);
663        self.recover(is_top_level_start);
664        true
665    }
666
667    /// A typl definition keyword or an `internal`/`error` modifier at the top
668    /// level of an `.rsdl` file. A modifier run in front of an rsdl declaration
669    /// keyword is FORM-102 on each modifier (rsdl reference §2: the five
670    /// declarations take no modifier), and the declaration after it still
671    /// parses. Anything else is a typl declaration, RSDL-604: the modifiers,
672    /// the keyword and the rest of the declaration land in one `ErrorNode`
673    /// ([`Parser::rsdl_foreign_declaration`]), so the declaration draws one
674    /// diagnostic, not one per word.
675    fn rsdl_typl_word_at_top_level(&mut self) {
676        let mut modifiers = 0;
677        while matches!(
678            self.nth(modifiers),
679            Some(SyntaxKind::InternalKw | SyntaxKind::ErrorKw)
680        ) {
681            modifiers += 1;
682        }
683        if modifiers > 0 && self.nth(modifiers).is_some_and(is_rsdl_declaration_start) {
684            for _ in 0..modifiers {
685                let word = self.current_text();
686                self.error_at_current(
687                    "FORM-102",
688                    format!(
689                        "`{word}` cannot modify an rsdl declaration — the closure is \
690                         workspace-wide, so every declaration it names is visible from the \
691                         system's package (rsdl reference §2)"
692                    ),
693                );
694                self.start(SyntaxKind::ErrorNode);
695                self.bump();
696                self.builder.finish_node();
697            }
698            return;
699        }
700        self.rsdl_foreign_declaration(modifiers);
701    }
702
703    /// RSDL-604 (rsdl reference §2): a declaration of another profile at the
704    /// top level of an `.rsdl` file, starting at the current token after
705    /// `modifiers` `internal`/`error` words. The declaration draws one
706    /// diagnostic, on its first token, naming its keyword. Recovery is
707    /// brace-aware, like [`Parser::recover_definition_in_body`]: a body
708    /// `{ … }` is consumed whole, so a ridl word inside it (`signal`) is not
709    /// taken for the next declaration; at depth 0 recovery stops at a
710    /// top-level keyword or at a reserved word, which starts the next
711    /// declaration of another profile.
712    fn rsdl_foreign_declaration(&mut self, modifiers: usize) {
713        let keyword = self.nth_text(modifiers);
714        self.error_at_current("RSDL-604", rsdl_foreign_declaration_message(keyword));
715        self.start(SyntaxKind::ErrorNode);
716        for _ in 0..=modifiers {
717            self.bump();
718        }
719        let mut depth = 0usize;
720        while let Some(kind) = self.current() {
721            match kind {
722                SyntaxKind::LBrace => depth += 1,
723                SyntaxKind::RBrace if depth > 0 => depth -= 1,
724                _ if depth == 0
725                    && (is_top_level_start(kind) || kind == SyntaxKind::ReservedWord) =>
726                {
727                    break;
728                }
729                _ => {}
730            }
731            self.bump();
732        }
733        self.builder.finish_node();
734    }
735
736    /// Source text of the `n`-th significant token ahead (`nth_text(0)` is
737    /// [`Parser::current_text`]), or `""` past the end of input.
738    fn nth_text(&self, n: usize) -> &'a str {
739        self.tokens[self.pos..]
740            .iter()
741            .filter(|token| !token.kind.is_trivia())
742            .nth(n)
743            .map_or("", |token| token.text)
744    }
745
746    /// The rsdl containers with no relation clause — `system`, `component`,
747    /// `distribution` and `machine` (rsdl reference §3, general form §2 Shape
748    /// 3): `kw Name AttrBlock? '{' lines '}'`.
749    fn rsdl_container(&mut self, kind: SyntaxKind, body: RsdlBody) {
750        self.start(kind);
751        self.bump(); // the declaration keyword
752        self.name();
753        if self.at(SyntaxKind::LBracket) {
754            self.attr_block();
755        }
756        self.rsdl_body(body);
757        self.builder.finish_node();
758    }
759
760    /// `DeploymentDef = 'deployment' Name 'for' system:Reference AttrBlock?
761    /// '{' (machines:MachineDef ','?)* '}'` (rsdl reference §3.4). The clause
762    /// comes before the attributes (R5). A missing `for` is FORM-101 and the
763    /// body still parses.
764    fn deployment_def(&mut self) {
765        self.start(SyntaxKind::DeploymentDef);
766        self.bump(); // 'deployment'
767        self.name();
768        if self.at(SyntaxKind::ForKw) {
769            self.bump(); // 'for'
770            self.reference();
771        } else {
772            self.error_at_current(
773                "FORM-101",
774                "expected `for` and the system this deployment places".to_string(),
775            );
776        }
777        if self.at(SyntaxKind::LBracket) {
778            self.attr_block();
779        }
780        self.rsdl_body(RsdlBody::Machines);
781        self.builder.finish_node();
782    }
783
784    /// The body loop of an rsdl container, the rsdl counterpart of
785    /// [`Parser::block_body`]: lines separated by newlines or commas, a
786    /// trailing comma permitted (R8). A token that starts no line of this body
787    /// is FORM-102 and recovery resynchronizes at the next line, comma or `}`.
788    /// A reference where a component line is expected is the one-reference-
789    /// per-line rule (rsdl reference §3.2), and its message says so.
790    fn rsdl_body(&mut self, body: RsdlBody) {
791        if !self.block_open() {
792            return;
793        }
794        loop {
795            self.eat_trivia();
796            match self.current() {
797                None => {
798                    self.error_at_current("FORM-103", "unclosed `{`".to_string());
799                    break;
800                }
801                Some(SyntaxKind::RBrace) => {
802                    self.bump();
803                    break;
804                }
805                Some(SyntaxKind::Comma) => self.bump(),
806                Some(kind) if body.starts_line(kind) => match body {
807                    RsdlBody::Members => self.member_line(),
808                    RsdlBody::ComponentLines => self.component_line(),
809                    RsdlBody::Machines => {
810                        self.rsdl_container(SyntaxKind::MachineDef, RsdlBody::Members);
811                    }
812                },
813                Some(kind) if is_top_level_start(kind) => {
814                    self.error_at_current("FORM-103", "unclosed `{`".to_string());
815                    break;
816                }
817                Some(_) => {
818                    let sync = move |kind: SyntaxKind| {
819                        matches!(kind, SyntaxKind::RBrace | SyntaxKind::Comma)
820                            || body.starts_line(kind)
821                            || is_top_level_start(kind)
822                    };
823                    if body == RsdlBody::ComponentLines && self.at_path_segment() {
824                        self.error_at_current(
825                            "FORM-102",
826                            format!(
827                                "`{}` is a second reference — a component line takes one \
828                                 reference, so write its own `offers` or `requires` before it \
829                                 (rsdl reference §3.2)",
830                                self.current_text()
831                            ),
832                        );
833                        self.recover(sync);
834                    } else {
835                        let context = match body {
836                            RsdlBody::Members => "in a member list",
837                            RsdlBody::ComponentLines => "in a component body",
838                            RsdlBody::Machines => "in a deployment body",
839                        };
840                        self.err_and_recover(context, sync);
841                    }
842                }
843            }
844        }
845    }
846
847    /// `MemberLine = Reference AttrBlock?` — a bare reference in a `system`,
848    /// `distribution` or `machine` body (rsdl reference §4).
849    fn member_line(&mut self) {
850        self.start(SyntaxKind::MemberLine);
851        self.reference();
852        if self.at(SyntaxKind::LBracket) {
853            self.attr_block();
854        }
855        self.builder.finish_node();
856    }
857
858    /// `ComponentLine = ('offers' | 'requires') Reference AttrBlock?` (rsdl
859    /// reference §3.2).
860    fn component_line(&mut self) {
861        self.start(SyntaxKind::ComponentLine);
862        self.bump(); // 'offers' | 'requires'
863        self.reference();
864        if self.at(SyntaxKind::LBracket) {
865            self.attr_block();
866        }
867        self.builder.finish_node();
868    }
869
870    /// `Reference = QualifiedName` (rsdl reference §4, Appendix B). No node is
871    /// built when the reference is missing.
872    fn reference(&mut self) {
873        if !self.at_path_segment() {
874            self.error_at_current("FORM-101", "expected a reference".to_string());
875            return;
876        }
877        self.start(SyntaxKind::Reference);
878        self.qualified_name();
879        self.builder.finish_node();
880    }
881
882    /// `PackageDecl = 'package' QualifiedName`
883    fn package_decl(&mut self) {
884        self.start(SyntaxKind::PackageDecl);
885        self.bump(); // 'package'
886        self.qualified_name();
887        self.builder.finish_node();
888    }
889
890    /// `Import = 'import' QualifiedName ('as' alias:Name)?`
891    fn import(&mut self) {
892        self.start(SyntaxKind::Import);
893        self.bump(); // 'import'
894        self.qualified_name();
895        if self.at(SyntaxKind::AsKw) {
896            self.bump();
897            self.name();
898        }
899        self.builder.finish_node();
900    }
901
902    /// `Definition = TypeDef | ConstDef | StructDef | EnumDef | EnumSetDef |
903    /// UnionDef`, each with optional leading `internal`/`error` modifiers.
904    /// The definition keyword is found by looking past the modifiers; a
905    /// modifier with no definition keyword after it is an unexpected token.
906    fn definition(&mut self) {
907        let mut n = 0;
908        while matches!(
909            self.nth(n),
910            Some(SyntaxKind::InternalKw | SyntaxKind::ErrorKw)
911        ) {
912            n += 1;
913        }
914        match self.nth(n) {
915            Some(SyntaxKind::TypeKw) => self.type_def(),
916            Some(SyntaxKind::ConstKw) => self.const_def(),
917            Some(SyntaxKind::StructKw) => self.struct_def(),
918            Some(SyntaxKind::EnumKw) => self.enum_def(),
919            Some(SyntaxKind::EnumsetKw) => self.enum_set_def(),
920            Some(SyntaxKind::UnionKw) => self.union_def(),
921            Some(SyntaxKind::InterfaceKw) => self.interface_def(),
922            _ => self.err_and_recover("in a definition", is_top_level_start),
923        }
924    }
925
926    /// Consumes the `internal`/`error` modifier run into the open node.
927    fn modifiers(&mut self) {
928        while matches!(
929            self.current(),
930            Some(SyntaxKind::InternalKw | SyntaxKind::ErrorKw)
931        ) {
932            self.bump();
933        }
934    }
935
936    /// `TypeDef = 'internal'? 'error'? 'type' Name ':' Backing Constraint?
937    /// InitValue?` — the constraint is a direct child of `TypeDef` here,
938    /// never nested inside `PrimitiveType` (that position is for field
939    /// types).
940    fn type_def(&mut self) {
941        self.start(SyntaxKind::TypeDef);
942        self.modifiers();
943        self.bump(); // 'type'
944        self.name();
945        self.expect(SyntaxKind::Colon);
946        let stringish = self.backing();
947        if self.at(SyntaxKind::LBracket) {
948            self.constraint(stringish);
949        }
950        self.init_value_opt();
951        self.builder.finish_node();
952    }
953
954    /// `Backing = PrimitiveType | UnitExpr` in `type`-definition position.
955    /// Returns whether the backing is `string`/`bytes` — the bound policy
956    /// input for the constraint that may follow.
957    fn backing(&mut self) -> bool {
958        match self.current() {
959            Some(
960                kw @ (SyntaxKind::BooleanKw
961                | SyntaxKind::IntegerKw
962                | SyntaxKind::FloatKw
963                | SyntaxKind::StringKw
964                | SyntaxKind::BytesKw),
965            ) => {
966                self.start(SyntaxKind::PrimitiveType);
967                self.bump();
968                self.builder.finish_node();
969                matches!(kw, SyntaxKind::StringKw | SyntaxKind::BytesKw)
970            }
971            Some(SyntaxKind::Ident | SyntaxKind::Slash | SyntaxKind::Dot | SyntaxKind::Percent) => {
972                // `UnitExpr = ('ident' | '/' | '.' | '%')*` — a UCUM
973                // expression (`km/h`, `N.m`, `/min`, `%`). Semantic
974                // validation is the ucum module's job (TYPL-110).
975                self.start(SyntaxKind::UnitExpr);
976                while matches!(
977                    self.current(),
978                    Some(
979                        SyntaxKind::Ident
980                            | SyntaxKind::Slash
981                            | SyntaxKind::Dot
982                            | SyntaxKind::Percent
983                    )
984                ) {
985                    self.bump();
986                }
987                self.builder.finish_node();
988                false
989            }
990            _ => {
991                self.error_at_current("FORM-101", "expected a backing type".to_string());
992                false
993            }
994        }
995    }
996
997    /// `ConstDef = 'internal'? 'error'? 'const' Name (':' type_ref:PathType)?
998    /// '=' value:Literal`
999    fn const_def(&mut self) {
1000        self.start(SyntaxKind::ConstDef);
1001        self.modifiers();
1002        self.bump(); // 'const'
1003        self.name();
1004        if self.at(SyntaxKind::Colon) {
1005            self.bump();
1006            self.path_type();
1007        }
1008        self.expect(SyntaxKind::Eq);
1009        self.literal();
1010        self.builder.finish_node();
1011    }
1012
1013    /// `StructDef = 'internal'? 'error'? 'struct' Name '{' (members ','?)*
1014    /// '}'` — a member is a `FieldDef` or a `ReservedEntry`.
1015    fn struct_def(&mut self) {
1016        self.start(SyntaxKind::StructDef);
1017        self.modifiers();
1018        self.bump(); // 'struct'
1019        self.name();
1020        self.block_body("in a struct body", true, Self::field_def);
1021        self.builder.finish_node();
1022    }
1023
1024    /// `EnumDef = 'internal'? 'error'? 'enum' Name '{' ((values | reserved)
1025    /// ','?)* '}'`
1026    fn enum_def(&mut self) {
1027        self.start(SyntaxKind::EnumDef);
1028        self.modifiers();
1029        self.bump(); // 'enum'
1030        self.name();
1031        self.block_body("in an enum body", true, Self::enum_value);
1032        self.builder.finish_node();
1033    }
1034
1035    /// `EnumSetDef` — the standalone form (`enumset Name '{' bits '}'`) or
1036    /// the derived form (`enumset Name ':' backing_ref:PathType`), §9.1–§9.2.
1037    fn enum_set_def(&mut self) {
1038        self.start(SyntaxKind::EnumSetDef);
1039        self.modifiers();
1040        self.bump(); // 'enumset'
1041        self.name();
1042        if self.at(SyntaxKind::Colon) {
1043            self.bump();
1044            self.path_type();
1045        } else {
1046            self.block_body("in an enumset body", false, Self::enum_set_bit);
1047        }
1048        self.builder.finish_node();
1049    }
1050
1051    /// `UnionDef = 'internal'? 'error'? 'union' Name '{' ((arms | reserved)
1052    /// ','?)* '}'`
1053    fn union_def(&mut self) {
1054        self.start(SyntaxKind::UnionDef);
1055        self.modifiers();
1056        self.bump(); // 'union'
1057        self.name();
1058        self.block_body("in a union body", true, Self::union_arm);
1059        self.builder.finish_node();
1060    }
1061
1062    /// `UnionArm = Name ':' type_ref:PathType` — arms reference named types
1063    /// only; a primitive keyword still parses as a path segment and the
1064    /// checker rejects it (TYPL-204).
1065    fn union_arm(&mut self) {
1066        self.start(SyntaxKind::UnionArm);
1067        self.name();
1068        self.expect(SyntaxKind::Colon);
1069        self.path_type();
1070        self.builder.finish_node();
1071    }
1072
1073    // --- ridl interaction productions (ridl reference Appendix C) --
1074
1075    /// `InterfaceDef = 'internal'? 'error'? 'interface' Name '{' (members
1076    /// ','?)* '}'` — an interface body holds interactions and `reserved`
1077    /// tombstones only (ridl reference §14.1); a type declaration inside it
1078    /// is RIDL-107, raised by the body loop. The body loop is the interaction
1079    /// counterpart of [`Parser::block_body`]: members are announced by the
1080    /// five interaction keywords instead of an `Ident`, and those keywords
1081    /// are the recovery sync points, so garbage inside a body
1082    /// resynchronizes at the next interaction.
1083    fn interface_def(&mut self) {
1084        self.start(SyntaxKind::InterfaceDef);
1085        self.modifiers();
1086        self.bump(); // 'interface'
1087        self.name();
1088        if !self.block_open() {
1089            self.builder.finish_node();
1090            return;
1091        }
1092        self.interface_body("an interface", "interface");
1093        self.builder.finish_node();
1094    }
1095
1096    /// The interaction-body loop shared by an `interface` body and a
1097    /// `service` inline body: the opening `{` has already been
1098    /// consumed. Members are announced by the five interaction keywords, and
1099    /// those keywords plus the top-level starters are the recovery sync
1100    /// points, so garbage inside a body resynchronizes at the next
1101    /// interaction. A `service` inline body runs the same structural pass as
1102    /// an interface (ridl reference §14.5).
1103    ///
1104    /// `noun` and `shape` name the enclosing construct for the RIDL-107
1105    /// message — `"an interface"`/`"interface"` or `"a service"`/`"service"`.
1106    /// The two callers share this loop, and a reader is told where the stray
1107    /// declaration has to move to.
1108    fn interface_body(&mut self, noun: &str, shape: &str) {
1109        loop {
1110            self.eat_trivia();
1111            match self.current() {
1112                None => {
1113                    self.error_at_current("FORM-103", "unclosed `{`".to_string());
1114                    break;
1115                }
1116                Some(SyntaxKind::RBrace) => {
1117                    self.bump();
1118                    break;
1119                }
1120                Some(SyntaxKind::Comma) => self.bump(),
1121                Some(SyntaxKind::ReservedKw) => self.reserved_entry(),
1122                Some(SyntaxKind::SignalKw) => self.value_interaction(SyntaxKind::SignalDef),
1123                Some(SyntaxKind::EventKw) => self.value_interaction(SyntaxKind::EventDef),
1124                Some(SyntaxKind::CommandKw) => self.callable_interaction(SyntaxKind::CommandDef),
1125                Some(SyntaxKind::QueryKw) => self.callable_interaction(SyntaxKind::QueryDef),
1126                Some(SyntaxKind::FixedKw) => self.value_interaction(SyntaxKind::FixedDef),
1127                // A typl definition keyword inside the body: the body holds
1128                // interactions and tombstones only (ridl §14.1). When the
1129                // body's `}` still lies ahead, the declaration recovers into
1130                // a body-local ErrorNode — brace-aware, so a composite body
1131                // stays inside it and the members after it keep their place.
1132                // With no `}` ahead the guard fails and the keyword falls
1133                // through to the unclosed-`{` arm below, exactly like the
1134                // remaining top-level keywords (`package`, `import`,
1135                // `internal`, `error`, `interface`, `service`).
1136                //
1137                // RIDL-107 is raised here rather than by the checker over the
1138                // recovered node. The parser has already recognised exactly
1139                // what this is, so the generic FORM-102 "unexpected token in
1140                // an interface body" it used to raise was both wrong and a
1141                // second diagnostic for one mistake: every RIDL-107 arrived
1142                // paired with a contradicting FORM-102 at the same span. The
1143                // profile-boundary codes RIDL-403 and TYPL-304 are raised from
1144                // the parser for the same reason.
1145                Some(kind)
1146                    if is_typl_definition_start(kind) && self.interface_body_close_ahead() =>
1147                {
1148                    self.error_at_current(
1149                        "RIDL-107",
1150                        format!(
1151                            "`{}` starts a typl declaration, and {noun} body holds interactions \
1152                             and `reserved` tombstones only — move the declaration to package \
1153                             level, beside the {shape} (ridl reference §14.1)",
1154                            self.current_text(),
1155                        ),
1156                    );
1157                    self.recover_definition_in_body();
1158                }
1159                // An unclosed `{`: the body ran into the next top-level
1160                // declaration. Report the missing brace and hand the
1161                // declaration back, exactly as `block_body` does.
1162                Some(kind) if is_top_level_start(kind) => {
1163                    self.error_at_current("FORM-103", "unclosed `{`".to_string());
1164                    break;
1165                }
1166                Some(_) => self.err_and_recover("in an interface body", |kind| {
1167                    matches!(
1168                        kind,
1169                        SyntaxKind::RBrace | SyntaxKind::Comma | SyntaxKind::ReservedKw
1170                    ) || is_interaction_start(kind)
1171                        || is_top_level_start(kind)
1172                }),
1173            }
1174        }
1175    }
1176
1177    /// `ServiceDef = 'service' DottedName (':' shapes (',' shapes)* ','? |
1178    /// '{' (inline_members ','?)* '}')` — the global published declaration of
1179    /// one or more interfaces (ridl reference §14.5, ADR-0015 decision 12).
1180    /// The named form carries a comma-separated shape list after `:`; the
1181    /// inline form carries an interaction body reusing
1182    /// [`Parser::interface_body`], so the checker runs the same structural pass
1183    /// over it (RIDL-401/-402). Never both forms (ADR-0015 decision 14). A
1184    /// service takes no `internal`/`error` modifiers — it is a global, published
1185    /// contract.
1186    fn service_def(&mut self) {
1187        self.start(SyntaxKind::ServiceDef);
1188        self.bump(); // 'service'
1189        self.dotted_name();
1190        match self.current() {
1191            Some(SyntaxKind::Colon) => {
1192                self.bump(); // ':'
1193                self.service_shape_list();
1194            }
1195            Some(SyntaxKind::LBrace) => {
1196                self.bump(); // '{'
1197                self.interface_body("a service", "service");
1198            }
1199            _ => self.error_at_current(
1200                "FORM-101",
1201                "expected `:` and an interface list, or `{` and an inline shape".to_string(),
1202            ),
1203        }
1204        self.builder.finish_node();
1205    }
1206
1207    /// The comma-separated shape list of a service's named form: one
1208    /// `PathType` per shape (ADR-0015 decision 12).
1209    ///
1210    /// Commas are **required** between shapes, diverging from the family's
1211    /// optional-comma convention, and the reason is structural (ADR-0015
1212    /// decision 13): every other list in the grammar is terminated by a
1213    /// closing token — `}` for a body, `)` for a parameter list, `]` for an
1214    /// attribute block — and this one is not, because it ends where the next
1215    /// declaration begins. It would still parse without commas, since every
1216    /// top-level declaration starts with a keyword and a bare `CamelCase`
1217    /// identifier never does — but it would parse greedily, so a mistyped
1218    /// declaration on a following line (`Struct Foo {` for `struct Foo {`)
1219    /// would be absorbed as another shape and the error would surface at the
1220    /// `{` with no connection to the mistake. Ending the list at the first
1221    /// missing comma instead leaves that identifier to the top-level loop,
1222    /// whose FORM-102 points at it directly. A trailing comma stays optional.
1223    fn service_shape_list(&mut self) {
1224        // One shape: an interface reference. A primitive keyword still parses
1225        // as a path segment and the checker rejects it (RIDL-141), the E1
1226        // lenient-parser discipline. `reserved` is not a shape: a service's
1227        // list is a set with no slot to retire (lock design §9), so the list
1228        // ends before it and the top-level loop reports the stray keyword.
1229        self.path_type();
1230        // `current()` peeks past trivia without consuming it, so a list that
1231        // ends here leaves the trailing trivia outside the ServiceDef node.
1232        while self.at(SyntaxKind::Comma) {
1233            self.bump(); // ','
1234            // A trailing comma: nothing after it starts a shape.
1235            if !self.at_path_segment() {
1236                break;
1237            }
1238            self.path_type();
1239        }
1240    }
1241
1242    /// `DottedName = 'ident' ('.' 'ident')*` — a dotted global service name
1243    /// (`veh.adas.cruise`, ADR-0002 §1). Each segment is a plain identifier;
1244    /// a trailing `.` with no segment after it is FORM-101.
1245    fn dotted_name(&mut self) {
1246        self.start(SyntaxKind::DottedName);
1247        if self.at(SyntaxKind::Ident) {
1248            self.bump();
1249            while self.at(SyntaxKind::Dot) {
1250                self.bump(); // '.'
1251                if self.at(SyntaxKind::Ident) {
1252                    self.bump();
1253                } else {
1254                    self.error_at_current(
1255                        "FORM-101",
1256                        "expected a name segment after `.`".to_string(),
1257                    );
1258                    break;
1259                }
1260            }
1261        } else {
1262            self.error_at_current("FORM-101", "expected a service name".to_string());
1263        }
1264        self.builder.finish_node();
1265    }
1266
1267    /// Whether the interface body being parsed still closes: scans forward,
1268    /// brace-aware, for an `RBrace` at depth 0 before the end of input or an
1269    /// unambiguous new-top-level marker (`package`, `import`, `interface`).
1270    /// Decides the recovery for a typl definition keyword inside a body: a
1271    /// body-local ErrorNode when the body closes (RIDL-107),
1272    /// an unclosed-`{` report when it does not. The scan runs through the
1273    /// definition keywords themselves — several stray declarations inside
1274    /// one closed body must all recover in place.
1275    fn interface_body_close_ahead(&self) -> bool {
1276        let mut depth = 0usize;
1277        for token in self.tokens[self.significant_pos()..]
1278            .iter()
1279            .filter(|token| !token.kind.is_trivia())
1280        {
1281            match token.kind {
1282                SyntaxKind::LBrace => depth += 1,
1283                SyntaxKind::RBrace if depth == 0 => return true,
1284                SyntaxKind::RBrace => depth -= 1,
1285                SyntaxKind::PackageKw
1286                | SyntaxKind::ImportKw
1287                | SyntaxKind::InterfaceKw
1288                | SyntaxKind::ServiceKw
1289                    if depth == 0 =>
1290                {
1291                    return false;
1292                }
1293                _ => {}
1294            }
1295        }
1296        false
1297    }
1298
1299    /// Consumes one stray typl declaration inside an interface body into a
1300    /// single [`ErrorNode`](SyntaxKind::ErrorNode). Brace-aware, unlike
1301    /// [`Parser::recover`]: a composite body (`struct`/`enum`/… with its
1302    /// `{ … }`, commas included) is consumed whole, so the declaration's own
1303    /// `}` is never taken for the interface's closer and the members after
1304    /// it stay in the body. At depth 0 the interface sync set applies. The
1305    /// caller has confirmed the body's `}` lies ahead
1306    /// ([`Parser::interface_body_close_ahead`]), so the loop terminates
1307    /// there at the latest.
1308    fn recover_definition_in_body(&mut self) {
1309        self.start(SyntaxKind::ErrorNode);
1310        self.bump(); // the typl definition keyword
1311        let mut depth = 0usize;
1312        while let Some(kind) = self.current() {
1313            match kind {
1314                SyntaxKind::LBrace => depth += 1,
1315                SyntaxKind::RBrace if depth > 0 => depth -= 1,
1316                _ if depth == 0
1317                    && (matches!(
1318                        kind,
1319                        SyntaxKind::RBrace | SyntaxKind::Comma | SyntaxKind::ReservedKw
1320                    ) || is_interaction_start(kind)
1321                        || is_top_level_start(kind)) =>
1322                {
1323                    break;
1324                }
1325                _ => {}
1326            }
1327            self.bump();
1328        }
1329        self.builder.finish_node();
1330    }
1331
1332    /// The shared `kw Name ':' payload InitValue? annotations` shape of the
1333    /// three value interactions — `SignalDef`, `EventDef`, and `FixedDef`.
1334    /// The bare `= value` init comes before the timing (ADR-0008 decision
1335    /// 2). All three kinds accept an init, a timing, and an attr block, as
1336    /// the reference's Appendix C shows; the checker narrows them (FORM-102
1337    /// for an init on an event or a fixed, RIDL-106/-301).
1338    fn value_interaction(&mut self, kind: SyntaxKind) {
1339        self.start(kind);
1340        self.bump(); // 'signal' | 'event' | 'fixed'
1341        self.name();
1342        self.expect(SyntaxKind::Colon);
1343        self.field_type();
1344        self.init_value_opt();
1345        self.interaction_annotations();
1346        self.builder.finish_node();
1347    }
1348
1349    /// The shared `kw Name '(' params ')' (':' ReturnType)? annotations`
1350    /// shape of the two callable interactions — `CommandDef` and
1351    /// `QueryDef`. A command's return type is lenient here (RIDL-104,
1352    /// checker scope); a query's is mandatory — a missing `:` draws
1353    /// FORM-101 (ridl reference §6.1, §7.1).
1354    fn callable_interaction(&mut self, kind: SyntaxKind) {
1355        self.start(kind);
1356        self.bump(); // 'command' | 'query'
1357        self.name();
1358        self.param_list();
1359        if self.at(SyntaxKind::Colon) {
1360            self.bump();
1361            self.return_type();
1362        } else if kind == SyntaxKind::QueryDef {
1363            self.error_at_current("FORM-101", "expected `:` and a return type".to_string());
1364        }
1365        self.interaction_annotations();
1366        self.builder.finish_node();
1367    }
1368
1369    /// `ParamList = '(' (params:Param ','?)* ')'` — separator commas are
1370    /// direct children of the list node, mirroring the block-body
1371    /// discipline (typl reference §15.2). No node is built when the `(` is
1372    /// missing, so `CommandDef::params()` sees `None`.
1373    fn param_list(&mut self) {
1374        if !self.at(SyntaxKind::LParen) {
1375            self.error_at_current("FORM-101", "expected `(`".to_string());
1376            return;
1377        }
1378        self.start(SyntaxKind::ParamList);
1379        self.bump(); // '('
1380        loop {
1381            self.eat_trivia();
1382            match self.current() {
1383                None => {
1384                    self.error_at_current("FORM-103", "unclosed `(`".to_string());
1385                    break;
1386                }
1387                Some(SyntaxKind::RParen) => {
1388                    self.bump();
1389                    break;
1390                }
1391                Some(SyntaxKind::Comma) => self.bump(),
1392                Some(SyntaxKind::Ident) => self.param(),
1393                // An unclosed `(`: the list ran into an interaction, body,
1394                // or top-level boundary. Report it and hand the token back.
1395                Some(kind)
1396                    if kind == SyntaxKind::RBrace
1397                        || is_interaction_start(kind)
1398                        || is_top_level_start(kind) =>
1399                {
1400                    self.error_at_current("FORM-103", "unclosed `(`".to_string());
1401                    break;
1402                }
1403                Some(_) => self.err_and_recover("in a parameter list", |kind| {
1404                    matches!(
1405                        kind,
1406                        SyntaxKind::RParen
1407                            | SyntaxKind::Comma
1408                            | SyntaxKind::Ident
1409                            | SyntaxKind::RBrace
1410                    ) || is_interaction_start(kind)
1411                        || is_top_level_start(kind)
1412                }),
1413            }
1414        }
1415        self.builder.finish_node();
1416    }
1417
1418    /// `Param = Name ':' (FieldType | StreamType)` — a named typl type, a
1419    /// tuple (typl §11), or a stream `<T>` (ridl reference §12.1); the
1420    /// stream parses through the shared field-type dispatch.
1421    fn param(&mut self) {
1422        self.start(SyntaxKind::Param);
1423        self.name();
1424        self.expect(SyntaxKind::Colon);
1425        self.field_type();
1426        self.builder.finish_node();
1427    }
1428
1429    /// `ReturnType = PathType | TupleType | StreamType | FallibleType` —
1430    /// the four return shapes (ridl reference §7.1). A named type followed
1431    /// by `|` extends into `FallibleType = ok '|' err` (general form §6.1,
1432    /// ADR-0008 decision 1). No node is built when no shape starts here, so
1433    /// `return_type()` accessors see `None`.
1434    fn return_type(&mut self) {
1435        self.eat_trivia();
1436        match self.current() {
1437            Some(SyntaxKind::LParen) => {
1438                self.start(SyntaxKind::ReturnType);
1439                self.tuple_type();
1440                self.builder.finish_node();
1441            }
1442            Some(SyntaxKind::Lt) => {
1443                self.start(SyntaxKind::ReturnType);
1444                self.stream_type();
1445                self.builder.finish_node();
1446            }
1447            _ if self.at_path_segment() => {
1448                self.start(SyntaxKind::ReturnType);
1449                let checkpoint = self.builder.checkpoint();
1450                self.path_type();
1451                if self.at(SyntaxKind::Pipe) {
1452                    self.builder
1453                        .start_node_at(checkpoint, SyntaxKind::FallibleType.into());
1454                    self.bump(); // '|'
1455                    self.path_type();
1456                    self.builder.finish_node();
1457                }
1458                self.builder.finish_node();
1459            }
1460            _ => {
1461                self.error_at_current(
1462                    "FORM-101",
1463                    "a return type must be a named type, a named-field tuple `(a: A, b: B)`, a \
1464                     stream `<T>`, or a fallible `T | E` (ridl reference §7.1)"
1465                        .to_string(),
1466                );
1467                // Consume what stands here into an `ErrorNode` rather than
1468                // leaving it for `interaction_annotations`. A rejected return
1469                // shape most often starts with `[` — a collection, `[Level;
1470                // 0..8]` — and leaving it behind made the annotation parser
1471                // read it as this member's attribute block, so one mistake drew
1472                // a FORM-102 and a FORM-106 "unknown attribute key `Level`" on
1473                // top of the real diagnostic. `@` stays in the sync set so a
1474                // timing annotation written after a broken return is still
1475                // parsed and still reaches its own check.
1476                if self.current().is_some_and(|kind| !is_return_sync(kind)) {
1477                    self.recover(is_return_sync);
1478                }
1479            }
1480        }
1481    }
1482
1483    /// `StreamType = '<' (PathType | 'string' | 'bytes') '>'` — the element
1484    /// is a named type, or a bare raw `string`/`bytes` token (ridl
1485    /// reference §12.2, the one exception to typl §15.3). Callers have
1486    /// confirmed the `<`.
1487    fn stream_type(&mut self) {
1488        self.start(SyntaxKind::StreamType);
1489        self.bump(); // '<'
1490        if matches!(
1491            self.current(),
1492            Some(SyntaxKind::StringKw | SyntaxKind::BytesKw)
1493        ) && self.nth(1) == Some(SyntaxKind::Gt)
1494        {
1495            self.bump(); // the raw element keyword
1496        } else if self.at_path_segment() {
1497            self.path_type();
1498        } else {
1499            self.error_at_current("FORM-101", "expected an element type".to_string());
1500        }
1501        self.expect(SyntaxKind::Gt);
1502        self.builder.finish_node();
1503    }
1504
1505    /// The lenient trailing annotations of an interaction: at most one
1506    /// [`Timing`](SyntaxKind::Timing) and at most one
1507    /// [`AttrBlock`](SyntaxKind::AttrBlock), in either order. Which kinds
1508    /// may carry which annotation is checker scope (RIDL-104/-106/-301); the
1509    /// parser accepts both on every interaction.
1510    fn interaction_annotations(&mut self) {
1511        let mut seen_timing = false;
1512        let mut seen_attrs = false;
1513        loop {
1514            match self.current() {
1515                Some(SyntaxKind::At) if !seen_timing => {
1516                    seen_timing = true;
1517                    self.timing();
1518                }
1519                Some(SyntaxKind::LBracket) if !seen_attrs => {
1520                    seen_attrs = true;
1521                    self.attr_block();
1522                }
1523                _ => break,
1524            }
1525        }
1526    }
1527
1528    /// `Timing = '@' ('duration' | '[' TimingRange ']')` — strict periodic
1529    /// or range (ridl reference §9). Callers have confirmed the `@`.
1530    fn timing(&mut self) {
1531        self.start(SyntaxKind::Timing);
1532        self.bump(); // '@'
1533        if self.at(SyntaxKind::Duration) {
1534            self.bump();
1535        } else if self.at(SyntaxKind::LBracket) {
1536            self.bump();
1537            self.timing_range();
1538            self.expect(SyntaxKind::RBracket);
1539        } else {
1540            self.error_at_current("FORM-101", "expected a duration or `[`".to_string());
1541        }
1542        self.builder.finish_node();
1543    }
1544
1545    /// `TimingRange = 'duration'? '..' 'duration'?` — both bounds or the
1546    /// half-open forms `min..` and `..max` (ridl reference §9). A range
1547    /// with neither bound is a structural error (FORM-101).
1548    fn timing_range(&mut self) {
1549        self.start(SyntaxKind::TimingRange);
1550        let has_min = self.at(SyntaxKind::Duration);
1551        if has_min {
1552            self.bump();
1553        }
1554        self.expect(SyntaxKind::DotDot);
1555        let has_max = self.at(SyntaxKind::Duration);
1556        if has_max {
1557            self.bump();
1558        }
1559        if !has_min && !has_max {
1560            self.error_at_current("FORM-101", "expected a duration".to_string());
1561        }
1562        self.builder.finish_node();
1563    }
1564
1565    /// `AttrBlock = '[' (attributes:Attribute ','?)* ']'` — the single
1566    /// attribute production of the general form (§4.2–§4.3). Separator
1567    /// commas are direct children of the block node, mirroring the
1568    /// block-body discipline. gf §4.2 requires at least one attribute per
1569    /// block: an empty `[]` still parses losslessly into an `AttrBlock`
1570    /// node and FORM-101 (`expected an attribute`) lands on the closing
1571    /// bracket. An unclosed block stops at an interaction or body boundary
1572    /// (FORM-103) instead of swallowing the rest of the interface.
1573    fn attr_block(&mut self) {
1574        self.start(SyntaxKind::AttrBlock);
1575        self.bump(); // '['
1576        let mut saw_attribute = false;
1577        loop {
1578            match self.current() {
1579                None => {
1580                    self.error_at_current("FORM-103", "unclosed `[`".to_string());
1581                    break;
1582                }
1583                Some(SyntaxKind::RBracket) => {
1584                    if !saw_attribute {
1585                        self.error_at_current("FORM-101", "expected an attribute".to_string());
1586                    }
1587                    self.bump();
1588                    break;
1589                }
1590                Some(SyntaxKind::Comma) => self.bump(),
1591                // A `ReservedWord` in key position goes through
1592                // [`Parser::name`], which holds it in an `ErrorNode` with
1593                // FORM-105 — the E1 reserved-word discipline — so the rest
1594                // of the attribute (`= value`) still parses.
1595                Some(
1596                    SyntaxKind::Ident
1597                    | SyntaxKind::RequireKw
1598                    | SyntaxKind::EnsureKw
1599                    | SyntaxKind::ReservedWord,
1600                ) => {
1601                    saw_attribute = true;
1602                    self.attribute();
1603                }
1604                Some(kind)
1605                    if kind == SyntaxKind::RBrace
1606                        || is_interaction_start(kind)
1607                        || is_top_level_start(kind) =>
1608                {
1609                    self.error_at_current("FORM-103", "unclosed `[`".to_string());
1610                    break;
1611                }
1612                Some(_) => self.err_and_recover("in an attribute block", |kind| {
1613                    matches!(
1614                        kind,
1615                        SyntaxKind::RBracket
1616                            | SyntaxKind::Comma
1617                            | SyntaxKind::Ident
1618                            | SyntaxKind::RequireKw
1619                            | SyntaxKind::EnsureKw
1620                            | SyntaxKind::ReservedWord
1621                            | SyntaxKind::RBrace
1622                    ) || is_interaction_start(kind)
1623                        || is_top_level_start(kind)
1624                }),
1625            }
1626        }
1627        self.builder.finish_node();
1628    }
1629
1630    /// `Attribute = key | key '=' const_value | ('require'|'ensure') expr`
1631    /// — the three forms of gf §4.2. One grammar production for all of
1632    /// them; which keys are legal where is checker scope (gf §4.3,
1633    /// FORM-106/107/108). Callers have confirmed the leading token is an
1634    /// `Ident` or a predicate keyword.
1635    fn attribute(&mut self) {
1636        self.start(SyntaxKind::Attribute);
1637        match self.current() {
1638            Some(SyntaxKind::RequireKw | SyntaxKind::EnsureKw) => {
1639                self.bump(); // 'require' | 'ensure'
1640                self.expr();
1641            }
1642            _ => {
1643                self.name(); // the attr key
1644                // A backend key `namespace.key` (rsdl reference §5, Appendix
1645                // B `key`). Only the rsdl profile admits the dotted key; under
1646                // typl and ridl the `.` stays an unexpected token in the block.
1647                if self.profile == Profile::Rsdl && self.at(SyntaxKind::Dot) {
1648                    self.bump(); // '.'
1649                    self.name();
1650                }
1651                if self.at(SyntaxKind::Eq) {
1652                    self.bump();
1653                    self.attr_value();
1654                }
1655            }
1656        }
1657        self.builder.finish_node();
1658    }
1659
1660    /// `const_value = literal | SCREAMING_SNAKE_ID | '(' const_value (','
1661    /// const_value)* ')'` (gf §4.2), as an [`AttrValue`](SyntaxKind::AttrValue)
1662    /// node: one `Literal` child (an `ident` value token is the constant
1663    /// reference), or a parenthesised list of nested `AttrValue`s. The
1664    /// depth guard bounds pathological list nesting, sharing the
1665    /// [`MAX_TYPE_DEPTH`] budget with the type and expression grammars.
1666    fn attr_value(&mut self) {
1667        if self.depth >= MAX_TYPE_DEPTH {
1668            self.error_at_current(
1669                "FORM-102",
1670                format!("value nesting deeper than {MAX_TYPE_DEPTH} levels"),
1671            );
1672            self.start(SyntaxKind::ErrorNode);
1673            self.bump();
1674            self.builder.finish_node();
1675            return;
1676        }
1677        self.depth += 1;
1678        self.attr_value_inner();
1679        self.depth -= 1;
1680    }
1681
1682    fn attr_value_inner(&mut self) {
1683        self.eat_trivia();
1684        if self.at(SyntaxKind::LParen) {
1685            self.start(SyntaxKind::AttrValue);
1686            self.bump(); // '('
1687            loop {
1688                self.eat_trivia();
1689                match self.current() {
1690                    None => {
1691                        self.error_at_current("FORM-103", "unclosed `(`".to_string());
1692                        break;
1693                    }
1694                    Some(SyntaxKind::RParen) => {
1695                        self.bump();
1696                        break;
1697                    }
1698                    Some(SyntaxKind::Comma) => self.bump(),
1699                    Some(SyntaxKind::LParen) => self.attr_value(),
1700                    Some(kind)
1701                        if kind == SyntaxKind::RBracket
1702                            || kind == SyntaxKind::RBrace
1703                            || is_interaction_start(kind)
1704                            || is_top_level_start(kind) =>
1705                    {
1706                        self.error_at_current("FORM-103", "unclosed `(`".to_string());
1707                        break;
1708                    }
1709                    _ if self.literal_len_at(0) > 0 => self.attr_value(),
1710                    Some(_) => self.err_and_recover("in an attribute value", |kind| {
1711                        matches!(
1712                            kind,
1713                            SyntaxKind::RParen
1714                                | SyntaxKind::Comma
1715                                | SyntaxKind::LParen
1716                                | SyntaxKind::RBracket
1717                                | SyntaxKind::RBrace
1718                        ) || is_interaction_start(kind)
1719                            || is_top_level_start(kind)
1720                    }),
1721                }
1722            }
1723            self.builder.finish_node();
1724        } else if self.literal_len_at(0) > 0 {
1725            self.start(SyntaxKind::AttrValue);
1726            self.literal();
1727            self.builder.finish_node();
1728        } else {
1729            self.error_at_current("FORM-101", "expected a value".to_string());
1730        }
1731    }
1732
1733    // --- the guaranteed-subset expression grammar ------------------
1734    //
1735    // The expr-core specification §3.1 productions, one function per
1736    // precedence level, loosest to tightest: `||` — `&&` — comparison —
1737    // additive — multiplicative — unary — member access. Binary levels are
1738    // left-associative (each iteration wraps the run so far in a fresh
1739    // BinaryExpr from the same checkpoint); a comparison never chains.
1740    // Inside an expression `<` is always the comparison operator — the
1741    // stream-type reading of `<` exists only in param-type and return-type
1742    // position, and the two positions never overlap.
1743    //
1744    // The height bound (driftsys/ridl#346). A left-associative chain builds
1745    // a tree as high as its term count, and a pass that recurses over the
1746    // tree needs stack in proportion to that height, so the parser bounds
1747    // the height of every expression tree at MAX_TYPE_DEPTH nodes. Every
1748    // function below returns the height of the subtree it built (1 for a
1749    // node whose children are all tokens, 0 when no node was built), and
1750    // `depth` counts the expression nodes open above the cursor. A node is
1751    // built only when `depth + height <= MAX_TYPE_DEPTH` (`expr_fits`): a
1752    // chain checks the wrap before consuming its operator, from the height
1753    // of the run so far plus one, and parses the right operand one level
1754    // deeper, so the operand's own checks account for the wrap above it; a
1755    // member step is checked like a chain wrap; a group or a prefix is
1756    // opened only when it and one leaf below it fit.
1757    // The invariant holds by induction over the build order: each node's
1758    // check covers the node itself, and a child built earlier sits one level
1759    // deeper under a parent whose height is at least the child's plus one.
1760    // A leaf is never checked, because every node above it was admitted
1761    // with room for one — a chain wrap counts its left operand as at least
1762    // one high even when that operand is missing. A
1763    // budget charged per parse call and released on return would not bound
1764    // the tree, because chains closed inside groups, and chains that are the
1765    // first operand of a looser chain, stack on the left spine.
1766    //
1767    // Past the limit the expression draws one FORM-102 and the rest of the
1768    // current group goes flat, as tokens under one ErrorNode: the tree stays
1769    // lossless and a later part of the same expression that does not fit
1770    // either is consumed the same way without a second diagnostic.
1771
1772    /// `expr = or_expr` — the entry point, called from a predicate
1773    /// attribute; a parenthesised group recurses through [`Parser::primary`].
1774    /// An attribute block is never inside a type or a value, so the
1775    /// expression starts at depth 0 and a leaf always fits below it.
1776    fn expr(&mut self) {
1777        self.expr_refused = false;
1778        self.or_expr();
1779    }
1780
1781    /// Whether an expression node `height` levels high fits at the current
1782    /// depth. Past the limit, reports FORM-102 at the current token unless
1783    /// the expression has already drawn one, so that one overlong expression
1784    /// draws one diagnostic whatever its shape. The message says how the
1785    /// levels are counted — one per binary operator, member access,
1786    /// parenthesised group and prefix — because the nesting of a flat
1787    /// operator chain is not visible in the source.
1788    fn expr_fits(&mut self, height: usize) -> bool {
1789        if self.depth + height <= MAX_TYPE_DEPTH {
1790            return true;
1791        }
1792        if !self.expr_refused {
1793            self.expr_refused = true;
1794            self.error_at_current(
1795                "FORM-102",
1796                format!(
1797                    "expression nesting deeper than {MAX_TYPE_DEPTH} levels (each operator, \
1798                     member access, parenthesised group and prefix nests one level)"
1799                ),
1800            );
1801        }
1802        false
1803    }
1804
1805    /// Consumes the rest of the current expression level as flat children
1806    /// of one [`ErrorNode`](SyntaxKind::ErrorNode): every token up to the
1807    /// `)` that closes the enclosing group, the `]` or `,` that ends the
1808    /// attribute, a brace, the end of input, a token that starts another
1809    /// construct, or the start of the next attribute, with or without a
1810    /// comma before it — a `require` or `ensure`, a reserved word in key
1811    /// position, or a key, which is an identifier where the expression has
1812    /// just ended in an operand and no operator can follow. A group opened
1813    /// inside is consumed through its own `)`.
1814    fn skip_expr_rest(&mut self) {
1815        self.start(SyntaxKind::ErrorNode);
1816        self.skip_expr_tokens();
1817        self.builder.finish_node();
1818    }
1819
1820    /// The token loop of [`Parser::skip_expr_rest`], without the node.
1821    fn skip_expr_tokens(&mut self) {
1822        let mut open = 0usize;
1823        let mut after_operand = false;
1824        while let Some(kind) = self.current() {
1825            match kind {
1826                SyntaxKind::RBracket
1827                | SyntaxKind::Comma
1828                | SyntaxKind::LBrace
1829                | SyntaxKind::RBrace
1830                | SyntaxKind::RequireKw
1831                | SyntaxKind::EnsureKw
1832                | SyntaxKind::ReservedWord => break,
1833                SyntaxKind::RParen if open == 0 => break,
1834                SyntaxKind::Ident if after_operand => break,
1835                _ if is_interaction_start(kind) || is_top_level_start(kind) => break,
1836                SyntaxKind::RParen => open -= 1,
1837                SyntaxKind::LParen => open += 1,
1838                _ => {}
1839            }
1840            after_operand = matches!(
1841                kind,
1842                SyntaxKind::Ident
1843                    | SyntaxKind::IntNumber
1844                    | SyntaxKind::FloatNumber
1845                    | SyntaxKind::String
1846                    | SyntaxKind::TrueKw
1847                    | SyntaxKind::FalseKw
1848                    | SyntaxKind::Duration
1849                    | SyntaxKind::RParen
1850            );
1851            self.bump();
1852        }
1853    }
1854
1855    /// The shared loop of the four chaining binary levels: `operand { op
1856    /// operand }`, each `op` a token `is_op` accepts, each iteration wrapping
1857    /// the run so far in a [`BinaryExpr`](SyntaxKind::BinaryExpr) from the
1858    /// same checkpoint. Returns the height of the tree built.
1859    fn chain(&mut self, is_op: fn(SyntaxKind) -> bool, operand: fn(&mut Self) -> usize) -> usize {
1860        self.eat_trivia();
1861        let checkpoint = self.builder.checkpoint();
1862        let mut height = operand(self);
1863        while self.current().is_some_and(is_op) {
1864            // A missing left operand (FORM-101, already reported) has height
1865            // 0; the wrap still holds the right operand, so it is at least
1866            // two high, and the check must say so for the leaf below to fit.
1867            if !self.expr_fits(height.max(1) + 1) {
1868                self.skip_expr_rest();
1869                break;
1870            }
1871            self.builder
1872                .start_node_at(checkpoint, SyntaxKind::BinaryExpr.into());
1873            self.bump();
1874            self.depth += 1;
1875            let rhs = operand(self);
1876            self.depth -= 1;
1877            self.builder.finish_node();
1878            height = 1 + height.max(rhs);
1879        }
1880        height
1881    }
1882
1883    /// `or_expr = and_expr { '||' and_expr }`
1884    fn or_expr(&mut self) -> usize {
1885        self.chain(|kind| kind == SyntaxKind::PipePipe, Self::and_expr)
1886    }
1887
1888    /// `and_expr = cmp_expr { '&&' cmp_expr }`
1889    fn and_expr(&mut self) -> usize {
1890        self.chain(|kind| kind == SyntaxKind::AmpAmp, Self::cmp_expr)
1891    }
1892
1893    /// `cmp_expr = add_expr [ cmp_op add_expr ]` — at most one comparison:
1894    /// `a < b < c` is a parse error (write `a < b && b < c`), reported by
1895    /// whatever context the leftover operator lands in.
1896    fn cmp_expr(&mut self) -> usize {
1897        self.eat_trivia();
1898        let checkpoint = self.builder.checkpoint();
1899        let mut height = self.add_expr();
1900        if matches!(
1901            self.current(),
1902            Some(
1903                SyntaxKind::EqEq
1904                    | SyntaxKind::Neq
1905                    | SyntaxKind::Lt
1906                    | SyntaxKind::Le
1907                    | SyntaxKind::Gt
1908                    | SyntaxKind::Ge
1909            )
1910        ) {
1911            if !self.expr_fits(height.max(1) + 1) {
1912                self.skip_expr_rest();
1913                return height;
1914            }
1915            self.builder
1916                .start_node_at(checkpoint, SyntaxKind::BinaryExpr.into());
1917            self.bump();
1918            self.depth += 1;
1919            let rhs = self.add_expr();
1920            self.depth -= 1;
1921            self.builder.finish_node();
1922            height = 1 + height.max(rhs);
1923        }
1924        height
1925    }
1926
1927    /// `add_expr = mul_expr { ('+' | '-') mul_expr }`
1928    fn add_expr(&mut self) -> usize {
1929        self.chain(
1930            |kind| matches!(kind, SyntaxKind::Plus | SyntaxKind::Minus),
1931            Self::mul_expr,
1932        )
1933    }
1934
1935    /// `mul_expr = unary_expr { ('*' | '/' | '%') unary_expr }`
1936    fn mul_expr(&mut self) -> usize {
1937        self.chain(
1938            |kind| {
1939                matches!(
1940                    kind,
1941                    SyntaxKind::Star | SyntaxKind::Slash | SyntaxKind::Percent
1942                )
1943            },
1944            Self::unary_expr,
1945        )
1946    }
1947
1948    /// `unary_expr = [ '!' | '-' ] postfix_expr` — at most one prefix.
1949    fn unary_expr(&mut self) -> usize {
1950        if matches!(self.current(), Some(SyntaxKind::Bang | SyntaxKind::Minus)) {
1951            if !self.expr_fits(2) {
1952                self.skip_expr_rest();
1953                return 1;
1954            }
1955            self.start(SyntaxKind::PrefixExpr);
1956            self.bump();
1957            self.depth += 1;
1958            let operand = self.postfix_expr();
1959            self.depth -= 1;
1960            self.builder.finish_node();
1961            1 + operand
1962        } else {
1963            self.postfix_expr()
1964        }
1965    }
1966
1967    /// `postfix_expr = primary { '.' member }` — each `.member` step wraps
1968    /// the run so far in a [`MemberExpr`](SyntaxKind::MemberExpr), so
1969    /// `filter.severity` and `GearPosition.PARK` nest left-associatively.
1970    fn postfix_expr(&mut self) -> usize {
1971        self.eat_trivia();
1972        let checkpoint = self.builder.checkpoint();
1973        let mut height = self.primary();
1974        while self.at(SyntaxKind::Dot) {
1975            if !self.expr_fits(height + 1) {
1976                self.skip_expr_rest();
1977                break;
1978            }
1979            self.builder
1980                .start_node_at(checkpoint, SyntaxKind::MemberExpr.into());
1981            self.bump(); // '.'
1982            if self.at(SyntaxKind::Ident) {
1983                self.bump();
1984            } else {
1985                self.error_at_current("FORM-101", "expected a member name".to_string());
1986            }
1987            self.builder.finish_node();
1988            height += 1;
1989        }
1990        height
1991    }
1992
1993    /// `primary = literal | duration_lit | path_head | '(' expr ')'` — a
1994    /// [`LiteralExpr`](SyntaxKind::LiteralExpr) (typl literal or duration —
1995    /// zero durations are legal in expression position, expr-core spec
1996    /// §3.1), a [`PathExpr`](SyntaxKind::PathExpr), or a parenthesised
1997    /// group. No node is built when no primary starts here, so a missing
1998    /// operand reports FORM-101 without consuming the boundary token. The
1999    /// group is where the grammar recurses, so the height bound is also what
2000    /// keeps a run of `(` from overflowing the parser's own stack: a group
2001    /// that does not fit is consumed flat through its `)`.
2002    fn primary(&mut self) -> usize {
2003        match self.current() {
2004            Some(
2005                SyntaxKind::IntNumber
2006                | SyntaxKind::FloatNumber
2007                | SyntaxKind::String
2008                | SyntaxKind::TrueKw
2009                | SyntaxKind::FalseKw
2010                | SyntaxKind::Duration,
2011            ) => {
2012                self.start(SyntaxKind::LiteralExpr);
2013                if self.at(SyntaxKind::IntNumber) {
2014                    self.flag_leading_zeros();
2015                }
2016                self.bump();
2017                self.builder.finish_node();
2018                1
2019            }
2020            Some(SyntaxKind::Ident) => {
2021                self.start(SyntaxKind::PathExpr);
2022                self.bump();
2023                self.builder.finish_node();
2024                1
2025            }
2026            Some(SyntaxKind::LParen) => {
2027                if !self.expr_fits(2) {
2028                    self.start(SyntaxKind::ErrorNode);
2029                    self.bump(); // '('
2030                    self.skip_expr_tokens();
2031                    if self.at(SyntaxKind::RParen) {
2032                        self.bump();
2033                    }
2034                    self.builder.finish_node();
2035                    return 1;
2036                }
2037                self.start(SyntaxKind::ParenExpr);
2038                self.bump();
2039                self.depth += 1;
2040                let inner = self.or_expr();
2041                self.depth -= 1;
2042                self.expect(SyntaxKind::RParen);
2043                self.builder.finish_node();
2044                1 + inner
2045            }
2046            _ => {
2047                self.error_at_current("FORM-101", "expected an expression".to_string());
2048                0
2049            }
2050        }
2051    }
2052
2053    /// `EnumValue = Name '=' value:Literal`
2054    fn enum_value(&mut self) {
2055        self.value_assignment(SyntaxKind::EnumValue);
2056    }
2057
2058    /// `EnumSetBit = Name '=' value:Literal`
2059    fn enum_set_bit(&mut self) {
2060        self.value_assignment(SyntaxKind::EnumSetBit);
2061    }
2062
2063    /// The shared `Name '=' Literal` shape of enum values and enumset bits.
2064    fn value_assignment(&mut self, kind: SyntaxKind) {
2065        self.start(kind);
2066        self.name();
2067        self.expect(SyntaxKind::Eq);
2068        self.literal();
2069        self.builder.finish_node();
2070    }
2071
2072    /// The shared block-body loop (§15.2): members separated by newlines or
2073    /// commas, trailing comma permitted, separator commas placed as direct
2074    /// children of the block node between members. `member` parses the
2075    /// member a leading `Ident` announces; `allow_reserved` admits
2076    /// `ReservedEntry` members (structs, enums, unions — not enumsets).
2077    fn block_body(&mut self, context: &str, allow_reserved: bool, member: fn(&mut Self)) {
2078        if !self.block_open() {
2079            return;
2080        }
2081        loop {
2082            self.eat_trivia();
2083            match self.current() {
2084                None => {
2085                    self.error_at_current("FORM-103", "unclosed `{`".to_string());
2086                    break;
2087                }
2088                Some(SyntaxKind::RBrace) => {
2089                    self.bump();
2090                    break;
2091                }
2092                Some(SyntaxKind::Comma) => self.bump(),
2093                Some(SyntaxKind::ReservedKw) if allow_reserved => self.reserved_entry(),
2094                Some(SyntaxKind::Ident) => member(self),
2095                // An unclosed `{`: the body ran into the next top-level
2096                // declaration. Report the missing brace and let `source_file`
2097                // resynchronize instead of swallowing the declaration.
2098                Some(kind) if is_top_level_start(kind) => {
2099                    self.error_at_current("FORM-103", "unclosed `{`".to_string());
2100                    break;
2101                }
2102                Some(_) => self.err_and_recover(context, |kind| {
2103                    matches!(
2104                        kind,
2105                        SyntaxKind::RBrace | SyntaxKind::Comma | SyntaxKind::Ident
2106                    ) || (allow_reserved && kind == SyntaxKind::ReservedKw)
2107                        || is_top_level_start(kind)
2108                }),
2109            }
2110        }
2111    }
2112
2113    /// Consumes the `{` opening a block body; reports FORM-101 and returns
2114    /// `false` when it is missing, so the caller skips the body loop instead
2115    /// of swallowing the rest of the file.
2116    fn block_open(&mut self) -> bool {
2117        if self.at(SyntaxKind::LBrace) {
2118            self.bump();
2119            true
2120        } else {
2121            self.error_at_current("FORM-101", "expected `{`".to_string());
2122            false
2123        }
2124    }
2125
2126    /// `FieldDef = Name ':' FieldType InitValue?`
2127    fn field_def(&mut self) {
2128        self.start(SyntaxKind::FieldDef);
2129        self.name();
2130        self.expect(SyntaxKind::Colon);
2131        self.field_type();
2132        self.init_value_opt();
2133        self.builder.finish_node();
2134    }
2135
2136    /// `ReservedEntry = 'reserved' (Name | int_lit)` — the tombstone (§7.4).
2137    /// typl Appendix E spells it `reserved = "reserved" ( camelCase_id |
2138    /// int_lit )`. The production is body-agnostic and this parser keeps it
2139    /// that way: both forms parse in every body that admits a tombstone.
2140    ///
2141    /// What each form *means* is per body, and **nothing narrows it** — there
2142    /// is no per-body check anywhere, so this comment describes the language,
2143    /// not an enforced rule. The name form is meaningful everywhere (TYPL-210
2144    /// in a struct, union or enum; RIDL-401 in an interface). The integer form
2145    /// is meaningful in an `enum`, where it retires a wire value (TYPL-210),
2146    /// and in an interaction body, where the nameless spelling records the
2147    /// ordinal it protects (`veh-cluster/cluster/evolution.ridl`). In a
2148    /// `struct` or `union` body it is **inert**: members there carry no
2149    /// explicit value, so nothing can ever match it and no retired name is
2150    /// recorded. `test_data/parser/ok/grammar_overapprox.typl` carries that
2151    /// case as an over-approximation awaiting a checker rule; see
2152    /// `veh-cluster/NOTES` for the residual and what closing it needs.
2153    ///
2154    /// Any other literal — a string, a boolean, a float, a regex, a bare
2155    /// constant reference — is outside the grammar and draws FORM-102 here
2156    /// rather than parsing as a `Literal`. Lowering keeps only a `Name` or an
2157    /// integer, so an ungrammatical literal would otherwise consume the
2158    /// ordinal while recording neither: the tombstone survives but the
2159    /// retired identity it exists to record is destroyed, with no diagnostic.
2160    /// The offending token is held in an `ErrorNode` so the tree stays
2161    /// lossless and the body loop resumes at the next member.
2162    fn reserved_entry(&mut self) {
2163        self.start(SyntaxKind::ReservedEntry);
2164        self.bump(); // 'reserved'
2165        if self.at(SyntaxKind::Ident) {
2166            self.name();
2167        } else if let Some(kind) = self.literal_value_kind_at(0) {
2168            if kind == SyntaxKind::IntNumber {
2169                self.literal();
2170            } else {
2171                self.start(SyntaxKind::ErrorNode);
2172                // A leading `-` belongs to the literal but is not what makes
2173                // it ungrammatical, so it is consumed before the diagnostic is
2174                // raised: the caret then lands on the value token the message
2175                // names, as it already does for every single-token shape.
2176                if self.at(SyntaxKind::Minus) {
2177                    self.bump();
2178                }
2179                self.error_at_current(
2180                    "FORM-102",
2181                    format!(
2182                        "a `reserved` tombstone takes a retired member name or a retired integer value, not {}",
2183                        ungrammatical_reserved_noun(kind),
2184                    ),
2185                );
2186                self.bump();
2187                self.builder.finish_node();
2188            }
2189        } else {
2190            self.error_at_current(
2191                "FORM-101",
2192                "expected a name or an integer value".to_string(),
2193            );
2194        }
2195        self.builder.finish_node();
2196    }
2197
2198    /// `FieldType = PathType | PrimitiveType | TupleType | ArrayType |
2199    /// MapType | OptionalType` — the type of a field, tuple field, or
2200    /// collection element. Each `?` suffix wraps the type parsed so far in an
2201    /// `OptionalType` node. The depth guard keeps a pathological nesting of
2202    /// collection and tuple types from overflowing the stack — the parser
2203    /// must never panic.
2204    fn field_type(&mut self) {
2205        if self.depth >= MAX_TYPE_DEPTH {
2206            self.error_at_current(
2207                "FORM-102",
2208                format!("type nesting deeper than {MAX_TYPE_DEPTH} levels"),
2209            );
2210            self.start(SyntaxKind::ErrorNode);
2211            self.bump();
2212            self.builder.finish_node();
2213            return;
2214        }
2215        self.depth += 1;
2216        self.field_type_inner();
2217        self.depth -= 1;
2218    }
2219
2220    fn field_type_inner(&mut self) {
2221        self.eat_trivia();
2222        let checkpoint = self.builder.checkpoint();
2223        match self.current() {
2224            Some(
2225                kw @ (SyntaxKind::BooleanKw
2226                | SyntaxKind::IntegerKw
2227                | SyntaxKind::FloatKw
2228                | SyntaxKind::StringKw
2229                | SyntaxKind::BytesKw),
2230            ) => {
2231                // The inline constrained primitive (`integer [0..6]`,
2232                // §15.3): in field position the constraint nests inside
2233                // PrimitiveType, unlike the `type`-definition position.
2234                self.start(SyntaxKind::PrimitiveType);
2235                self.bump();
2236                if self.at(SyntaxKind::LBracket) {
2237                    let stringish = matches!(kw, SyntaxKind::StringKw | SyntaxKind::BytesKw);
2238                    self.constraint(stringish);
2239                }
2240                self.builder.finish_node();
2241            }
2242            Some(SyntaxKind::Ident) => self.path_type(),
2243            Some(SyntaxKind::LParen) => self.tuple_type(),
2244            Some(SyntaxKind::LBracket) => self.array_or_map(checkpoint),
2245            Some(SyntaxKind::Lt) => {
2246                // The stream container `<T>` (ridl reference §12) parses in
2247                // every type position under both profiles; in a `.typl`
2248                // parse it is the profile boundary — TYPL-301 — and parsing
2249                // continues (ADR-0007 decision 10). Under `Profile::Ridl`
2250                // the positions where a stream is not allowed (struct
2251                // fields, signal and event payloads) are checker scope.
2252                if self.profile == Profile::Typl {
2253                    self.error_at_current("TYPL-301", "stream type in typl context".to_string());
2254                }
2255                self.stream_type();
2256            }
2257            _ => {
2258                self.error_at_current("FORM-101", "expected a type".to_string());
2259                return;
2260            }
2261        }
2262        // Each `?` wraps one OptionalType node, so an unbounded run would
2263        // build a tree deep enough to overflow the stack when it is later
2264        // traversed or dropped. The wrap count shares the MAX_TYPE_DEPTH
2265        // bound: past it, the remaining `?` tokens land flat in a single
2266        // ErrorNode with one FORM-102.
2267        let mut wraps = 0;
2268        while self.at(SyntaxKind::Question) {
2269            if wraps >= MAX_TYPE_DEPTH {
2270                self.error_at_current(
2271                    "FORM-102",
2272                    format!("type nesting deeper than {MAX_TYPE_DEPTH} levels"),
2273                );
2274                self.start(SyntaxKind::ErrorNode);
2275                while self.at(SyntaxKind::Question) {
2276                    self.bump();
2277                }
2278                self.builder.finish_node();
2279                break;
2280            }
2281            self.builder
2282                .start_node_at(checkpoint, SyntaxKind::OptionalType.into());
2283            self.bump();
2284            self.builder.finish_node();
2285            wraps += 1;
2286        }
2287    }
2288
2289    /// `TupleType = '(' fields:TupleField (',' fields:TupleField)* ')'` —
2290    /// separator commas are direct children of the tuple node.
2291    fn tuple_type(&mut self) {
2292        self.start(SyntaxKind::TupleType);
2293        self.bump(); // '('
2294        loop {
2295            self.eat_trivia();
2296            match self.current() {
2297                None => {
2298                    self.error_at_current("FORM-103", "unclosed `(`".to_string());
2299                    break;
2300                }
2301                Some(SyntaxKind::RParen) => {
2302                    self.bump();
2303                    break;
2304                }
2305                Some(SyntaxKind::Comma) => self.bump(),
2306                Some(SyntaxKind::Ident) => self.tuple_field(),
2307                // An unclosed `(`: the tuple ran into a block or top-level
2308                // boundary. Report it and let the enclosing loop recover.
2309                Some(kind) if kind == SyntaxKind::RBrace || is_top_level_start(kind) => {
2310                    self.error_at_current("FORM-103", "unclosed `(`".to_string());
2311                    break;
2312                }
2313                Some(_) => self.err_and_recover("in a tuple type", |kind| {
2314                    matches!(
2315                        kind,
2316                        SyntaxKind::RParen
2317                            | SyntaxKind::Comma
2318                            | SyntaxKind::Ident
2319                            | SyntaxKind::RBrace
2320                    ) || is_top_level_start(kind)
2321                }),
2322            }
2323        }
2324        self.builder.finish_node();
2325    }
2326
2327    /// `TupleField = Name ':' FieldType`
2328    fn tuple_field(&mut self) {
2329        self.start(SyntaxKind::TupleField);
2330        self.name();
2331        self.expect(SyntaxKind::Colon);
2332        self.field_type();
2333        self.builder.finish_node();
2334    }
2335
2336    /// `ArrayType = '[' element:FieldType ';' Bound ']'` or
2337    /// `MapType = '[' key:FieldType ':' value:FieldType ';' Bound ']'` — the
2338    /// node kind is decided by the token after the first type, then wrapped
2339    /// around everything from the checkpoint (the `[`).
2340    fn array_or_map(&mut self, checkpoint: rowan::Checkpoint) {
2341        self.bump(); // '['
2342        self.field_type(); // the element or key type
2343        if self.at(SyntaxKind::Colon) {
2344            self.builder
2345                .start_node_at(checkpoint, SyntaxKind::MapType.into());
2346            self.bump(); // ':'
2347            self.field_type(); // the value type
2348        } else {
2349            self.builder
2350                .start_node_at(checkpoint, SyntaxKind::ArrayType.into());
2351        }
2352        self.expect(SyntaxKind::Semicolon);
2353        self.bound();
2354        self.expect(SyntaxKind::RBracket);
2355        self.builder.finish_node();
2356    }
2357
2358    /// `Constraint = '[' … ']'` — see the module doc for the bound policy.
2359    fn constraint(&mut self, stringish: bool) {
2360        self.start(SyntaxKind::Constraint);
2361        self.bump(); // '['
2362        self.constraint_body(stringish);
2363        self.expect(SyntaxKind::RBracket);
2364        self.builder.finish_node();
2365    }
2366
2367    /// The three constraint shapes behind the brackets: a scalar range with
2368    /// optional step, a length bound with optional match, and a bare match.
2369    fn constraint_body(&mut self, stringish: bool) {
2370        match self.current() {
2371            Some(SyntaxKind::MatchKw) => {
2372                self.bump();
2373                self.literal();
2374            }
2375            Some(SyntaxKind::DotDot) => {
2376                // `[..max]` — an open lower bound is always the scalar shape.
2377                self.bump();
2378                self.literal();
2379                self.step_opt();
2380            }
2381            _ if self.literal_len_at(0) > 0 => self.constraint_led_by_literal(stringish),
2382            _ => self.error_at_current("FORM-101", "expected a constraint".to_string()),
2383        }
2384    }
2385
2386    /// A constraint whose body starts with a literal: decide between the
2387    /// length-`Bound` shape and the scalar-range shape (module doc policy).
2388    fn constraint_led_by_literal(&mut self, stringish: bool) {
2389        let first_len = self.literal_len_at(0);
2390        match self.nth(first_len) {
2391            // A single literal with no `..` is always a length bound:
2392            // `[17]`, `[8]`, `[17 match P]`.
2393            Some(SyntaxKind::RBracket | SyntaxKind::MatchKw) | None => {
2394                self.bound();
2395                self.match_opt();
2396            }
2397            Some(SyntaxKind::DotDot) => {
2398                let second_len = self.literal_len_at(first_len + 1);
2399                let after_second = self.nth(first_len + 1 + second_len);
2400                let bound_shape = stringish
2401                    && second_len > 0
2402                    && !self.literal_is_float_at(0)
2403                    && !self.literal_is_float_at(first_len + 1)
2404                    && matches!(
2405                        after_second,
2406                        Some(SyntaxKind::RBracket | SyntaxKind::MatchKw) | None
2407                    );
2408                if bound_shape {
2409                    self.bound();
2410                    self.match_opt();
2411                } else {
2412                    self.literal(); // min
2413                    self.bump(); // '..'
2414                    if self.literal_len_at(0) > 0 {
2415                        self.literal(); // max — absent on `[min..]`
2416                    }
2417                    self.step_opt();
2418                }
2419            }
2420            _ => {
2421                // Not a legal shape after the literal; parse the literal as a
2422                // length bound and let the closing-bracket check report.
2423                self.bound();
2424                self.match_opt();
2425            }
2426        }
2427    }
2428
2429    /// `Bound = min:Literal ('..' max:Literal)?`
2430    fn bound(&mut self) {
2431        if self.literal_len_at(0) == 0 {
2432            self.error_at_current("FORM-101", "expected a bound".to_string());
2433            return;
2434        }
2435        self.start(SyntaxKind::Bound);
2436        self.literal();
2437        if self.at(SyntaxKind::DotDot) {
2438            self.bump();
2439            self.literal();
2440        }
2441        self.builder.finish_node();
2442    }
2443
2444    /// `('step' step:Literal)?`
2445    fn step_opt(&mut self) {
2446        if self.at(SyntaxKind::StepKw) {
2447            self.bump();
2448            self.literal();
2449        }
2450    }
2451
2452    /// `('match' match_pattern:Literal)?`
2453    fn match_opt(&mut self) {
2454        if self.at(SyntaxKind::MatchKw) {
2455            self.bump();
2456            self.literal();
2457        }
2458    }
2459
2460    /// `InitValue = '=' Literal`, when present.
2461    fn init_value_opt(&mut self) {
2462        if self.at(SyntaxKind::Eq) {
2463            self.start(SyntaxKind::InitValue);
2464            self.bump();
2465            self.literal();
2466            self.builder.finish_node();
2467        }
2468    }
2469
2470    /// How many significant tokens the literal starting at the `n`-th
2471    /// significant position spans: 2 for `-` + value, 1 for a bare value, 0
2472    /// when no literal starts there.
2473    fn literal_len_at(&self, n: usize) -> usize {
2474        match self.nth(n) {
2475            Some(SyntaxKind::Minus) => match self.nth(n + 1) {
2476                Some(kind) if is_value_token(kind) => 2,
2477                _ => 0,
2478            },
2479            Some(kind) if is_value_token(kind) => 1,
2480            _ => 0,
2481        }
2482    }
2483
2484    /// The value token of the literal starting at the `n`-th significant
2485    /// position, looking past a leading `-`. `None` when no literal starts
2486    /// there. Lets a caller admit one literal shape and refuse the rest.
2487    fn literal_value_kind_at(&self, n: usize) -> Option<SyntaxKind> {
2488        match self.nth(n) {
2489            Some(SyntaxKind::Minus) => self.nth(n + 1).filter(|kind| is_value_token(*kind)),
2490            Some(kind) if is_value_token(kind) => Some(kind),
2491            _ => None,
2492        }
2493    }
2494
2495    /// Whether the literal starting at the `n`-th significant position has a
2496    /// float value token.
2497    fn literal_is_float_at(&self, n: usize) -> bool {
2498        match self.nth(n) {
2499            Some(SyntaxKind::FloatNumber) => true,
2500            Some(SyntaxKind::Minus) => matches!(self.nth(n + 1), Some(SyntaxKind::FloatNumber)),
2501            _ => false,
2502        }
2503    }
2504
2505    /// `Literal = '-'? ('int_number' | 'float_number' | 'string_lit' | 'true'
2506    /// | 'false' | 'regex' | 'ident')` — an `ident` is a constant reference
2507    /// in a value position. A duration literal here in a `.typl` parse is the
2508    /// profile boundary (TYPL-302); an integer with leading zeros is FORM-005.
2509    /// Under [`Profile::Ridl`] a duration is an ordinary token that is simply
2510    /// not a literal, so it falls through to the generic missing-value path.
2511    fn literal(&mut self) {
2512        if self.profile == Profile::Typl && self.at(SyntaxKind::Duration) {
2513            self.error_at_current("TYPL-302", "duration literal in typl context".to_string());
2514            self.start(SyntaxKind::ErrorNode);
2515            self.bump();
2516            self.builder.finish_node();
2517            return;
2518        }
2519        if self.literal_len_at(0) == 0 {
2520            self.error_at_current("FORM-101", "expected a value".to_string());
2521            return;
2522        }
2523        self.start(SyntaxKind::Literal);
2524        if self.at(SyntaxKind::Minus) {
2525            self.bump();
2526        }
2527        if self.at(SyntaxKind::IntNumber) {
2528            self.flag_leading_zeros();
2529        }
2530        self.bump();
2531        self.builder.finish_node();
2532    }
2533
2534    /// FORM-005: an integer literal with leading zeros (typl reference §2.4)
2535    /// lexes as one token and is flagged here.
2536    fn flag_leading_zeros(&mut self) {
2537        let i = self.significant_pos();
2538        let text = self.tokens[i].text;
2539        if text.len() > 1 && text.starts_with('0') {
2540            self.error_at_current("FORM-005", "integer literal has leading zeros".to_string());
2541        }
2542    }
2543
2544    /// A declared name — a single `Ident` wrapped in a `Name` node. A family
2545    /// reserved word is held in an `ErrorNode` and flagged FORM-105; otherwise
2546    /// no node is built when the name is missing, so accessors see `None`
2547    /// rather than an empty `Name`.
2548    fn name(&mut self) {
2549        if self.at(SyntaxKind::Ident) {
2550            self.start(SyntaxKind::Name);
2551            self.bump();
2552            self.builder.finish_node();
2553        } else if self.at(SyntaxKind::ReservedWord) {
2554            // A family reserved word (typl reference §1.4) used where a
2555            // declared name is expected: hold it in an `ErrorNode` so the
2556            // rest of the declaration still parses, and flag FORM-105.
2557            let message = format!(
2558                "reserved word `{}` used as identifier",
2559                self.tokens[self.significant_pos()].text,
2560            );
2561            self.error_at_current("FORM-105", message);
2562            self.start(SyntaxKind::ErrorNode);
2563            self.bump();
2564            self.builder.finish_node();
2565        } else {
2566            self.error_at_current("FORM-101", "expected a name".to_string());
2567        }
2568    }
2569
2570    /// Whether the current token can be a path segment. Primitive keywords
2571    /// are admitted as segments so `const MAX_GEAR : integer = 6` (typl
2572    /// reference Appendix B) parses; the checker narrows where a primitive
2573    /// is not allowed (TYPL-204 and the related composite checks).
2574    fn at_path_segment(&self) -> bool {
2575        matches!(
2576            self.current(),
2577            Some(
2578                SyntaxKind::Ident
2579                    | SyntaxKind::BooleanKw
2580                    | SyntaxKind::IntegerKw
2581                    | SyntaxKind::FloatKw
2582                    | SyntaxKind::StringKw
2583                    | SyntaxKind::BytesKw
2584            )
2585        )
2586    }
2587
2588    /// `PathType = QualifiedName` — a type reference in type position. No
2589    /// node is built when the reference is missing.
2590    fn path_type(&mut self) {
2591        if !self.at_path_segment() {
2592            self.error_at_current("FORM-101", "expected a type name".to_string());
2593            return;
2594        }
2595        self.start(SyntaxKind::PathType);
2596        self.qualified_name();
2597        self.builder.finish_node();
2598    }
2599
2600    /// `QualifiedName = 'ident' ('.' 'ident')*`
2601    fn qualified_name(&mut self) {
2602        if !self.at_path_segment() {
2603            self.error_at_current("FORM-101", "expected a name".to_string());
2604            return;
2605        }
2606        self.start(SyntaxKind::QualifiedName);
2607        self.bump();
2608        while self.at(SyntaxKind::Dot) {
2609            self.bump();
2610            if self.at_path_segment() {
2611                self.bump();
2612            } else {
2613                self.error_at_current("FORM-101", "expected a name after `.`".to_string());
2614                break;
2615            }
2616        }
2617        self.builder.finish_node();
2618    }
2619}
2620
2621#[cfg(test)]
2622mod tests {
2623    use super::*;
2624
2625    const FIXTURE: &str = include_str!("../fixtures/walking_skeleton.typl");
2626
2627    #[test]
2628    fn fixture_round_trips_losslessly() {
2629        let parse = parse(FIXTURE, Profile::Typl);
2630        assert_eq!(
2631            parse.syntax().text().to_string(),
2632            FIXTURE,
2633            "the tree text must reproduce the source byte for byte",
2634        );
2635        assert!(
2636            parse.errors().is_empty(),
2637            "the fixture must parse without errors, got: {:?}",
2638            parse.errors(),
2639        );
2640    }
2641
2642    #[test]
2643    fn mangled_input_round_trips_and_reports_errors() {
2644        let input = "type 123 :: [";
2645        let parse = parse(input, Profile::Typl);
2646        assert_eq!(
2647            parse.syntax().text().to_string(),
2648            input,
2649            "recovery must not drop any text",
2650        );
2651        assert!(
2652            !parse.errors().is_empty(),
2653            "broken input must produce at least one error",
2654        );
2655    }
2656
2657    #[test]
2658    fn parse_equality_is_green_node_identity() {
2659        assert_eq!(
2660            parse(FIXTURE, Profile::Typl),
2661            parse(FIXTURE, Profile::Typl),
2662            "parsing identical input twice must compare equal",
2663        );
2664        assert_ne!(
2665            parse(FIXTURE, Profile::Typl),
2666            parse("package fixtures\ntype X: m", Profile::Typl),
2667            "parsing different input must not compare equal",
2668        );
2669    }
2670
2671    /// The codes of the recorded errors, in source order.
2672    fn error_codes(input: &str) -> Vec<&'static str> {
2673        parse(input, Profile::Typl)
2674            .errors()
2675            .iter()
2676            .map(|e| e.code)
2677            .collect()
2678    }
2679
2680    #[test]
2681    fn missing_package_flags_form_104() {
2682        let codes = error_codes("type Speed: km/h\n");
2683        assert_eq!(codes, vec!["FORM-104"]);
2684    }
2685
2686    #[test]
2687    fn leading_zero_integer_flags_form_005() {
2688        let codes = error_codes("package p\nconst BAD = 042\n");
2689        assert_eq!(codes, vec!["FORM-005"]);
2690    }
2691
2692    #[test]
2693    fn duration_literal_flags_typl_302() {
2694        let parse = parse("package p\nconst BAD = 10ms\n", Profile::Typl);
2695        assert_eq!(
2696            parse.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2697            vec!["TYPL-302"],
2698        );
2699        assert_eq!(
2700            parse.syntax().text().to_string(),
2701            "package p\nconst BAD = 10ms\n",
2702            "the rejected duration token must stay in the tree",
2703        );
2704    }
2705
2706    #[test]
2707    fn stray_at_sigil_flags_typl_302() {
2708        let codes = error_codes("package p\n@\n");
2709        assert_eq!(codes, vec!["TYPL-302"]);
2710    }
2711
2712    // Under `Profile::Ridl` durations and `@` are ordinary tokens — no TYPL-302
2713    // fires anywhere.
2714    #[test]
2715    fn duration_and_at_draw_no_typl_302_under_ridl() {
2716        let parsed = parse("package p\nconst BAD = 10ms\n", Profile::Ridl);
2717        assert!(
2718            parsed.errors().iter().all(|e| e.code != "TYPL-302"),
2719            "no TYPL-302 under Ridl, got: {:?}",
2720            parsed.errors(),
2721        );
2722        let parsed = parse("package p\n@\n", Profile::Ridl);
2723        assert_eq!(
2724            parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2725            vec!["FORM-102"],
2726            "a stray `@` under Ridl is a generic unexpected token",
2727        );
2728    }
2729
2730    // An interaction keyword at declaration-start in a `.typl` parse is the
2731    // profile boundary — TYPL-304, recovering like FORM-105 does (ErrorNode,
2732    // resync at the next top-level keyword).
2733    #[test]
2734    fn interaction_keyword_in_typl_flags_typl_304_and_recovers() {
2735        let input = "package p\ninterface X {}\ntype Fine: m\n";
2736        let parsed = parse(input, Profile::Typl);
2737        assert_eq!(
2738            parsed.syntax().text().to_string(),
2739            input,
2740            "TYPL-304 recovery must stay lossless",
2741        );
2742        assert_eq!(
2743            parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2744            vec!["TYPL-304"],
2745        );
2746        assert_eq!(def_names_in(Profile::Typl, input), vec!["Fine"]);
2747
2748        // The same boundary fires for every interaction kind.
2749        let codes: Vec<_> = parse("package p\nsignal speed: Speed\n", Profile::Typl)
2750            .errors()
2751            .iter()
2752            .map(|e| e.code)
2753            .collect();
2754        assert_eq!(codes, vec!["TYPL-304"]);
2755    }
2756
2757    // The stream grammar parses under both profiles; in a `.typl` parse a `<T>`
2758    // in type position is the profile boundary — TYPL-301 — and the StreamType
2759    // node is still built, losslessly.
2760    #[test]
2761    fn stream_type_in_typl_flags_typl_301_and_keeps_parsing() {
2762        let input = "package p\nstruct S {\n  f : <Frame>\n  g : integer [0..1]\n}\n";
2763        let parsed = parse(input, Profile::Typl);
2764        assert_eq!(
2765            parsed.syntax().text().to_string(),
2766            input,
2767            "the TYPL-301 boundary must stay lossless",
2768        );
2769        assert_eq!(
2770            parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2771            vec!["TYPL-301"],
2772        );
2773        let has_stream = parsed
2774            .syntax()
2775            .descendants()
2776            .any(|node| node.kind() == SyntaxKind::StreamType);
2777        assert!(has_stream, "the stream still parses into a StreamType node");
2778
2779        // Under `Profile::Ridl` the same field parses with no error at all —
2780        // stream placement is checker scope there.
2781        let parsed = parse(input, Profile::Ridl);
2782        assert!(
2783            parsed.errors().is_empty(),
2784            "no parser error under Ridl, got: {:?}",
2785            parsed.errors(),
2786        );
2787    }
2788
2789    // A reserved word of another profile at declaration-start in a `.ridl` parse
2790    // is RIDL-403, with the same recovery.
2791    #[test]
2792    fn reserved_word_in_ridl_flags_ridl_403_and_recovers() {
2793        let input = "package p\nmodel X {}\ntype Fine: m\n";
2794        let parsed = parse(input, Profile::Ridl);
2795        assert_eq!(
2796            parsed.syntax().text().to_string(),
2797            input,
2798            "RIDL-403 recovery must stay lossless",
2799        );
2800        assert_eq!(
2801            parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2802            vec!["RIDL-403"],
2803        );
2804        assert_eq!(def_names_in(Profile::Ridl, input), vec!["Fine"]);
2805    }
2806
2807    // rsdl reference §2, the boundary seen from the other two profiles: an
2808    // rsdl declaration in a `.typl` file draws the generic FORM-102 (the typl
2809    // boundary names ridl words only), and in a `.ridl` file RIDL-403. Both
2810    // recover at the next top-level keyword.
2811    #[test]
2812    fn rsdl_declaration_in_typl_and_ridl_draws_their_existing_codes() {
2813        let input = "package p\ndistribution Adas { Cruise }\ntype Fine: m\n";
2814        for (profile, code) in [(Profile::Typl, "FORM-102"), (Profile::Ridl, "RIDL-403")] {
2815            let parsed = parse(input, profile);
2816            assert_eq!(parsed.syntax().text().to_string(), input);
2817            assert_eq!(
2818                parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2819                vec![code],
2820                "under {profile:?}",
2821            );
2822            assert_eq!(
2823                def_names_in(profile, input),
2824                vec!["Fine"],
2825                "under {profile:?}"
2826            );
2827        }
2828    }
2829
2830    // rsdl reference §2 and §3.1: under the rsdl profile the five declarations
2831    // parse clean, and a declaration of another profile is RSDL-604 — once per
2832    // declaration, with the rsdl declaration after it still parsed.
2833    #[test]
2834    fn rsdl_profile_parses_its_declarations_and_rejects_the_others() {
2835        let clean = "package p\nsystem Vehicle { Cruise, veh.diag.access }\n";
2836        assert_eq!(parse(clean, Profile::Rsdl).errors(), &[]);
2837
2838        for foreign in [
2839            "type Speed: km/h",
2840            "internal type Speed: km/h",
2841            "struct S { a: integer [0..1] }",
2842            "interface I { signal s: S @10ms }",
2843            "service veh.a.b : I",
2844        ] {
2845            let input = format!("package p\n{foreign}\nsystem Vehicle {{ Cruise }}\n");
2846            let parsed = parse(&input, Profile::Rsdl);
2847            assert_eq!(parsed.syntax().text().to_string(), input);
2848            assert_eq!(
2849                parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2850                vec!["RSDL-604"],
2851                "`{foreign}`",
2852            );
2853            assert!(
2854                parsed
2855                    .syntax()
2856                    .children()
2857                    .any(|node| node.kind() == SyntaxKind::SystemDef),
2858                "the system after `{foreign}` still parses",
2859            );
2860        }
2861    }
2862
2863    // rsdl reference §5: a backend key `namespace.key` is an rsdl attribute
2864    // key. Under ridl the `.` stays an unexpected token.
2865    #[test]
2866    fn a_backend_key_parses_under_rsdl_only() {
2867        let rsdl = "package p\nsystem V [ linux.cpuset = (2, 3), linux.realtime ] { A }\n";
2868        assert_eq!(parse(rsdl, Profile::Rsdl).errors(), &[]);
2869
2870        let ridl = "package p\ninterface I {\n  command c() [ linux.cpuset = 1 ]\n}\n";
2871        assert_eq!(
2872            parse(ridl, Profile::Ridl)
2873                .errors()
2874                .iter()
2875                .map(|e| e.code)
2876                .collect::<Vec<_>>(),
2877            vec!["FORM-102"],
2878        );
2879    }
2880
2881    /// Recovery from a rejected return type stops *before* a sync token — it
2882    /// never consumes the construct that follows.
2883    ///
2884    /// `return_type` reports and then recovers, and `recover` always bumps the
2885    /// current token, so without the `!is_return_sync(current)` guard a
2886    /// `query a() :` written immediately before a `}` eats the interface's own
2887    /// closing brace and the file then reports an unclosed `{`. Each row here
2888    /// is one member of the sync set, and each asserts on what *survived* — a
2889    /// diagnostic-count assertion cannot see over-consumption, because
2890    /// swallowing the `}` produces one extra diagnostic and swallowing an
2891    /// interaction produces none at all.
2892    #[test]
2893    fn a_rejected_return_type_never_consumes_the_construct_after_it() {
2894        for (sync, body, survivor) in [
2895            (
2896                "the next interaction keyword",
2897                "  query broken() :
2898  signal speed : Speed @10ms
2899",
2900                SyntaxKind::SignalDef,
2901            ),
2902            (
2903                "a `reserved` tombstone",
2904                "  query broken() :
2905  reserved legacyTemp
2906",
2907                SyntaxKind::ReservedEntry,
2908            ),
2909            (
2910                "the body's own closing brace",
2911                "  query broken() :
2912",
2913                SyntaxKind::InterfaceDef,
2914            ),
2915        ] {
2916            let input = format!(
2917                "package p
2918interface I {{
2919{body}}}
2920"
2921            );
2922            let parsed = parse(&input, Profile::Ridl);
2923            assert_eq!(
2924                parsed.syntax().text().to_string(),
2925                input,
2926                "{sync}: recovery must stay lossless",
2927            );
2928            assert_eq!(
2929                parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2930                vec!["FORM-101"],
2931                "{sync}: the broken return type is the only diagnostic — an                  unclosed `{{` here means the `}}` was consumed",
2932            );
2933            assert!(
2934                parsed
2935                    .syntax()
2936                    .descendants()
2937                    .any(|node| node.kind() == survivor),
2938                "{sync}: the {survivor:?} after the broken return type is gone",
2939            );
2940        }
2941    }
2942
2943    #[test]
2944    fn pathological_type_nesting_does_not_panic_or_drop_text() {
2945        let input = format!("package p\nstruct S {{ f : {} }}\n", "[".repeat(300));
2946        let parse = parse(&input, Profile::Typl);
2947        assert_eq!(
2948            parse.syntax().text().to_string(),
2949            input,
2950            "deep nesting must stay lossless",
2951        );
2952        assert!(!parse.errors().is_empty());
2953    }
2954
2955    #[test]
2956    fn pathological_question_repetition_does_not_panic_or_drop_text() {
2957        // Each `?` wraps one OptionalType; an unbounded run used to build a
2958        // tree deep enough to overflow the stack on traversal or drop.
2959        let input = format!("package p\nstruct S {{ f : T{} }}\n", "?".repeat(30_000));
2960        let parse = parse(&input, Profile::Typl);
2961        assert_eq!(
2962            parse.syntax().text().to_string(),
2963            input,
2964            "the capped optional run must stay lossless",
2965        );
2966        assert_eq!(
2967            parse.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2968            vec!["FORM-102"],
2969            "the cap must report exactly one error",
2970        );
2971    }
2972
2973    #[test]
2974    fn misplaced_error_modifier_parses_clean() {
2975        // TYPL-212 is checker scope: the grammar admits `error` on every
2976        // definition kind.
2977        let codes = error_codes("package p\nerror type Legacy : integer [0..1]\n");
2978        assert_eq!(codes, Vec::<&str>::new());
2979    }
2980
2981    #[test]
2982    fn error_ranges_cover_the_offending_token() {
2983        // `042` sits at bytes 22..25 of the input.
2984        let parse = parse("package p\nconst BAD = 042\n", Profile::Typl);
2985        let error = &parse.errors()[0];
2986        assert_eq!(error.code, "FORM-005");
2987        assert_eq!(
2988            error.range,
2989            TextRange::new(TextSize::new(22), TextSize::new(25)),
2990        );
2991    }
2992
2993    /// The declared names of every top-level definition, in source order —
2994    /// the recovery proof that real declaration nodes survive garbage.
2995    fn def_names(input: &str) -> Vec<String> {
2996        def_names_in(Profile::Typl, input)
2997    }
2998
2999    /// [`def_names`] under an explicit profile.
3000    fn def_names_in(profile: Profile, input: &str) -> Vec<String> {
3001        use crate::ast::{AstNode, HasName, SourceFile};
3002        let file = SourceFile::cast(parse(input, profile).syntax()).expect("root is a SourceFile");
3003        file.definitions()
3004            .filter_map(|def| Some(def.name()?.ident_token()?.text().to_string()))
3005            .collect()
3006    }
3007
3008    #[test]
3009    fn top_level_garbage_resyncs_to_the_next_declaration() {
3010        // Valid, then garbage, then valid: the run of stray tokens is wrapped
3011        // in one ErrorNode and the declaration after it is a real node again.
3012        let input = "package p\ntype Good: km/h\n] } garbage 9\ntype AlsoGood: integer [0..1]\n";
3013        let parse = parse(input, Profile::Typl);
3014        assert_eq!(
3015            parse.syntax().text().to_string(),
3016            input,
3017            "resync must stay lossless",
3018        );
3019        assert_eq!(def_names(input), vec!["Good", "AlsoGood"]);
3020        assert_eq!(error_codes(input), vec!["FORM-102"]);
3021    }
3022
3023    #[test]
3024    fn unclosed_brace_resyncs_to_the_next_declaration() {
3025        // A struct body that never closes hands the next `type` back to the
3026        // top level (FORM-103) instead of swallowing it.
3027        let input = "package p\nstruct Broken {\n  gear: integer\n\ntype After: km/h\n";
3028        let parse = parse(input, Profile::Typl);
3029        assert_eq!(
3030            parse.syntax().text().to_string(),
3031            input,
3032            "unclosed-brace recovery must stay lossless",
3033        );
3034        assert_eq!(def_names(input), vec!["Broken", "After"]);
3035        assert_eq!(error_codes(input), vec!["FORM-103"]);
3036    }
3037
3038    #[test]
3039    fn reserved_word_as_name_flags_form_105_and_keeps_parsing() {
3040        // `signal` is a family reserved word (typl reference §1.4); used as a
3041        // type name it is held in an ErrorNode and the backing still parses.
3042        let input = "package p\ntype signal: integer [0..1]\ntype Fine: integer [0..1]\n";
3043        assert_eq!(error_codes(input), vec!["FORM-105"]);
3044        // Only `Fine` has a real Name; `signal` sits in an ErrorNode.
3045        assert_eq!(def_names(input), vec!["Fine"]);
3046    }
3047
3048    #[test]
3049    fn unclosed_brackets_do_not_flood_diagnostics() {
3050        // 300 unclosed `[` in a field type: before the one-error-per-offset
3051        // rule the deep-recursion unwind piled hundreds of diagnostics on the
3052        // stuck tokens. Recovery now collapses the run to a handful.
3053        let input = format!("package p\nstruct S {{ f : {} }}\n", "[".repeat(300));
3054        let parse = parse(&input, Profile::Typl);
3055        assert_eq!(
3056            parse.syntax().text().to_string(),
3057            input,
3058            "the unclosed-bracket flood must stay lossless",
3059        );
3060        assert!(
3061            parse.errors().len() <= 4,
3062            "expected a bounded diagnostic count, got {}: {:?}",
3063            parse.errors().len(),
3064            parse.errors(),
3065        );
3066    }
3067
3068    #[test]
3069    fn duration_in_constraint_reports_both_form_101_and_typl_302() {
3070        // A duration or `@` inside a constraint fails a positional check on the
3071        // same token first; the profile-boundary TYPL-302 must still fire — it
3072        // is exempt from the one-diagnostic-per-offset suppression, so both
3073        // codes are recorded (matching the honest init-position behavior).
3074        assert_eq!(
3075            error_codes("package p\ntype X: integer [0..10ms]\n"),
3076            vec!["FORM-101", "TYPL-302"],
3077        );
3078        assert_eq!(
3079            error_codes("package p\ntype X: integer [10ms]\n"),
3080            vec!["FORM-101", "TYPL-302"],
3081        );
3082        assert_eq!(
3083            error_codes("package p\ntype X: integer [0..5 @ 3]\n"),
3084            vec!["FORM-101", "TYPL-302"],
3085        );
3086    }
3087
3088    #[test]
3089    fn closed_deep_nesting_does_not_flood_diagnostics() {
3090        // A balanced 200-level nested array, deeper than MAX_TYPE_DEPTH: the
3091        // closed shape once produced over a thousand diagnostics on unwind.
3092        let deep = format!("{}integer{}", "[".repeat(200), ";1]".repeat(200));
3093        let input = format!("package p\nstruct S {{ f : {deep} }}\n");
3094        let parse = parse(&input, Profile::Typl);
3095        assert_eq!(
3096            parse.syntax().text().to_string(),
3097            input,
3098            "the deep-nesting flood must stay lossless",
3099        );
3100        assert!(
3101            parse.errors().len() <= 4,
3102            "expected a bounded diagnostic count, got {}: {:?}",
3103            parse.errors().len(),
3104            parse.errors(),
3105        );
3106    }
3107
3108    /// typl Appendix E: `reserved = "reserved" ( camelCase_id | int_lit )`.
3109    /// The literal shapes outside that production draw FORM-102 in every body
3110    /// that admits a tombstone, under both profiles. Before this rule the
3111    /// entry parsed as an ordinary `Literal`, lowered to a slot with neither a
3112    /// name nor a value, and reported nothing.
3113    #[test]
3114    fn ungrammatical_reserved_literal_flags_form_102_in_every_body() {
3115        let bodies = [
3116            (
3117                Profile::Typl,
3118                "struct S {\n  a : X\n  reserved {}\n  b : X\n}",
3119            ),
3120            (
3121                Profile::Typl,
3122                "enum E {\n  A = 1\n  reserved {}\n  B = 2\n}",
3123            ),
3124            (
3125                Profile::Typl,
3126                "union U {\n  a : X\n  reserved {}\n  b : X\n}",
3127            ),
3128            (
3129                Profile::Ridl,
3130                "interface I {\n  signal a : X\n  reserved {}\n  signal b : X\n}",
3131            ),
3132            (
3133                Profile::Ridl,
3134                "service p.svc {\n  signal a : X\n  reserved {}\n  signal b : X\n}",
3135            ),
3136        ];
3137        for (profile, shape) in bodies {
3138            for literal in ["\"oldName\"", "true", "false", "1.5", "-1.5", "-MAX"] {
3139                let input = format!("package p\n{}\n", shape.replace("{}", literal));
3140                let parsed = parse(&input, profile);
3141                assert_eq!(
3142                    parsed.syntax().text().to_string(),
3143                    input,
3144                    "refusing `reserved {literal}` must stay lossless in {shape}",
3145                );
3146                assert_eq!(
3147                    parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
3148                    vec!["FORM-102"],
3149                    "`reserved {literal}` in {shape} must draw exactly one FORM-102",
3150                );
3151                assert!(
3152                    parsed.errors()[0].message.starts_with(
3153                        "a `reserved` tombstone takes a retired member name or a retired \
3154                         integer value, not "
3155                    ),
3156                    "the message must lead with what a tombstone does take, got {:?}",
3157                    parsed.errors()[0].message,
3158                );
3159                // The entry keeps its place as a member and the refused token
3160                // is held losslessly, so the member after it is still parsed
3161                // in position and no ordinal shifts.
3162                let entry = parsed
3163                    .syntax()
3164                    .descendants()
3165                    .find(|node| node.kind() == SyntaxKind::ReservedEntry)
3166                    .expect("the tombstone still forms a ReservedEntry");
3167                assert!(
3168                    entry
3169                        .children()
3170                        .any(|child| child.kind() == SyntaxKind::ErrorNode),
3171                    "the refused literal is held in an ErrorNode, got {entry:#?}",
3172                );
3173                assert!(
3174                    entry
3175                        .children()
3176                        .all(|child| child.kind() != SyntaxKind::Literal),
3177                    "the refused literal must not form a Literal, got {entry:#?}",
3178                );
3179            }
3180        }
3181    }
3182
3183    /// The two grammatical tombstone forms keep parsing, in every body and
3184    /// under both profiles: a name, a bare integer, and a negative integer
3185    /// (`int_lit = "-"? [0-9]+`). Narrowing the production must not narrow it
3186    /// past what Appendix E writes.
3187    #[test]
3188    fn grammatical_reserved_forms_still_parse_in_every_body() {
3189        let bodies = [
3190            (
3191                Profile::Typl,
3192                "struct S {\n  a : X\n  reserved {}\n  b : X\n}",
3193            ),
3194            (
3195                Profile::Typl,
3196                "enum E {\n  A = 1\n  reserved {}\n  B = 2\n}",
3197            ),
3198            (
3199                Profile::Typl,
3200                "union U {\n  a : X\n  reserved {}\n  b : X\n}",
3201            ),
3202            (
3203                Profile::Ridl,
3204                "interface I {\n  signal a : X\n  reserved {}\n  signal b : X\n}",
3205            ),
3206            (
3207                Profile::Ridl,
3208                "service p.svc {\n  signal a : X\n  reserved {}\n  signal b : X\n}",
3209            ),
3210        ];
3211        for (profile, shape) in bodies {
3212            for literal in ["legacyChecksum", "3", "-3"] {
3213                let input = format!("package p\n{}\n", shape.replace("{}", literal));
3214                let parsed = parse(&input, profile);
3215                assert!(
3216                    parsed.errors().is_empty(),
3217                    "`reserved {literal}` in {shape} must parse clean, got {:?}",
3218                    parsed.errors(),
3219                );
3220                let entry = parsed
3221                    .syntax()
3222                    .descendants()
3223                    .find(|node| node.kind() == SyntaxKind::ReservedEntry)
3224                    .expect("the tombstone forms a ReservedEntry");
3225                let kept = entry
3226                    .children()
3227                    .any(|child| matches!(child.kind(), SyntaxKind::Name | SyntaxKind::Literal));
3228                assert!(
3229                    kept,
3230                    "`reserved {literal}` must keep the retired identity, got {entry:#?}",
3231                );
3232            }
3233        }
3234    }
3235
3236    /// ADR-0015 decision 13: commas are required between service shapes,
3237    /// because the list has no closing token — it ends where the next
3238    /// declaration begins. A missing comma therefore ends the list, and the
3239    /// following bare `CamelCase` identifier is reported at the top level,
3240    /// **at the identifier**: the greedy alternative would absorb a mistyped
3241    /// `Struct Foo {` as another shape and surface the error at the `{` with
3242    /// no connection to the mistake.
3243    #[test]
3244    fn a_missing_comma_ends_the_shape_list_at_the_next_identifier() {
3245        let input = "package p\nservice p.svc : DoorControl\nStruct Foo {\n  a : X\n}\n";
3246        let parsed = parse(input, Profile::Ridl);
3247        assert_eq!(
3248            parsed.syntax().text().to_string(),
3249            input,
3250            "the ended list must stay lossless",
3251        );
3252        // The ServiceDef holds exactly the one shape before the missing comma.
3253        let service = parsed
3254            .syntax()
3255            .descendants()
3256            .find(|node| node.kind() == SyntaxKind::ServiceDef)
3257            .expect("the service parses");
3258        assert_eq!(
3259            service
3260                .children()
3261                .filter(|child| child.kind() == SyntaxKind::PathType)
3262                .count(),
3263            1,
3264            "`Struct` must not be absorbed as a second shape, got {service:#?}",
3265        );
3266        // The error points at `Struct` — the identifier itself, where the
3267        // mistake is — never at the `{` after it.
3268        let struct_offset = input.find("Struct").expect("the fixture spells it") as u32;
3269        let error = &parsed.errors()[0];
3270        assert_eq!(
3271            u32::from(error.range.start()),
3272            struct_offset,
3273            "the diagnostic lands on the identifier, got: {:?}",
3274            parsed.errors(),
3275        );
3276    }
3277
3278    /// The trailing comma stays optional (ADR-0015 decision 13), and every
3279    /// shape is a direct `PathType` child of the ServiceDef. `reserved` is not
3280    /// a shape (lock design §9): the list ends at the comma before it, the
3281    /// stray keyword is reported, and nothing after it joins the list.
3282    #[test]
3283    fn a_shape_list_admits_a_trailing_comma_and_ends_before_reserved() {
3284        let input = "package p\nservice p.svc : DoorControl, MotorControl,\n";
3285        let parsed = parse(input, Profile::Ridl);
3286        assert!(
3287            parsed.errors().is_empty(),
3288            "the list parses clean, got: {:?}",
3289            parsed.errors(),
3290        );
3291        assert_eq!(
3292            shape_kinds(&parsed),
3293            [SyntaxKind::PathType, SyntaxKind::PathType]
3294        );
3295
3296        let input = "package p\nservice p.svc : DoorControl, reserved LegacyDiag, MotorControl,\n";
3297        let parsed = parse(input, Profile::Ridl);
3298        assert!(
3299            !parsed.errors().is_empty(),
3300            "`reserved` in a service's list is a parse error",
3301        );
3302        assert_eq!(
3303            shape_kinds(&parsed),
3304            [SyntaxKind::PathType],
3305            "the list ends before the stray keyword",
3306        );
3307    }
3308
3309    /// The kinds of the shape children of the first ServiceDef in `parsed`.
3310    fn shape_kinds(parsed: &Parse) -> Vec<SyntaxKind> {
3311        parsed
3312            .syntax()
3313            .descendants()
3314            .find(|node| node.kind() == SyntaxKind::ServiceDef)
3315            .expect("the service parses")
3316            .children()
3317            .filter(|child| {
3318                matches!(
3319                    child.kind(),
3320                    SyntaxKind::PathType | SyntaxKind::ReservedEntry
3321                )
3322            })
3323            .map(|child| child.kind())
3324            .collect()
3325    }
3326
3327    /// Nothing at all after `reserved` is a missing token, not a wrong one:
3328    /// FORM-101, naming both admitted forms.
3329    #[test]
3330    fn reserved_with_no_target_flags_form_101() {
3331        let parsed = parse("package p\nstruct S {\n  reserved\n}\n", Profile::Typl);
3332        assert_eq!(
3333            parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
3334            vec!["FORM-101"],
3335        );
3336        assert_eq!(
3337            parsed.errors()[0].message,
3338            "expected a name or an integer value",
3339        );
3340    }
3341
3342    // --- operator chains (driftsys/ridl#346) --------------------------------
3343
3344    /// A contract expression in a minimal ridl file.
3345    fn contract_file(expr: &str) -> String {
3346        format!(
3347            "package app\ntype N : integer [0..10]\ninterface I {{\n  command c(a: N) [ require {expr} ] @[..50ms]\n}}\n"
3348        )
3349    }
3350
3351    /// A flat chain of `terms` operands under `op`, closed into a boolean
3352    /// where the operator is not one already.
3353    fn flat_chain(op: &str, terms: usize) -> String {
3354        match op {
3355            "||" | "&&" => vec!["a == 1"; terms].join(&format!(" {op} ")),
3356            "." => format!("a{} == 1", ".b".repeat(terms - 1)),
3357            _ => format!("{} == 1", vec!["a"; terms].join(&format!(" {op} "))),
3358        }
3359    }
3360
3361    /// The deepest node below `root`, counted without recursion, so that
3362    /// measuring a tree cannot itself exhaust the stack.
3363    fn tree_depth(root: &SyntaxNode) -> usize {
3364        let (mut depth, mut deepest) = (0usize, 0usize);
3365        for event in root.preorder() {
3366            match event {
3367                rowan::WalkEvent::Enter(_) => {
3368                    depth += 1;
3369                    deepest = deepest.max(depth);
3370                }
3371                rowan::WalkEvent::Leave(_) => depth -= 1,
3372            }
3373        }
3374        deepest
3375    }
3376
3377    /// Runs `body` on a thread with a 64 MiB stack. Without the fix a chain
3378    /// builds a tree thousands of levels deep, and dropping it recurses; the
3379    /// large stack keeps that from aborting the whole test binary, so the
3380    /// test fails on its assertions instead.
3381    fn on_a_large_stack(body: impl FnOnce() + Send + 'static) {
3382        std::thread::Builder::new()
3383            .stack_size(64 << 20)
3384            .spawn(body)
3385            .expect("spawn the test thread")
3386            .join()
3387            .expect("the test thread must not panic");
3388    }
3389
3390    /// The bound every expression tree must stay within, measured from the
3391    /// file root. A checker pass that recurses over the tree is sized against
3392    /// it; a flat chain once built a tree as deep as its term count.
3393    const TREE_DEPTH_BOUND: usize = 2 * MAX_TYPE_DEPTH;
3394
3395    #[test]
3396    fn a_flat_operator_chain_past_the_depth_limit_draws_one_form_102() {
3397        on_a_large_stack(|| {
3398            for op in ["||", "&&", "+", "-", "*", "/", "%", "."] {
3399                let input = contract_file(&flat_chain(op, 1000));
3400                let parsed = parse(&input, Profile::Ridl);
3401                let form_102 = parsed
3402                    .errors()
3403                    .iter()
3404                    .filter(|error| error.code == "FORM-102")
3405                    .count();
3406                assert_eq!(
3407                    form_102,
3408                    1,
3409                    "a 1000-term `{op}` chain draws exactly one FORM-102: {:?}",
3410                    parsed.errors(),
3411                );
3412                assert_eq!(
3413                    parsed.syntax().text().to_string(),
3414                    input,
3415                    "the refused `{op}` chain must stay lossless",
3416                );
3417                let depth = tree_depth(&parsed.syntax());
3418                assert!(
3419                    depth <= TREE_DEPTH_BOUND,
3420                    "a 1000-term `{op}` chain builds a tree {depth} levels deep",
3421                );
3422            }
3423        });
3424    }
3425
3426    /// The height of the expression tree under `root`: the most expression
3427    /// nodes on one path from the root to a leaf, counted without recursion.
3428    /// Only the expression kinds count, so the declaration nodes above the
3429    /// attribute and the flat `ErrorNode` of a refusal do not.
3430    fn expr_height(root: &SyntaxNode) -> usize {
3431        let is_expr = |kind: SyntaxKind| {
3432            matches!(
3433                kind,
3434                SyntaxKind::BinaryExpr
3435                    | SyntaxKind::PrefixExpr
3436                    | SyntaxKind::MemberExpr
3437                    | SyntaxKind::PathExpr
3438                    | SyntaxKind::ParenExpr
3439                    | SyntaxKind::LiteralExpr
3440            )
3441        };
3442        let (mut depth, mut deepest) = (0usize, 0usize);
3443        for event in root.preorder() {
3444            match event {
3445                rowan::WalkEvent::Enter(node) if is_expr(node.kind()) => {
3446                    depth += 1;
3447                    deepest = deepest.max(depth);
3448                }
3449                rowan::WalkEvent::Leave(node) if is_expr(node.kind()) => depth -= 1,
3450                _ => {}
3451            }
3452        }
3453        deepest
3454    }
3455
3456    /// The bound as an author meets it, over every shape that raises the
3457    /// height, at every size around the limit and one far past it: the tree
3458    /// built is never higher than `MAX_TYPE_DEPTH`, and FORM-102 is drawn
3459    /// exactly when the complete tree would not fit. Each generator states
3460    /// the height its complete tree has at `n`; where that fits, the built
3461    /// tree must have exactly that height, which checks the formula. The
3462    /// right-leaning shapes are the ones a bound that forgets to parse a
3463    /// right operand one level deeper would let through; the group and
3464    /// prefix towers are the ones a bound that opens a group or a prefix
3465    /// without room for a leaf below it would let through.
3466    #[test]
3467    fn the_expression_height_bound_holds_for_every_shape() {
3468        type Shape = (&'static str, fn(usize) -> String, fn(usize) -> usize);
3469        let shapes: [Shape; 15] = [
3470            ("left chain", |n| vec!["a"; n].join(" + "), |n| n),
3471            (
3472                "`||` chain of comparisons",
3473                |n| vec!["a == 1"; n].join(" || "),
3474                |n| n + 1,
3475            ),
3476            (
3477                "member steps",
3478                |n| format!("a{}", ".b".repeat(n - 1)),
3479                |n| n,
3480            ),
3481            (
3482                "groups around a leaf",
3483                |n| format!("{}a{}", "(".repeat(n - 1), ")".repeat(n - 1)),
3484                |n| n,
3485            ),
3486            (
3487                "groups around a negated leaf",
3488                |n| format!("{}-a{}", "(".repeat(n - 1), ")".repeat(n - 1)),
3489                |n| n + 1,
3490            ),
3491            (
3492                "groups around a `!` leaf",
3493                |n| format!("{}!a{}", "(".repeat(n - 1), ")".repeat(n - 1)),
3494                |n| n + 1,
3495            ),
3496            (
3497                "right-nested chain",
3498                |n| {
3499                    let mut expr = "a".to_string();
3500                    for _ in 1..n {
3501                        expr = format!("a + ({expr})");
3502                    }
3503                    expr
3504                },
3505                |n| 2 * n - 1,
3506            ),
3507            (
3508                "comparison with a grouped chain on the right",
3509                |n| format!("a == ({})", vec!["a"; n].join(" + ")),
3510                |n| n + 2,
3511            ),
3512            (
3513                "`!(` tower",
3514                |n| format!("{}a{}", "!(".repeat(n - 1), ")".repeat(n - 1)),
3515                |n| 2 * n - 1,
3516            ),
3517            (
3518                "`-(` tower",
3519                |n| format!("{}a{}", "-(".repeat(n - 1), ")".repeat(n - 1)),
3520                |n| 2 * n - 1,
3521            ),
3522            (
3523                "prefixed operands in a chain",
3524                |n| vec!["-a"; n].join(" * "),
3525                |n| n + 1,
3526            ),
3527            (
3528                "grouped member steps as a right operand",
3529                |n| format!("a + (a{})", ".b".repeat(n - 1)),
3530                |n| n + 2,
3531            ),
3532            (
3533                "`||` right-nested",
3534                |n| {
3535                    let mut expr = "a == 1".to_string();
3536                    for _ in 1..n {
3537                        expr = format!("a == 1 || ({expr})");
3538                    }
3539                    expr
3540                },
3541                |n| 2 * n,
3542            ),
3543            (
3544                "a deep right operand, then a long left chain",
3545                |n| {
3546                    format!(
3547                        "a + ({}a{}){}",
3548                        "(".repeat(60),
3549                        ")".repeat(60),
3550                        " + a".repeat(n - 1)
3551                    )
3552                },
3553                // The group written around the 60 counts too: 61 groups, a
3554                // leaf, and the wrap, then one level per further term.
3555                |n| n + 62,
3556            ),
3557            (
3558                "a prefix tower, then a chain",
3559                |n| {
3560                    format!(
3561                        "{}a == 1{}{}",
3562                        "!(".repeat(30),
3563                        ")".repeat(30),
3564                        " && a == 1".repeat(n - 1)
3565                    )
3566                },
3567                |n| n + 61,
3568            ),
3569        ];
3570        for (shape, build, complete_height) in shapes {
3571            // The smallest sizes check the formula; the sizes whose complete
3572            // height is within eight levels of the limit check the bound on
3573            // both sides of it; 300 is far past it.
3574            let mut sizes: Vec<usize> = (1..)
3575                .take_while(|&n| complete_height(n) <= MAX_TYPE_DEPTH + 8)
3576                .filter(|&n| n <= 3 || complete_height(n) + 8 >= MAX_TYPE_DEPTH)
3577                .collect();
3578            sizes.push(300);
3579            for n in sizes {
3580                let input = contract_file(&build(n));
3581                let parsed = parse(&input, Profile::Ridl);
3582                let complete = complete_height(n);
3583                let built = expr_height(&parsed.syntax());
3584                let form_102 = parsed
3585                    .errors()
3586                    .iter()
3587                    .filter(|error| error.code == "FORM-102")
3588                    .count();
3589                assert!(
3590                    built <= MAX_TYPE_DEPTH,
3591                    "the {shape} at n = {n} builds a tree {built} high",
3592                );
3593                assert_eq!(
3594                    parsed.syntax().text().to_string(),
3595                    input,
3596                    "{shape} at n = {n}"
3597                );
3598                if complete <= MAX_TYPE_DEPTH {
3599                    assert!(
3600                        parsed.errors().is_empty(),
3601                        "the {shape} at n = {n} fits in {complete} levels: {:?}",
3602                        parsed.errors(),
3603                    );
3604                    assert_eq!(
3605                        built, complete,
3606                        "the {shape} at n = {n} builds its complete tree"
3607                    );
3608                } else {
3609                    assert_eq!(
3610                        form_102,
3611                        1,
3612                        "the {shape} at n = {n} would be {complete} high: {:?}",
3613                        parsed.errors(),
3614                    );
3615                }
3616            }
3617        }
3618    }
3619
3620    /// Past the limit the diagnostics are exactly one FORM-102: the refused
3621    /// group is consumed through its own `)` together with the groups inside
3622    /// it, the chain after the outermost group goes flat without a second
3623    /// diagnostic, and the next interaction parses as usual.
3624    #[test]
3625    fn a_refused_group_draws_only_form_102_and_the_next_interaction_parses() {
3626        use crate::ast::AstNode;
3627        let groups = MAX_TYPE_DEPTH + 2;
3628        let input = format!(
3629            "package app\ntype N : integer [0..10]\ninterface I {{\n  \
3630             command c(a: N) [ require {}(a) + (a){} + a + a ] @[..50ms]\n  \
3631             command d(a: N) [ require a == 1 ] @[..50ms]\n}}\n",
3632            "(".repeat(groups),
3633            ")".repeat(groups),
3634        );
3635        let parsed = parse(&input, Profile::Ridl);
3636        let codes: Vec<&str> = parsed.errors().iter().map(|error| error.code).collect();
3637        assert_eq!(codes, vec!["FORM-102"]);
3638        assert_eq!(parsed.syntax().text().to_string(), input);
3639        let root = parsed.syntax();
3640        assert!(expr_height(&root) <= MAX_TYPE_DEPTH);
3641        assert_eq!(
3642            root.descendants()
3643                .filter(|node| node.kind() == SyntaxKind::CommandDef)
3644                .count(),
3645            2,
3646        );
3647        let last = root
3648            .descendants()
3649            .filter_map(crate::ast::Attribute::cast)
3650            .last()
3651            .expect("the second command's attribute");
3652        assert_eq!(
3653            last.expr().expect("its expression").syntax().text(),
3654            "a == 1",
3655        );
3656    }
3657
3658    /// A chain whose left operand is missing still keeps the bound: the
3659    /// wrap holds only its right operand, and counting the missing side as
3660    /// zero high would let the leaf below the deepest wrap sit one level
3661    /// past the limit. The shapes put the wrap at the deepest group the
3662    /// bound admits.
3663    #[test]
3664    fn a_missing_left_operand_keeps_the_bound() {
3665        for inner in ["+ a", "== a", "|| a == 1", "+ a == a"] {
3666            let groups = MAX_TYPE_DEPTH - 1;
3667            let input = contract_file(&format!(
3668                "{}{inner}{}",
3669                "(".repeat(groups),
3670                ")".repeat(groups)
3671            ));
3672            let parsed = parse(&input, Profile::Ridl);
3673            let built = expr_height(&parsed.syntax());
3674            assert!(
3675                built <= MAX_TYPE_DEPTH,
3676                "`{inner}` under {groups} groups builds a tree {built} high: {:?}",
3677                parsed.errors(),
3678            );
3679            assert!(
3680                parsed.errors().iter().any(|error| error.code == "FORM-101"),
3681                "the missing operand is reported: {:?}",
3682                parsed.errors(),
3683            );
3684            assert_eq!(parsed.syntax().text().to_string(), input);
3685        }
3686    }
3687
3688    /// A refused expression ends where the expression would have ended: the
3689    /// next attribute in the block — after a comma, a key on its own line, or
3690    /// an `ensure` on the same line with no comma — and the later
3691    /// declarations are parsed as usual, including a syntax error in one of
3692    /// them. Each overlong expression draws its own FORM-102. The stop at a
3693    /// `require`, a reserved word and a key after each kind of operand is
3694    /// pinned by the test after this one.
3695    #[test]
3696    fn a_refused_expression_does_not_swallow_what_follows_it() {
3697        use crate::ast::AstNode;
3698        let long = flat_chain("+", 200);
3699        let input = format!(
3700            "package app\ntype N : integer [0..10]\ninterface I {{\n  \
3701             command c(a: N) [ require {long}, require a == 1 ] @[..50ms]\n  \
3702             command d(a: N) [ require {long}\n    key = 1\n    require a == 1 ] @[..50ms]\n  \
3703             command e(a: N) [ require a == ] @[..50ms]\n  \
3704             command f(a: N) [ require {long} ensure a == 1 ] @[..50ms]\n}}\n"
3705        );
3706        let parsed = parse(&input, Profile::Ridl);
3707        assert_eq!(parsed.syntax().text().to_string(), input);
3708        let codes: Vec<&str> = parsed.errors().iter().map(|error| error.code).collect();
3709        assert_eq!(
3710            codes.iter().filter(|code| **code == "FORM-102").count(),
3711            3,
3712            "one FORM-102 per overlong expression: {codes:?}",
3713        );
3714        assert!(
3715            codes.contains(&"FORM-101"),
3716            "the syntax error in the later declaration is still reported: {codes:?}",
3717        );
3718        let spans: Vec<_> = parsed
3719            .errors()
3720            .iter()
3721            .filter(|error| error.code == "FORM-102")
3722            .map(|error| error.range.start())
3723            .collect();
3724        assert!(
3725            spans.windows(2).all(|pair| pair[0] < pair[1]),
3726            "each FORM-102 sits at its own expression: {spans:?}",
3727        );
3728        let root = parsed.syntax();
3729        assert_eq!(
3730            root.descendants()
3731                .filter(|node| node.kind() == SyntaxKind::CommandDef)
3732                .count(),
3733            4,
3734        );
3735        let attributes: Vec<crate::ast::Attribute> = root
3736            .descendants()
3737            .filter_map(crate::ast::Attribute::cast)
3738            .collect();
3739        assert_eq!(attributes.len(), 8, "{attributes:?}");
3740        assert_eq!(
3741            attributes
3742                .iter()
3743                .filter(|attribute| attribute
3744                    .expr()
3745                    .is_some_and(|expr| expr.syntax().text() == "a == 1"))
3746                .count(),
3747            3,
3748            "the `a == 1` after each refused chain is its own attribute",
3749        );
3750        assert!(
3751            attributes.iter().any(|attribute| attribute
3752                .syntax()
3753                .text()
3754                .to_string()
3755                .starts_with("key")),
3756            "the key after the refused chain is its own attribute",
3757        );
3758    }
3759
3760    /// Each way the skipped run of a refused chain can end before the next
3761    /// attribute, with no comma: a `require` directly after the chain, a
3762    /// reserved word in key position (which still draws its own FORM-105),
3763    /// and a key after a chain that ends in a number, a name or a group.
3764    #[test]
3765    fn a_refused_chain_stops_at_every_kind_of_next_attribute() {
3766        use crate::ast::AstNode;
3767        let numbers = flat_chain("+", 200);
3768        let names = vec!["a"; 200].join(" + ");
3769        let groups = vec!["(a)"; 200].join(" + ");
3770        let cases = [
3771            ("a `require`", format!("{numbers}\n    require a == 1")),
3772            ("a reserved word", format!("{numbers}\n    states = 1")),
3773            ("a key after a number", format!("{numbers}\n    key = 1")),
3774            ("a key after a name", format!("{names}\n    key = 1")),
3775            ("a key after a group", format!("{groups}\n    key = 1")),
3776        ];
3777        for (case, body) in cases {
3778            let input = format!(
3779                "package app\ntype N : integer [0..10]\ninterface I {{\n  \
3780                 command c(a: N) [ require {body} ] @[..50ms]\n}}\n"
3781            );
3782            let parsed = parse(&input, Profile::Ridl);
3783            assert_eq!(parsed.syntax().text().to_string(), input, "{case}");
3784            let codes: Vec<&str> = parsed.errors().iter().map(|error| error.code).collect();
3785            let expected: &[&str] = if case == "a reserved word" {
3786                &["FORM-102", "FORM-105"]
3787            } else {
3788                &["FORM-102"]
3789            };
3790            assert_eq!(codes, expected, "{case}");
3791            let attributes: Vec<String> = parsed
3792                .syntax()
3793                .descendants()
3794                .filter_map(crate::ast::Attribute::cast)
3795                .map(|attribute| attribute.syntax().text().to_string())
3796                .collect();
3797            assert_eq!(
3798                attributes.len(),
3799                2,
3800                "{case}: the next attribute is its own node: {attributes:?}",
3801            );
3802            let next = attributes[1].trim();
3803            let starts = match case {
3804                "a `require`" => "require a == 1",
3805                "a reserved word" => "states = 1",
3806                _ => "key = 1",
3807            };
3808            assert_eq!(next, starts, "{case}");
3809        }
3810    }
3811
3812    #[test]
3813    fn a_long_chain_under_the_depth_limit_parses_clean() {
3814        for op in ["||", "&&", "+", "-", "*", "/", "%", "."] {
3815            let input = contract_file(&flat_chain(op, 100));
3816            let parsed = parse(&input, Profile::Ridl);
3817            assert!(
3818                parsed.errors().is_empty(),
3819                "a 100-term `{op}` chain is accepted: {:?}",
3820                parsed.errors(),
3821            );
3822        }
3823    }
3824
3825    #[test]
3826    fn chains_stacked_through_parentheses_and_precedence_stay_bounded() {
3827        on_a_large_stack(|| {
3828            // Each parenthesis level closes a chain of its own, so a bound
3829            // that is charged while a chain is parsed and released when it
3830            // returns lets the chains stack on the left spine.
3831            let mut nested = "a".to_string();
3832            for _ in 0..120 {
3833                nested = format!("({nested}{})", " + a".repeat(119));
3834            }
3835            // One chain per precedence level, each the first operand of the
3836            // next: member, multiplicative, additive, comparison, `&&`, `||`.
3837            let ladder = format!(
3838                "a{}{}{} == a{}{}",
3839                ".b".repeat(119),
3840                " * a".repeat(119),
3841                " + a".repeat(119),
3842                " && a == a".repeat(119),
3843                " || a == a".repeat(119),
3844            );
3845            for (shape, expr) in [("nested", format!("{nested} == 1")), ("ladder", ladder)] {
3846                let input = contract_file(&expr);
3847                let parsed = parse(&input, Profile::Ridl);
3848                assert!(
3849                    parsed.errors().iter().any(|error| error.code == "FORM-102"),
3850                    "the {shape} shape draws FORM-102: {:?}",
3851                    parsed.errors(),
3852                );
3853                assert!(
3854                    parsed.errors().len() <= 4,
3855                    "the {shape} shape floods {} diagnostics",
3856                    parsed.errors().len(),
3857                );
3858                assert_eq!(parsed.syntax().text().to_string(), input);
3859                let depth = tree_depth(&parsed.syntax());
3860                assert!(
3861                    depth <= TREE_DEPTH_BOUND,
3862                    "the {shape} shape builds a tree {depth} levels deep",
3863                );
3864            }
3865        });
3866    }
3867}