quiltlang 0.6.0

Quilt, a polyglot metaprogramming language: source code with arrow-bracket syntax for embedding and manipulating code fragments of other languages at code-generation time.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
//! Quilt's surface parser: hand-written, one pass, straight to [`Node`].
//!
//! Quilt's outer syntax is a *lexical* language — glyph-delimited brackets over
//! otherwise-opaque text — so the whole grammar is a scanner plus one rule for
//! nesting. Running a generalised parser over it (issue #254) meant building a
//! CST, walking it, and converting every node into the [`Node`] we actually
//! wanted, with the byte ranges recovered from the tree on the way past. This
//! module skips both the tree and the walk.
//!
//! ## Two ways in
//!
//! [`Node::parse`] is the strict one: the first diagnostic wins and nothing
//! comes back. [`scan`] is the recovering one — every token with its byte
//! range, every diagnostic, and no failure mode. `quilt-lsp` needs the second,
//! because an editor buffer is malformed most of the time someone is typing in
//! it, and blanking every region in the file between the `↖` and its `↗` would
//! make the server useless. Both drive the same `step`, so there is one
//! description of Quilt's syntax here and not two.
//!
//! ## The behaviours that are easy to get wrong
//!
//! All pinned by the unit tests below and by `tests/parser_corpus.rs`, whose
//! snapshots were taken while `tree-sitter-quilt` was still in the tree and
//! agreeing with this parser token for token:
//!
//! * **Longest-token-at-each-position.** `1a↓` is content `1` then a reduce
//!   annotated `a`, because the annotation regex `([a-z][a-z0-9]*)?↓` cannot
//!   start at the digit. `x = 42↖1↗` keeps `42` as content for the same reason.
//! * **`//` always wins over content**, wherever it appears — the grammar gives
//!   `plain_line_comment` a token precedence over the character class, so
//!   `https://example.com` really is content `https:` plus a comment.
//! * **Inside a bracket a line comment stops at `↗`/`↘`** (issue #226) while at
//!   ground level it runs to end of line, closing arrows and all.
//! * **Quilt's own comments vanish**, and the line form swallows a preceding
//!   `\n` plus indentation, so removing one leaves no blank line behind. They
//!   never merge the content on either side into one node.
//! * **An escape is its own node.** `a\↖b` is three `Content`s, not one.
//! * **An unterminated `/* … */` is not a comment at all**, it is content.
//! * **A `⟨/*⟩` comment ends at the first *aligned* `⟨*/⟩`**, not the first one
//!   that occurs — see [`Parser::q_block_close`].
//!
//! ## Depth
//!
//! Nesting is tracked on an explicit [`Vec`] rather than by recursing, so
//! parsing has no depth limit of its own: `↖`×`100_000` is a diagnostic, where
//! the tree-sitter path aborted the process. That is the contract
//! `fuzz/fuzz_targets/parse_quilt.rs` and `quilt check` rest on.
//!
//! What is left is not the parser's: a deeply nested [`Node`] is a deeply
//! nested *value*, and `Node`'s derived `Drop` recurses like any tree's. The
//! ceiling moved from ~`2_000` nested brackets to ~`8_000` rather than away, and
//! moving it further means an iterative `Drop` for `Node` — a change to the
//! type, not to this file.

use super::Node;
use crate::glyphs::{ESCAPE_LEN, GLYPHS, MACHINE};
use crate::prelude::*;
use miette::LabeledSpan;

/// Quilt's own line comment. Stripped from the output entirely, unlike
/// [`Node::PlainLineComment`], which passes through.
const Q_LINE: &str = "⟨//⟩";
/// Quilt's own block comment delimiters. Also stripped.
const Q_BLOCK_OPEN: &str = "⟨/*⟩";
const Q_BLOCK_CLOSE: &str = "⟨*/⟩";
/// An empty one. Because it is stripped, it is the only separator Quilt's
/// surface syntax has that leaves no text of its own behind — which is what
/// [`Node::coparse`] needs to keep two adjacent nodes from lexing as one
/// comment token (issue #256).
pub(super) const Q_BLOCK_EMPTY: &str = "⟨/*⟩⟨*/⟩";
/// The `⟨T⟩` type placeholder and `⟨N⟩` name placeholder.
pub(super) const TYPE: &str = "⟨T⟩";
pub(super) const NAME: &str = "⟨N⟩";

/// Parse Quilt source into a flat list of [`Node`]s. See [`Node::parse`].
pub(super) fn parse(src: &str) -> Result<Box<[Node]>> {
    Parser::new(src).run()
}

/// One token of Quilt surface syntax, with its byte range in the source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Token {
    /// Byte range in the scanned source.
    pub span: Span,
    pub kind: TokenKind,
}

/// What a [`Token`] is.
///
/// Deliberately coarser than [`Node`] in one place and finer in another. An
/// escape (`\↖`) is [`TokenKind::Content`], because to every consumer it is
/// bytes to copy. A Quilt comment is [`TokenKind::Comment`] and *has* a token,
/// where the `Node` tree drops it entirely — which is the whole reason
/// `quilt-lsp` needs [`scan`] rather than [`Node::parse`]: it has to know where
/// the comments were in order to translate their delimiters.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TokenKind {
    /// Ordinary text, including `\`-escapes.
    Content,
    NewLine,
    /// `anno↖`, annotation included.
    OpenQuote,
    /// `↗`. Also the token that closes a `↙` a `↗` was written for — a
    /// mismatched closer still closes, and the diagnostic says so.
    CloseQuote,
    /// `anno↙`, annotation included.
    OpenUnquote,
    /// `↘`.
    CloseUnquote,
    Lift,
    /// `anno↓`, annotation included.
    Reduce,
    Emit,
    Type,
    Name,
    /// `anno⟨M⟩`, annotation included.
    Machine,
    /// `// …`, which passes through to the output.
    PlainLineComment,
    /// `/* … */`, which passes through to the output.
    PlainBlockComment,
    /// `⟨//⟩ …` or `⟨/*⟩ … ⟨*/⟩` — Quilt's own, stripped from the output. The
    /// line form's span includes the newline and indentation in front of it,
    /// which is how deleting one leaves no blank line behind.
    Comment,
    /// Bytes the scanner could not make sense of. There is a matching entry in
    /// [`scan`]'s error list; this is here so the tokens still tile the source.
    Error,
}

