drawlang-syntax 0.1.2

Lexer, parser, lossless syntax tree, and formatter for the drawlang DSL
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
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
//! Recursive-descent parser with error recovery: a malformed statement is
//! reported and skipped, and parsing continues, so one pass reports every
//! error in the file.

use crate::ast::*;
use crate::diag::Diagnostic;
use crate::lexer::{Token, TokenKind};
use crate::span::Span;

pub struct ParseOutput {
    pub file: File,
    pub diagnostics: Vec<Diagnostic>,
}

pub fn parse(src: &str, tokens: Vec<Token>) -> ParseOutput {
    let mut p = Parser {
        src,
        tokens,
        pos: 0,
        diags: Vec::new(),
    };
    let file = p.parse_file();
    ParseOutput {
        file,
        diagnostics: p.diags,
    }
}

const STMT_KEYWORDS: &[&str] = &[
    "canvas",
    "def",
    "group",
    "class",
    "constrain",
    "pin",
    "for",
    "port",
];

struct Parser<'a> {
    src: &'a str,
    tokens: Vec<Token>,
    pos: usize,
    diags: Vec<Diagnostic>,
}

/// Internal error marker; the diagnostic is already pushed when this is raised.
struct Bail;
type PResult<T> = Result<T, Bail>;

impl<'a> Parser<'a> {
    // ------------------------------------------------------------- cursors

    fn peek(&self) -> &TokenKind {
        &self.tokens[self.pos].kind
    }

    fn peek_at(&self, ahead: usize) -> &TokenKind {
        let idx = (self.pos + ahead).min(self.tokens.len() - 1);
        &self.tokens[idx].kind
    }

    fn span(&self) -> Span {
        self.tokens[self.pos].span
    }

    fn prev_span(&self) -> Span {
        self.tokens[self.pos.saturating_sub(1)].span
    }

    fn bump(&mut self) -> Token {
        let t = self.tokens[self.pos].clone();
        if self.pos < self.tokens.len() - 1 {
            self.pos += 1;
        }
        t
    }

    fn at_eof(&self) -> bool {
        matches!(self.peek(), TokenKind::Eof)
    }

    fn eat(&mut self, kind: &TokenKind) -> bool {
        if self.peek() == kind {
            self.bump();
            true
        } else {
            false
        }
    }

    /// Skip newlines and comments without recording them (used inside
    /// parenthesized lists where trivia placement doesn't matter).
    fn skip_trivia(&mut self) {
        while matches!(self.peek(), TokenKind::Newline | TokenKind::Comment(_)) {
            self.bump();
        }
    }

    fn expect(&mut self, kind: TokenKind, ctx: &str) -> PResult<Token> {
        if self.peek() == &kind {
            return Ok(self.bump());
        }
        let found = self.peek().describe();
        self.diags.push(
            Diagnostic::error(
                "E0103",
                format!("expected {} {ctx}, found {found}", kind.describe()),
            )
            .with_label(self.span(), format!("expected {} here", kind.describe())),
        );
        Err(Bail)
    }

    fn expect_ident(&mut self, ctx: &str) -> PResult<Ident> {
        if let TokenKind::Ident(name) = self.peek() {
            let name = name.clone();
            let t = self.bump();
            return Ok(Ident { name, span: t.span });
        }
        let found = self.peek().describe();
        self.diags.push(
            Diagnostic::error("E0103", format!("expected a name {ctx}, found {found}"))
                .with_label(self.span(), "expected an identifier here"),
        );
        Err(Bail)
    }

    /// Is the current token an identifier with this exact text?
    fn at_kw(&self, kw: &str) -> bool {
        matches!(self.peek(), TokenKind::Ident(n) if n == kw)
    }

    /// After a failed statement: skip to the next plausible statement start —
    /// past the end of the current line, consuming balanced braces so we
    /// don't resynchronize in the middle of a block we were inside.
    fn recover(&mut self) {
        let mut depth = 0usize;
        loop {
            match self.peek() {
                TokenKind::Eof => return,
                TokenKind::LBrace => {
                    depth += 1;
                    self.bump();
                }
                TokenKind::RBrace => {
                    if depth == 0 {
                        return; // let the enclosing block see it
                    }
                    depth -= 1;
                    self.bump();
                }
                TokenKind::Newline | TokenKind::Semi if depth == 0 => {
                    self.bump();
                    return;
                }
                _ => {
                    self.bump();
                }
            }
        }
    }

    // ---------------------------------------------------------------- file

    fn parse_file(&mut self) -> File {
        let header = self.parse_header();
        let stmts = self.parse_stmt_list(true);
        File { header, stmts }
    }

