Skip to main content

quilt/node/
parse.rs

1//! Quilt's surface parser: hand-written, one pass, straight to [`Node`].
2//!
3//! Quilt's outer syntax is a *lexical* language — glyph-delimited brackets over
4//! otherwise-opaque text — so the whole grammar is a scanner plus one rule for
5//! nesting. Running a generalised parser over it (issue #254) meant building a
6//! CST, walking it, and converting every node into the [`Node`] we actually
7//! wanted, with the byte ranges recovered from the tree on the way past. This
8//! module skips both the tree and the walk.
9//!
10//! ## Two ways in
11//!
12//! [`Node::parse`] is the strict one: the first diagnostic wins and nothing
13//! comes back. [`scan`] is the recovering one — every token with its byte
14//! range, every diagnostic, and no failure mode. `quilt-lsp` needs the second,
15//! because an editor buffer is malformed most of the time someone is typing in
16//! it, and blanking every region in the file between the `↖` and its `↗` would
17//! make the server useless. Both drive the same `step`, so there is one
18//! description of Quilt's syntax here and not two.
19//!
20//! ## The behaviours that are easy to get wrong
21//!
22//! All pinned by the unit tests below and by `tests/parser_corpus.rs`, whose
23//! snapshots were taken while `tree-sitter-quilt` was still in the tree and
24//! agreeing with this parser token for token:
25//!
26//! * **Longest-token-at-each-position.** `1a↓` is content `1` then a reduce
27//!   annotated `a`, because the annotation regex `([a-z][a-z0-9]*)?↓` cannot
28//!   start at the digit. `x = 42↖1↗` keeps `42` as content for the same reason.
29//! * **`//` always wins over content**, wherever it appears — the grammar gives
30//!   `plain_line_comment` a token precedence over the character class, so
31//!   `https://example.com` really is content `https:` plus a comment.
32//! * **Inside a bracket a line comment stops at `↗`/`↘`** (issue #226) while at
33//!   ground level it runs to end of line, closing arrows and all.
34//! * **Quilt's own comments vanish**, and the line form swallows a preceding
35//!   `\n` plus indentation, so removing one leaves no blank line behind. They
36//!   never merge the content on either side into one node.
37//! * **An escape is its own node.** `a\↖b` is three `Content`s, not one.
38//! * **An unterminated `/* … */` is not a comment at all**, it is content.
39//! * **A `⟨/*⟩` comment ends at the first *aligned* `⟨*/⟩`**, not the first one
40//!   that occurs — see [`Parser::q_block_close`].
41//!
42//! ## Depth
43//!
44//! Nesting is tracked on an explicit [`Vec`] rather than by recursing, so
45//! parsing has no depth limit of its own: `↖`×`100_000` is a diagnostic, where
46//! the tree-sitter path aborted the process. That is the contract
47//! `fuzz/fuzz_targets/parse_quilt.rs` and `quilt check` rest on.
48//!
49//! What is left is not the parser's: a deeply nested [`Node`] is a deeply
50//! nested *value*, and `Node`'s derived `Drop` recurses like any tree's. The
51//! ceiling moved from ~`2_000` nested brackets to ~`8_000` rather than away, and
52//! moving it further means an iterative `Drop` for `Node` — a change to the
53//! type, not to this file.
54
55use super::Node;
56use crate::glyphs::{ESCAPE_LEN, GLYPHS, MACHINE};
57use crate::prelude::*;
58use miette::LabeledSpan;
59
60/// Quilt's own line comment. Stripped from the output entirely, unlike
61/// [`Node::PlainLineComment`], which passes through.
62const Q_LINE: &str = "⟨//⟩";
63/// Quilt's own block comment delimiters. Also stripped.
64const Q_BLOCK_OPEN: &str = "⟨/*⟩";
65const Q_BLOCK_CLOSE: &str = "⟨*/⟩";
66/// An empty one. Because it is stripped, it is the only separator Quilt's
67/// surface syntax has that leaves no text of its own behind — which is what
68/// [`Node::coparse`] needs to keep two adjacent nodes from lexing as one
69/// comment token (issue #256).
70pub(super) const Q_BLOCK_EMPTY: &str = "⟨/*⟩⟨*/⟩";
71/// The `⟨T⟩` type placeholder and `⟨N⟩` name placeholder.
72pub(super) const TYPE: &str = "⟨T⟩";
73pub(super) const NAME: &str = "⟨N⟩";
74
75/// Parse Quilt source into a flat list of [`Node`]s. See [`Node::parse`].
76pub(super) fn parse(src: &str) -> Result<Box<[Node]>> {
77    Parser::new(src).run()
78}
79
80/// One token of Quilt surface syntax, with its byte range in the source.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Token {
83    /// Byte range in the scanned source.
84    pub span: Span,
85    pub kind: TokenKind,
86}
87
88/// What a [`Token`] is.
89///
90/// Deliberately coarser than [`Node`] in one place and finer in another. An
91/// escape (`\↖`) is [`TokenKind::Content`], because to every consumer it is
92/// bytes to copy. A Quilt comment is [`TokenKind::Comment`] and *has* a token,
93/// where the `Node` tree drops it entirely — which is the whole reason
94/// `quilt-lsp` needs [`scan`] rather than [`Node::parse`]: it has to know where
95/// the comments were in order to translate their delimiters.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
97pub enum TokenKind {
98    /// Ordinary text, including `\`-escapes.
99    Content,
100    NewLine,
101    /// `anno↖`, annotation included.
102    OpenQuote,
103    /// `↗`. Also the token that closes a `↙` a `↗` was written for — a
104    /// mismatched closer still closes, and the diagnostic says so.
105    CloseQuote,
106    /// `anno↙`, annotation included.
107    OpenUnquote,
108    /// `↘`.
109    CloseUnquote,
110    Lift,
111    /// `anno↓`, annotation included.
112    Reduce,
113    Emit,
114    Type,
115    Name,
116    /// `anno⟨M⟩`, annotation included.
117    Machine,
118    /// `// …`, which passes through to the output.
119    PlainLineComment,
120    /// `/* … */`, which passes through to the output.
121    PlainBlockComment,
122    /// `⟨//⟩ …` or `⟨/*⟩ … ⟨*/⟩` — Quilt's own, stripped from the output. The
123    /// line form's span includes the newline and indentation in front of it,
124    /// which is how deleting one leaves no blank line behind.
125    Comment,
126    /// Bytes the scanner could not make sense of. There is a matching entry in
127    /// [`scan`]'s error list; this is here so the tokens still tile the source.
128    Error,
129}
130
131impl TokenKind {
132    /// Whether this token is a Quilt *construct* — a quote, unquote or operator
133    /// glyph — rather than bytes that pass through: content, newlines, the
134    /// comments (Quilt's own and the object language's), and whatever failed to
135    /// scan.
136    ///
137    /// It answers "does expanding this source produce anything other than the
138    /// source?", which is why both ends of the toolchain key off it: `quilt
139    /// expand` injects a runtime import only into a file that has one (issue
140    /// #274), and `quilt-lsp` emits its ground prologue only for a file that
141    /// has one — so a construct-free `.rs.quilt` still projects to itself byte
142    /// for byte.
143    #[must_use]
144    pub fn is_construct(self) -> bool {
145        !matches!(
146            self,
147            TokenKind::Content
148                | TokenKind::NewLine
149                | TokenKind::PlainLineComment
150                | TokenKind::PlainBlockComment
151                | TokenKind::Comment
152                | TokenKind::Error
153        )
154    }
155}
156
157/// A diagnostic from [`scan`].
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct ParseError {
160    pub span: Span,
161    pub message: Box<str>,
162}
163
164/// Scan Quilt source into spanned tokens and diagnostics. Never fails.
165///
166/// The tokens **tile the source**: concatenating `&src[t.span]` in order
167/// reproduces it exactly, with no gaps and no overlaps (`tokens_tile_the_source`
168/// pins that). A consumer walking them therefore sees every byte, which is what
169/// lets `quilt-lsp` build its projections by copying spans.
170///
171/// Recovery is: a bracket still open at end of input is reported and closed, a
172/// closer that does not match the open bracket closes it anyway, and anything
173/// else unparseable becomes a [`TokenKind::Error`] token and the scan carries
174/// on. Errors come back in source order.
175#[must_use]
176pub fn scan(src: &str) -> (Vec<Token>, Vec<ParseError>) {
177    let mut parser = Parser::new(src);
178    let mut tokens: Vec<Token> = Vec::new();
179    let mut errors: Vec<ParseError> = Vec::new();
180    // (index of the opening token, is it a quote)
181    let mut stack: Vec<(usize, bool)> = Vec::new();
182    loop {
183        let start = parser.pos;
184        let step = parser.step(stack.last().map(|&(_, quote)| quote));
185        let span = start..parser.pos;
186        let kind = match step {
187            Step::Done => break,
188            Step::Skip => TokenKind::Comment,
189            Step::Node(node) => token_kind(&node),
190            Step::Open { quote, .. } => {
191                stack.push((tokens.len(), quote));
192                if quote {
193                    TokenKind::OpenQuote
194                } else {
195                    TokenKind::OpenUnquote
196                }
197            }
198            Step::Close { error, .. } => {
199                let (_, quote) = stack.pop().expect("`step` only closes an open frame");
200                if let Some(what) = error {
201                    errors.push(ParseError {
202                        span: span.clone(),
203                        message: what.into(),
204                    });
205                }
206                if quote {
207                    TokenKind::CloseQuote
208                } else {
209                    TokenKind::CloseUnquote
210                }
211            }
212            Step::Error(what) => {
213                errors.push(ParseError {
214                    span: span.clone(),
215                    message: what.into(),
216                });
217                TokenKind::Error
218            }
219        };
220        tokens.push(Token { span, kind });
221    }
222    for (open, _) in stack {
223        errors.push(ParseError {
224            span: tokens[open].span.clone(),
225            message: NEVER_CLOSED.into(),
226        });
227    }
228    errors.sort_by_key(|e| (e.span.start, e.span.end));
229    (tokens, errors)
230}
231
232/// What a scan says about the Quilt *constructs* a source uses: whether it has
233/// any at all, and which languages its quotes name (issue #274).
234///
235/// Both answers are needed before a line of the expansion exists — they decide
236/// whether the generated file needs a runtime import and, for a host whose lift
237/// spelling is target-directed, which names that import has to carry. A scan is
238/// enough for it, and a scan is cheap and never fails.
239#[derive(Debug, Clone, Default, PartialEq, Eq)]
240pub struct Constructs {
241    /// Whether any quote, unquote or operator glyph occurs — i.e. whether the
242    /// expansion is anything other than the source itself.
243    ///
244    /// A Quilt *comment* does not count. `⟨//⟩` is deleted by the expander, not
245    /// translated into a call, so a file whose only construct is one expands to
246    /// plain source and needs nothing in scope.
247    pub any: bool,
248    /// Every language annotation a quote names, in first-seen order (`sql↖…↗` →
249    /// `sql`). Un-annotated quotes contribute nothing: their language comes
250    /// from the file's chain, which the caller already has.
251    ///
252    /// Deliberately an over-approximation of what an expansion lifts into — a
253    /// language listed but never lifted into costs an unused import, while one
254    /// missing costs a name that is not in scope.
255    pub annos: Vec<Box<str>>,
256}
257
258/// Scan `src` for the constructs it uses. See [`Constructs`].
259#[must_use]
260pub fn constructs(src: &str) -> Constructs {
261    let (tokens, _) = scan(src);
262    let mut out = Constructs::default();
263    for t in &tokens {
264        if !t.kind.is_construct() {
265            continue;
266        }
267        out.any = true;
268        if t.kind == TokenKind::OpenQuote {
269            // The span is `anno↖`, annotation included.
270            let text = &src[t.span.clone()];
271            let anno = crate::glyphs::split_anno(text.strip_suffix('↖').unwrap_or(text)).0;
272            if !anno.is_empty() && !out.annos.iter().any(|a| &**a == anno) {
273                out.annos.push(anno.into());
274            }
275        }
276    }
277    out
278}
279
280/// The [`TokenKind`] for a node the scanner just produced.
281fn token_kind(node: &Node) -> TokenKind {
282    match node {
283        Node::Content(_) => TokenKind::Content,
284        Node::NewLine => TokenKind::NewLine,
285        Node::Lift => TokenKind::Lift,
286        Node::Reduce { .. } => TokenKind::Reduce,
287        Node::Emit => TokenKind::Emit,
288        Node::Type => TokenKind::Type,
289        Node::Name => TokenKind::Name,
290        Node::Machine { .. } => TokenKind::Machine,
291        Node::PlainLineComment(_) => TokenKind::PlainLineComment,
292        Node::PlainBlockComment(_) => TokenKind::PlainBlockComment,
293        // `step` never returns a bracket as a `Step::Node`; they arrive as
294        // `Step::Open`/`Step::Close` and are handled there.
295        Node::Quote { .. } => TokenKind::OpenQuote,
296        Node::Unquote { .. } => TokenKind::OpenUnquote,
297    }
298}
299
300/// What a language annotation is attached to. Almost always a single glyph;
301/// `⟨M⟩` (issue #273) is the exception, which is why this is not a `char`.
302#[derive(Clone, Copy)]
303enum Annotated {
304    /// `anno↖`, `anno↙` or `anno↓`.
305    Glyph(char),
306    /// `anno⟨M⟩`.
307    Machine,
308    /// `anno⟨repr⟩↖`: a quote with a representation; holds the length of
309    /// the `⟨repr⟩`.
310    Repr(usize),
311}
312
313/// One open `anno↖` / `anno↙` and the nodes collected inside it so far.
314struct Frame {
315    anno: Box<str>,
316    /// Byte offset of the *whole* opener token, annotation included — which is
317    /// where the "never closed" diagnostic points.
318    open: usize,
319    /// `true` for `↖…↗`, `false` for `↙…↘`.
320    quote: bool,
321    nodes: Vec<Node>,
322}
323
324impl Frame {
325    /// The opener token's byte range: the annotation plus its glyph.
326    fn opener(&self) -> Span {
327        let glyph = if self.quote { '↖' } else { '↙' };
328        self.open..self.open + self.anno.len() + glyph.len_utf8()
329    }
330}
331
332/// What one turn of the scanner produced.
333///
334/// Every variant leaves [`Parser::pos`] past the token it consumed, including
335/// [`Step::Error`] — which is what lets a caller that wants every diagnostic
336/// (rather than just the first) carry on scanning. See [`scan`].
337enum Step {
338    /// End of input.
339    Done,
340    /// A token that leaves no node behind — one of Quilt's own comments.
341    Skip,
342    Node(Node),
343    Open {
344        anno: Box<str>,
345        quote: bool,
346        open: usize,
347    },
348    /// A closer for the frame on top of the stack; carries its end offset so
349    /// the bracket's span can be sealed. `error` is set when the closer was the
350    /// *wrong* one — the frame still closes, because leaving it open would
351    /// report every bracket after it as broken too.
352    Close {
353        end: usize,
354        error: Option<&'static str>,
355    },
356    /// Malformed syntax. The offending token is consumed; nothing is produced.
357    Error(&'static str),
358}
359
360struct Parser<'a> {
361    src: &'a str,
362    pos: usize,
363    /// Memo for [`Parser::comment_after_newline`]. A `\n…` probe's outcome
364    /// depends only on where the whitespace run *ends*, so once one has failed
365    /// every `\n` inside that run fails too. Without this, a file of blank
366    /// lines is quadratic.
367    probe_failed_until: usize,
368    /// Memo: there is no `*/` at or after this offset. A failed search from `p`
369    /// settles every `p' >= p`, which keeps `/*/*/*…` linear.
370    no_block_close_from: usize,
371    /// The same, for `⟨*/⟩`.
372    no_q_block_close_from: usize,
373    /// How many brackets are open: [`Step::Open`] and [`Step::Close`] keep it.
374    depth: usize,
375    /// Comments interrupted by a bracket, innermost last: the depth the
376    /// bracket opened at, and the kind of comment to pick up again once it
377    /// closes. See [`Parser::comment`].
378    paused: Vec<(usize, Plain)>,
379    /// A comment to continue at the next token: its bracket (or escape) just
380    /// ended.
381    resume: Option<Plain>,
382    /// A comment an escaped arrow interrupted, to continue after the escape.
383    escaped: Option<Plain>,
384}
385
386/// The two object-language comment forms Quilt lexes itself.
387#[derive(Clone, Copy, PartialEq, Eq, Debug)]
388enum Plain {
389    /// `// …`
390    Line,
391    /// `/* … */`
392    Block,
393}
394
395impl<'a> Parser<'a> {
396    fn new(src: &'a str) -> Self {
397        Self {
398            src,
399            pos: 0,
400            probe_failed_until: 0,
401            no_block_close_from: usize::MAX,
402            no_q_block_close_from: usize::MAX,
403            depth: 0,
404            paused: Vec::new(),
405            resume: None,
406            escaped: None,
407        }
408    }
409
410    /// The strict parse behind [`Node::parse`]: the first diagnostic wins and
411    /// nothing is returned. [`scan`] is the recovering half.
412    fn run(mut self) -> Result<Box<[Node]>> {
413        let mut stack: Vec<Frame> = Vec::new();
414        let mut out: Vec<Node> = Vec::new();
415        loop {
416            let start = self.pos;
417            match self.step(stack.last().map(|f| f.quote)) {
418                Step::Done => {
419                    // Anything still open at end of input is the error, and the
420                    // *innermost* one is the most specific thing to point at.
421                    return match stack.last() {
422                        Some(frame) => Err(error(frame.opener(), NEVER_CLOSED)),
423                        None => Ok(out.into()),
424                    };
425                }
426                // The recovering half keeps going here (see [`scan`]); the
427                // strict one stops at the first thing it cannot justify.
428                Step::Error(what)
429                | Step::Close {
430                    error: Some(what), ..
431                } => return Err(error(start..self.pos, what)),
432                Step::Skip => {}
433                Step::Node(node) => sink(&mut stack, &mut out).push(node),
434                Step::Open { anno, quote, open } => stack.push(Frame {
435                    anno,
436                    open,
437                    quote,
438                    nodes: Vec::new(),
439                }),
440                Step::Close { end, error: None } => {
441                    let frame = stack.pop().expect("`step` only closes an open frame");
442                    let span = frame.open..end;
443                    let nodes = frame.nodes.into_iter().map(arc).collect();
444                    let anno = frame.anno;
445                    let node = if frame.quote {
446                        Node::Quote { anno, nodes, span }
447                    } else {
448                        Node::Unquote { anno, nodes, span }
449                    };
450                    sink(&mut stack, &mut out).push(node);
451                }
452            }
453        }
454    }
455
456    /// Consume one token. `open` is the top frame's kind, or `None` at ground
457    /// level — it decides both whether a closer is expected and how far a line
458    /// comment may run (issue #226).
459    fn step(&mut self, open: Option<bool>) -> Step {
460        let step = self.token(open);
461        match step {
462            Step::Open { .. } => self.depth += 1,
463            Step::Close { .. } => {
464                self.depth -= 1;
465                if self.paused.last().is_some_and(|&(d, _)| d == self.depth) {
466                    self.resume = self.paused.pop().map(|(_, kind)| kind);
467                }
468            }
469            _ => {}
470        }
471        step
472    }
473
474    /// [`Self::step`]'s scanner, without the bracket bookkeeping.
475    fn token(&mut self, open: Option<bool>) -> Step {
476        let start = self.pos;
477        // The rest of a comment a bracket or an escape interrupted (see
478        // [`Self::comment`]). A line comment that has reached its newline is
479        // over; anything else picks up where it left off.
480        if let Some(kind) = self.resume.take() {
481            let more = match kind {
482                Plain::Line => !matches!(self.peek(), None | Some('\n')),
483                Plain::Block => self.peek().is_some(),
484            };
485            if more {
486                if let Some(node) = self.comment(kind, start, open.is_some()) {
487                    return Step::Node(node);
488                }
489            }
490        }
491        let Some(c) = self.peek() else {
492            return Step::Done;
493        };
494        match c {
495            // A Quilt comment may begin with the newline before it, taking the
496            // line's indentation with it. Only if the whole token matches,
497            // though — otherwise this is an ordinary line break.
498            '\n' => {
499                if self.comment_after_newline(open.is_some()) {
500                    return Step::Skip;
501                }
502                self.pos += 1;
503                Step::Node(Node::NewLine)
504            }
505            '⟨' => self.angle(open.is_some()),
506            // A closer that does not match the open frame still closes it.
507            // Leaving the frame open would report every bracket after it as
508            // broken too, and one typo should be one diagnostic.
509            '↗' | '↘' => {
510                let quote = c == '↗';
511                self.pos += c.len_utf8();
512                match open {
513                    Some(o) if o == quote => Step::Close {
514                        end: self.pos,
515                        error: None,
516                    },
517                    Some(_) if quote => Step::Close {
518                        end: self.pos,
519                        error: Some("expected `↘` here: the open bracket is a `↙` unquote"),
520                    },
521                    Some(_) => Step::Close {
522                        end: self.pos,
523                        error: Some("expected `↗` here: the open bracket is a `↖` quote"),
524                    },
525                    None if quote => Step::Error("no `↖` is open here"),
526                    None => Step::Error("no `↙` is open here"),
527                }
528            }
529            '↖' | '↙' => {
530                self.pos += c.len_utf8();
531                Step::Open {
532                    anno: "".into(),
533                    quote: c == '↖',
534                    open: start,
535                }
536            }
537            '↑' => {
538                self.pos += c.len_utf8();
539                Step::Node(Node::Lift)
540            }
541            '↓' => {
542                self.pos += c.len_utf8();
543                Step::Node(Node::Reduce { anno: "".into() })
544            }
545            '←' => {
546                self.pos += c.len_utf8();
547                Step::Node(Node::Emit)
548            }
549            '⟩' => {
550                self.pos += c.len_utf8();
551                Step::Error("a bare `⟩` has no meaning; `\\⟩` writes one literally")
552            }
553            // `\` + glyph is an escape and becomes content holding the bare
554            // glyph. `\` + anything else is ordinary content (the grammar's
555            // `_non_escape`), and a `\` with nothing after it is an error.
556            '\\' => match self.char_at(start + ESCAPE_LEN) {
557                Some(g) if GLYPHS.contains(&g) => {
558                    self.pos = start + ESCAPE_LEN + g.len_utf8();
559                    // An escape that cut a comment short hands it back.
560                    self.resume = self.escaped.take();
561                    Step::Node(Node::Content(self.src[start + ESCAPE_LEN..self.pos].into()))
562                }
563                Some(_) => Step::Node(self.content()),
564                None => {
565                    self.pos += ESCAPE_LEN;
566                    Step::Error("a `\\` escape needs a character after it")
567                }
568            },
569            '/' if self.at(start, "//") => {
570                self.pos = start + 2;
571                let node = self.comment(Plain::Line, start, open.is_some());
572                Step::Node(node.expect("a comment holds at least its `//`"))
573            }
574            '/' if self.at(start, "/*") => match self.block_close(start + 2) {
575                Some(_) => {
576                    self.pos = start + 2;
577                    let node = self.comment(Plain::Block, start, open.is_some());
578                    Step::Node(node.expect("a comment holds at least its `/*`"))
579                }
580                // An unterminated `/*` is not a comment token at all, so it is
581                // plain content — matching the grammar, where the token simply
582                // fails to match and the character class picks the `/` up.
583                None => Step::Node(self.content()),
584            },
585            // An annotated opener or reduce: `[a-z][a-z0-9]*` immediately
586            // followed by `↖`, `↙` or `↓`.
587            c if c.is_ascii_lowercase() => {
588                let run = self.ident_run_end(start);
589                match self.annotation_target(run) {
590                    Some(Annotated::Machine) => {
591                        let anno: Box<str> = self.src[start..run].into();
592                        self.pos = run + MACHINE.len();
593                        Step::Node(Node::Machine { anno })
594                    }
595                    Some(Annotated::Repr(n)) => {
596                        let anno: Box<str> = self.src[start..run + n].into();
597                        self.pos = run + n + '↖'.len_utf8();
598                        Step::Open {
599                            anno,
600                            quote: true,
601                            open: start,
602                        }
603                    }
604                    Some(Annotated::Glyph(g)) => {
605                        let anno: Box<str> = self.src[start..run].into();
606                        self.pos = run + g.len_utf8();
607                        match g {
608                            '↓' => Step::Node(Node::Reduce { anno }),
609                            _ => Step::Open {
610                                anno,
611                                quote: g == '↖',
612                                open: start,
613                            },
614                        }
615                    }
616                    None => Step::Node(self.content()),
617                }
618            }
619            _ => Step::Node(self.content()),
620        }
621    }
622
623    /// A run of ordinary characters, ending where any other token could begin.
624    ///
625    /// Always consumes at least one character: every caller has already
626    /// established that the character at [`Self::pos`] is not the start of some
627    /// other token.
628    fn content(&mut self) -> Node {
629        let start = self.pos;
630        while let Some(c) = self.peek() {
631            match c {
632                '\n' => break,
633                '\\' => match self.char_at(self.pos + ESCAPE_LEN) {
634                    // An `escape` token starts here.
635                    Some(g) if GLYPHS.contains(&g) => break,
636                    Some(other) => self.pos += ESCAPE_LEN + other.len_utf8(),
637                    // A `\` with nothing after it. Everything before it is
638                    // content; `step` reports the `\` itself next time round.
639                    None => break,
640                },
641                _ if GLYPHS.contains(&c) => break,
642                '/' if self.at(self.pos, "//") => break,
643                '/' if self.at(self.pos, "/*") && self.block_close(self.pos + 2).is_some() => break,
644                // A run of `[a-z0-9]` may end in an annotation. If it does, the
645                // annotation begins at the run's first *letter* — a digit
646                // cannot start one — and everything before that stays content.
647                _ if c.is_ascii_lowercase() || c.is_ascii_digit() => {
648                    let run = self.ident_run_end(self.pos);
649                    let anno = self
650                        .annotation_target(run)
651                        .and_then(|_| self.first_lowercase(self.pos, run));
652                    match anno {
653                        // `step` dispatches an annotation before it ever calls
654                        // `content`, so `anno == self.pos` only happens after
655                        // this loop has already consumed something.
656                        Some(anno) if anno > start => {
657                            self.pos = anno;
658                            break;
659                        }
660                        _ => self.pos = run,
661                    }
662                }
663                _ => self.pos += c.len_utf8(),
664            }
665        }
666        debug_assert!(self.pos > start, "content must make progress");
667        Node::Content(self.src[start..self.pos].into())
668    }
669
670    /// A token opening with `⟨`: the two placeholders, or one of Quilt's own
671    /// comments. Anything else is a stray glyph.
672    fn angle(&mut self, bracketed: bool) -> Step {
673        let start = self.pos;
674        if self.at(start, TYPE) {
675            self.pos = start + TYPE.len();
676            return Step::Node(Node::Type);
677        }
678        if self.at(start, NAME) {
679            self.pos = start + NAME.len();
680            return Step::Node(Node::Name);
681        }
682        if self.at(start, MACHINE) {
683            self.pos = start + MACHINE.len();
684            return Step::Node(Node::Machine {
685                anno: Box::default(),
686            });
687        }
688        // `⟨repr⟩↖`: a quote of the inherited language, in representation
689        // `repr` (`⟨str⟩↖…↗`).
690        if let Some(n) = crate::glyphs::repr_len(&self.src[start..]) {
691            self.pos = start + n + '↖'.len_utf8();
692            return Step::Open {
693                anno: self.src[start..start + n].into(),
694                quote: true,
695                open: start,
696            };
697        }
698        if self.at(start, Q_LINE) {
699            self.pos = start + Q_LINE.len();
700            self.pos = self.line_end(bracketed);
701            return Step::Skip;
702        }
703        if self.at(start, Q_BLOCK_OPEN) {
704            let Some(end) = self.q_block_close(start + Q_BLOCK_OPEN.len()) else {
705                self.pos = start + Q_BLOCK_OPEN.len();
706                return Step::Error("this `⟨/*⟩` comment is never closed");
707            };
708            self.pos = end;
709            return Step::Skip;
710        }
711        self.pos = start + '⟨'.len_utf8();
712        Step::Error("`⟨` only opens `⟨T⟩`, `⟨N⟩`, `⟨M⟩`, `⟨//⟩`, `⟨/*⟩` or a quote representation (`⟨str⟩↖`)")
713    }
714
715    /// A Quilt comment reached from the newline in front of it, which it takes
716    /// with it along with the indentation that follows — so deleting the
717    /// comment does not leave a blank line. Returns whether one was consumed;
718    /// on `false` nothing has moved.
719    fn comment_after_newline(&mut self, bracketed: bool) -> bool {
720        if self.pos < self.probe_failed_until {
721            return false;
722        }
723        let bytes = self.src.as_bytes();
724        let mut p = self.pos + 1;
725        // The grammar spells this `/\n\s*/`, and tree-sitter's `\s` is the six
726        // ASCII whitespace characters — `\u{a0}` and friends are not in it.
727        while bytes
728            .get(p)
729            .is_some_and(|b| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c))
730        {
731            p += 1;
732        }
733        if self.at(p, Q_LINE) {
734            self.pos = p + Q_LINE.len();
735            self.pos = self.line_end(bracketed);
736            return true;
737        }
738        if self.at(p, Q_BLOCK_OPEN) {
739            if let Some(end) = self.q_block_close(p + Q_BLOCK_OPEN.len()) {
740                self.pos = end;
741                return true;
742            }
743        }
744        self.probe_failed_until = p;
745        false
746    }
747
748    /// An object-language comment, `//` or `/* … */`, from `start` (its
749    /// delimiter, or where an interruption left it) and scanning on from
750    /// [`Self::pos`]. `None` if it would be empty, which only a continuation
751    /// can be.
752    ///
753    /// At ground level a comment is prose: it runs to its end, and every glyph
754    /// in it is text. Inside a bracket, the bracket's closer ends it (issue
755    /// #226), and an opener — `↙` or `↖`, annotation and all — interrupts it:
756    /// the comment stops in front, the bracket is parsed as usual, and the
757    /// comment resumes once that bracket closes. So a quoted `// built from
758    /// ↙x↘ today` takes a hole the way a `#` comment always has, while `↑`,
759    /// `↓` and `←` stay prose. `\↖`, `\↗`, `\↙` and `\↘` interrupt it the same way,
760    /// so an escaped arrow is still an escape.
761    fn comment(&mut self, kind: Plain, start: usize, bracketed: bool) -> Option<Node> {
762        let end = self.comment_end(kind, bracketed);
763        self.pos = end;
764        (end > start).then(|| {
765            let text = self.src[start..end].into();
766            match kind {
767                Plain::Line => Node::PlainLineComment(text),
768                Plain::Block => Node::PlainBlockComment(text),
769            }
770        })
771    }
772
773    /// Where the comment [`Self::comment`] is scanning ends, recording an
774    /// interruption for [`Self::step`] to resume after.
775    fn comment_end(&mut self, kind: Plain, bracketed: bool) -> usize {
776        const ARROWS: [char; 4] = ['↖', '↗', '↙', '↘'];
777        let mut p = self.pos;
778        while let Some(c) = self.char_at(p) {
779            match c {
780                '\n' if kind == Plain::Line => return p,
781                '*' if kind == Plain::Block && self.at(p, "*/") => return p + 2,
782                _ if !bracketed => {}
783                '↗' | '↘' => return p,
784                '↖' | '↙' => {
785                    self.paused.push((self.depth, kind));
786                    return p;
787                }
788                '\\' if self
789                    .char_at(p + ESCAPE_LEN)
790                    .is_some_and(|g| ARROWS.contains(&g)) =>
791                {
792                    self.escaped = Some(kind);
793                    return p;
794                }
795                // A run of `[a-z0-9]` may end in an annotated opener, which
796                // begins at the run's first letter (see [`Self::content`]).
797                _ if c.is_ascii_lowercase() || c.is_ascii_digit() => {
798                    let run = self.ident_run_end(p);
799                    if let Some(Annotated::Glyph('↖' | '↙')) = self.annotation_target(run) {
800                        self.paused.push((self.depth, kind));
801                        return self.first_lowercase(p, run).unwrap_or(run);
802                    }
803                    p = run;
804                    continue;
805                }
806                _ => {}
807            }
808            p += c.len_utf8();
809        }
810        p
811    }
812
813    /// Where a line comment that started at [`Self::pos`] ends: the next
814    /// newline, or — inside a bracket — the next closing arrow, whichever comes
815    /// first (issue #226).
816    fn line_end(&self, bracketed: bool) -> usize {
817        let rest = &self.src[self.pos..];
818        let end = rest
819            .find(|c: char| c == '\n' || (bracketed && (c == '↗' || c == '↘')))
820            .unwrap_or(rest.len());
821        self.pos + end
822    }
823
824    /// The end offset of the first `*/` at or after `from`.
825    fn block_close(&mut self, from: usize) -> Option<usize> {
826        if from >= self.no_block_close_from {
827            return None;
828        }
829        let Some(i) = self.src[from..].find("*/") else {
830            self.no_block_close_from = from;
831            return None;
832        };
833        Some(from + i + 2)
834    }
835
836    /// The end offset of the `⟨*/⟩` that closes a `⟨/*⟩` opened at `from`.
837    ///
838    /// **Not** the first `⟨*/⟩` substring after `from`. The grammar spells the
839    /// body as a repeat of "any char that is not `⟨`, or a `⟨` that is not the
840    /// start of the terminator", and those alternatives consume the character
841    /// *after* the `⟨` as well — so a `⟨` can swallow the `⟨` that would have
842    /// closed the comment. `⟨/*⟩⟨⟨*/⟩` is the smallest case: the body's `⟨⟨`
843    /// eats both, leaving `*/⟩`, and the comment is never closed. Scanning for
844    /// the substring calls that a comment; the grammar does not.
845    fn q_block_close(&mut self, from: usize) -> Option<usize> {
846        // Cheap, sound pre-filter: if the terminator does not occur at all,
847        // neither does an aligned one, and that settles every later `from` too
848        // — which is what keeps a long file of unterminated `⟨/*⟩` linear.
849        if from >= self.no_q_block_close_from {
850            return None;
851        }
852        if !self.src[from..].contains(Q_BLOCK_CLOSE) {
853            self.no_q_block_close_from = from;
854            return None;
855        }
856        let mut p = from;
857        while let Some(c) = self.char_at(p) {
858            if c != '⟨' {
859                p += c.len_utf8();
860                continue;
861            }
862            if self.at(p, Q_BLOCK_CLOSE) {
863                return Some(p + Q_BLOCK_CLOSE.len());
864            }
865            // Not the terminator, so the body matched one of `⟨[^*]`,
866            // `⟨\*[^/]`, `⟨\*/[^⟩]` — and each consumes the character that
867            // ruled the terminator out, not just the `⟨`. That trailing
868            // character is the whole subtlety: it can itself be the `⟨` of a
869            // real `⟨*/⟩`, which the body then eats.
870            p += c.len_utf8();
871            for expected in ['*', '/', '⟩'] {
872                // Input ran out mid-alternative: no body, so no comment.
873                let got = self.char_at(p)?;
874                p += got.len_utf8();
875                if got != expected {
876                    break;
877                }
878            }
879        }
880        None
881    }
882
883    /// The end of the maximal `[a-z0-9]` run starting at `from`.
884    fn ident_run_end(&self, from: usize) -> usize {
885        let bytes = self.src.as_bytes();
886        let mut p = from;
887        while bytes
888            .get(p)
889            .is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
890        {
891            p += 1;
892        }
893        p
894    }
895
896    /// What an annotation ending at `run` would be attached to, if anything.
897    fn annotation_target(&self, run: usize) -> Option<Annotated> {
898        match self.char_at(run) {
899            Some(g @ ('↖' | '↙' | '↓')) => Some(Annotated::Glyph(g)),
900            // `⟨M⟩` is the one annotated spelling wider than a single glyph, so
901            // it is matched as a string rather than by its first character —
902            // `sql⟨N⟩` is content, not an annotated name placeholder.
903            Some('⟨') if self.at(run, MACHINE) => Some(Annotated::Machine),
904            Some('⟨') => crate::glyphs::repr_len(&self.src[run..]).map(Annotated::Repr),
905            _ => None,
906        }
907    }
908
909    /// The first `[a-z]` in `src[from..to]`, where an annotation could start.
910    fn first_lowercase(&self, from: usize, to: usize) -> Option<usize> {
911        self.src.as_bytes()[from..to]
912            .iter()
913            .position(u8::is_ascii_lowercase)
914            .map(|i| from + i)
915    }
916
917    fn peek(&self) -> Option<char> {
918        self.src[self.pos..].chars().next()
919    }
920
921    fn char_at(&self, at: usize) -> Option<char> {
922        self.src.get(at..).and_then(|s| s.chars().next())
923    }
924
925    fn at(&self, at: usize, what: &str) -> bool {
926        self.src[at..].starts_with(what)
927    }
928}
929
930/// Where the next node goes: into the innermost open bracket, or into the
931/// top-level list.
932fn sink<'a>(stack: &'a mut [Frame], out: &'a mut Vec<Node>) -> &'a mut Vec<Node> {
933    match stack.last_mut() {
934        Some(frame) => &mut frame.nodes,
935        None => out,
936    }
937}
938
939/// The diagnostic for a bracket still open at end of input. It is reported
940/// against the *opener* rather than the end of the file: that is where the fix
941/// goes, and a zero-width span past the last byte renders with no caret at all.
942/// `tests/ui/unbalanced_bracket.rs.quilt` pins the rendering.
943const NEVER_CLOSED: &str = "this bracket is never closed";
944
945/// A diagnostic for malformed Quilt surface syntax, pointing at the offending
946/// span. Callers holding the source text (the CLI, the LSP) can attach it with
947/// [`miette::Report::with_source_code`] to render the snippet.
948fn error(span: Span, what: &str) -> miette::Report {
949    miette!(
950        labels = vec![LabeledSpan::at(span.clone(), what)],
951        help = "Quilt brackets must be balanced and nested: `↖…↗` quotes and \
952                `↙…↘` unquotes. A glyph meant as literal text needs a `\\` \
953                escape.",
954        "malformed Quilt syntax (source bytes {}..{})",
955        span.start,
956        span.end,
957    )
958}
959
960/**************************************************************/
961
962#[cfg(test)]
963mod tests {
964    use super::*;
965
966    /// One label, and it says what it should. `tests/ui/` snapshots the
967    /// rendering of the unclosed-bracket case; these pin the rest, which the
968    /// differential test deliberately does not compare (tree-sitter's error
969    /// recovery reports what its parse *states* justify — for `↖x↘` that is the
970    /// whole input — while the scanner reports the token it choked on).
971    #[test]
972    fn diagnostics_point_at_the_offending_token() {
973        for (src, span, label) in [
974            ("let x = ↖1 + 2;\n", 8..11, "this bracket is never closed"),
975            ("py↖", 0..5, "this bracket is never closed"),
976            ("aaaa↗bbbb", 4..7, "no `↖` is open here"),
977            ("↘", 0..3, "no `↙` is open here"),
978            (
979                "↖x↘",
980                4..7,
981                "expected `↗` here: the open bracket is a `↖` quote",
982            ),
983            (
984                "↙x↗",
985                4..7,
986                "expected `↘` here: the open bracket is a `↙` unquote",
987            ),
988            (
989                "⟨X⟩",
990                0..3,
991                "`⟨` only opens `⟨T⟩`, `⟨N⟩`, `⟨M⟩`, `⟨//⟩`, `⟨/*⟩` or a quote representation (`⟨str⟩↖`)",
992            ),
993            (
994                "⟩",
995                0..3,
996                "a bare `⟩` has no meaning; `\\⟩` writes one literally",
997            ),
998            ("a\\", 1..2, "a `\\` escape needs a character after it"),
999            ("⟨/*⟩ nope", 0..8, "this `⟨/*⟩` comment is never closed"),
1000        ] {
1001            let err = Node::parse(src).expect_err("should not parse");
1002            assert!(
1003                err.to_string().contains("malformed Quilt syntax"),
1004                "{src:?}: {err}"
1005            );
1006            let labels: Vec<_> = err.labels().into_iter().flatten().collect();
1007            assert_eq!(
1008                labels.len(),
1009                1,
1010                "{src:?}: expected one label, got {labels:?}"
1011            );
1012            assert_eq!(
1013                labels[0].offset()..labels[0].offset() + labels[0].len(),
1014                span,
1015                "{src:?}: wrong span"
1016            );
1017            assert_eq!(labels[0].label(), Some(label), "{src:?}: wrong label");
1018        }
1019    }
1020
1021    /// `⟨M⟩` is the one annotated spelling wider than a single glyph (#273),
1022    /// so the annotation scan cannot key on the character after the run the
1023    /// way it does for `↖`/`↙`/`↓`. The cases that go wrong if it does.
1024    #[test]
1025    fn the_machine_glyph_takes_the_same_annotation_as_the_arrows() {
1026        let m = |anno: &str| Node::Machine { anno: anno.into() };
1027        let c = |s: &str| Node::Content(s.into());
1028        for (src, want) in [
1029            ("⟨M⟩", vec![m("")]),
1030            ("sql⟨M⟩", vec![m("sql")]),
1031            // A digit inside the run is fine; a digit *starting* it is not an
1032            // annotation at all, so `42` stays content — the same rule that
1033            // keeps `x = 42↖…↗` a literal followed by a bare quote.
1034            ("lean4⟨M⟩", vec![m("lean4")]),
1035            ("42⟨M⟩", vec![c("42"), m("")]),
1036            ("x = 42⟨M⟩", vec![c("x = 42"), m("")]),
1037            // An annotation starts at the run's first *letter*, so a leading
1038            // digit splits the run rather than voiding it.
1039            ("1sql⟨M⟩", vec![c("1"), m("sql")]),
1040            ("a1sql⟨M⟩", vec![m("a1sql")]),
1041            ("x = sql⟨M⟩", vec![c("x = "), m("sql")]),
1042            // `⟨N⟩` and `⟨T⟩` take no annotation, so a run in front of one is
1043            // ordinary content — matching by the `⟨` alone would break this.
1044            ("sql⟨N⟩", vec![c("sql"), Node::Name]),
1045            ("sql⟨T⟩", vec![c("sql"), Node::Type]),
1046            // The escape is the existing `\⟨`/`\⟩` pair; nothing new is
1047            // reserved, and an escape never merges with its neighbours.
1048            (r"\⟨M\⟩", vec![c("⟨"), c("M"), c("⟩")]),
1049        ] {
1050            let got = Node::parse(src).unwrap_or_else(|e| panic!("{src:?}: {e}"));
1051            assert_eq!(&*got, &*want, "{src:?}");
1052            // And every one of them round-trips through the writer.
1053            assert_eq!(&*Node::coparse(&got), src, "{src:?} does not coparse back");
1054        }
1055    }
1056
1057    /// Nesting lives on a `Vec`, not the call stack, so *parsing* has no depth
1058    /// limit: 100k unclosed brackets is a diagnostic, where the tree-sitter
1059    /// path aborted the process well before that.
1060    ///
1061    /// The balanced case is capped lower on purpose. It builds the term, and a
1062    /// term that deep is a recursive value whose `Drop` recurses — nothing to
1063    /// do with the parser, and the reason this is `4_000` and not `100_000`. Even
1064    /// so it is twice what the tree-sitter path survived (`↖`×2000 with its
1065    /// closers overflowed the stack outright).
1066    #[test]
1067    fn deep_nesting_does_not_overflow() {
1068        assert!(Node::parse(&"↖".repeat(100_000)).is_err());
1069
1070        let balanced = format!("{}x{}", "↖".repeat(4_000), "↗".repeat(4_000));
1071        let nodes = Node::parse(&balanced).expect("balanced brackets, however deep");
1072        assert_eq!(nodes.len(), 1);
1073        assert_eq!(&*Node::coparse(&nodes), balanced);
1074    }
1075
1076    /// The scans that could go quadratic, at a size where quadratic would not
1077    /// finish: an unterminated `⟨/*⟩` or `/*` searches to end of input, and a
1078    /// `\n` before whitespace probes for a comment that is not there. Each is
1079    /// memoised on the offset that settled it, and each of these inputs is one
1080    /// where the memo is the only thing standing between linear and 10^10
1081    /// character steps.
1082    #[test]
1083    fn pathological_input_stays_linear() {
1084        for src in [
1085            "⟨/*⟩".repeat(50_000),
1086            "/*".repeat(50_000),
1087            "\n".repeat(200_000),
1088            "\n \t".repeat(100_000),
1089        ] {
1090            // The assertion is that this returns at all, in test-suite time.
1091            let _ = Node::parse(&src);
1092        }
1093    }
1094
1095    /// A `⟨/*⟩` comment ends at the first *aligned* `⟨*/⟩`, not the first one
1096    /// that occurs — the grammar's body alternatives consume the character
1097    /// after a `⟨`, which can be the `⟨` that would have closed the comment.
1098    /// Found by the sweep in `tests/parser_corpus.rs`, not by hand.
1099    #[test]
1100    fn a_block_comment_terminator_can_be_eaten() {
1101        // `⟨⟨` is one body item, so by the time the scan resumes the `⟨*/⟩`
1102        // that follows has become `*/⟩`, and nothing closes the comment.
1103        assert!(Node::parse("⟨/*⟩⟨⟨*/⟩").is_err());
1104        // The same eaten `⟨*/⟩`, but with a second one behind it: the comment
1105        // ends at the *last* occurrence here, not the first.
1106        assert_eq!(&*Node::parse("⟨/*⟩⟨⟨*/⟩⟨*/⟩").expect("closed"), &[]);
1107        // `⟨*/⟨` is the four-character alternative — `⟨\*/[^⟩]` — and it eats
1108        // the `⟨` that starts the real terminator just the same.
1109        assert!(Node::parse("⟨/*⟩⟨*/⟨*/⟩").is_err());
1110        assert_eq!(&*Node::parse("⟨/*⟩⟨*/⟨⟨*/⟩").expect("closed"), &[]);
1111    }
1112
1113    /// [`constructs`] answers "does expanding this do anything?", which is what
1114    /// decides whether the generated file needs a runtime import (issue #274).
1115    /// Text, newlines and *comments* — Quilt's own included, since one is
1116    /// deleted rather than translated into a call — are not constructs.
1117    #[test]
1118    fn constructs_sees_only_the_constructs() {
1119        assert!(!constructs("fn main() {}\n").any);
1120        assert!(!constructs("⟨//⟩ note\nfn main() {}\n").any);
1121        assert!(!constructs("⟨/*⟩ note ⟨*/⟩\n").any);
1122        assert!(!constructs("// ordinary ↖ in a comment is content\n").any);
1123        for src in ["↖1↗", "x.↑", "x.↓", "x.←", "⟨T⟩", "⟨N⟩", "py⟨M⟩"] {
1124            assert!(constructs(src).any, "{src:?} is a construct");
1125        }
1126    }
1127
1128    /// The annotations a source names are what a target-directed host builds
1129    /// its import list from, so they are collected in first-seen order, with
1130    /// duplicates and the un-annotated case (whose language comes from the
1131    /// file's chain instead) left out.
1132    #[test]
1133    fn constructs_collects_quote_annotations() {
1134        let annos = |src| {
1135            constructs(src)
1136                .annos
1137                .iter()
1138                .map(|a| a.to_string())
1139                .collect::<Vec<_>>()
1140        };
1141        assert_eq!(annos("let x = ↖1↗;"), Vec::<String>::new());
1142        assert_eq!(annos("let x = sql↖SELECT 1↗;"), vec!["sql"]);
1143        assert_eq!(
1144            annos("let a = html↖<p/>↗; let b = wgsl↖1u↗; let c = html↖<i/>↗;"),
1145            vec!["html", "wgsl"]
1146        );
1147    }
1148}