impl TokenKind {
    /// Whether this token is a Quilt *construct* — a quote, unquote or operator
    /// glyph — rather than bytes that pass through: content, newlines, the
    /// comments (Quilt's own and the object language's), and whatever failed to
    /// scan.
    ///
    /// It answers "does expanding this source produce anything other than the
    /// source?", which is why both ends of the toolchain key off it: `quilt
    /// expand` injects a runtime import only into a file that has one (issue
    /// #274), and `quilt-lsp` emits its ground prologue only for a file that
    /// has one — so a construct-free `.rs.quilt` still projects to itself byte
    /// for byte.
    #[must_use]
    pub fn is_construct(self) -> bool {
        !matches!(
            self,
            TokenKind::Content
                | TokenKind::NewLine
                | TokenKind::PlainLineComment
                | TokenKind::PlainBlockComment
                | TokenKind::Comment
                | TokenKind::Error
        )
    }
}

/// A diagnostic from [`scan`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    pub span: Span,
    pub message: Box<str>,
}

/// Scan Quilt source into spanned tokens and diagnostics. Never fails.
///
/// The tokens **tile the source**: concatenating `&src[t.span]` in order
/// reproduces it exactly, with no gaps and no overlaps (`tokens_tile_the_source`
/// pins that). A consumer walking them therefore sees every byte, which is what
/// lets `quilt-lsp` build its projections by copying spans.
///
/// Recovery is: a bracket still open at end of input is reported and closed, a
/// closer that does not match the open bracket closes it anyway, and anything
/// else unparseable becomes a [`TokenKind::Error`] token and the scan carries
/// on. Errors come back in source order.
#[must_use]
pub fn scan(src: &str) -> (Vec<Token>, Vec<ParseError>) {
    let mut parser = Parser::new(src);
    let mut tokens: Vec<Token> = Vec::new();
    let mut errors: Vec<ParseError> = Vec::new();
    // (index of the opening token, is it a quote)
    let mut stack: Vec<(usize, bool)> = Vec::new();
    loop {
        let start = parser.pos;
        let step = parser.step(stack.last().map(|&(_, quote)| quote));
        let span = start..parser.pos;
        let kind = match step {
            Step::Done => break,
            Step::Skip => TokenKind::Comment,
            Step::Node(node) => token_kind(&node),
            Step::Open { quote, .. } => {
                stack.push((tokens.len(), quote));
                if quote {
                    TokenKind::OpenQuote
                } else {
                    TokenKind::OpenUnquote
                }
            }
            Step::Close { error, .. } => {
                let (_, quote) = stack.pop().expect("`step` only closes an open frame");
                if let Some(what) = error {
                    errors.push(ParseError {
                        span: span.clone(),
                        message: what.into(),
                    });
                }
                if quote {
                    TokenKind::CloseQuote
                } else {
                    TokenKind::CloseUnquote
                }
            }
            Step::Error(what) => {
                errors.push(ParseError {
                    span: span.clone(),
                    message: what.into(),
                });
                TokenKind::Error
            }
        };
        tokens.push(Token { span, kind });
    }
    for (open, _) in stack {
        errors.push(ParseError {
            span: tokens[open].span.clone(),
            message: NEVER_CLOSED.into(),
        });
    }
    errors.sort_by_key(|e| (e.span.start, e.span.end));
    (tokens, errors)
}

/// What a scan says about the Quilt *constructs* a source uses: whether it has
/// any at all, and which languages its quotes name (issue #274).
///
/// Both answers are needed before a line of the expansion exists — they decide
/// whether the generated file needs a runtime import and, for a host whose lift
/// spelling is target-directed, which names that import has to carry. A scan is
/// enough for it, and a scan is cheap and never fails.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Constructs {
    /// Whether any quote, unquote or operator glyph occurs — i.e. whether the
    /// expansion is anything other than the source itself.
    ///
    /// A Quilt *comment* does not count. `⟨//⟩` is deleted by the expander, not
    /// translated into a call, so a file whose only construct is one expands to
    /// plain source and needs nothing in scope.
    pub any: bool,
    /// Every language annotation a quote names, in first-seen order (`sql↖…↗` →
    /// `sql`). Un-annotated quotes contribute nothing: their language comes
    /// from the file's chain, which the caller already has.
    ///
    /// Deliberately an over-approximation of what an expansion lifts into — a
    /// language listed but never lifted into costs an unused import, while one
    /// missing costs a name that is not in scope.
    pub annos: Vec<Box<str>>,
}

/// Scan `src` for the constructs it uses. See [`Constructs`].
#[must_use]
pub fn constructs(src: &str) -> Constructs {
    let (tokens, _) = scan(src);
    let mut out = Constructs::default();
    for t in &tokens {
        if !t.kind.is_construct() {
            continue;
        }
        out.any = true;
        if t.kind == TokenKind::OpenQuote {
            // The span is `anno↖`, annotation included.
            let text = &src[t.span.clone()];
            let anno = crate::glyphs::split_anno(text.strip_suffix('↖').unwrap_or(text)).0;
            if !anno.is_empty() && !out.annos.iter().any(|a| &**a == anno) {
                out.annos.push(anno.into());
            }
        }
    }
    out
}