    fn parse_header(&mut self) -> Option<Header> {
        self.skip_trivia();
        if !self.at_kw("drawl") {
            let span = self.span();
            self.diags.push(
                Diagnostic::warning("W0101", "missing `drawl` version header")
                    .with_label(
                        Span::new(span.start, span.start),
                        "file should start with a version header",
                    )
                    .with_help("add `drawl 0.1` as the first line"),
            );
            return None;
        }
        let kw = self.bump();
        let (version, vspan) = match self.peek().clone() {
            TokenKind::Float(v) => {
                let t = self.bump();
                (format!("{v}"), t.span)
            }
            TokenKind::Int(v) => {
                let t = self.bump();
                (format!("{v}"), t.span)
            }
            other => {
                self.diags.push(
                    Diagnostic::error(
                        "E0103",
                        format!(
                            "expected a version number after `drawl`, found {}",
                            other.describe()
                        ),
                    )
                    .with_label(self.span(), "expected something like `0.1`"),
                );
                self.recover();
                return Some(Header {
                    version: "0.1".into(),
                    span: kw.span,
                });
            }
        };
        if version != "0.1" {
            self.diags.push(
                Diagnostic::error("E0106", format!("unsupported drawl version `{version}`"))
                    .with_label(vspan, "this tool understands version `0.1`")
                    .with_help("change the header to `drawl 0.1`"),
            );
        }
        Some(Header {
            version,
            span: kw.span.to(vspan),
        })
    }

    /// Parse statements until `}` (or EOF when `top_level`).
    fn parse_stmt_list(&mut self, top_level: bool) -> Vec<Stmt> {
        let mut stmts = Vec::new();
        loop {
            let trivia = self.collect_leading_trivia();
            match self.peek() {
                TokenKind::Eof => {
                    self.flush_orphan_comments(trivia, &mut stmts);
                    return stmts;
                }
                TokenKind::RBrace => {
                    if top_level {
                        self.diags.push(
                            Diagnostic::error("E0110", "unmatched `}`")
                                .with_label(self.span(), "no open block to close here"),
                        );
                        self.bump();
                        continue;
                    }
                    self.flush_orphan_comments(trivia, &mut stmts);
                    return stmts;
                }
                _ => {}
            }
            let start = self.span();
            match self.parse_stmt() {
                Ok(mut stmt) => {
                    stmt.trivia = trivia;
                    self.attach_trailing_comment(&mut stmt);
                    stmts.push(stmt);
                }
                Err(Bail) => {
                    self.recover();
                    // Guard against zero-progress loops.
                    if self.span() == start && !self.at_eof() {
                        self.bump();
                    }
                }
            }
        }
    }

    fn collect_leading_trivia(&mut self) -> Trivia {
        let mut trivia = Trivia::default();
        let mut newline_run = 0usize;
        loop {
            match self.peek() {
                // `;` separates statements on one line, like a newline.
                TokenKind::Semi => {
                    self.bump();
                }
                TokenKind::Newline => {
                    newline_run += 1;
                    if newline_run >= 2 && !trivia.leading.is_empty() {
                        // Blank line after comments: those comments are
                        // orphans, not attached to the next statement. Keep
                        // them anyway (better than dropping); fmt prints them.
                    }
                    if newline_run >= 2 {
                        trivia.blank_before = true;
                    }
                    self.bump();
                }
                TokenKind::Comment(text) => {
                    let text = text.clone();
                    trivia.leading.push(text);
                    newline_run = 0;
                    self.bump();
                }
                _ => return trivia,
            }
        }
    }

    /// Comments at the end of a block with no following statement: keep them
    /// as a no-op empty statement so fmt round-trips them.
    fn flush_orphan_comments(&mut self, trivia: Trivia, stmts: &mut Vec<Stmt>) {
        if !trivia.leading.is_empty() {
            stmts.push(Stmt {
                kind: StmtKind::Prop(Prop {
                    key: Vec::new(),
                    value: Value::Num(0.0, Span::DUMMY),
                    span: Span::DUMMY,
                }),
                span: Span::DUMMY,
                trivia,
            });
        }
    }

    fn attach_trailing_comment(&mut self, stmt: &mut Stmt) {
        if let TokenKind::Comment(text) = self.peek() {
            stmt.trivia.trailing = Some(text.clone());
            self.bump();
        }
    }

    // ----------------------------------------------------------- statements

