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, so the rest of the attribute still parses.
1594 // The rsdl predicate words are recognized by `attribute`
1595 // instead, for semantic placement checking.
1596 Some(
1597 SyntaxKind::Ident
1598 | SyntaxKind::RequireKw
1599 | SyntaxKind::EnsureKw
1600 | SyntaxKind::ReservedWord,
1601 ) => {
1602 saw_attribute = true;
1603 self.attribute();
1604 }
1605 Some(kind)
1606 if kind == SyntaxKind::RBrace
1607 || is_interaction_start(kind)
1608 || is_top_level_start(kind) =>
1609 {
1610 self.error_at_current("FORM-103", "unclosed `[`".to_string());
1611 break;
1612 }
1613 Some(_) => self.err_and_recover("in an attribute block", |kind| {
1614 matches!(
1615 kind,
1616 SyntaxKind::RBracket
1617 | SyntaxKind::Comma
1618 | SyntaxKind::Ident
1619 | SyntaxKind::RequireKw
1620 | SyntaxKind::EnsureKw
1621 | SyntaxKind::ReservedWord
1622 | SyntaxKind::RBrace
1623 ) || is_interaction_start(kind)
1624 || is_top_level_start(kind)
1625 }),
1626 }
1627 }
1628 self.builder.finish_node();
1629 }
1630
1631 /// `Attribute = key | key '=' const_value | ('require'|'ensure') expr`
1632 /// — the three forms of gf §4.2. One grammar production for all of
1633 /// them; which keys are legal where is checker scope (gf §4.3,
1634 /// FORM-106/107/108). Callers have confirmed the leading token is an
1635 /// `Ident`, a predicate keyword, or a reserved word.
1636 fn attribute(&mut self) {
1637 self.start(SyntaxKind::Attribute);
1638 // Predicate words stay reserved in rsdl names, but the shared
1639 // attribute grammar leaves their placement to the semantic checker.
1640 let predicate = match self.current() {
1641 Some(kind @ (SyntaxKind::RequireKw | SyntaxKind::EnsureKw)) => Some(kind),
1642 Some(SyntaxKind::ReservedWord) if self.profile == Profile::Rsdl => {
1643 match self.current_text() {
1644 "require" => Some(SyntaxKind::RequireKw),
1645 "ensure" => Some(SyntaxKind::EnsureKw),
1646 _ => None,
1647 }
1648 }
1649 _ => None,
1650 };
1651 if let Some(kind) = predicate {
1652 self.eat_trivia();
1653 let token = &self.tokens[self.pos];
1654 self.builder.token(kind.into(), token.text);
1655 self.pos += 1;
1656 self.expr();
1657 } else {
1658 self.name(); // the attr key
1659 // A backend key `namespace.key` (rsdl reference §5, Appendix
1660 // B `key`). Only the rsdl profile admits the dotted key; under
1661 // typl and ridl the `.` stays an unexpected token in the block.
1662 if self.profile == Profile::Rsdl && self.at(SyntaxKind::Dot) {
1663 self.bump(); // '.'
1664 self.name();
1665 }
1666 if self.at(SyntaxKind::Eq) {
1667 self.bump();
1668 self.attr_value();
1669 }
1670 }
1671 self.builder.finish_node();
1672 }
1673
1674 /// `const_value = literal | SCREAMING_SNAKE_ID | '(' const_value (','
1675 /// const_value)* ')'` (gf §4.2), as an [`AttrValue`](SyntaxKind::AttrValue)
1676 /// node: one `Literal` child (an `ident` value token is the constant
1677 /// reference), or a parenthesised list of nested `AttrValue`s. The
1678 /// depth guard bounds pathological list nesting, sharing the
1679 /// [`MAX_TYPE_DEPTH`] budget with the type and expression grammars.
1680 fn attr_value(&mut self) {
1681 if self.depth >= MAX_TYPE_DEPTH {
1682 self.error_at_current(
1683 "FORM-102",
1684 format!("value nesting deeper than {MAX_TYPE_DEPTH} levels"),
1685 );
1686 self.start(SyntaxKind::ErrorNode);
1687 self.bump();
1688 self.builder.finish_node();
1689 return;
1690 }
1691 self.depth += 1;
1692 self.attr_value_inner();
1693 self.depth -= 1;
1694 }
1695
1696 fn attr_value_inner(&mut self) {
1697 self.eat_trivia();
1698 if self.at(SyntaxKind::LParen) {
1699 self.start(SyntaxKind::AttrValue);
1700 self.bump(); // '('
1701 loop {
1702 self.eat_trivia();
1703 match self.current() {
1704 None => {
1705 self.error_at_current("FORM-103", "unclosed `(`".to_string());
1706 break;
1707 }
1708 Some(SyntaxKind::RParen) => {
1709 self.bump();
1710 break;
1711 }
1712 Some(SyntaxKind::Comma) => self.bump(),
1713 Some(SyntaxKind::LParen) => self.attr_value(),
1714 Some(kind)
1715 if kind == SyntaxKind::RBracket
1716 || kind == SyntaxKind::RBrace
1717 || is_interaction_start(kind)
1718 || is_top_level_start(kind) =>
1719 {
1720 self.error_at_current("FORM-103", "unclosed `(`".to_string());
1721 break;
1722 }
1723 _ if self.literal_len_at(0) > 0 => self.attr_value(),
1724 Some(_) => self.err_and_recover("in an attribute value", |kind| {
1725 matches!(
1726 kind,
1727 SyntaxKind::RParen
1728 | SyntaxKind::Comma
1729 | SyntaxKind::LParen
1730 | SyntaxKind::RBracket
1731 | SyntaxKind::RBrace
1732 ) || is_interaction_start(kind)
1733 || is_top_level_start(kind)
1734 }),
1735 }
1736 }
1737 self.builder.finish_node();
1738 } else if self.literal_len_at(0) > 0 {
1739 self.start(SyntaxKind::AttrValue);
1740 self.literal();
1741 self.builder.finish_node();
1742 } else {
1743 self.error_at_current("FORM-101", "expected a value".to_string());
1744 }
1745 }
1746
1747 // --- the guaranteed-subset expression grammar ------------------
1748 //
1749 // The expr-core specification §3.1 productions, one function per
1750 // precedence level, loosest to tightest: `||` — `&&` — comparison —
1751 // additive — multiplicative — unary — member access. Binary levels are
1752 // left-associative (each iteration wraps the run so far in a fresh
1753 // BinaryExpr from the same checkpoint); a comparison never chains.
1754 // Inside an expression `<` is always the comparison operator — the
1755 // stream-type reading of `<` exists only in param-type and return-type
1756 // position, and the two positions never overlap.
1757 //
1758 // The height bound (driftsys/ridl#346). A left-associative chain builds
1759 // a tree as high as its term count, and a pass that recurses over the
1760 // tree needs stack in proportion to that height, so the parser bounds
1761 // the height of every expression tree at MAX_TYPE_DEPTH nodes. Every
1762 // function below returns the height of the subtree it built (1 for a
1763 // node whose children are all tokens, 0 when no node was built), and
1764 // `depth` counts the expression nodes open above the cursor. A node is
1765 // built only when `depth + height <= MAX_TYPE_DEPTH` (`expr_fits`): a
1766 // chain checks the wrap before consuming its operator, from the height
1767 // of the run so far plus one, and parses the right operand one level
1768 // deeper, so the operand's own checks account for the wrap above it; a
1769 // member step is checked like a chain wrap; a group or a prefix is
1770 // opened only when it and one leaf below it fit.
1771 // The invariant holds by induction over the build order: each node's
1772 // check covers the node itself, and a child built earlier sits one level
1773 // deeper under a parent whose height is at least the child's plus one.
1774 // A leaf is never checked, because every node above it was admitted
1775 // with room for one — a chain wrap counts its left operand as at least
1776 // one high even when that operand is missing. A
1777 // budget charged per parse call and released on return would not bound
1778 // the tree, because chains closed inside groups, and chains that are the
1779 // first operand of a looser chain, stack on the left spine.
1780 //
1781 // Past the limit the expression draws one FORM-102 and the rest of the
1782 // current group goes flat, as tokens under one ErrorNode: the tree stays
1783 // lossless and a later part of the same expression that does not fit
1784 // either is consumed the same way without a second diagnostic.
1785
1786 /// `expr = or_expr` — the entry point, called from a predicate
1787 /// attribute; a parenthesised group recurses through [`Parser::primary`].
1788 /// An attribute block is never inside a type or a value, so the
1789 /// expression starts at depth 0 and a leaf always fits below it.
1790 fn expr(&mut self) {
1791 self.expr_refused = false;
1792 self.or_expr();
1793 }
1794
1795 /// Whether an expression node `height` levels high fits at the current
1796 /// depth. Past the limit, reports FORM-102 at the current token unless
1797 /// the expression has already drawn one, so that one overlong expression
1798 /// draws one diagnostic whatever its shape. The message says how the
1799 /// levels are counted — one per binary operator, member access,
1800 /// parenthesised group and prefix — because the nesting of a flat
1801 /// operator chain is not visible in the source.
1802 fn expr_fits(&mut self, height: usize) -> bool {
1803 if self.depth + height <= MAX_TYPE_DEPTH {
1804 return true;
1805 }
1806 if !self.expr_refused {
1807 self.expr_refused = true;
1808 self.error_at_current(
1809 "FORM-102",
1810 format!(
1811 "expression nesting deeper than {MAX_TYPE_DEPTH} levels (each operator, \
1812 member access, parenthesised group and prefix nests one level)"
1813 ),
1814 );
1815 }
1816 false
1817 }
1818
1819 /// Consumes the rest of the current expression level as flat children
1820 /// of one [`ErrorNode`](SyntaxKind::ErrorNode): every token up to the
1821 /// `)` that closes the enclosing group, the `]` or `,` that ends the
1822 /// attribute, a brace, the end of input, a token that starts another
1823 /// construct, or the start of the next attribute, with or without a
1824 /// comma before it — a `require` or `ensure`, a reserved word in key
1825 /// position, or a key, which is an identifier where the expression has
1826 /// just ended in an operand and no operator can follow. A group opened
1827 /// inside is consumed through its own `)`.
1828 fn skip_expr_rest(&mut self) {
1829 self.start(SyntaxKind::ErrorNode);
1830 self.skip_expr_tokens();
1831 self.builder.finish_node();
1832 }
1833
1834 /// The token loop of [`Parser::skip_expr_rest`], without the node.
1835 fn skip_expr_tokens(&mut self) {
1836 let mut open = 0usize;
1837 let mut after_operand = false;
1838 while let Some(kind) = self.current() {
1839 match kind {
1840 SyntaxKind::RBracket
1841 | SyntaxKind::Comma
1842 | SyntaxKind::LBrace
1843 | SyntaxKind::RBrace
1844 | SyntaxKind::RequireKw
1845 | SyntaxKind::EnsureKw
1846 | SyntaxKind::ReservedWord => break,
1847 SyntaxKind::RParen if open == 0 => break,
1848 SyntaxKind::Ident if after_operand => break,
1849 _ if is_interaction_start(kind) || is_top_level_start(kind) => break,
1850 SyntaxKind::RParen => open -= 1,
1851 SyntaxKind::LParen => open += 1,
1852 _ => {}
1853 }
1854 after_operand = matches!(
1855 kind,
1856 SyntaxKind::Ident
1857 | SyntaxKind::IntNumber
1858 | SyntaxKind::FloatNumber
1859 | SyntaxKind::String
1860 | SyntaxKind::TrueKw
1861 | SyntaxKind::FalseKw
1862 | SyntaxKind::Duration
1863 | SyntaxKind::RParen
1864 );
1865 self.bump();
1866 }
1867 }
1868
1869 /// The shared loop of the four chaining binary levels: `operand { op
1870 /// operand }`, each `op` a token `is_op` accepts, each iteration wrapping
1871 /// the run so far in a [`BinaryExpr`](SyntaxKind::BinaryExpr) from the
1872 /// same checkpoint. Returns the height of the tree built.
1873 fn chain(&mut self, is_op: fn(SyntaxKind) -> bool, operand: fn(&mut Self) -> usize) -> usize {
1874 self.eat_trivia();
1875 let checkpoint = self.builder.checkpoint();
1876 let mut height = operand(self);
1877 while self.current().is_some_and(is_op) {
1878 // A missing left operand (FORM-101, already reported) has height
1879 // 0; the wrap still holds the right operand, so it is at least
1880 // two high, and the check must say so for the leaf below to fit.
1881 if !self.expr_fits(height.max(1) + 1) {
1882 self.skip_expr_rest();
1883 break;
1884 }
1885 self.builder
1886 .start_node_at(checkpoint, SyntaxKind::BinaryExpr.into());
1887 self.bump();
1888 self.depth += 1;
1889 let rhs = operand(self);
1890 self.depth -= 1;
1891 self.builder.finish_node();
1892 height = 1 + height.max(rhs);
1893 }
1894 height
1895 }
1896
1897 /// `or_expr = and_expr { '||' and_expr }`
1898 fn or_expr(&mut self) -> usize {
1899 self.chain(|kind| kind == SyntaxKind::PipePipe, Self::and_expr)
1900 }
1901
1902 /// `and_expr = cmp_expr { '&&' cmp_expr }`
1903 fn and_expr(&mut self) -> usize {
1904 self.chain(|kind| kind == SyntaxKind::AmpAmp, Self::cmp_expr)
1905 }
1906
1907 /// `cmp_expr = add_expr [ cmp_op add_expr ]` — at most one comparison:
1908 /// `a < b < c` is a parse error (write `a < b && b < c`), reported by
1909 /// whatever context the leftover operator lands in.
1910 fn cmp_expr(&mut self) -> usize {
1911 self.eat_trivia();
1912 let checkpoint = self.builder.checkpoint();
1913 let mut height = self.add_expr();
1914 if matches!(
1915 self.current(),
1916 Some(
1917 SyntaxKind::EqEq
1918 | SyntaxKind::Neq
1919 | SyntaxKind::Lt
1920 | SyntaxKind::Le
1921 | SyntaxKind::Gt
1922 | SyntaxKind::Ge
1923 )
1924 ) {
1925 if !self.expr_fits(height.max(1) + 1) {
1926 self.skip_expr_rest();
1927 return height;
1928 }
1929 self.builder
1930 .start_node_at(checkpoint, SyntaxKind::BinaryExpr.into());
1931 self.bump();
1932 self.depth += 1;
1933 let rhs = self.add_expr();
1934 self.depth -= 1;
1935 self.builder.finish_node();
1936 height = 1 + height.max(rhs);
1937 }
1938 height
1939 }
1940
1941 /// `add_expr = mul_expr { ('+' | '-') mul_expr }`
1942 fn add_expr(&mut self) -> usize {
1943 self.chain(
1944 |kind| matches!(kind, SyntaxKind::Plus | SyntaxKind::Minus),
1945 Self::mul_expr,
1946 )
1947 }
1948
1949 /// `mul_expr = unary_expr { ('*' | '/' | '%') unary_expr }`
1950 fn mul_expr(&mut self) -> usize {
1951 self.chain(
1952 |kind| {
1953 matches!(
1954 kind,
1955 SyntaxKind::Star | SyntaxKind::Slash | SyntaxKind::Percent
1956 )
1957 },
1958 Self::unary_expr,
1959 )
1960 }
1961
1962 /// `unary_expr = [ '!' | '-' ] postfix_expr` — at most one prefix.
1963 fn unary_expr(&mut self) -> usize {
1964 if matches!(self.current(), Some(SyntaxKind::Bang | SyntaxKind::Minus)) {
1965 if !self.expr_fits(2) {
1966 self.skip_expr_rest();
1967 return 1;
1968 }
1969 self.start(SyntaxKind::PrefixExpr);
1970 self.bump();
1971 self.depth += 1;
1972 let operand = self.postfix_expr();
1973 self.depth -= 1;
1974 self.builder.finish_node();
1975 1 + operand
1976 } else {
1977 self.postfix_expr()
1978 }
1979 }
1980
1981 /// `postfix_expr = primary { '.' member }` — each `.member` step wraps
1982 /// the run so far in a [`MemberExpr`](SyntaxKind::MemberExpr), so
1983 /// `filter.severity` and `GearPosition.PARK` nest left-associatively.
1984 fn postfix_expr(&mut self) -> usize {
1985 self.eat_trivia();
1986 let checkpoint = self.builder.checkpoint();
1987 let mut height = self.primary();
1988 while self.at(SyntaxKind::Dot) {
1989 if !self.expr_fits(height + 1) {
1990 self.skip_expr_rest();
1991 break;
1992 }
1993 self.builder
1994 .start_node_at(checkpoint, SyntaxKind::MemberExpr.into());
1995 self.bump(); // '.'
1996 if self.at(SyntaxKind::Ident) {
1997 self.bump();
1998 } else {
1999 self.error_at_current("FORM-101", "expected a member name".to_string());
2000 }
2001 self.builder.finish_node();
2002 height += 1;
2003 }
2004 height
2005 }
2006
2007 /// `primary = literal | duration_lit | path_head | '(' expr ')'` — a
2008 /// [`LiteralExpr`](SyntaxKind::LiteralExpr) (typl literal or duration —
2009 /// zero durations are legal in expression position, expr-core spec
2010 /// §3.1), a [`PathExpr`](SyntaxKind::PathExpr), or a parenthesised
2011 /// group. No node is built when no primary starts here, so a missing
2012 /// operand reports FORM-101 without consuming the boundary token. The
2013 /// group is where the grammar recurses, so the height bound is also what
2014 /// keeps a run of `(` from overflowing the parser's own stack: a group
2015 /// that does not fit is consumed flat through its `)`.
2016 fn primary(&mut self) -> usize {
2017 match self.current() {
2018 Some(
2019 SyntaxKind::IntNumber
2020 | SyntaxKind::FloatNumber
2021 | SyntaxKind::String
2022 | SyntaxKind::TrueKw
2023 | SyntaxKind::FalseKw
2024 | SyntaxKind::Duration,
2025 ) => {
2026 self.start(SyntaxKind::LiteralExpr);
2027 if self.at(SyntaxKind::IntNumber) {
2028 self.flag_leading_zeros();
2029 }
2030 self.bump();
2031 self.builder.finish_node();
2032 1
2033 }
2034 Some(SyntaxKind::Ident) => {
2035 self.start(SyntaxKind::PathExpr);
2036 self.bump();
2037 self.builder.finish_node();
2038 1
2039 }
2040 Some(SyntaxKind::LParen) => {
2041 if !self.expr_fits(2) {
2042 self.start(SyntaxKind::ErrorNode);
2043 self.bump(); // '('
2044 self.skip_expr_tokens();
2045 if self.at(SyntaxKind::RParen) {
2046 self.bump();
2047 }
2048 self.builder.finish_node();
2049 return 1;
2050 }
2051 self.start(SyntaxKind::ParenExpr);
2052 self.bump();
2053 self.depth += 1;
2054 let inner = self.or_expr();
2055 self.depth -= 1;
2056 self.expect(SyntaxKind::RParen);
2057 self.builder.finish_node();
2058 1 + inner
2059 }
2060 _ => {
2061 self.error_at_current("FORM-101", "expected an expression".to_string());
2062 0
2063 }
2064 }
2065 }
2066
2067 /// `EnumValue = Name '=' value:Literal`
2068 fn enum_value(&mut self) {
2069 self.value_assignment(SyntaxKind::EnumValue);
2070 }
2071
2072 /// `EnumSetBit = Name '=' value:Literal`
2073 fn enum_set_bit(&mut self) {
2074 self.value_assignment(SyntaxKind::EnumSetBit);
2075 }
2076
2077 /// The shared `Name '=' Literal` shape of enum values and enumset bits.
2078 fn value_assignment(&mut self, kind: SyntaxKind) {
2079 self.start(kind);
2080 self.name();
2081 self.expect(SyntaxKind::Eq);
2082 self.literal();
2083 self.builder.finish_node();
2084 }
2085
2086 /// The shared block-body loop (§15.2): members separated by newlines or
2087 /// commas, trailing comma permitted, separator commas placed as direct
2088 /// children of the block node between members. `member` parses the
2089 /// member a leading `Ident` announces; `allow_reserved` admits
2090 /// `ReservedEntry` members (structs, enums, unions — not enumsets).
2091 fn block_body(&mut self, context: &str, allow_reserved: bool, member: fn(&mut Self)) {
2092 if !self.block_open() {
2093 return;
2094 }
2095 loop {
2096 self.eat_trivia();
2097 match self.current() {
2098 None => {
2099 self.error_at_current("FORM-103", "unclosed `{`".to_string());
2100 break;
2101 }
2102 Some(SyntaxKind::RBrace) => {
2103 self.bump();
2104 break;
2105 }
2106 Some(SyntaxKind::Comma) => self.bump(),
2107 Some(SyntaxKind::ReservedKw) if allow_reserved => self.reserved_entry(),
2108 Some(SyntaxKind::Ident) => member(self),
2109 // An unclosed `{`: the body ran into the next top-level
2110 // declaration. Report the missing brace and let `source_file`
2111 // resynchronize instead of swallowing the declaration.
2112 Some(kind) if is_top_level_start(kind) => {
2113 self.error_at_current("FORM-103", "unclosed `{`".to_string());
2114 break;
2115 }
2116 Some(_) => self.err_and_recover(context, |kind| {
2117 matches!(
2118 kind,
2119 SyntaxKind::RBrace | SyntaxKind::Comma | SyntaxKind::Ident
2120 ) || (allow_reserved && kind == SyntaxKind::ReservedKw)
2121 || is_top_level_start(kind)
2122 }),
2123 }
2124 }
2125 }
2126
2127 /// Consumes the `{` opening a block body; reports FORM-101 and returns
2128 /// `false` when it is missing, so the caller skips the body loop instead
2129 /// of swallowing the rest of the file.
2130 fn block_open(&mut self) -> bool {
2131 if self.at(SyntaxKind::LBrace) {
2132 self.bump();
2133 true
2134 } else {
2135 self.error_at_current("FORM-101", "expected `{`".to_string());
2136 false
2137 }
2138 }
2139
2140 /// `FieldDef = Name ':' FieldType InitValue?`
2141 fn field_def(&mut self) {
2142 self.start(SyntaxKind::FieldDef);
2143 self.name();
2144 self.expect(SyntaxKind::Colon);
2145 self.field_type();
2146 self.init_value_opt();
2147 self.builder.finish_node();
2148 }
2149
2150 /// `ReservedEntry = 'reserved' (Name | int_lit)` — the tombstone (§7.4).
2151 /// typl Appendix E spells it `reserved = "reserved" ( camelCase_id |
2152 /// int_lit )`. The production is body-agnostic and this parser keeps it
2153 /// that way: both forms parse in every body that admits a tombstone.
2154 ///
2155 /// What each form *means* is per body, and **nothing narrows it** — there
2156 /// is no per-body check anywhere, so this comment describes the language,
2157 /// not an enforced rule. The name form is meaningful everywhere (TYPL-210
2158 /// in a struct, union or enum; RIDL-401 in an interface). The integer form
2159 /// is meaningful in an `enum`, where it retires a wire value (TYPL-210),
2160 /// and in an interaction body, where the nameless spelling records the
2161 /// ordinal it protects (`veh-cluster/cluster/evolution.ridl`). In a
2162 /// `struct` or `union` body it is **inert**: members there carry no
2163 /// explicit value, so nothing can ever match it and no retired name is
2164 /// recorded. `test_data/parser/ok/grammar_overapprox.typl` carries that
2165 /// case as an over-approximation awaiting a checker rule; see
2166 /// `veh-cluster/NOTES` for the residual and what closing it needs.
2167 ///
2168 /// Any other literal — a string, a boolean, a float, a regex, a bare
2169 /// constant reference — is outside the grammar and draws FORM-102 here
2170 /// rather than parsing as a `Literal`. Lowering keeps only a `Name` or an
2171 /// integer, so an ungrammatical literal would otherwise consume the
2172 /// ordinal while recording neither: the tombstone survives but the
2173 /// retired identity it exists to record is destroyed, with no diagnostic.
2174 /// The offending token is held in an `ErrorNode` so the tree stays
2175 /// lossless and the body loop resumes at the next member.
2176 fn reserved_entry(&mut self) {
2177 self.start(SyntaxKind::ReservedEntry);
2178 self.bump(); // 'reserved'
2179 if self.at(SyntaxKind::Ident) {
2180 self.name();
2181 } else if let Some(kind) = self.literal_value_kind_at(0) {
2182 if kind == SyntaxKind::IntNumber {
2183 self.literal();
2184 } else {
2185 self.start(SyntaxKind::ErrorNode);
2186 // A leading `-` belongs to the literal but is not what makes
2187 // it ungrammatical, so it is consumed before the diagnostic is
2188 // raised: the caret then lands on the value token the message
2189 // names, as it already does for every single-token shape.
2190 if self.at(SyntaxKind::Minus) {
2191 self.bump();
2192 }
2193 self.error_at_current(
2194 "FORM-102",
2195 format!(
2196 "a `reserved` tombstone takes a retired member name or a retired integer value, not {}",
2197 ungrammatical_reserved_noun(kind),
2198 ),
2199 );
2200 self.bump();
2201 self.builder.finish_node();
2202 }
2203 } else {
2204 self.error_at_current(
2205 "FORM-101",
2206 "expected a name or an integer value".to_string(),
2207 );
2208 }
2209 self.builder.finish_node();
2210 }
2211
2212 /// `FieldType = PathType | PrimitiveType | TupleType | ArrayType |
2213 /// MapType | OptionalType` — the type of a field, tuple field, or
2214 /// collection element. Each `?` suffix wraps the type parsed so far in an
2215 /// `OptionalType` node. The depth guard keeps a pathological nesting of
2216 /// collection and tuple types from overflowing the stack — the parser
2217 /// must never panic.
2218 fn field_type(&mut self) {
2219 if self.depth >= MAX_TYPE_DEPTH {
2220 self.error_at_current(
2221 "FORM-102",
2222 format!("type nesting deeper than {MAX_TYPE_DEPTH} levels"),
2223 );
2224 self.start(SyntaxKind::ErrorNode);
2225 self.bump();
2226 self.builder.finish_node();
2227 return;
2228 }
2229 self.depth += 1;
2230 self.field_type_inner();
2231 self.depth -= 1;
2232 }
2233
2234 fn field_type_inner(&mut self) {
2235 self.eat_trivia();
2236 let checkpoint = self.builder.checkpoint();
2237 match self.current() {
2238 Some(
2239 kw @ (SyntaxKind::BooleanKw
2240 | SyntaxKind::IntegerKw
2241 | SyntaxKind::FloatKw
2242 | SyntaxKind::StringKw
2243 | SyntaxKind::BytesKw),
2244 ) => {
2245 // The inline constrained primitive (`integer [0..6]`,
2246 // §15.3): in field position the constraint nests inside
2247 // PrimitiveType, unlike the `type`-definition position.
2248 self.start(SyntaxKind::PrimitiveType);
2249 self.bump();
2250 if self.at(SyntaxKind::LBracket) {
2251 let stringish = matches!(kw, SyntaxKind::StringKw | SyntaxKind::BytesKw);
2252 self.constraint(stringish);
2253 }
2254 self.builder.finish_node();
2255 }
2256 Some(SyntaxKind::Ident) => self.path_type(),
2257 Some(SyntaxKind::LParen) => self.tuple_type(),
2258 Some(SyntaxKind::LBracket) => self.array_or_map(checkpoint),
2259 Some(SyntaxKind::Lt) => {
2260 // The stream container `<T>` (ridl reference §12) parses in
2261 // every type position under both profiles; in a `.typl`
2262 // parse it is the profile boundary — TYPL-301 — and parsing
2263 // continues (ADR-0007 decision 10). Under `Profile::Ridl`
2264 // the positions where a stream is not allowed (struct
2265 // fields, signal and event payloads) are checker scope.
2266 if self.profile == Profile::Typl {
2267 self.error_at_current("TYPL-301", "stream type in typl context".to_string());
2268 }
2269 self.stream_type();
2270 }
2271 _ => {
2272 self.error_at_current("FORM-101", "expected a type".to_string());
2273 return;
2274 }
2275 }
2276 // Each `?` wraps one OptionalType node, so an unbounded run would
2277 // build a tree deep enough to overflow the stack when it is later
2278 // traversed or dropped. The wrap count shares the MAX_TYPE_DEPTH
2279 // bound: past it, the remaining `?` tokens land flat in a single
2280 // ErrorNode with one FORM-102.
2281 let mut wraps = 0;
2282 while self.at(SyntaxKind::Question) {
2283 if wraps >= MAX_TYPE_DEPTH {
2284 self.error_at_current(
2285 "FORM-102",
2286 format!("type nesting deeper than {MAX_TYPE_DEPTH} levels"),
2287 );
2288 self.start(SyntaxKind::ErrorNode);
2289 while self.at(SyntaxKind::Question) {
2290 self.bump();
2291 }
2292 self.builder.finish_node();
2293 break;
2294 }
2295 self.builder
2296 .start_node_at(checkpoint, SyntaxKind::OptionalType.into());
2297 self.bump();
2298 self.builder.finish_node();
2299 wraps += 1;
2300 }
2301 }
2302
2303 /// `TupleType = '(' fields:TupleField (',' fields:TupleField)* ')'` —
2304 /// separator commas are direct children of the tuple node.
2305 fn tuple_type(&mut self) {
2306 self.start(SyntaxKind::TupleType);
2307 self.bump(); // '('
2308 loop {
2309 self.eat_trivia();
2310 match self.current() {
2311 None => {
2312 self.error_at_current("FORM-103", "unclosed `(`".to_string());
2313 break;
2314 }
2315 Some(SyntaxKind::RParen) => {
2316 self.bump();
2317 break;
2318 }
2319 Some(SyntaxKind::Comma) => self.bump(),
2320 Some(SyntaxKind::Ident) => self.tuple_field(),
2321 // An unclosed `(`: the tuple ran into a block or top-level
2322 // boundary. Report it and let the enclosing loop recover.
2323 Some(kind) if kind == SyntaxKind::RBrace || is_top_level_start(kind) => {
2324 self.error_at_current("FORM-103", "unclosed `(`".to_string());
2325 break;
2326 }
2327 Some(_) => self.err_and_recover("in a tuple type", |kind| {
2328 matches!(
2329 kind,
2330 SyntaxKind::RParen
2331 | SyntaxKind::Comma
2332 | SyntaxKind::Ident
2333 | SyntaxKind::RBrace
2334 ) || is_top_level_start(kind)
2335 }),
2336 }
2337 }
2338 self.builder.finish_node();
2339 }
2340
2341 /// `TupleField = Name ':' FieldType`
2342 fn tuple_field(&mut self) {
2343 self.start(SyntaxKind::TupleField);
2344 self.name();
2345 self.expect(SyntaxKind::Colon);
2346 self.field_type();
2347 self.builder.finish_node();
2348 }
2349
2350 /// `ArrayType = '[' element:FieldType ';' Bound ']'` or
2351 /// `MapType = '[' key:FieldType ':' value:FieldType ';' Bound ']'` — the
2352 /// node kind is decided by the token after the first type, then wrapped
2353 /// around everything from the checkpoint (the `[`).
2354 fn array_or_map(&mut self, checkpoint: rowan::Checkpoint) {
2355 self.bump(); // '['
2356 self.field_type(); // the element or key type
2357 if self.at(SyntaxKind::Colon) {
2358 self.builder
2359 .start_node_at(checkpoint, SyntaxKind::MapType.into());
2360 self.bump(); // ':'
2361 self.field_type(); // the value type
2362 } else {
2363 self.builder
2364 .start_node_at(checkpoint, SyntaxKind::ArrayType.into());
2365 }
2366 self.expect(SyntaxKind::Semicolon);
2367 self.bound();
2368 self.expect(SyntaxKind::RBracket);
2369 self.builder.finish_node();
2370 }
2371
2372 /// `Constraint = '[' … ']'` — see the module doc for the bound policy.
2373 fn constraint(&mut self, stringish: bool) {
2374 self.start(SyntaxKind::Constraint);
2375 self.bump(); // '['
2376 self.constraint_body(stringish);
2377 self.expect(SyntaxKind::RBracket);
2378 self.builder.finish_node();
2379 }
2380
2381 /// The three constraint shapes behind the brackets: a scalar range with
2382 /// optional step, a length bound with optional match, and a bare match.
2383 fn constraint_body(&mut self, stringish: bool) {
2384 match self.current() {
2385 Some(SyntaxKind::MatchKw) => {
2386 self.bump();
2387 self.literal();
2388 }
2389 Some(SyntaxKind::DotDot) => {
2390 // `[..max]` — an open lower bound is always the scalar shape.
2391 self.bump();
2392 self.literal();
2393 self.step_opt();
2394 }
2395 _ if self.literal_len_at(0) > 0 => self.constraint_led_by_literal(stringish),
2396 _ => self.error_at_current("FORM-101", "expected a constraint".to_string()),
2397 }
2398 }
2399
2400 /// A constraint whose body starts with a literal: decide between the
2401 /// length-`Bound` shape and the scalar-range shape (module doc policy).
2402 fn constraint_led_by_literal(&mut self, stringish: bool) {
2403 let first_len = self.literal_len_at(0);
2404 match self.nth(first_len) {
2405 // A single literal with no `..` is always a length bound:
2406 // `[17]`, `[8]`, `[17 match P]`.
2407 Some(SyntaxKind::RBracket | SyntaxKind::MatchKw) | None => {
2408 self.bound();
2409 self.match_opt();
2410 }
2411 Some(SyntaxKind::DotDot) => {
2412 let second_len = self.literal_len_at(first_len + 1);
2413 let after_second = self.nth(first_len + 1 + second_len);
2414 let bound_shape = stringish
2415 && second_len > 0
2416 && !self.literal_is_float_at(0)
2417 && !self.literal_is_float_at(first_len + 1)
2418 && matches!(
2419 after_second,
2420 Some(SyntaxKind::RBracket | SyntaxKind::MatchKw) | None
2421 );
2422 if bound_shape {
2423 self.bound();
2424 self.match_opt();
2425 } else {
2426 self.literal(); // min
2427 self.bump(); // '..'
2428 if self.literal_len_at(0) > 0 {
2429 self.literal(); // max — absent on `[min..]`
2430 }
2431 self.step_opt();
2432 }
2433 }
2434 _ => {
2435 // Not a legal shape after the literal; parse the literal as a
2436 // length bound and let the closing-bracket check report.
2437 self.bound();
2438 self.match_opt();
2439 }
2440 }
2441 }
2442
2443 /// `Bound = min:Literal ('..' max:Literal)?`
2444 fn bound(&mut self) {
2445 if self.literal_len_at(0) == 0 {
2446 self.error_at_current("FORM-101", "expected a bound".to_string());
2447 return;
2448 }
2449 self.start(SyntaxKind::Bound);
2450 self.literal();
2451 if self.at(SyntaxKind::DotDot) {
2452 self.bump();
2453 self.literal();
2454 }
2455 self.builder.finish_node();
2456 }
2457
2458 /// `('step' step:Literal)?`
2459 fn step_opt(&mut self) {
2460 if self.at(SyntaxKind::StepKw) {
2461 self.bump();
2462 self.literal();
2463 }
2464 }
2465
2466 /// `('match' match_pattern:Literal)?`
2467 fn match_opt(&mut self) {
2468 if self.at(SyntaxKind::MatchKw) {
2469 self.bump();
2470 self.literal();
2471 }
2472 }
2473
2474 /// `InitValue = '=' Literal`, when present.
2475 fn init_value_opt(&mut self) {
2476 if self.at(SyntaxKind::Eq) {
2477 self.start(SyntaxKind::InitValue);
2478 self.bump();
2479 self.literal();
2480 self.builder.finish_node();
2481 }
2482 }
2483
2484 /// How many significant tokens the literal starting at the `n`-th
2485 /// significant position spans: 2 for `-` + value, 1 for a bare value, 0
2486 /// when no literal starts there.
2487 fn literal_len_at(&self, n: usize) -> usize {
2488 match self.nth(n) {
2489 Some(SyntaxKind::Minus) => match self.nth(n + 1) {
2490 Some(kind) if is_value_token(kind) => 2,
2491 _ => 0,
2492 },
2493 Some(kind) if is_value_token(kind) => 1,
2494 _ => 0,
2495 }
2496 }
2497
2498 /// The value token of the literal starting at the `n`-th significant
2499 /// position, looking past a leading `-`. `None` when no literal starts
2500 /// there. Lets a caller admit one literal shape and refuse the rest.
2501 fn literal_value_kind_at(&self, n: usize) -> Option<SyntaxKind> {
2502 match self.nth(n) {
2503 Some(SyntaxKind::Minus) => self.nth(n + 1).filter(|kind| is_value_token(*kind)),
2504 Some(kind) if is_value_token(kind) => Some(kind),
2505 _ => None,
2506 }
2507 }
2508
2509 /// Whether the literal starting at the `n`-th significant position has a
2510 /// float value token.
2511 fn literal_is_float_at(&self, n: usize) -> bool {
2512 match self.nth(n) {
2513 Some(SyntaxKind::FloatNumber) => true,
2514 Some(SyntaxKind::Minus) => matches!(self.nth(n + 1), Some(SyntaxKind::FloatNumber)),
2515 _ => false,
2516 }
2517 }
2518
2519 /// `Literal = '-'? ('int_number' | 'float_number' | 'string_lit' | 'true'
2520 /// | 'false' | 'regex' | 'ident')` — an `ident` is a constant reference
2521 /// in a value position. A duration literal here in a `.typl` parse is the
2522 /// profile boundary (TYPL-302); an integer with leading zeros is FORM-005.
2523 /// Under [`Profile::Ridl`] a duration is an ordinary token that is simply
2524 /// not a literal, so it falls through to the generic missing-value path.
2525 fn literal(&mut self) {
2526 if self.profile == Profile::Typl && self.at(SyntaxKind::Duration) {
2527 self.error_at_current("TYPL-302", "duration literal in typl context".to_string());
2528 self.start(SyntaxKind::ErrorNode);
2529 self.bump();
2530 self.builder.finish_node();
2531 return;
2532 }
2533 if self.literal_len_at(0) == 0 {
2534 self.error_at_current("FORM-101", "expected a value".to_string());
2535 return;
2536 }
2537 self.start(SyntaxKind::Literal);
2538 if self.at(SyntaxKind::Minus) {
2539 self.bump();
2540 }
2541 if self.at(SyntaxKind::IntNumber) {
2542 self.flag_leading_zeros();
2543 }
2544 self.bump();
2545 self.builder.finish_node();
2546 }
2547
2548 /// FORM-005: an integer literal with leading zeros (typl reference §2.4)
2549 /// lexes as one token and is flagged here.
2550 fn flag_leading_zeros(&mut self) {
2551 let i = self.significant_pos();
2552 let text = self.tokens[i].text;
2553 if text.len() > 1 && text.starts_with('0') {
2554 self.error_at_current("FORM-005", "integer literal has leading zeros".to_string());
2555 }
2556 }
2557
2558 /// A declared name — a single `Ident` wrapped in a `Name` node. A family
2559 /// reserved word is held in an `ErrorNode` and flagged FORM-105; otherwise
2560 /// no node is built when the name is missing, so accessors see `None`
2561 /// rather than an empty `Name`.
2562 fn name(&mut self) {
2563 if self.at(SyntaxKind::Ident) {
2564 self.start(SyntaxKind::Name);
2565 self.bump();
2566 self.builder.finish_node();
2567 } else if self.at(SyntaxKind::ReservedWord) {
2568 // A family reserved word (typl reference §1.4) used where a
2569 // declared name is expected: hold it in an `ErrorNode` so the
2570 // rest of the declaration still parses, and flag FORM-105.
2571 let message = format!(
2572 "reserved word `{}` used as identifier",
2573 self.tokens[self.significant_pos()].text,
2574 );
2575 self.error_at_current("FORM-105", message);
2576 self.start(SyntaxKind::ErrorNode);
2577 self.bump();
2578 self.builder.finish_node();
2579 } else {
2580 self.error_at_current("FORM-101", "expected a name".to_string());
2581 }
2582 }
2583
2584 /// Whether the current token can be a path segment. Primitive keywords
2585 /// are admitted as segments so `const MAX_GEAR : integer = 6` (typl
2586 /// reference Appendix B) parses; the checker narrows where a primitive
2587 /// is not allowed (TYPL-204 and the related composite checks).
2588 fn at_path_segment(&self) -> bool {
2589 matches!(
2590 self.current(),
2591 Some(
2592 SyntaxKind::Ident
2593 | SyntaxKind::BooleanKw
2594 | SyntaxKind::IntegerKw
2595 | SyntaxKind::FloatKw
2596 | SyntaxKind::StringKw
2597 | SyntaxKind::BytesKw
2598 )
2599 )
2600 }
2601
2602 /// `PathType = QualifiedName` — a type reference in type position. No
2603 /// node is built when the reference is missing.
2604 fn path_type(&mut self) {
2605 if !self.at_path_segment() {
2606 self.error_at_current("FORM-101", "expected a type name".to_string());
2607 return;
2608 }
2609 self.start(SyntaxKind::PathType);
2610 self.qualified_name();
2611 self.builder.finish_node();
2612 }
2613
2614 /// `QualifiedName = 'ident' ('.' 'ident')*`
2615 fn qualified_name(&mut self) {
2616 if !self.at_path_segment() {
2617 self.error_at_current("FORM-101", "expected a name".to_string());
2618 return;
2619 }
2620 self.start(SyntaxKind::QualifiedName);
2621 self.bump();
2622 while self.at(SyntaxKind::Dot) {
2623 self.bump();
2624 if self.at_path_segment() {
2625 self.bump();
2626 } else {
2627 self.error_at_current("FORM-101", "expected a name after `.`".to_string());
2628 break;
2629 }
2630 }
2631 self.builder.finish_node();
2632 }
2633}
2634
2635#[cfg(test)]
2636mod tests {
2637 use super::*;
2638
2639 const FIXTURE: &str = include_str!("../fixtures/walking_skeleton.typl");
2640
2641 #[test]
2642 fn fixture_round_trips_losslessly() {
2643 let parse = parse(FIXTURE, Profile::Typl);
2644 assert_eq!(
2645 parse.syntax().text().to_string(),
2646 FIXTURE,
2647 "the tree text must reproduce the source byte for byte",
2648 );
2649 assert!(
2650 parse.errors().is_empty(),
2651 "the fixture must parse without errors, got: {:?}",
2652 parse.errors(),
2653 );
2654 }
2655
2656 #[test]
2657 fn mangled_input_round_trips_and_reports_errors() {
2658 let input = "type 123 :: [";
2659 let parse = parse(input, Profile::Typl);
2660 assert_eq!(
2661 parse.syntax().text().to_string(),
2662 input,
2663 "recovery must not drop any text",
2664 );
2665 assert!(
2666 !parse.errors().is_empty(),
2667 "broken input must produce at least one error",
2668 );
2669 }
2670
2671 #[test]
2672 fn parse_equality_is_green_node_identity() {
2673 assert_eq!(
2674 parse(FIXTURE, Profile::Typl),
2675 parse(FIXTURE, Profile::Typl),
2676 "parsing identical input twice must compare equal",
2677 );
2678 assert_ne!(
2679 parse(FIXTURE, Profile::Typl),
2680 parse("package fixtures\ntype X: m", Profile::Typl),
2681 "parsing different input must not compare equal",
2682 );
2683 }
2684
2685 /// The codes of the recorded errors, in source order.
2686 fn error_codes(input: &str) -> Vec<&'static str> {
2687 parse(input, Profile::Typl)
2688 .errors()
2689 .iter()
2690 .map(|e| e.code)
2691 .collect()
2692 }
2693
2694 #[test]
2695 fn missing_package_flags_form_104() {
2696 let codes = error_codes("type Speed: km/h\n");
2697 assert_eq!(codes, vec!["FORM-104"]);
2698 }
2699
2700 #[test]
2701 fn leading_zero_integer_flags_form_005() {
2702 let codes = error_codes("package p\nconst BAD = 042\n");
2703 assert_eq!(codes, vec!["FORM-005"]);
2704 }
2705
2706 #[test]
2707 fn duration_literal_flags_typl_302() {
2708 let parse = parse("package p\nconst BAD = 10ms\n", Profile::Typl);
2709 assert_eq!(
2710 parse.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2711 vec!["TYPL-302"],
2712 );
2713 assert_eq!(
2714 parse.syntax().text().to_string(),
2715 "package p\nconst BAD = 10ms\n",
2716 "the rejected duration token must stay in the tree",
2717 );
2718 }
2719
2720 #[test]
2721 fn stray_at_sigil_flags_typl_302() {
2722 let codes = error_codes("package p\n@\n");
2723 assert_eq!(codes, vec!["TYPL-302"]);
2724 }
2725
2726 // Under `Profile::Ridl` durations and `@` are ordinary tokens — no TYPL-302
2727 // fires anywhere.
2728 #[test]
2729 fn duration_and_at_draw_no_typl_302_under_ridl() {
2730 let parsed = parse("package p\nconst BAD = 10ms\n", Profile::Ridl);
2731 assert!(
2732 parsed.errors().iter().all(|e| e.code != "TYPL-302"),
2733 "no TYPL-302 under Ridl, got: {:?}",
2734 parsed.errors(),
2735 );
2736 let parsed = parse("package p\n@\n", Profile::Ridl);
2737 assert_eq!(
2738 parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2739 vec!["FORM-102"],
2740 "a stray `@` under Ridl is a generic unexpected token",
2741 );
2742 }
2743
2744 // An interaction keyword at declaration-start in a `.typl` parse is the
2745 // profile boundary — TYPL-304, recovering like FORM-105 does (ErrorNode,
2746 // resync at the next top-level keyword).
2747 #[test]
2748 fn interaction_keyword_in_typl_flags_typl_304_and_recovers() {
2749 let input = "package p\ninterface X {}\ntype Fine: m\n";
2750 let parsed = parse(input, Profile::Typl);
2751 assert_eq!(
2752 parsed.syntax().text().to_string(),
2753 input,
2754 "TYPL-304 recovery must stay lossless",
2755 );
2756 assert_eq!(
2757 parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2758 vec!["TYPL-304"],
2759 );
2760 assert_eq!(def_names_in(Profile::Typl, input), vec!["Fine"]);
2761
2762 // The same boundary fires for every interaction kind.
2763 let codes: Vec<_> = parse("package p\nsignal speed: Speed\n", Profile::Typl)
2764 .errors()
2765 .iter()
2766 .map(|e| e.code)
2767 .collect();
2768 assert_eq!(codes, vec!["TYPL-304"]);
2769 }
2770
2771 // The stream grammar parses under both profiles; in a `.typl` parse a `<T>`
2772 // in type position is the profile boundary — TYPL-301 — and the StreamType
2773 // node is still built, losslessly.
2774 #[test]
2775 fn stream_type_in_typl_flags_typl_301_and_keeps_parsing() {
2776 let input = "package p\nstruct S {\n f : <Frame>\n g : integer [0..1]\n}\n";
2777 let parsed = parse(input, Profile::Typl);
2778 assert_eq!(
2779 parsed.syntax().text().to_string(),
2780 input,
2781 "the TYPL-301 boundary must stay lossless",
2782 );
2783 assert_eq!(
2784 parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2785 vec!["TYPL-301"],
2786 );
2787 let has_stream = parsed
2788 .syntax()
2789 .descendants()
2790 .any(|node| node.kind() == SyntaxKind::StreamType);
2791 assert!(has_stream, "the stream still parses into a StreamType node");
2792
2793 // Under `Profile::Ridl` the same field parses with no error at all —
2794 // stream placement is checker scope there.
2795 let parsed = parse(input, Profile::Ridl);
2796 assert!(
2797 parsed.errors().is_empty(),
2798 "no parser error under Ridl, got: {:?}",
2799 parsed.errors(),
2800 );
2801 }
2802
2803 // A reserved word of another profile at declaration-start in a `.ridl` parse
2804 // is RIDL-403, with the same recovery.
2805 #[test]
2806 fn reserved_word_in_ridl_flags_ridl_403_and_recovers() {
2807 let input = "package p\nmodel X {}\ntype Fine: m\n";
2808 let parsed = parse(input, Profile::Ridl);
2809 assert_eq!(
2810 parsed.syntax().text().to_string(),
2811 input,
2812 "RIDL-403 recovery must stay lossless",
2813 );
2814 assert_eq!(
2815 parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2816 vec!["RIDL-403"],
2817 );
2818 assert_eq!(def_names_in(Profile::Ridl, input), vec!["Fine"]);
2819 }
2820
2821 // rsdl reference §2, the boundary seen from the other two profiles: an
2822 // rsdl declaration in a `.typl` file draws the generic FORM-102 (the typl
2823 // boundary names ridl words only), and in a `.ridl` file RIDL-403. Both
2824 // recover at the next top-level keyword.
2825 #[test]
2826 fn rsdl_declaration_in_typl_and_ridl_draws_their_existing_codes() {
2827 let input = "package p\ndistribution Adas { Cruise }\ntype Fine: m\n";
2828 for (profile, code) in [(Profile::Typl, "FORM-102"), (Profile::Ridl, "RIDL-403")] {
2829 let parsed = parse(input, profile);
2830 assert_eq!(parsed.syntax().text().to_string(), input);
2831 assert_eq!(
2832 parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2833 vec![code],
2834 "under {profile:?}",
2835 );
2836 assert_eq!(
2837 def_names_in(profile, input),
2838 vec!["Fine"],
2839 "under {profile:?}"
2840 );
2841 }
2842 }
2843
2844 // rsdl reference §2 and §3.1: under the rsdl profile the five declarations
2845 // parse clean, and a declaration of another profile is RSDL-604 — once per
2846 // declaration, with the rsdl declaration after it still parsed.
2847 #[test]
2848 fn rsdl_profile_parses_its_declarations_and_rejects_the_others() {
2849 let clean = "package p\nsystem Vehicle { Cruise, veh.diag.access }\n";
2850 assert_eq!(parse(clean, Profile::Rsdl).errors(), &[]);
2851
2852 for foreign in [
2853 "type Speed: km/h",
2854 "internal type Speed: km/h",
2855 "struct S { a: integer [0..1] }",
2856 "interface I { signal s: S @10ms }",
2857 "service veh.a.b : I",
2858 ] {
2859 let input = format!("package p\n{foreign}\nsystem Vehicle {{ Cruise }}\n");
2860 let parsed = parse(&input, Profile::Rsdl);
2861 assert_eq!(parsed.syntax().text().to_string(), input);
2862 assert_eq!(
2863 parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2864 vec!["RSDL-604"],
2865 "`{foreign}`",
2866 );
2867 assert!(
2868 parsed
2869 .syntax()
2870 .children()
2871 .any(|node| node.kind() == SyntaxKind::SystemDef),
2872 "the system after `{foreign}` still parses",
2873 );
2874 }
2875 }
2876
2877 // rsdl reference §5: a backend key `namespace.key` is an rsdl attribute
2878 // key. Under ridl the `.` stays an unexpected token.
2879 #[test]
2880 fn a_backend_key_parses_under_rsdl_only() {
2881 let rsdl = "package p\nsystem V [ linux.cpuset = (2, 3), linux.realtime ] { A }\n";
2882 assert_eq!(parse(rsdl, Profile::Rsdl).errors(), &[]);
2883
2884 let ridl = "package p\ninterface I {\n command c() [ linux.cpuset = 1 ]\n}\n";
2885 assert_eq!(
2886 parse(ridl, Profile::Ridl)
2887 .errors()
2888 .iter()
2889 .map(|e| e.code)
2890 .collect::<Vec<_>>(),
2891 vec!["FORM-102"],
2892 );
2893 }
2894
2895 /// Recovery from a rejected return type stops *before* a sync token — it
2896 /// never consumes the construct that follows.
2897 ///
2898 /// `return_type` reports and then recovers, and `recover` always bumps the
2899 /// current token, so without the `!is_return_sync(current)` guard a
2900 /// `query a() :` written immediately before a `}` eats the interface's own
2901 /// closing brace and the file then reports an unclosed `{`. Each row here
2902 /// is one member of the sync set, and each asserts on what *survived* — a
2903 /// diagnostic-count assertion cannot see over-consumption, because
2904 /// swallowing the `}` produces one extra diagnostic and swallowing an
2905 /// interaction produces none at all.
2906 #[test]
2907 fn a_rejected_return_type_never_consumes_the_construct_after_it() {
2908 for (sync, body, survivor) in [
2909 (
2910 "the next interaction keyword",
2911 " query broken() :
2912 signal speed : Speed @10ms
2913",
2914 SyntaxKind::SignalDef,
2915 ),
2916 (
2917 "a `reserved` tombstone",
2918 " query broken() :
2919 reserved legacyTemp
2920",
2921 SyntaxKind::ReservedEntry,
2922 ),
2923 (
2924 "the body's own closing brace",
2925 " query broken() :
2926",
2927 SyntaxKind::InterfaceDef,
2928 ),
2929 ] {
2930 let input = format!(
2931 "package p
2932interface I {{
2933{body}}}
2934"
2935 );
2936 let parsed = parse(&input, Profile::Ridl);
2937 assert_eq!(
2938 parsed.syntax().text().to_string(),
2939 input,
2940 "{sync}: recovery must stay lossless",
2941 );
2942 assert_eq!(
2943 parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2944 vec!["FORM-101"],
2945 "{sync}: the broken return type is the only diagnostic — an unclosed `{{` here means the `}}` was consumed",
2946 );
2947 assert!(
2948 parsed
2949 .syntax()
2950 .descendants()
2951 .any(|node| node.kind() == survivor),
2952 "{sync}: the {survivor:?} after the broken return type is gone",
2953 );
2954 }
2955 }
2956
2957 #[test]
2958 fn pathological_type_nesting_does_not_panic_or_drop_text() {
2959 let input = format!("package p\nstruct S {{ f : {} }}\n", "[".repeat(300));
2960 let parse = parse(&input, Profile::Typl);
2961 assert_eq!(
2962 parse.syntax().text().to_string(),
2963 input,
2964 "deep nesting must stay lossless",
2965 );
2966 assert!(!parse.errors().is_empty());
2967 }
2968
2969 #[test]
2970 fn pathological_question_repetition_does_not_panic_or_drop_text() {
2971 // Each `?` wraps one OptionalType; an unbounded run used to build a
2972 // tree deep enough to overflow the stack on traversal or drop.
2973 let input = format!("package p\nstruct S {{ f : T{} }}\n", "?".repeat(30_000));
2974 let parse = parse(&input, Profile::Typl);
2975 assert_eq!(
2976 parse.syntax().text().to_string(),
2977 input,
2978 "the capped optional run must stay lossless",
2979 );
2980 assert_eq!(
2981 parse.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
2982 vec!["FORM-102"],
2983 "the cap must report exactly one error",
2984 );
2985 }
2986
2987 #[test]
2988 fn misplaced_error_modifier_parses_clean() {
2989 // TYPL-212 is checker scope: the grammar admits `error` on every
2990 // definition kind.
2991 let codes = error_codes("package p\nerror type Legacy : integer [0..1]\n");
2992 assert_eq!(codes, Vec::<&str>::new());
2993 }
2994
2995 #[test]
2996 fn error_ranges_cover_the_offending_token() {
2997 // `042` sits at bytes 22..25 of the input.
2998 let parse = parse("package p\nconst BAD = 042\n", Profile::Typl);
2999 let error = &parse.errors()[0];
3000 assert_eq!(error.code, "FORM-005");
3001 assert_eq!(
3002 error.range,
3003 TextRange::new(TextSize::new(22), TextSize::new(25)),
3004 );
3005 }
3006
3007 /// The declared names of every top-level definition, in source order —
3008 /// the recovery proof that real declaration nodes survive garbage.
3009 fn def_names(input: &str) -> Vec<String> {
3010 def_names_in(Profile::Typl, input)
3011 }
3012
3013 /// [`def_names`] under an explicit profile.
3014 fn def_names_in(profile: Profile, input: &str) -> Vec<String> {
3015 use crate::ast::{AstNode, HasName, SourceFile};
3016 let file = SourceFile::cast(parse(input, profile).syntax()).expect("root is a SourceFile");
3017 file.definitions()
3018 .filter_map(|def| Some(def.name()?.ident_token()?.text().to_string()))
3019 .collect()
3020 }
3021
3022 #[test]
3023 fn top_level_garbage_resyncs_to_the_next_declaration() {
3024 // Valid, then garbage, then valid: the run of stray tokens is wrapped
3025 // in one ErrorNode and the declaration after it is a real node again.
3026 let input = "package p\ntype Good: km/h\n] } garbage 9\ntype AlsoGood: integer [0..1]\n";
3027 let parse = parse(input, Profile::Typl);
3028 assert_eq!(
3029 parse.syntax().text().to_string(),
3030 input,
3031 "resync must stay lossless",
3032 );
3033 assert_eq!(def_names(input), vec!["Good", "AlsoGood"]);
3034 assert_eq!(error_codes(input), vec!["FORM-102"]);
3035 }
3036
3037 #[test]
3038 fn unclosed_brace_resyncs_to_the_next_declaration() {
3039 // A struct body that never closes hands the next `type` back to the
3040 // top level (FORM-103) instead of swallowing it.
3041 let input = "package p\nstruct Broken {\n gear: integer\n\ntype After: km/h\n";
3042 let parse = parse(input, Profile::Typl);
3043 assert_eq!(
3044 parse.syntax().text().to_string(),
3045 input,
3046 "unclosed-brace recovery must stay lossless",
3047 );
3048 assert_eq!(def_names(input), vec!["Broken", "After"]);
3049 assert_eq!(error_codes(input), vec!["FORM-103"]);
3050 }
3051
3052 #[test]
3053 fn reserved_word_as_name_flags_form_105_and_keeps_parsing() {
3054 // `signal` is a family reserved word (typl reference §1.4); used as a
3055 // type name it is held in an ErrorNode and the backing still parses.
3056 let input = "package p\ntype signal: integer [0..1]\ntype Fine: integer [0..1]\n";
3057 assert_eq!(error_codes(input), vec!["FORM-105"]);
3058 // Only `Fine` has a real Name; `signal` sits in an ErrorNode.
3059 assert_eq!(def_names(input), vec!["Fine"]);
3060 }
3061
3062 #[test]
3063 fn unclosed_brackets_do_not_flood_diagnostics() {
3064 // 300 unclosed `[` in a field type: before the one-error-per-offset
3065 // rule the deep-recursion unwind piled hundreds of diagnostics on the
3066 // stuck tokens. Recovery now collapses the run to a handful.
3067 let input = format!("package p\nstruct S {{ f : {} }}\n", "[".repeat(300));
3068 let parse = parse(&input, Profile::Typl);
3069 assert_eq!(
3070 parse.syntax().text().to_string(),
3071 input,
3072 "the unclosed-bracket flood must stay lossless",
3073 );
3074 assert!(
3075 parse.errors().len() <= 4,
3076 "expected a bounded diagnostic count, got {}: {:?}",
3077 parse.errors().len(),
3078 parse.errors(),
3079 );
3080 }
3081
3082 #[test]
3083 fn duration_in_constraint_reports_both_form_101_and_typl_302() {
3084 // A duration or `@` inside a constraint fails a positional check on the
3085 // same token first; the profile-boundary TYPL-302 must still fire — it
3086 // is exempt from the one-diagnostic-per-offset suppression, so both
3087 // codes are recorded (matching the honest init-position behavior).
3088 assert_eq!(
3089 error_codes("package p\ntype X: integer [0..10ms]\n"),
3090 vec!["FORM-101", "TYPL-302"],
3091 );
3092 assert_eq!(
3093 error_codes("package p\ntype X: integer [10ms]\n"),
3094 vec!["FORM-101", "TYPL-302"],
3095 );
3096 assert_eq!(
3097 error_codes("package p\ntype X: integer [0..5 @ 3]\n"),
3098 vec!["FORM-101", "TYPL-302"],
3099 );
3100 }
3101
3102 #[test]
3103 fn closed_deep_nesting_does_not_flood_diagnostics() {
3104 // A balanced 200-level nested array, deeper than MAX_TYPE_DEPTH: the
3105 // closed shape once produced over a thousand diagnostics on unwind.
3106 let deep = format!("{}integer{}", "[".repeat(200), ";1]".repeat(200));
3107 let input = format!("package p\nstruct S {{ f : {deep} }}\n");
3108 let parse = parse(&input, Profile::Typl);
3109 assert_eq!(
3110 parse.syntax().text().to_string(),
3111 input,
3112 "the deep-nesting flood must stay lossless",
3113 );
3114 assert!(
3115 parse.errors().len() <= 4,
3116 "expected a bounded diagnostic count, got {}: {:?}",
3117 parse.errors().len(),
3118 parse.errors(),
3119 );
3120 }
3121
3122 /// typl Appendix E: `reserved = "reserved" ( camelCase_id | int_lit )`.
3123 /// The literal shapes outside that production draw FORM-102 in every body
3124 /// that admits a tombstone, under both profiles. Before this rule the
3125 /// entry parsed as an ordinary `Literal`, lowered to a slot with neither a
3126 /// name nor a value, and reported nothing.
3127 #[test]
3128 fn ungrammatical_reserved_literal_flags_form_102_in_every_body() {
3129 let bodies = [
3130 (
3131 Profile::Typl,
3132 "struct S {\n a : X\n reserved {}\n b : X\n}",
3133 ),
3134 (
3135 Profile::Typl,
3136 "enum E {\n A = 1\n reserved {}\n B = 2\n}",
3137 ),
3138 (
3139 Profile::Typl,
3140 "union U {\n a : X\n reserved {}\n b : X\n}",
3141 ),
3142 (
3143 Profile::Ridl,
3144 "interface I {\n signal a : X\n reserved {}\n signal b : X\n}",
3145 ),
3146 (
3147 Profile::Ridl,
3148 "service p.svc {\n signal a : X\n reserved {}\n signal b : X\n}",
3149 ),
3150 ];
3151 for (profile, shape) in bodies {
3152 for literal in ["\"oldName\"", "true", "false", "1.5", "-1.5", "-MAX"] {
3153 let input = format!("package p\n{}\n", shape.replace("{}", literal));
3154 let parsed = parse(&input, profile);
3155 assert_eq!(
3156 parsed.syntax().text().to_string(),
3157 input,
3158 "refusing `reserved {literal}` must stay lossless in {shape}",
3159 );
3160 assert_eq!(
3161 parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
3162 vec!["FORM-102"],
3163 "`reserved {literal}` in {shape} must draw exactly one FORM-102",
3164 );
3165 assert!(
3166 parsed.errors()[0].message.starts_with(
3167 "a `reserved` tombstone takes a retired member name or a retired \
3168 integer value, not "
3169 ),
3170 "the message must lead with what a tombstone does take, got {:?}",
3171 parsed.errors()[0].message,
3172 );
3173 // The entry keeps its place as a member and the refused token
3174 // is held losslessly, so the member after it is still parsed
3175 // in position and no ordinal shifts.
3176 let entry = parsed
3177 .syntax()
3178 .descendants()
3179 .find(|node| node.kind() == SyntaxKind::ReservedEntry)
3180 .expect("the tombstone still forms a ReservedEntry");
3181 assert!(
3182 entry
3183 .children()
3184 .any(|child| child.kind() == SyntaxKind::ErrorNode),
3185 "the refused literal is held in an ErrorNode, got {entry:#?}",
3186 );
3187 assert!(
3188 entry
3189 .children()
3190 .all(|child| child.kind() != SyntaxKind::Literal),
3191 "the refused literal must not form a Literal, got {entry:#?}",
3192 );
3193 }
3194 }
3195 }
3196
3197 /// The two grammatical tombstone forms keep parsing, in every body and
3198 /// under both profiles: a name, a bare integer, and a negative integer
3199 /// (`int_lit = "-"? [0-9]+`). Narrowing the production must not narrow it
3200 /// past what Appendix E writes.
3201 #[test]
3202 fn grammatical_reserved_forms_still_parse_in_every_body() {
3203 let bodies = [
3204 (
3205 Profile::Typl,
3206 "struct S {\n a : X\n reserved {}\n b : X\n}",
3207 ),
3208 (
3209 Profile::Typl,
3210 "enum E {\n A = 1\n reserved {}\n B = 2\n}",
3211 ),
3212 (
3213 Profile::Typl,
3214 "union U {\n a : X\n reserved {}\n b : X\n}",
3215 ),
3216 (
3217 Profile::Ridl,
3218 "interface I {\n signal a : X\n reserved {}\n signal b : X\n}",
3219 ),
3220 (
3221 Profile::Ridl,
3222 "service p.svc {\n signal a : X\n reserved {}\n signal b : X\n}",
3223 ),
3224 ];
3225 for (profile, shape) in bodies {
3226 for literal in ["legacyChecksum", "3", "-3"] {
3227 let input = format!("package p\n{}\n", shape.replace("{}", literal));
3228 let parsed = parse(&input, profile);
3229 assert!(
3230 parsed.errors().is_empty(),
3231 "`reserved {literal}` in {shape} must parse clean, got {:?}",
3232 parsed.errors(),
3233 );
3234 let entry = parsed
3235 .syntax()
3236 .descendants()
3237 .find(|node| node.kind() == SyntaxKind::ReservedEntry)
3238 .expect("the tombstone forms a ReservedEntry");
3239 let kept = entry
3240 .children()
3241 .any(|child| matches!(child.kind(), SyntaxKind::Name | SyntaxKind::Literal));
3242 assert!(
3243 kept,
3244 "`reserved {literal}` must keep the retired identity, got {entry:#?}",
3245 );
3246 }
3247 }
3248 }
3249
3250 /// ADR-0015 decision 13: commas are required between service shapes,
3251 /// because the list has no closing token — it ends where the next
3252 /// declaration begins. A missing comma therefore ends the list, and the
3253 /// following bare `CamelCase` identifier is reported at the top level,
3254 /// **at the identifier**: the greedy alternative would absorb a mistyped
3255 /// `Struct Foo {` as another shape and surface the error at the `{` with
3256 /// no connection to the mistake.
3257 #[test]
3258 fn a_missing_comma_ends_the_shape_list_at_the_next_identifier() {
3259 let input = "package p\nservice p.svc : DoorControl\nStruct Foo {\n a : X\n}\n";
3260 let parsed = parse(input, Profile::Ridl);
3261 assert_eq!(
3262 parsed.syntax().text().to_string(),
3263 input,
3264 "the ended list must stay lossless",
3265 );
3266 // The ServiceDef holds exactly the one shape before the missing comma.
3267 let service = parsed
3268 .syntax()
3269 .descendants()
3270 .find(|node| node.kind() == SyntaxKind::ServiceDef)
3271 .expect("the service parses");
3272 assert_eq!(
3273 service
3274 .children()
3275 .filter(|child| child.kind() == SyntaxKind::PathType)
3276 .count(),
3277 1,
3278 "`Struct` must not be absorbed as a second shape, got {service:#?}",
3279 );
3280 // The error points at `Struct` — the identifier itself, where the
3281 // mistake is — never at the `{` after it.
3282 let struct_offset = input.find("Struct").expect("the fixture spells it") as u32;
3283 let error = &parsed.errors()[0];
3284 assert_eq!(
3285 u32::from(error.range.start()),
3286 struct_offset,
3287 "the diagnostic lands on the identifier, got: {:?}",
3288 parsed.errors(),
3289 );
3290 }
3291
3292 /// The trailing comma stays optional (ADR-0015 decision 13), and every
3293 /// shape is a direct `PathType` child of the ServiceDef. `reserved` is not
3294 /// a shape (lock design §9): the list ends at the comma before it, the
3295 /// stray keyword is reported, and nothing after it joins the list.
3296 #[test]
3297 fn a_shape_list_admits_a_trailing_comma_and_ends_before_reserved() {
3298 let input = "package p\nservice p.svc : DoorControl, MotorControl,\n";
3299 let parsed = parse(input, Profile::Ridl);
3300 assert!(
3301 parsed.errors().is_empty(),
3302 "the list parses clean, got: {:?}",
3303 parsed.errors(),
3304 );
3305 assert_eq!(
3306 shape_kinds(&parsed),
3307 [SyntaxKind::PathType, SyntaxKind::PathType]
3308 );
3309
3310 let input = "package p\nservice p.svc : DoorControl, reserved LegacyDiag, MotorControl,\n";
3311 let parsed = parse(input, Profile::Ridl);
3312 assert!(
3313 !parsed.errors().is_empty(),
3314 "`reserved` in a service's list is a parse error",
3315 );
3316 assert_eq!(
3317 shape_kinds(&parsed),
3318 [SyntaxKind::PathType],
3319 "the list ends before the stray keyword",
3320 );
3321 }
3322
3323 /// The kinds of the shape children of the first ServiceDef in `parsed`.
3324 fn shape_kinds(parsed: &Parse) -> Vec<SyntaxKind> {
3325 parsed
3326 .syntax()
3327 .descendants()
3328 .find(|node| node.kind() == SyntaxKind::ServiceDef)
3329 .expect("the service parses")
3330 .children()
3331 .filter(|child| {
3332 matches!(
3333 child.kind(),
3334 SyntaxKind::PathType | SyntaxKind::ReservedEntry
3335 )
3336 })
3337 .map(|child| child.kind())
3338 .collect()
3339 }
3340
3341 /// Nothing at all after `reserved` is a missing token, not a wrong one:
3342 /// FORM-101, naming both admitted forms.
3343 #[test]
3344 fn reserved_with_no_target_flags_form_101() {
3345 let parsed = parse("package p\nstruct S {\n reserved\n}\n", Profile::Typl);
3346 assert_eq!(
3347 parsed.errors().iter().map(|e| e.code).collect::<Vec<_>>(),
3348 vec!["FORM-101"],
3349 );
3350 assert_eq!(
3351 parsed.errors()[0].message,
3352 "expected a name or an integer value",
3353 );
3354 }
3355
3356 // --- operator chains (driftsys/ridl#346) --------------------------------
3357
3358 /// A contract expression in a minimal ridl file.
3359 fn contract_file(expr: &str) -> String {
3360 format!(
3361 "package app\ntype N : integer [0..10]\ninterface I {{\n command c(a: N) [ require {expr} ] @[..50ms]\n}}\n"
3362 )
3363 }
3364
3365 /// A flat chain of `terms` operands under `op`, closed into a boolean
3366 /// where the operator is not one already.
3367 fn flat_chain(op: &str, terms: usize) -> String {
3368 match op {
3369 "||" | "&&" => vec!["a == 1"; terms].join(&format!(" {op} ")),
3370 "." => format!("a{} == 1", ".b".repeat(terms - 1)),
3371 _ => format!("{} == 1", vec!["a"; terms].join(&format!(" {op} "))),
3372 }
3373 }
3374
3375 /// The deepest node below `root`, counted without recursion, so that
3376 /// measuring a tree cannot itself exhaust the stack.
3377 fn tree_depth(root: &SyntaxNode) -> usize {
3378 let (mut depth, mut deepest) = (0usize, 0usize);
3379 for event in root.preorder() {
3380 match event {
3381 rowan::WalkEvent::Enter(_) => {
3382 depth += 1;
3383 deepest = deepest.max(depth);
3384 }
3385 rowan::WalkEvent::Leave(_) => depth -= 1,
3386 }
3387 }
3388 deepest
3389 }
3390
3391 /// Runs `body` on a thread with a 64 MiB stack. Without the fix a chain
3392 /// builds a tree thousands of levels deep, and dropping it recurses; the
3393 /// large stack keeps that from aborting the whole test binary, so the
3394 /// test fails on its assertions instead.
3395 fn on_a_large_stack(body: impl FnOnce() + Send + 'static) {
3396 std::thread::Builder::new()
3397 .stack_size(64 << 20)
3398 .spawn(body)
3399 .expect("spawn the test thread")
3400 .join()
3401 .expect("the test thread must not panic");
3402 }
3403
3404 /// The bound every expression tree must stay within, measured from the
3405 /// file root. A checker pass that recurses over the tree is sized against
3406 /// it; a flat chain once built a tree as deep as its term count.
3407 const TREE_DEPTH_BOUND: usize = 2 * MAX_TYPE_DEPTH;
3408
3409 #[test]
3410 fn a_flat_operator_chain_past_the_depth_limit_draws_one_form_102() {
3411 on_a_large_stack(|| {
3412 for op in ["||", "&&", "+", "-", "*", "/", "%", "."] {
3413 let input = contract_file(&flat_chain(op, 1000));
3414 let parsed = parse(&input, Profile::Ridl);
3415 let form_102 = parsed
3416 .errors()
3417 .iter()
3418 .filter(|error| error.code == "FORM-102")
3419 .count();
3420 assert_eq!(
3421 form_102,
3422 1,
3423 "a 1000-term `{op}` chain draws exactly one FORM-102: {:?}",
3424 parsed.errors(),
3425 );
3426 assert_eq!(
3427 parsed.syntax().text().to_string(),
3428 input,
3429 "the refused `{op}` chain must stay lossless",
3430 );
3431 let depth = tree_depth(&parsed.syntax());
3432 assert!(
3433 depth <= TREE_DEPTH_BOUND,
3434 "a 1000-term `{op}` chain builds a tree {depth} levels deep",
3435 );
3436 }
3437 });
3438 }
3439
3440 /// The height of the expression tree under `root`: the most expression
3441 /// nodes on one path from the root to a leaf, counted without recursion.
3442 /// Only the expression kinds count, so the declaration nodes above the
3443 /// attribute and the flat `ErrorNode` of a refusal do not.
3444 fn expr_height(root: &SyntaxNode) -> usize {
3445 let is_expr = |kind: SyntaxKind| {
3446 matches!(
3447 kind,
3448 SyntaxKind::BinaryExpr
3449 | SyntaxKind::PrefixExpr
3450 | SyntaxKind::MemberExpr
3451 | SyntaxKind::PathExpr
3452 | SyntaxKind::ParenExpr
3453 | SyntaxKind::LiteralExpr
3454 )
3455 };
3456 let (mut depth, mut deepest) = (0usize, 0usize);
3457 for event in root.preorder() {
3458 match event {
3459 rowan::WalkEvent::Enter(node) if is_expr(node.kind()) => {
3460 depth += 1;
3461 deepest = deepest.max(depth);
3462 }
3463 rowan::WalkEvent::Leave(node) if is_expr(node.kind()) => depth -= 1,
3464 _ => {}
3465 }
3466 }
3467 deepest
3468 }
3469
3470 /// The bound as an author meets it, over every shape that raises the
3471 /// height, at every size around the limit and one far past it: the tree
3472 /// built is never higher than `MAX_TYPE_DEPTH`, and FORM-102 is drawn
3473 /// exactly when the complete tree would not fit. Each generator states
3474 /// the height its complete tree has at `n`; where that fits, the built
3475 /// tree must have exactly that height, which checks the formula. The
3476 /// right-leaning shapes are the ones a bound that forgets to parse a
3477 /// right operand one level deeper would let through; the group and
3478 /// prefix towers are the ones a bound that opens a group or a prefix
3479 /// without room for a leaf below it would let through.
3480 #[test]
3481 fn the_expression_height_bound_holds_for_every_shape() {
3482 type Shape = (&'static str, fn(usize) -> String, fn(usize) -> usize);
3483 let shapes: [Shape; 15] = [
3484 ("left chain", |n| vec!["a"; n].join(" + "), |n| n),
3485 (
3486 "`||` chain of comparisons",
3487 |n| vec!["a == 1"; n].join(" || "),
3488 |n| n + 1,
3489 ),
3490 (
3491 "member steps",
3492 |n| format!("a{}", ".b".repeat(n - 1)),
3493 |n| n,
3494 ),
3495 (
3496 "groups around a leaf",
3497 |n| format!("{}a{}", "(".repeat(n - 1), ")".repeat(n - 1)),
3498 |n| n,
3499 ),
3500 (
3501 "groups around a negated leaf",
3502 |n| format!("{}-a{}", "(".repeat(n - 1), ")".repeat(n - 1)),
3503 |n| n + 1,
3504 ),
3505 (
3506 "groups around a `!` leaf",
3507 |n| format!("{}!a{}", "(".repeat(n - 1), ")".repeat(n - 1)),
3508 |n| n + 1,
3509 ),
3510 (
3511 "right-nested chain",
3512 |n| {
3513 let mut expr = "a".to_string();
3514 for _ in 1..n {
3515 expr = format!("a + ({expr})");
3516 }
3517 expr
3518 },
3519 |n| 2 * n - 1,
3520 ),
3521 (
3522 "comparison with a grouped chain on the right",
3523 |n| format!("a == ({})", vec!["a"; n].join(" + ")),
3524 |n| n + 2,
3525 ),
3526 (
3527 "`!(` tower",
3528 |n| format!("{}a{}", "!(".repeat(n - 1), ")".repeat(n - 1)),
3529 |n| 2 * n - 1,
3530 ),
3531 (
3532 "`-(` tower",
3533 |n| format!("{}a{}", "-(".repeat(n - 1), ")".repeat(n - 1)),
3534 |n| 2 * n - 1,
3535 ),
3536 (
3537 "prefixed operands in a chain",
3538 |n| vec!["-a"; n].join(" * "),
3539 |n| n + 1,
3540 ),
3541 (
3542 "grouped member steps as a right operand",
3543 |n| format!("a + (a{})", ".b".repeat(n - 1)),
3544 |n| n + 2,
3545 ),
3546 (
3547 "`||` right-nested",
3548 |n| {
3549 let mut expr = "a == 1".to_string();
3550 for _ in 1..n {
3551 expr = format!("a == 1 || ({expr})");
3552 }
3553 expr
3554 },
3555 |n| 2 * n,
3556 ),
3557 (
3558 "a deep right operand, then a long left chain",
3559 |n| {
3560 format!(
3561 "a + ({}a{}){}",
3562 "(".repeat(60),
3563 ")".repeat(60),
3564 " + a".repeat(n - 1)
3565 )
3566 },
3567 // The group written around the 60 counts too: 61 groups, a
3568 // leaf, and the wrap, then one level per further term.
3569 |n| n + 62,
3570 ),
3571 (
3572 "a prefix tower, then a chain",
3573 |n| {
3574 format!(
3575 "{}a == 1{}{}",
3576 "!(".repeat(30),
3577 ")".repeat(30),
3578 " && a == 1".repeat(n - 1)
3579 )
3580 },
3581 |n| n + 61,
3582 ),
3583 ];
3584 for (shape, build, complete_height) in shapes {
3585 // The smallest sizes check the formula; the sizes whose complete
3586 // height is within eight levels of the limit check the bound on
3587 // both sides of it; 300 is far past it.
3588 let mut sizes: Vec<usize> = (1..)
3589 .take_while(|&n| complete_height(n) <= MAX_TYPE_DEPTH + 8)
3590 .filter(|&n| n <= 3 || complete_height(n) + 8 >= MAX_TYPE_DEPTH)
3591 .collect();
3592 sizes.push(300);
3593 for n in sizes {
3594 let input = contract_file(&build(n));
3595 let parsed = parse(&input, Profile::Ridl);
3596 let complete = complete_height(n);
3597 let built = expr_height(&parsed.syntax());
3598 let form_102 = parsed
3599 .errors()
3600 .iter()
3601 .filter(|error| error.code == "FORM-102")
3602 .count();
3603 assert!(
3604 built <= MAX_TYPE_DEPTH,
3605 "the {shape} at n = {n} builds a tree {built} high",
3606 );
3607 assert_eq!(
3608 parsed.syntax().text().to_string(),
3609 input,
3610 "{shape} at n = {n}"
3611 );
3612 if complete <= MAX_TYPE_DEPTH {
3613 assert!(
3614 parsed.errors().is_empty(),
3615 "the {shape} at n = {n} fits in {complete} levels: {:?}",
3616 parsed.errors(),
3617 );
3618 assert_eq!(
3619 built, complete,
3620 "the {shape} at n = {n} builds its complete tree"
3621 );
3622 } else {
3623 assert_eq!(
3624 form_102,
3625 1,
3626 "the {shape} at n = {n} would be {complete} high: {:?}",
3627 parsed.errors(),
3628 );
3629 }
3630 }
3631 }
3632 }
3633
3634 /// Past the limit the diagnostics are exactly one FORM-102: the refused
3635 /// group is consumed through its own `)` together with the groups inside
3636 /// it, the chain after the outermost group goes flat without a second
3637 /// diagnostic, and the next interaction parses as usual.
3638 #[test]
3639 fn a_refused_group_draws_only_form_102_and_the_next_interaction_parses() {
3640 use crate::ast::AstNode;
3641 let groups = MAX_TYPE_DEPTH + 2;
3642 let input = format!(
3643 "package app\ntype N : integer [0..10]\ninterface I {{\n \
3644 command c(a: N) [ require {}(a) + (a){} + a + a ] @[..50ms]\n \
3645 command d(a: N) [ require a == 1 ] @[..50ms]\n}}\n",
3646 "(".repeat(groups),
3647 ")".repeat(groups),
3648 );
3649 let parsed = parse(&input, Profile::Ridl);
3650 let codes: Vec<&str> = parsed.errors().iter().map(|error| error.code).collect();
3651 assert_eq!(codes, vec!["FORM-102"]);
3652 assert_eq!(parsed.syntax().text().to_string(), input);
3653 let root = parsed.syntax();
3654 assert!(expr_height(&root) <= MAX_TYPE_DEPTH);
3655 assert_eq!(
3656 root.descendants()
3657 .filter(|node| node.kind() == SyntaxKind::CommandDef)
3658 .count(),
3659 2,
3660 );
3661 let last = root
3662 .descendants()
3663 .filter_map(crate::ast::Attribute::cast)
3664 .last()
3665 .expect("the second command's attribute");
3666 assert_eq!(
3667 last.expr().expect("its expression").syntax().text(),
3668 "a == 1",
3669 );
3670 }
3671
3672 /// A chain whose left operand is missing still keeps the bound: the
3673 /// wrap holds only its right operand, and counting the missing side as
3674 /// zero high would let the leaf below the deepest wrap sit one level
3675 /// past the limit. The shapes put the wrap at the deepest group the
3676 /// bound admits.
3677 #[test]
3678 fn a_missing_left_operand_keeps_the_bound() {
3679 for inner in ["+ a", "== a", "|| a == 1", "+ a == a"] {
3680 let groups = MAX_TYPE_DEPTH - 1;
3681 let input = contract_file(&format!(
3682 "{}{inner}{}",
3683 "(".repeat(groups),
3684 ")".repeat(groups)
3685 ));
3686 let parsed = parse(&input, Profile::Ridl);
3687 let built = expr_height(&parsed.syntax());
3688 assert!(
3689 built <= MAX_TYPE_DEPTH,
3690 "`{inner}` under {groups} groups builds a tree {built} high: {:?}",
3691 parsed.errors(),
3692 );
3693 assert!(
3694 parsed.errors().iter().any(|error| error.code == "FORM-101"),
3695 "the missing operand is reported: {:?}",
3696 parsed.errors(),
3697 );
3698 assert_eq!(parsed.syntax().text().to_string(), input);
3699 }
3700 }
3701
3702 /// A refused expression ends where the expression would have ended: the
3703 /// next attribute in the block — after a comma, a key on its own line, or
3704 /// an `ensure` on the same line with no comma — and the later
3705 /// declarations are parsed as usual, including a syntax error in one of
3706 /// them. Each overlong expression draws its own FORM-102. The stop at a
3707 /// `require`, a reserved word and a key after each kind of operand is
3708 /// pinned by the test after this one.
3709 #[test]
3710 fn a_refused_expression_does_not_swallow_what_follows_it() {
3711 use crate::ast::AstNode;
3712 let long = flat_chain("+", 200);
3713 let input = format!(
3714 "package app\ntype N : integer [0..10]\ninterface I {{\n \
3715 command c(a: N) [ require {long}, require a == 1 ] @[..50ms]\n \
3716 command d(a: N) [ require {long}\n key = 1\n require a == 1 ] @[..50ms]\n \
3717 command e(a: N) [ require a == ] @[..50ms]\n \
3718 command f(a: N) [ require {long} ensure a == 1 ] @[..50ms]\n}}\n"
3719 );
3720 let parsed = parse(&input, Profile::Ridl);
3721 assert_eq!(parsed.syntax().text().to_string(), input);
3722 let codes: Vec<&str> = parsed.errors().iter().map(|error| error.code).collect();
3723 assert_eq!(
3724 codes.iter().filter(|code| **code == "FORM-102").count(),
3725 3,
3726 "one FORM-102 per overlong expression: {codes:?}",
3727 );
3728 assert!(
3729 codes.contains(&"FORM-101"),
3730 "the syntax error in the later declaration is still reported: {codes:?}",
3731 );
3732 let spans: Vec<_> = parsed
3733 .errors()
3734 .iter()
3735 .filter(|error| error.code == "FORM-102")
3736 .map(|error| error.range.start())
3737 .collect();
3738 assert!(
3739 spans.windows(2).all(|pair| pair[0] < pair[1]),
3740 "each FORM-102 sits at its own expression: {spans:?}",
3741 );
3742 let root = parsed.syntax();
3743 assert_eq!(
3744 root.descendants()
3745 .filter(|node| node.kind() == SyntaxKind::CommandDef)
3746 .count(),
3747 4,
3748 );
3749 let attributes: Vec<crate::ast::Attribute> = root
3750 .descendants()
3751 .filter_map(crate::ast::Attribute::cast)
3752 .collect();
3753 assert_eq!(attributes.len(), 8, "{attributes:?}");
3754 assert_eq!(
3755 attributes
3756 .iter()
3757 .filter(|attribute| attribute
3758 .expr()
3759 .is_some_and(|expr| expr.syntax().text() == "a == 1"))
3760 .count(),
3761 3,
3762 "the `a == 1` after each refused chain is its own attribute",
3763 );
3764 assert!(
3765 attributes.iter().any(|attribute| attribute
3766 .syntax()
3767 .text()
3768 .to_string()
3769 .starts_with("key")),
3770 "the key after the refused chain is its own attribute",
3771 );
3772 }
3773
3774 /// Each way the skipped run of a refused chain can end before the next
3775 /// attribute, with no comma: a `require` directly after the chain, a
3776 /// reserved word in key position (which still draws its own FORM-105),
3777 /// and a key after a chain that ends in a number, a name or a group.
3778 #[test]
3779 fn a_refused_chain_stops_at_every_kind_of_next_attribute() {
3780 use crate::ast::AstNode;
3781 let numbers = flat_chain("+", 200);
3782 let names = vec!["a"; 200].join(" + ");
3783 let groups = vec!["(a)"; 200].join(" + ");
3784 let cases = [
3785 ("a `require`", format!("{numbers}\n require a == 1")),
3786 ("a reserved word", format!("{numbers}\n states = 1")),
3787 ("a key after a number", format!("{numbers}\n key = 1")),
3788 ("a key after a name", format!("{names}\n key = 1")),
3789 ("a key after a group", format!("{groups}\n key = 1")),
3790 ];
3791 for (case, body) in cases {
3792 let input = format!(
3793 "package app\ntype N : integer [0..10]\ninterface I {{\n \
3794 command c(a: N) [ require {body} ] @[..50ms]\n}}\n"
3795 );
3796 let parsed = parse(&input, Profile::Ridl);
3797 assert_eq!(parsed.syntax().text().to_string(), input, "{case}");
3798 let codes: Vec<&str> = parsed.errors().iter().map(|error| error.code).collect();
3799 let expected: &[&str] = if case == "a reserved word" {
3800 &["FORM-102", "FORM-105"]
3801 } else {
3802 &["FORM-102"]
3803 };
3804 assert_eq!(codes, expected, "{case}");
3805 let attributes: Vec<String> = parsed
3806 .syntax()
3807 .descendants()
3808 .filter_map(crate::ast::Attribute::cast)
3809 .map(|attribute| attribute.syntax().text().to_string())
3810 .collect();
3811 assert_eq!(
3812 attributes.len(),
3813 2,
3814 "{case}: the next attribute is its own node: {attributes:?}",
3815 );
3816 let next = attributes[1].trim();
3817 let starts = match case {
3818 "a `require`" => "require a == 1",
3819 "a reserved word" => "states = 1",
3820 _ => "key = 1",
3821 };
3822 assert_eq!(next, starts, "{case}");
3823 }
3824 }
3825
3826 #[test]
3827 fn a_long_chain_under_the_depth_limit_parses_clean() {
3828 for op in ["||", "&&", "+", "-", "*", "/", "%", "."] {
3829 let input = contract_file(&flat_chain(op, 100));
3830 let parsed = parse(&input, Profile::Ridl);
3831 assert!(
3832 parsed.errors().is_empty(),
3833 "a 100-term `{op}` chain is accepted: {:?}",
3834 parsed.errors(),
3835 );
3836 }
3837 }
3838
3839 #[test]
3840 fn chains_stacked_through_parentheses_and_precedence_stay_bounded() {
3841 on_a_large_stack(|| {
3842 // Each parenthesis level closes a chain of its own, so a bound
3843 // that is charged while a chain is parsed and released when it
3844 // returns lets the chains stack on the left spine.
3845 let mut nested = "a".to_string();
3846 for _ in 0..120 {
3847 nested = format!("({nested}{})", " + a".repeat(119));
3848 }
3849 // One chain per precedence level, each the first operand of the
3850 // next: member, multiplicative, additive, comparison, `&&`, `||`.
3851 let ladder = format!(
3852 "a{}{}{} == a{}{}",
3853 ".b".repeat(119),
3854 " * a".repeat(119),
3855 " + a".repeat(119),
3856 " && a == a".repeat(119),
3857 " || a == a".repeat(119),
3858 );
3859 for (shape, expr) in [("nested", format!("{nested} == 1")), ("ladder", ladder)] {
3860 let input = contract_file(&expr);
3861 let parsed = parse(&input, Profile::Ridl);
3862 assert!(
3863 parsed.errors().iter().any(|error| error.code == "FORM-102"),
3864 "the {shape} shape draws FORM-102: {:?}",
3865 parsed.errors(),
3866 );
3867 assert!(
3868 parsed.errors().len() <= 4,
3869 "the {shape} shape floods {} diagnostics",
3870 parsed.errors().len(),
3871 );
3872 assert_eq!(parsed.syntax().text().to_string(), input);
3873 let depth = tree_depth(&parsed.syntax());
3874 assert!(
3875 depth <= TREE_DEPTH_BOUND,
3876 "the {shape} shape builds a tree {depth} levels deep",
3877 );
3878 }
3879 });
3880 }
3881}