/// The [`TokenKind`] for a node the scanner just produced.
fn token_kind(node: &Node) -> TokenKind {
    match node {
        Node::Content(_) => TokenKind::Content,
        Node::NewLine => TokenKind::NewLine,
        Node::Lift => TokenKind::Lift,
        Node::Reduce { .. } => TokenKind::Reduce,
        Node::Emit => TokenKind::Emit,
        Node::Type => TokenKind::Type,
        Node::Name => TokenKind::Name,
        Node::Machine { .. } => TokenKind::Machine,
        Node::PlainLineComment(_) => TokenKind::PlainLineComment,
        Node::PlainBlockComment(_) => TokenKind::PlainBlockComment,
        // `step` never returns a bracket as a `Step::Node`; they arrive as
        // `Step::Open`/`Step::Close` and are handled there.
        Node::Quote { .. } => TokenKind::OpenQuote,
        Node::Unquote { .. } => TokenKind::OpenUnquote,
    }
}

/// What a language annotation is attached to. Almost always a single glyph;
/// `⟨M⟩` (issue #273) is the exception, which is why this is not a `char`.
#[derive(Clone, Copy)]
enum Annotated {
    /// `anno↖`, `anno↙` or `anno↓`.
    Glyph(char),
    /// `anno⟨M⟩`.
    Machine,
    /// `anno⟨repr⟩↖`: a quote with a representation; holds the length of
    /// the `⟨repr⟩`.
    Repr(usize),
}

/// One open `anno↖` / `anno↙` and the nodes collected inside it so far.
struct Frame {
    anno: Box<str>,
    /// Byte offset of the *whole* opener token, annotation included — which is
    /// where the "never closed" diagnostic points.
    open: usize,
    /// `true` for `↖…↗`, `false` for `↙…↘`.
    quote: bool,
    nodes: Vec<Node>,
}

impl Frame {
    /// The opener token's byte range: the annotation plus its glyph.
    fn opener(&self) -> Span {
        let glyph = if self.quote { '↖' } else { '↙' };
        self.open..self.open + self.anno.len() + glyph.len_utf8()
    }
}

/// What one turn of the scanner produced.
///
/// Every variant leaves [`Parser::pos`] past the token it consumed, including
/// [`Step::Error`] — which is what lets a caller that wants every diagnostic
/// (rather than just the first) carry on scanning. See [`scan`].
enum Step {
    /// End of input.
    Done,
    /// A token that leaves no node behind — one of Quilt's own comments.
    Skip,
    Node(Node),
    Open {
        anno: Box<str>,
        quote: bool,
        open: usize,
    },
    /// A closer for the frame on top of the stack; carries its end offset so
    /// the bracket's span can be sealed. `error` is set when the closer was the
    /// *wrong* one — the frame still closes, because leaving it open would
    /// report every bracket after it as broken too.
    Close {
        end: usize,
        error: Option<&'static str>,
    },
    /// Malformed syntax. The offending token is consumed; nothing is produced.
    Error(&'static str),
}

struct Parser<'a> {
    src: &'a str,
    pos: usize,
    /// Memo for [`Parser::comment_after_newline`]. A `\n…` probe's outcome
    /// depends only on where the whitespace run *ends*, so once one has failed
    /// every `\n` inside that run fails too. Without this, a file of blank
    /// lines is quadratic.
    probe_failed_until: usize,
    /// Memo: there is no `*/` at or after this offset. A failed search from `p`
    /// settles every `p' >= p`, which keeps `/*/*/*…` linear.
    no_block_close_from: usize,
    /// The same, for `⟨*/⟩`.
    no_q_block_close_from: usize,
    /// How many brackets are open: [`Step::Open`] and [`Step::Close`] keep it.
    depth: usize,
    /// Comments interrupted by a bracket, innermost last: the depth the
    /// bracket opened at, and the kind of comment to pick up again once it
    /// closes. See [`Parser::comment`].
    paused: Vec<(usize, Plain)>,
    /// A comment to continue at the next token: its bracket (or escape) just
    /// ended.
    resume: Option<Plain>,
    /// A comment an escaped arrow interrupted, to continue after the escape.
    escaped: Option<Plain>,
}

/// The two object-language comment forms Quilt lexes itself.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Plain {
    /// `// …`
    Line,
    /// `/* … */`
    Block,
}

impl<'a> Parser<'a> {
    fn new(src: &'a str) -> Self {
        Self {
            src,
            pos: 0,
            probe_failed_until: 0,
            no_block_close_from: usize::MAX,
            no_q_block_close_from: usize::MAX,
            depth: 0,
            paused: Vec::new(),
            resume: None,
            escaped: None,
        }
    }

    /// The strict parse behind [`Node::parse`]: the first diagnostic wins and
    /// nothing is returned. [`scan`] is the recovering half.
    fn run(mut self) -> Result<Box<[Node]>> {
        let mut stack: Vec<Frame> = Vec::new();
        let mut out: Vec<Node> = Vec::new();
        loop {
            let start = self.pos;
            match self.step(stack.last().map(|f| f.quote)) {
                Step::Done => {
                    // Anything still open at end of input is the error, and the
                    // *innermost* one is the most specific thing to point at.
                    return match stack.last() {
                        Some(frame) => Err(error(frame.opener(), NEVER_CLOSED)),
                        None => Ok(out.into()),
                    };
                }
                // The recovering half keeps going here (see [`scan`]); the
                // strict one stops at the first thing it cannot justify.
                Step::Error(what)
                | Step::Close {
                    error: Some(what), ..
                } => return Err(error(start..self.pos, what)),
                Step::Skip => {}
                Step::Node(node) => sink(&mut stack, &mut out).push(node),
                Step::Open { anno, quote, open } => stack.push(Frame {
                    anno,
                    open,
                    quote,
                    nodes: Vec::new(),
                }),
                Step::Close { end, error: None } => {
                    let frame = stack.pop().expect("`step` only closes an open frame");
                    let span = frame.open..end;
                    let nodes = frame.nodes.into_iter().map(arc).collect();
                    let anno = frame.anno;
                    let node = if frame.quote {
                        Node::Quote { anno, nodes, span }
                    } else {
                        Node::Unquote { anno, nodes, span }
                    };
                    sink(&mut stack, &mut out).push(node);
                }
            }
        }
    }