    fn parse_stmt(&mut self) -> PResult<Stmt> {
        let start = self.span();
        // Keywords only act as keywords when the next token fits their shape,
        // so `class: bus` (a property) coexists with `class bus { ... }`.
        let next_is_ident = matches!(self.peek_at(1), TokenKind::Ident(_));
        let next_is_lbrace = matches!(self.peek_at(1), TokenKind::LBrace);
        let kind = if self.at_kw("canvas") && next_is_lbrace {
            self.bump();
            StmtKind::Canvas(self.parse_block()?)
        } else if self.at_kw("def") && next_is_ident {
            self.bump();
            StmtKind::Def(self.parse_def()?)
        } else if self.at_kw("group")
            && (next_is_ident || matches!(self.peek_at(1), TokenKind::Str(_)))
        {
            self.bump();
            StmtKind::Group(self.parse_group()?)
        } else if self.at_kw("class") && next_is_ident {
            self.bump();
            let name = self.expect_ident("for the class")?;
            let body = self.parse_block()?;
            StmtKind::Class(Class { name, body })
        } else if self.at_kw("constrain") && next_is_lbrace {
            self.bump();
            StmtKind::Constrain(self.parse_constrain_block()?)
        } else if self.at_kw("pin") && next_is_ident {
            self.bump();
            StmtKind::Pin(self.parse_pin()?)
        } else if self.at_kw("for") && next_is_ident {
            self.bump();
            StmtKind::For(self.parse_for()?)
        } else if self.at_kw("port") && next_is_ident {
            self.bump();
            let name = self.expect_ident("for the port")?;
            let body = if matches!(self.peek(), TokenKind::LBrace) {
                self.parse_block()?
            } else {
                Block {
                    stmts: Vec::new(),
                    span: self.prev_span(),
                }
            };
            StmtKind::Port(Port { name, body })
        } else if matches!(self.peek(), TokenKind::Ident(_)) {
            self.parse_ident_stmt()?
        } else {
            let found = self.peek().describe();
            let mut d = Diagnostic::error("E0110", format!("expected a statement, found {found}"))
                .with_label(self.span(), "not the start of any drawlang statement");
            if let TokenKind::Ident(name) = self.peek() {
                if let Some(s) = crate::diag::suggest(name, STMT_KEYWORDS.iter().copied()) {
                    d = d.with_help(format!("did you mean `{s}`?"));
                }
            }
            d = d.with_help(
                "statements are nodes (`id { ... }`), edges (`a -> b`), properties \
                 (`key: value`), or the keywords canvas/def/group/class/constrain/pin/for/port",
            );
            self.diags.push(d);
            return Err(Bail);
        };
        let span = start.to(self.prev_span());
        Ok(Stmt {
            kind,
            span,
            trivia: Trivia::default(),
        })
    }

    /// Statements that begin with a plain identifier: node declarations,
    /// containers, instantiations, properties, and edges.
    fn parse_ident_stmt(&mut self) -> PResult<StmtKind> {
        // Try keyword suggestions for common typos at statement position:
        // an ident directly followed by another ident is never valid.
        if let (TokenKind::Ident(first), TokenKind::Ident(_)) = (self.peek(), self.peek_at(1)) {
            if let Some(s) = crate::diag::suggest(first, STMT_KEYWORDS.iter().copied()) {
                let first = first.clone();
                self.diags.push(
                    Diagnostic::error("E0110", format!("unknown statement `{first}`"))
                        .with_label(self.span(), "not a drawlang keyword")
                        .with_help(format!("did you mean `{s}`?")),
                );
                return Err(Bail);
            }
        }

        let path = self.parse_path(false)?;

        match self.peek() {
            // Edges -------------------------------------------------------
            TokenKind::Arrow | TokenKind::BidiArrow | TokenKind::BackArrow => {
                self.parse_edge_rest(path)
            }
            // Node with body ------------------------------------------------
            TokenKind::LBrace => {
                let name = self.path_as_single_name(path, "node")?;
                let body = self.parse_block()?;
                Ok(StmtKind::Node(Node {
                    name: Some(name),
                    kind: NodeKind::Plain { body },
                }))
            }
            // Bare instantiation -------------------------------------------
            TokenKind::LParen => {
                let callee = self.path_as_single_name(path, "component")?;
                let args = self.parse_call_args()?;
                let body = if matches!(self.peek(), TokenKind::LBrace) {
                    Some(self.parse_block()?)
                } else {
                    None
                };
                Ok(StmtKind::Node(Node {
                    name: None,
                    kind: NodeKind::Call { callee, args, body },
                }))
            }
            // `name: ...` — container, named call, or property ---------------
            TokenKind::Colon => {
                self.bump();
                self.parse_after_colon(path)
            }
            // Bare node ----------------------------------------------------
            TokenKind::Newline
            | TokenKind::Semi
            | TokenKind::Comment(_)
            | TokenKind::RBrace
            | TokenKind::Eof => {
                let name = self.path_as_single_name(path, "node")?;
                let span = name.span;
                Ok(StmtKind::Node(Node {
                    name: Some(name),
                    kind: NodeKind::Plain {
                        body: Block {
                            stmts: Vec::new(),
                            span,
                        },
                    },
                }))
            }
            other => {
                let found = other.describe();
                self.diags.push(
                    Diagnostic::error("E0103", format!(
                        "expected `{{`, `:`, `(`, or an edge arrow after `{}`, found {found}",
                        path.display()
                    ))
                    .with_label(self.span(), "unexpected here")
                    .with_help("write `id { ... }` for a node, `id: value` for a property, or `a -> b` for an edge"),
                );
                Err(Bail)
            }
        }
    }

    fn parse_after_colon(&mut self, key_path: PathRef) -> PResult<StmtKind> {
        // Containers: `row {`, `column {`, `grid 2x4 {`
        if (self.at_kw("row") || self.at_kw("column"))
            && matches!(self.peek_at(1), TokenKind::LBrace)
        {
            let name = self.path_as_single_name(key_path, "container")?;
            let kw = self.bump();
            let ctype = if let TokenKind::Ident(k) = &kw.kind {
                if k == "row" {
                    ContainerType::Row
                } else {
                    ContainerType::Column
                }
            } else {
                unreachable!()
            };
            let body = self.parse_block()?;
            return Ok(StmtKind::Node(Node {
                name: Some(name),
                kind: NodeKind::Container {
                    ctype,
                    ctype_span: kw.span,
                    body,
                },
            }));
        }
        if self.at_kw("grid") {
            let name = self.path_as_single_name(key_path, "container")?;
            let kw = self.bump();
            let (cols, rows, dspan) = match self.peek().clone() {
                TokenKind::Dimension(c, r) => {
                    let t = self.bump();
                    (c, r, t.span)
                }
                other => {
                    self.diags.push(
                        Diagnostic::error(
                            "E0103",
                            format!(
                                "expected grid dimensions after `grid`, found {}",
                                other.describe()
                            ),
                        )
                        .with_label(
                            self.span(),
                            "expected something like `2x4` (columns x rows)",
                        ),
                    );
                    return Err(Bail);
                }
            };
            if cols == 0 || rows == 0 {
                self.diags.push(
                    Diagnostic::error("E0105", "grid dimensions must be at least 1x1")
                        .with_label(dspan, "zero-sized grid"),
                );
            }
            let body = self.parse_block()?;
            return Ok(StmtKind::Node(Node {
                name: Some(name),
                kind: NodeKind::Container {
                    ctype: ContainerType::Grid { cols, rows },
                    ctype_span: kw.span.to(dspan),
                    body,
                },
            }));
        }
        // Named instantiation: `g0: gpu(0)`
        if matches!(self.peek(), TokenKind::Ident(_))
            && matches!(self.peek_at(1), TokenKind::LParen)
        {
            let name = self.path_as_single_name(key_path, "node")?;
            let callee = self.expect_ident("for the component")?;
            let args = self.parse_call_args()?;
            let body = if matches!(self.peek(), TokenKind::LBrace) {
                Some(self.parse_block()?)
            } else {
                None
            };
            return Ok(StmtKind::Node(Node {
                name: Some(name),
                kind: NodeKind::Call { callee, args, body },
            }));
        }
        // Property: `key: value` (key may be dotted: `label.wrap`).
        let key = self.path_as_prop_key(key_path)?;
        let value = self.parse_value()?;
        let span = key
            .first()
            .map(|k| k.span)
            .unwrap_or(Span::DUMMY)
            .to(value.span());
        Ok(StmtKind::Prop(Prop { key, value, span }))
    }

    fn parse_edge_rest(&mut self, from: PathRef) -> PResult<StmtKind> {
        let op_tok = self.bump();
        let to = self.parse_path(false)?;
        // `a <- b` is stored as `b -> a` so downstream code sees one direction.
        let (from, op, to) = match op_tok.kind {
            TokenKind::Arrow => (from, EdgeOp::Forward, to),
            TokenKind::BidiArrow => (from, EdgeOp::Bidirectional, to),
            TokenKind::BackArrow => (to, EdgeOp::Forward, from),
            _ => unreachable!(),
        };
        let label = if self.eat(&TokenKind::Colon) {
            match self.peek().clone() {
                TokenKind::Str(_) => Some(self.parse_strlit()?),
                other => {
                    self.diags.push(
                        Diagnostic::error(
                            "E0103",
                            format!(
                                "expected a string label after `:`, found {}",
                                other.describe()
                            ),
                        )
                        .with_label(
                            self.span(),
                            r#"edge labels are strings, like `: "PCIe 5.0 x16"`"#,
                        ),
                    );
                    return Err(Bail);
                }
            }
        } else {
            None
        };
        let props = if matches!(self.peek(), TokenKind::LBrace) {
            Some(self.parse_block()?)
        } else {
            None
        };
        Ok(StmtKind::Edge(Edge {
            from,
            op,
            op_span: op_tok.span,
            to,
            label,
            props,
        }))
    }