    /// Consume one token. `open` is the top frame's kind, or `None` at ground
    /// level — it decides both whether a closer is expected and how far a line
    /// comment may run (issue #226).
    fn step(&mut self, open: Option<bool>) -> Step {
        let step = self.token(open);
        match step {
            Step::Open { .. } => self.depth += 1,
            Step::Close { .. } => {
                self.depth -= 1;
                if self.paused.last().is_some_and(|&(d, _)| d == self.depth) {
                    self.resume = self.paused.pop().map(|(_, kind)| kind);
                }
            }
            _ => {}
        }
        step
    }

    /// [`Self::step`]'s scanner, without the bracket bookkeeping.
    fn token(&mut self, open: Option<bool>) -> Step {
        let start = self.pos;
        // The rest of a comment a bracket or an escape interrupted (see
        // [`Self::comment`]). A line comment that has reached its newline is
        // over; anything else picks up where it left off.
        if let Some(kind) = self.resume.take() {
            let more = match kind {
                Plain::Line => !matches!(self.peek(), None | Some('\n')),
                Plain::Block => self.peek().is_some(),
            };
            if more {
                if let Some(node) = self.comment(kind, start, open.is_some()) {
                    return Step::Node(node);
                }
            }
        }
        let Some(c) = self.peek() else {
            return Step::Done;
        };
        match c {
            // A Quilt comment may begin with the newline before it, taking the
            // line's indentation with it. Only if the whole token matches,
            // though — otherwise this is an ordinary line break.
            '\n' => {
                if self.comment_after_newline(open.is_some()) {
                    return Step::Skip;
                }
                self.pos += 1;
                Step::Node(Node::NewLine)
            }
            '⟨' => self.angle(open.is_some()),
            // A closer that does not match the open frame still closes it.
            // Leaving the frame open would report every bracket after it as
            // broken too, and one typo should be one diagnostic.
            '↗' | '↘' => {
                let quote = c == '↗';
                self.pos += c.len_utf8();
                match open {
                    Some(o) if o == quote => Step::Close {
                        end: self.pos,
                        error: None,
                    },
                    Some(_) if quote => Step::Close {
                        end: self.pos,
                        error: Some("expected `↘` here: the open bracket is a `↙` unquote"),
                    },
                    Some(_) => Step::Close {
                        end: self.pos,
                        error: Some("expected `↗` here: the open bracket is a `↖` quote"),
                    },
                    None if quote => Step::Error("no `↖` is open here"),
                    None => Step::Error("no `↙` is open here"),
                }
            }
            '↖' | '↙' => {
                self.pos += c.len_utf8();
                Step::Open {
                    anno: "".into(),
                    quote: c == '↖',
                    open: start,
                }
            }
            '↑' => {
                self.pos += c.len_utf8();
                Step::Node(Node::Lift)
            }
            '↓' => {
                self.pos += c.len_utf8();
                Step::Node(Node::Reduce { anno: "".into() })
            }
            '←' => {
                self.pos += c.len_utf8();
                Step::Node(Node::Emit)
            }
            '⟩' => {
                self.pos += c.len_utf8();
                Step::Error("a bare `⟩` has no meaning; `\\⟩` writes one literally")
            }
            // `\` + glyph is an escape and becomes content holding the bare
            // glyph. `\` + anything else is ordinary content (the grammar's
            // `_non_escape`), and a `\` with nothing after it is an error.
            '\\' => match self.char_at(start + ESCAPE_LEN) {
                Some(g) if GLYPHS.contains(&g) => {
                    self.pos = start + ESCAPE_LEN + g.len_utf8();
                    // An escape that cut a comment short hands it back.
                    self.resume = self.escaped.take();
                    Step::Node(Node::Content(self.src[start + ESCAPE_LEN..self.pos].into()))
                }
                Some(_) => Step::Node(self.content()),
                None => {
                    self.pos += ESCAPE_LEN;
                    Step::Error("a `\\` escape needs a character after it")
                }
            },
            '/' if self.at(start, "//") => {
                self.pos = start + 2;
                let node = self.comment(Plain::Line, start, open.is_some());
                Step::Node(node.expect("a comment holds at least its `//`"))
            }
            '/' if self.at(start, "/*") => match self.block_close(start + 2) {
                Some(_) => {
                    self.pos = start + 2;
                    let node = self.comment(Plain::Block, start, open.is_some());
                    Step::Node(node.expect("a comment holds at least its `/*`"))
                }
                // An unterminated `/*` is not a comment token at all, so it is
                // plain content — matching the grammar, where the token simply
                // fails to match and the character class picks the `/` up.
                None => Step::Node(self.content()),
            },
            // An annotated opener or reduce: `[a-z][a-z0-9]*` immediately
            // followed by `↖`, `↙` or `↓`.
            c if c.is_ascii_lowercase() => {
                let run = self.ident_run_end(start);
                match self.annotation_target(run) {
                    Some(Annotated::Machine) => {
                        let anno: Box<str> = self.src[start..run].into();
                        self.pos = run + MACHINE.len();
                        Step::Node(Node::Machine { anno })
                    }
                    Some(Annotated::Repr(n)) => {
                        let anno: Box<str> = self.src[start..run + n].into();
                        self.pos = run + n + '↖'.len_utf8();
                        Step::Open {
                            anno,
                            quote: true,
                            open: start,
                        }
                    }
                    Some(Annotated::Glyph(g)) => {
                        let anno: Box<str> = self.src[start..run].into();
                        self.pos = run + g.len_utf8();
                        match g {
                            '↓' => Step::Node(Node::Reduce { anno }),
                            _ => Step::Open {
                                anno,
                                quote: g == '↖',
                                open: start,
                            },
                        }
                    }
                    None => Step::Node(self.content()),
                }
            }
            _ => Step::Node(self.content()),
        }
    }