    fn parse_def(&mut self) -> PResult<Def> {
        let name = self.expect_ident("for the component")?;
        self.expect(TokenKind::LParen, "to open the parameter list")?;
        let mut params = Vec::new();
        self.skip_trivia();
        while !matches!(self.peek(), TokenKind::RParen | TokenKind::Eof) {
            params.push(self.expect_ident("for the parameter")?);
            self.skip_trivia();
            if !self.eat(&TokenKind::Comma) {
                break;
            }
            self.skip_trivia();
        }
        self.expect(TokenKind::RParen, "to close the parameter list")?;
        let body = self.parse_block()?;
        Ok(Def { name, params, body })
    }

    fn parse_group(&mut self) -> PResult<Group> {
        let name = self.expect_ident("for the group")?;
        let label = if matches!(self.peek(), TokenKind::Str(_)) {
            Some(self.parse_strlit()?)
        } else {
            None
        };
        let body = self.parse_block()?;
        Ok(Group { name, label, body })
    }

    fn parse_pin(&mut self) -> PResult<Pin> {
        let target = self.parse_path(false)?;
        if !self.at_kw("at") {
            self.diags.push(
                Diagnostic::error(
                    "E0103",
                    format!(
                        "expected `at` after the pin target, found {}",
                        self.peek().describe()
                    ),
                )
                .with_label(self.span(), "write `pin <element> at (x, y)`"),
            );
            return Err(Bail);
        }
        self.bump();
        self.expect(TokenKind::LParen, "to open the position")?;
        let x = self.parse_expr()?;
        self.expect(TokenKind::Comma, "between the x and y coordinates")?;
        let y = self.parse_expr()?;
        self.expect(TokenKind::RParen, "to close the position")?;
        Ok(Pin { target, x, y })
    }

    fn parse_for(&mut self) -> PResult<For> {
        let var = self.expect_ident("for the loop variable")?;
        if !self.at_kw("in") {
            self.diags.push(
                Diagnostic::error(
                    "E0103",
                    format!(
                        "expected `in` after the loop variable, found {}",
                        self.peek().describe()
                    ),
                )
                .with_label(self.span(), "write `for i in 0..4 { ... }`"),
            );
            return Err(Bail);
        }
        self.bump();
        let start = self.parse_expr()?;
        self.expect(TokenKind::DotDot, "in the loop range")?;
        let end = self.parse_expr()?;
        let body = self.parse_block()?;
        Ok(For {
            var,
            start,
            end,
            body,
        })
    }

    fn parse_constrain_block(&mut self) -> PResult<Vec<Constraint>> {
        self.expect(TokenKind::LBrace, "to open the constrain block")?;
        let mut constraints = Vec::new();
        loop {
            let trivia = self.collect_leading_trivia();
            match self.peek() {
                TokenKind::RBrace => {
                    self.bump();
                    return Ok(constraints);
                }
                TokenKind::Eof => {
                    self.diags.push(
                        Diagnostic::error("E0103", "unclosed `constrain` block")
                            .with_label(self.span(), "expected `}` before end of file"),
                    );
                    return Ok(constraints);
                }
                _ => {}
            }
            let before = self.pos;
            match self.parse_constraint(trivia) {
                Ok(c) => constraints.push(c),
                Err(Bail) => {
                    self.recover();
                    if self.pos == before && !self.at_eof() {
                        self.bump();
                    }
                }
            }
        }
    }

    fn parse_constraint(&mut self, trivia: Trivia) -> PResult<Constraint> {
        let start = self.span();
        // Constraint names may be hyphenated (`left-of`): join contiguous
        // ident `-` ident sequences.
        let mut name = self.expect_ident("for the constraint")?;
        while matches!(self.peek(), TokenKind::Minus)
            && self.span().start == name.span.end
            && matches!(self.peek_at(1), TokenKind::Ident(_))
        {
            self.bump(); // -
            let part = self.expect_ident("after `-`")?;
            name = Ident {
                name: format!("{}-{}", name.name, part.name),
                span: name.span.to(part.span),
            };
        }
        self.expect(TokenKind::LParen, "to open the constraint arguments")?;
        let mut args = Vec::new();
        self.skip_trivia();
        while !matches!(self.peek(), TokenKind::RParen | TokenKind::Eof) {
            args.push(self.parse_constraint_arg()?);
            self.skip_trivia();
            if !self.eat(&TokenKind::Comma) {
                break;
            }
            self.skip_trivia();
        }
        self.expect(TokenKind::RParen, "to close the constraint arguments")?;
        let mut c = Constraint {
            name,
            args,
            span: start.to(self.prev_span()),
            trivia: Trivia::default(),
        };
        c.trivia = trivia;
        // Trailing comment on the same line.
        if let TokenKind::Comment(text) = self.peek() {
            c.trivia.trailing = Some(text.clone());
            self.bump();
        }
        Ok(c)
    }