    /// A run of ordinary characters, ending where any other token could begin.
    ///
    /// Always consumes at least one character: every caller has already
    /// established that the character at [`Self::pos`] is not the start of some
    /// other token.
    fn content(&mut self) -> Node {
        let start = self.pos;
        while let Some(c) = self.peek() {
            match c {
                '\n' => break,
                '\\' => match self.char_at(self.pos + ESCAPE_LEN) {
                    // An `escape` token starts here.
                    Some(g) if GLYPHS.contains(&g) => break,
                    Some(other) => self.pos += ESCAPE_LEN + other.len_utf8(),
                    // A `\` with nothing after it. Everything before it is
                    // content; `step` reports the `\` itself next time round.
                    None => break,
                },
                _ if GLYPHS.contains(&c) => break,
                '/' if self.at(self.pos, "//") => break,
                '/' if self.at(self.pos, "/*") && self.block_close(self.pos + 2).is_some() => break,
                // A run of `[a-z0-9]` may end in an annotation. If it does, the
                // annotation begins at the run's first *letter* — a digit
                // cannot start one — and everything before that stays content.
                _ if c.is_ascii_lowercase() || c.is_ascii_digit() => {
                    let run = self.ident_run_end(self.pos);
                    let anno = self
                        .annotation_target(run)
                        .and_then(|_| self.first_lowercase(self.pos, run));
                    match anno {
                        // `step` dispatches an annotation before it ever calls
                        // `content`, so `anno == self.pos` only happens after
                        // this loop has already consumed something.
                        Some(anno) if anno > start => {
                            self.pos = anno;
                            break;
                        }
                        _ => self.pos = run,
                    }
                }
                _ => self.pos += c.len_utf8(),
            }
        }
        debug_assert!(self.pos > start, "content must make progress");
        Node::Content(self.src[start..self.pos].into())
    }

    /// A token opening with `⟨`: the two placeholders, or one of Quilt's own
    /// comments. Anything else is a stray glyph.
    fn angle(&mut self, bracketed: bool) -> Step {
        let start = self.pos;
        if self.at(start, TYPE) {
            self.pos = start + TYPE.len();
            return Step::Node(Node::Type);
        }
        if self.at(start, NAME) {
            self.pos = start + NAME.len();
            return Step::Node(Node::Name);
        }
        if self.at(start, MACHINE) {
            self.pos = start + MACHINE.len();
            return Step::Node(Node::Machine {
                anno: Box::default(),
            });
        }
        // `⟨repr⟩↖`: a quote of the inherited language, in representation
        // `repr` (`⟨str⟩↖…↗`).
        if let Some(n) = crate::glyphs::repr_len(&self.src[start..]) {
            self.pos = start + n + '↖'.len_utf8();
            return Step::Open {
                anno: self.src[start..start + n].into(),
                quote: true,
                open: start,
            };
        }
        if self.at(start, Q_LINE) {
            self.pos = start + Q_LINE.len();
            self.pos = self.line_end(bracketed);
            return Step::Skip;
        }
        if self.at(start, Q_BLOCK_OPEN) {
            let Some(end) = self.q_block_close(start + Q_BLOCK_OPEN.len()) else {
                self.pos = start + Q_BLOCK_OPEN.len();
                return Step::Error("this `⟨/*⟩` comment is never closed");
            };
            self.pos = end;
            return Step::Skip;
        }
        self.pos = start + '⟨'.len_utf8();
        Step::Error("`⟨` only opens `⟨T⟩`, `⟨N⟩`, `⟨M⟩`, `⟨//⟩`, `⟨/*⟩` or a quote representation (`⟨str⟩↖`)")
    }

    /// A Quilt comment reached from the newline in front of it, which it takes
    /// with it along with the indentation that follows — so deleting the
    /// comment does not leave a blank line. Returns whether one was consumed;
    /// on `false` nothing has moved.
    fn comment_after_newline(&mut self, bracketed: bool) -> bool {
        if self.pos < self.probe_failed_until {
            return false;
        }
        let bytes = self.src.as_bytes();
        let mut p = self.pos + 1;
        // The grammar spells this `/\n\s*/`, and tree-sitter's `\s` is the six
        // ASCII whitespace characters — `\u{a0}` and friends are not in it.
        while bytes
            .get(p)
            .is_some_and(|b| matches!(b, b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c))
        {
            p += 1;
        }
        if self.at(p, Q_LINE) {
            self.pos = p + Q_LINE.len();
            self.pos = self.line_end(bracketed);
            return true;
        }
        if self.at(p, Q_BLOCK_OPEN) {
            if let Some(end) = self.q_block_close(p + Q_BLOCK_OPEN.len()) {
                self.pos = end;
                return true;
            }
        }
        self.probe_failed_until = p;
        false
    }