    fn parse_constraint_arg(&mut self) -> PResult<ConstraintArg> {
        match self.peek().clone() {
            TokenKind::Int(v) => {
                let t = self.bump();
                Ok(ConstraintArg::Num(v as f64, t.span))
            }
            TokenKind::Float(v) => {
                let t = self.bump();
                Ok(ConstraintArg::Num(v, t.span))
            }
            TokenKind::Minus => {
                let start = self.bump().span;
                match self.peek().clone() {
                    TokenKind::Int(v) => {
                        let t = self.bump();
                        Ok(ConstraintArg::Num(-(v as f64), start.to(t.span)))
                    }
                    TokenKind::Float(v) => {
                        let t = self.bump();
                        Ok(ConstraintArg::Num(-v, start.to(t.span)))
                    }
                    other => {
                        self.diags.push(
                            Diagnostic::error(
                                "E0103",
                                format!("expected a number after `-`, found {}", other.describe()),
                            )
                            .with_label(self.span(), "expected a number"),
                        );
                        Err(Bail)
                    }
                }
            }
            TokenKind::Ident(_) => Ok(ConstraintArg::Path(self.parse_path(true)?)),
            other => {
                self.diags.push(
                    Diagnostic::error(
                        "E0103",
                        format!(
                            "expected an element path or number, found {}",
                            other.describe()
                        ),
                    )
                    .with_label(
                        self.span(),
                        "constraint arguments are element paths, keywords, or numbers",
                    ),
                );
                Err(Bail)
            }
        }
    }

    // ------------------------------------------------------------- helpers

    fn parse_block(&mut self) -> PResult<Block> {
        let open = self.expect(TokenKind::LBrace, "to open the block")?;
        let stmts = self.parse_stmt_list(false);
        let close = if matches!(self.peek(), TokenKind::RBrace) {
            self.bump().span
        } else {
            self.diags.push(
                Diagnostic::error("E0103", "unclosed block")
                    .with_label(open.span, "this `{` is never closed")
                    .with_label(self.span(), "expected `}` before this point"),
            );
            self.span()
        };
        Ok(Block {
            stmts,
            span: open.span.to(close),
        })
    }

    fn parse_call_args(&mut self) -> PResult<Vec<Expr>> {
        self.expect(TokenKind::LParen, "to open the arguments")?;
        let mut args = Vec::new();
        self.skip_trivia();
        while !matches!(self.peek(), TokenKind::RParen | TokenKind::Eof) {
            args.push(self.parse_expr()?);
            self.skip_trivia();
            if !self.eat(&TokenKind::Comma) {
                break;
            }
            self.skip_trivia();
        }
        self.expect(TokenKind::RParen, "to close the arguments")?;
        Ok(args)
    }

    fn path_as_single_name(&mut self, path: PathRef, what: &str) -> PResult<Ident> {
        match path.segments.as_slice() {
            [PathSeg::Name(id)] => Ok(id.clone()),
            _ => {
                self.diags.push(
                    Diagnostic::error("E0107", format!("{what} names must be a single identifier"))
                        .with_label(
                            path.span,
                            format!("`{}` is a path, not a name", path.display()),
                        )
                        .with_help(
                            "dots and indices are for *referring* to elements, not declaring them",
                        ),
                );
                Err(Bail)
            }
        }
    }

    fn path_as_prop_key(&mut self, path: PathRef) -> PResult<Vec<Ident>> {
        let mut key = Vec::new();
        for seg in &path.segments {
            match seg {
                PathSeg::Name(id) => key.push(id.clone()),
                _ => {
                    self.diags.push(
                        Diagnostic::error("E0107", "property keys cannot contain indices")
                            .with_label(path.span, "expected a key like `label.wrap`"),
                    );
                    return Err(Bail);
                }
            }
        }
        Ok(key)
    }

    fn parse_path(&mut self, allow_wildcard: bool) -> PResult<PathRef> {
        let first = self.expect_ident("to start an element path")?;
        let start = first.span;
        let mut segments = vec![PathSeg::Name(first)];
        loop {
            match self.peek() {
                TokenKind::Dot => {
                    self.bump();
                    let id = self.expect_ident("after `.`")?;
                    segments.push(PathSeg::Name(id));
                }
                TokenKind::LBracket => {
                    self.bump();
                    if matches!(self.peek(), TokenKind::Star) {
                        let star = self.bump();
                        if !allow_wildcard {
                            self.diags.push(
                                Diagnostic::error(
                                    "E0108",
                                    "`[*]` is only allowed in constraint arguments",
                                )
                                .with_label(star.span, "wildcard not allowed here")
                                .with_help("name a specific index, like `[0]`"),
                            );
                        }
                        segments.push(PathSeg::Wildcard(star.span));
                    } else {
                        let expr = self.parse_expr()?;
                        segments.push(PathSeg::Index(expr));
                    }
                    self.expect(TokenKind::RBracket, "to close the index")?;
                }
                _ => break,
            }
        }
        let span = start.to(self.prev_span());
        Ok(PathRef { segments, span })
    }