    /// An object-language comment, `//` or `/* … */`, from `start` (its
    /// delimiter, or where an interruption left it) and scanning on from
    /// [`Self::pos`]. `None` if it would be empty, which only a continuation
    /// can be.
    ///
    /// At ground level a comment is prose: it runs to its end, and every glyph
    /// in it is text. Inside a bracket, the bracket's closer ends it (issue
    /// #226), and an opener — `↙` or `↖`, annotation and all — interrupts it:
    /// the comment stops in front, the bracket is parsed as usual, and the
    /// comment resumes once that bracket closes. So a quoted `// built from
    /// ↙x↘ today` takes a hole the way a `#` comment always has, while `↑`,
    /// `↓` and `←` stay prose. `\↖`, `\↗`, `\↙` and `\↘` interrupt it the same way,
    /// so an escaped arrow is still an escape.
    fn comment(&mut self, kind: Plain, start: usize, bracketed: bool) -> Option<Node> {
        let end = self.comment_end(kind, bracketed);
        self.pos = end;
        (end > start).then(|| {
            let text = self.src[start..end].into();
            match kind {
                Plain::Line => Node::PlainLineComment(text),
                Plain::Block => Node::PlainBlockComment(text),
            }
        })
    }

    /// Where the comment [`Self::comment`] is scanning ends, recording an
    /// interruption for [`Self::step`] to resume after.
    fn comment_end(&mut self, kind: Plain, bracketed: bool) -> usize {
        const ARROWS: [char; 4] = ['↖', '↗', '↙', '↘'];
        let mut p = self.pos;
        while let Some(c) = self.char_at(p) {
            match c {
                '\n' if kind == Plain::Line => return p,
                '*' if kind == Plain::Block && self.at(p, "*/") => return p + 2,
                _ if !bracketed => {}
                '↗' | '↘' => return p,
                '↖' | '↙' => {
                    self.paused.push((self.depth, kind));
                    return p;
                }
                '\\' if self
                    .char_at(p + ESCAPE_LEN)
                    .is_some_and(|g| ARROWS.contains(&g)) =>
                {
                    self.escaped = Some(kind);
                    return p;
                }
                // A run of `[a-z0-9]` may end in an annotated opener, which
                // begins at the run's first letter (see [`Self::content`]).
                _ if c.is_ascii_lowercase() || c.is_ascii_digit() => {
                    let run = self.ident_run_end(p);
                    if let Some(Annotated::Glyph('↖' | '↙')) = self.annotation_target(run) {
                        self.paused.push((self.depth, kind));
                        return self.first_lowercase(p, run).unwrap_or(run);
                    }
                    p = run;
                    continue;
                }
                _ => {}
            }
            p += c.len_utf8();
        }
        p
    }

    /// Where a line comment that started at [`Self::pos`] ends: the next
    /// newline, or — inside a bracket — the next closing arrow, whichever comes
    /// first (issue #226).
    fn line_end(&self, bracketed: bool) -> usize {
        let rest = &self.src[self.pos..];
        let end = rest
            .find(|c: char| c == '\n' || (bracketed && (c == '↗' || c == '↘')))
            .unwrap_or(rest.len());
        self.pos + end
    }

    /// The end offset of the first `*/` at or after `from`.
    fn block_close(&mut self, from: usize) -> Option<usize> {
        if from >= self.no_block_close_from {
            return None;
        }
        let Some(i) = self.src[from..].find("*/") else {
            self.no_block_close_from = from;
            return None;
        };
        Some(from + i + 2)
    }

    /// The end offset of the `⟨*/⟩` that closes a `⟨/*⟩` opened at `from`.
    ///
    /// **Not** the first `⟨*/⟩` substring after `from`. The grammar spells the
    /// body as a repeat of "any char that is not `⟨`, or a `⟨` that is not the
    /// start of the terminator", and those alternatives consume the character
    /// *after* the `⟨` as well — so a `⟨` can swallow the `⟨` that would have
    /// closed the comment. `⟨/*⟩⟨⟨*/⟩` is the smallest case: the body's `⟨⟨`
    /// eats both, leaving `*/⟩`, and the comment is never closed. Scanning for
    /// the substring calls that a comment; the grammar does not.
    fn q_block_close(&mut self, from: usize) -> Option<usize> {
        // Cheap, sound pre-filter: if the terminator does not occur at all,
        // neither does an aligned one, and that settles every later `from` too
        // — which is what keeps a long file of unterminated `⟨/*⟩` linear.
        if from >= self.no_q_block_close_from {
            return None;
        }
        if !self.src[from..].contains(Q_BLOCK_CLOSE) {
            self.no_q_block_close_from = from;
            return None;
        }
        let mut p = from;
        while let Some(c) = self.char_at(p) {
            if c != '⟨' {
                p += c.len_utf8();
                continue;
            }
            if self.at(p, Q_BLOCK_CLOSE) {
                return Some(p + Q_BLOCK_CLOSE.len());
            }
            // Not the terminator, so the body matched one of `⟨[^*]`,
            // `⟨\*[^/]`, `⟨\*/[^⟩]` — and each consumes the character that
            // ruled the terminator out, not just the `⟨`. That trailing
            // character is the whole subtlety: it can itself be the `⟨` of a
            // real `⟨*/⟩`, which the body then eats.
            p += c.len_utf8();
            for expected in ['*', '/', '⟩'] {
                // Input ran out mid-alternative: no body, so no comment.
                let got = self.char_at(p)?;
                p += got.len_utf8();
                if got != expected {
                    break;
                }
            }
        }
        None
    }

    /// The end of the maximal `[a-z0-9]` run starting at `from`.
    fn ident_run_end(&self, from: usize) -> usize {
        let bytes = self.src.as_bytes();
        let mut p = from;
        while bytes
            .get(p)
            .is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
        {
            p += 1;
        }
        p
    }

    /// What an annotation ending at `run` would be attached to, if anything.
    fn annotation_target(&self, run: usize) -> Option<Annotated> {
        match self.char_at(run) {
            Some(g @ ('↖' | '↙' | '↓')) => Some(Annotated::Glyph(g)),
            // `⟨M⟩` is the one annotated spelling wider than a single glyph, so
            // it is matched as a string rather than by its first character —
            // `sql⟨N⟩` is content, not an annotated name placeholder.
            Some('⟨') if self.at(run, MACHINE) => Some(Annotated::Machine),
            Some('⟨') => crate::glyphs::repr_len(&self.src[run..]).map(Annotated::Repr),
            _ => None,
        }
    }

    /// The first `[a-z]` in `src[from..to]`, where an annotation could start.
    fn first_lowercase(&self, from: usize, to: usize) -> Option<usize> {
        self.src.as_bytes()[from..to]
            .iter()
            .position(u8::is_ascii_lowercase)
            .map(|i| from + i)
    }

    fn peek(&self) -> Option<char> {
        self.src[self.pos..].chars().next()
    }

    fn char_at(&self, at: usize) -> Option<char> {
        self.src.get(at..).and_then(|s| s.chars().next())
    }

    fn at(&self, at: usize, what: &str) -> bool {
        self.src[at..].starts_with(what)
    }
}

/// Where the next node goes: into the innermost open bracket, or into the
/// top-level list.
fn sink<'a>(stack: &'a mut [Frame], out: &'a mut Vec<Node>) -> &'a mut Vec<Node> {
    match stack.last_mut() {
        Some(frame) => &mut frame.nodes,
        None => out,
    }
}

/// The diagnostic for a bracket still open at end of input. It is reported
/// against the *opener* rather than the end of the file: that is where the fix
/// goes, and a zero-width span past the last byte renders with no caret at all.
/// `tests/ui/unbalanced_bracket.rs.quilt` pins the rendering.
const NEVER_CLOSED: &str = "this bracket is never closed";

/// A diagnostic for malformed Quilt surface syntax, pointing at the offending
/// span. Callers holding the source text (the CLI, the LSP) can attach it with
/// [`miette::Report::with_source_code`] to render the snippet.
fn error(span: Span, what: &str) -> miette::Report {
    miette!(
        labels = vec![LabeledSpan::at(span.clone(), what)],
        help = "Quilt brackets must be balanced and nested: `↖…↗` quotes and \
                `↙…↘` unquotes. A glyph meant as literal text needs a `\\` \
                escape.",
        "malformed Quilt syntax (source bytes {}..{})",
        span.start,
        span.end,
    )
}

/**************************************************************/

#[cfg(test)]
mod tests {
    use super::*;

    /// One label, and it says what it should. `tests/ui/` snapshots the
    /// rendering of the unclosed-bracket case; these pin the rest, which the
    /// differential test deliberately does not compare (tree-sitter's error
    /// recovery reports what its parse *states* justify — for `↖x↘` that is the
    /// whole input — while the scanner reports the token it choked on).
    #[test]
    fn diagnostics_point_at_the_offending_token() {
        for (src, span, label) in [
            ("let x = ↖1 + 2;\n", 8..11, "this bracket is never closed"),
            ("py↖", 0..5, "this bracket is never closed"),
            ("aaaa↗bbbb", 4..7, "no `↖` is open here"),
            ("↘", 0..3, "no `↙` is open here"),
            (
                "↖x↘",
                4..7,
                "expected `↗` here: the open bracket is a `↖` quote",
            ),
            (
                "↙x↗",
                4..7,
                "expected `↘` here: the open bracket is a `↙` unquote",
            ),
            (
                "⟨X⟩",
                0..3,
                "`⟨` only opens `⟨T⟩`, `⟨N⟩`, `⟨M⟩`, `⟨//⟩`, `⟨/*⟩` or a quote representation (`⟨str⟩↖`)",
            ),
            (
                "⟩",
                0..3,
                "a bare `⟩` has no meaning; `\\⟩` writes one literally",
            ),
            ("a\\", 1..2, "a `\\` escape needs a character after it"),
            ("⟨/*⟩ nope", 0..8, "this `⟨/*⟩` comment is never closed"),
        ] {
            let err = Node::parse(src).expect_err("should not parse");
            assert!(
                err.to_string().contains("malformed Quilt syntax"),
                "{src:?}: {err}"
            );
            let labels: Vec<_> = err.labels().into_iter().flatten().collect();
            assert_eq!(
                labels.len(),
                1,
                "{src:?}: expected one label, got {labels:?}"
            );
            assert_eq!(
                labels[0].offset()..labels[0].offset() + labels[0].len(),
                span,
                "{src:?}: wrong span"
            );
            assert_eq!(labels[0].label(), Some(label), "{src:?}: wrong label");
        }
    }