    fn parse_value(&mut self) -> PResult<Value> {
        match self.peek().clone() {
            TokenKind::Str(_) => Ok(Value::Str(self.parse_strlit()?)),
            TokenKind::Int(v) => {
                let t = self.bump();
                Ok(Value::Num(v as f64, t.span))
            }
            TokenKind::Float(v) => {
                let t = self.bump();
                Ok(Value::Num(v, t.span))
            }
            TokenKind::Minus => {
                let start = self.bump().span;
                match self.peek().clone() {
                    TokenKind::Int(v) => {
                        let t = self.bump();
                        Ok(Value::Num(-(v as f64), start.to(t.span)))
                    }
                    TokenKind::Float(v) => {
                        let t = self.bump();
                        Ok(Value::Num(-v, start.to(t.span)))
                    }
                    other => {
                        self.diags.push(
                            Diagnostic::error(
                                "E0103",
                                format!("expected a number after `-`, found {}", other.describe()),
                            )
                            .with_label(self.span(), "expected a number"),
                        );
                        Err(Bail)
                    }
                }
            }
            TokenKind::Ident(name) => {
                let t = self.bump();
                Ok(Value::Word(Ident { name, span: t.span }))
            }
            TokenKind::AtIdent(name) => {
                let t = self.bump();
                Ok(Value::ThemeToken(Ident { name, span: t.span }))
            }
            TokenKind::HexColor(hex) => {
                let t = self.bump();
                Ok(Value::Color(hex, t.span))
            }
            other => {
                self.diags.push(
                    Diagnostic::error(
                        "E0103",
                        format!("expected a property value, found {}", other.describe()),
                    )
                    .with_label(
                        self.span(),
                        "expected a string, number, word, `@token`, or `#color`",
                    ),
                );
                Err(Bail)
            }
        }
    }

    // --------------------------------------------------------- expressions

    fn parse_expr(&mut self) -> PResult<Expr> {
        self.parse_additive()
    }

    fn parse_additive(&mut self) -> PResult<Expr> {
        let mut lhs = self.parse_multiplicative()?;
        loop {
            let op = match self.peek() {
                TokenKind::Plus => BinOp::Add,
                TokenKind::Minus => BinOp::Sub,
                _ => return Ok(lhs),
            };
            self.bump();
            let rhs = self.parse_multiplicative()?;
            let span = lhs.span.to(rhs.span);
            lhs = Expr {
                kind: ExprKind::Binary(op, Box::new(lhs), Box::new(rhs)),
                span,
            };
        }
    }

    fn parse_multiplicative(&mut self) -> PResult<Expr> {
        let mut lhs = self.parse_unary()?;
        loop {
            let op = match self.peek() {
                TokenKind::Star => BinOp::Mul,
                TokenKind::Slash => BinOp::Div,
                TokenKind::Percent => BinOp::Mod,
                _ => return Ok(lhs),
            };
            self.bump();
            let rhs = self.parse_unary()?;
            let span = lhs.span.to(rhs.span);
            lhs = Expr {
                kind: ExprKind::Binary(op, Box::new(lhs), Box::new(rhs)),
                span,
            };
        }
    }

    fn parse_unary(&mut self) -> PResult<Expr> {
        if matches!(self.peek(), TokenKind::Minus) {
            let start = self.bump().span;
            let inner = self.parse_unary()?;
            let span = start.to(inner.span);
            return Ok(Expr {
                kind: ExprKind::Unary(UnOp::Neg, Box::new(inner)),
                span,
            });
        }
        self.parse_primary()
    }

    fn parse_primary(&mut self) -> PResult<Expr> {
        match self.peek().clone() {
            TokenKind::Int(v) => {
                let t = self.bump();
                Ok(Expr {
                    kind: ExprKind::Num(v as f64),
                    span: t.span,
                })
            }
            TokenKind::Float(v) => {
                let t = self.bump();
                Ok(Expr {
                    kind: ExprKind::Num(v),
                    span: t.span,
                })
            }
            TokenKind::Str(_) => {
                let s = self.parse_strlit()?;
                let span = s.span;
                Ok(Expr {
                    kind: ExprKind::Str(Box::new(s)),
                    span,
                })
            }
            TokenKind::Ident(name) => {
                let t = self.bump();
                Ok(Expr {
                    kind: ExprKind::Var(Ident { name, span: t.span }),
                    span: t.span,
                })
            }
            TokenKind::LParen => {
                self.bump();
                let inner = self.parse_expr()?;
                self.expect(TokenKind::RParen, "to close the parenthesized expression")?;
                Ok(inner)
            }
            other => {
                self.diags.push(
                    Diagnostic::error(
                        "E0103",
                        format!("expected an expression, found {}", other.describe()),
                    )
                    .with_label(self.span(), "expected a number, variable, or `(expr)`"),
                );
                Err(Bail)
            }
        }
    }

    // ------------------------------------------------------------- strings

    /// Parse the current Str token into literal/interpolated parts.
    /// Interpolated expressions are re-lexed from the original source so
    /// their spans point at the real file location.
    fn parse_strlit(&mut self) -> PResult<StrLit> {
        let tok = self.bump();
        let TokenKind::Str(_) = &tok.kind else {
            unreachable!("caller checked")
        };
        let span = tok.span;
        // Scan the raw source between the quotes so offsets stay exact.
        let inner_start = span.start + 1;
        let inner_end = span.end.saturating_sub(1).max(inner_start);
        let raw = &self.src[inner_start.min(self.src.len())..inner_end.min(self.src.len())];

        let mut parts = Vec::new();
        let mut text = String::new();
        let bytes = raw.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            match bytes[i] {
                b'\\' if i + 1 < bytes.len() => {
                    match bytes[i + 1] {
                        b'n' => text.push('\n'),
                        b't' => text.push('\t'),
                        b'"' => text.push('"'),
                        b'\\' => text.push('\\'),
                        b'{' => text.push('{'),
                        b'}' => text.push('}'),
                        other => text.push(other as char), // already diagnosed by lexer
                    }
                    i += 2;
                }
                b'{' => {
                    // Find the matching close brace.
                    let expr_start = i + 1;
                    let mut depth = 1;
                    let mut j = expr_start;
                    while j < bytes.len() && depth > 0 {
                        match bytes[j] {
                            b'{' => depth += 1,
                            b'}' => depth -= 1,
                            _ => {}
                        }
                        j += 1;
                    }
                    let expr_end = j - 1; // index of the closing `}` (or end)
                    if depth > 0 {
                        // Lexer already reported E0104; treat rest as text.
                        text.push_str(&raw[i..]);
                        i = bytes.len();
                        continue;
                    }
                    if !text.is_empty() {
                        parts.push(StrPart::Text(std::mem::take(&mut text)));
                    }
                    let expr_src = &raw[expr_start..expr_end];
                    let abs_offset = inner_start + expr_start;
                    parts.push(StrPart::Expr(
                        self.parse_embedded_expr(expr_src, abs_offset)?,
                    ));
                    i = j;
                }
                _ => {
                    let ch = raw[i..].chars().next().unwrap();
                    text.push(ch);
                    i += ch.len_utf8();
                }
            }
        }
        if !text.is_empty() {
            parts.push(StrPart::Text(text));
        }
        Ok(StrLit { parts, span })
    }

    fn parse_embedded_expr(&mut self, expr_src: &str, abs_offset: usize) -> PResult<Expr> {
        if expr_src.trim().is_empty() {
            self.diags.push(
                Diagnostic::error("E0104", "empty interpolation `{}` in string")
                    .with_label(
                        Span::new(abs_offset - 1, abs_offset + expr_src.len() + 1),
                        "nothing to interpolate",
                    )
                    .with_help(r#"put an expression inside the braces, like `"GPU {i}"`"#),
            );
            return Err(Bail);
        }
        let lexed = crate::lexer::lex(expr_src);
        // Shift sub-lexer diagnostics and token spans to absolute positions.
        for mut d in lexed.diagnostics {
            for l in &mut d.labels {
                l.span = Span::new(l.span.start + abs_offset, l.span.end + abs_offset);
            }
            self.diags.push(d);
        }
        let tokens: Vec<Token> = lexed
            .tokens
            .into_iter()
            .map(|t| Token {
                kind: t.kind,
                span: Span::new(t.span.start + abs_offset, t.span.end + abs_offset),
            })
            .collect();
        let mut sub = Parser {
            src: self.src,
            tokens,
            pos: 0,
            diags: Vec::new(),
        };
        let result = sub.parse_expr();
        let leftover = !matches!(sub.peek(), TokenKind::Newline | TokenKind::Eof);
        self.diags.extend(sub.diags);
        match result {
            Ok(expr) => {
                if leftover {
                    self.diags.push(
                        Diagnostic::error("E0104", "unexpected trailing tokens in interpolation")
                            .with_label(
                                Span::new(abs_offset, abs_offset + expr_src.len()),
                                "only a single expression is allowed inside `{...}`",
                            ),
                    );
                    return Err(Bail);
                }
                Ok(expr)
            }
            Err(Bail) => Err(Bail),
        }
    }
}