    /// `⟨M⟩` is the one annotated spelling wider than a single glyph (#273),
    /// so the annotation scan cannot key on the character after the run the
    /// way it does for `↖`/`↙`/`↓`. The cases that go wrong if it does.
    #[test]
    fn the_machine_glyph_takes_the_same_annotation_as_the_arrows() {
        let m = |anno: &str| Node::Machine { anno: anno.into() };
        let c = |s: &str| Node::Content(s.into());
        for (src, want) in [
            ("⟨M⟩", vec![m("")]),
            ("sql⟨M⟩", vec![m("sql")]),
            // A digit inside the run is fine; a digit *starting* it is not an
            // annotation at all, so `42` stays content — the same rule that
            // keeps `x = 42↖…↗` a literal followed by a bare quote.
            ("lean4⟨M⟩", vec![m("lean4")]),
            ("42⟨M⟩", vec![c("42"), m("")]),
            ("x = 42⟨M⟩", vec![c("x = 42"), m("")]),
            // An annotation starts at the run's first *letter*, so a leading
            // digit splits the run rather than voiding it.
            ("1sql⟨M⟩", vec![c("1"), m("sql")]),
            ("a1sql⟨M⟩", vec![m("a1sql")]),
            ("x = sql⟨M⟩", vec![c("x = "), m("sql")]),
            // `⟨N⟩` and `⟨T⟩` take no annotation, so a run in front of one is
            // ordinary content — matching by the `⟨` alone would break this.
            ("sql⟨N⟩", vec![c("sql"), Node::Name]),
            ("sql⟨T⟩", vec![c("sql"), Node::Type]),
            // The escape is the existing `\⟨`/`\⟩` pair; nothing new is
            // reserved, and an escape never merges with its neighbours.
            (r"\⟨M\⟩", vec![c("⟨"), c("M"), c("⟩")]),
        ] {
            let got = Node::parse(src).unwrap_or_else(|e| panic!("{src:?}: {e}"));
            assert_eq!(&*got, &*want, "{src:?}");
            // And every one of them round-trips through the writer.
            assert_eq!(&*Node::coparse(&got), src, "{src:?} does not coparse back");
        }
    }

    /// Nesting lives on a `Vec`, not the call stack, so *parsing* has no depth
    /// limit: 100k unclosed brackets is a diagnostic, where the tree-sitter
    /// path aborted the process well before that.
    ///
    /// The balanced case is capped lower on purpose. It builds the term, and a
    /// term that deep is a recursive value whose `Drop` recurses — nothing to
    /// do with the parser, and the reason this is `4_000` and not `100_000`. Even
    /// so it is twice what the tree-sitter path survived (`↖`×2000 with its
    /// closers overflowed the stack outright).
    #[test]
    fn deep_nesting_does_not_overflow() {
        assert!(Node::parse(&"↖".repeat(100_000)).is_err());

        let balanced = format!("{}x{}", "↖".repeat(4_000), "↗".repeat(4_000));
        let nodes = Node::parse(&balanced).expect("balanced brackets, however deep");
        assert_eq!(nodes.len(), 1);
        assert_eq!(&*Node::coparse(&nodes), balanced);
    }

    /// The scans that could go quadratic, at a size where quadratic would not
    /// finish: an unterminated `⟨/*⟩` or `/*` searches to end of input, and a
    /// `\n` before whitespace probes for a comment that is not there. Each is
    /// memoised on the offset that settled it, and each of these inputs is one
    /// where the memo is the only thing standing between linear and 10^10
    /// character steps.
    #[test]
    fn pathological_input_stays_linear() {
        for src in [
            "⟨/*⟩".repeat(50_000),
            "/*".repeat(50_000),
            "\n".repeat(200_000),
            "\n \t".repeat(100_000),
        ] {
            // The assertion is that this returns at all, in test-suite time.
            let _ = Node::parse(&src);
        }
    }

    /// A `⟨/*⟩` comment ends at the first *aligned* `⟨*/⟩`, not the first one
    /// that occurs — the grammar's body alternatives consume the character
    /// after a `⟨`, which can be the `⟨` that would have closed the comment.
    /// Found by the sweep in `tests/parser_corpus.rs`, not by hand.
    #[test]
    fn a_block_comment_terminator_can_be_eaten() {
        // `⟨⟨` is one body item, so by the time the scan resumes the `⟨*/⟩`
        // that follows has become `*/⟩`, and nothing closes the comment.
        assert!(Node::parse("⟨/*⟩⟨⟨*/⟩").is_err());
        // The same eaten `⟨*/⟩`, but with a second one behind it: the comment
        // ends at the *last* occurrence here, not the first.
        assert_eq!(&*Node::parse("⟨/*⟩⟨⟨*/⟩⟨*/⟩").expect("closed"), &[]);
        // `⟨*/⟨` is the four-character alternative — `⟨\*/[^⟩]` — and it eats
        // the `⟨` that starts the real terminator just the same.
        assert!(Node::parse("⟨/*⟩⟨*/⟨*/⟩").is_err());
        assert_eq!(&*Node::parse("⟨/*⟩⟨*/⟨⟨*/⟩").expect("closed"), &[]);
    }

    /// [`constructs`] answers "does expanding this do anything?", which is what
    /// decides whether the generated file needs a runtime import (issue #274).
    /// Text, newlines and *comments* — Quilt's own included, since one is
    /// deleted rather than translated into a call — are not constructs.
    #[test]
    fn constructs_sees_only_the_constructs() {
        assert!(!constructs("fn main() {}\n").any);
        assert!(!constructs("⟨//⟩ note\nfn main() {}\n").any);
        assert!(!constructs("⟨/*⟩ note ⟨*/⟩\n").any);
        assert!(!constructs("// ordinary ↖ in a comment is content\n").any);
        for src in ["↖1↗", "x.↑", "x.↓", "x.←", "⟨T⟩", "⟨N⟩", "py⟨M⟩"] {
            assert!(constructs(src).any, "{src:?} is a construct");
        }
    }

    /// The annotations a source names are what a target-directed host builds
    /// its import list from, so they are collected in first-seen order, with
    /// duplicates and the un-annotated case (whose language comes from the
    /// file's chain instead) left out.
    #[test]
    fn constructs_collects_quote_annotations() {
        let annos = |src| {
            constructs(src)
                .annos
                .iter()
                .map(|a| a.to_string())
                .collect::<Vec<_>>()
        };
        assert_eq!(annos("let x = ↖1↗;"), Vec::<String>::new());
        assert_eq!(annos("let x = sql↖SELECT 1↗;"), vec!["sql"]);
        assert_eq!(
            annos("let a = html↖<p/>↗; let b = wgsl↖1u↗; let c = html↖<i/>↗;"),
            vec!["html", "wgsl"]
        );
    }
}