lini 0.1.0

A small, human-readable language for plain-text diagrams that compiles to clean SVG
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
mod ir;
mod shapes;
mod styles;
mod vars;

pub use ir::*;

use crate::ast::{
    AttrItem, BodyItem, DefsBlock, DefsEntry, EndpointGroup, File, LineStyle, SceneConfig,
    ShapeDef, ShapeInst, StyleDef, TypeDefaults, TypeRef, VarOverride, WireConfig, WireDecl,
    WireEndpoint, WireOp,
};
use crate::error::Error;
use crate::span::Span;
use std::collections::{HashMap, HashSet};

#[cfg(test)]
pub fn resolve(file: File) -> Result<Program, Error> {
    resolve_with_theme(file, &[])
}

pub fn resolve_with_theme(file: File, theme: &[(String, String)]) -> Result<Program, Error> {
    // ─── Phase 2.1 — vars & defs setup ───
    let mut vars = vars::built_in_defaults();
    vars::apply_theme(&mut vars, theme);

    let split = split_defs(&file.defs)?;

    if !split.var_overrides.is_empty() {
        vars::apply_var_overrides(&mut vars, &split.var_overrides)?;
    }

    let styles_table = styles::StyleTable::build(&split.style_defs, &vars)?;
    let shapes_table = shapes::ShapesTable::build(
        &split.shape_defs,
        &split.type_defaults,
        &styles_table,
        &vars,
    )?;

    // ─── Phase 2.2 — partition top-level stmts ───
    let (root_nodes, root_wires) = partition_stmts(&file.stmts);

    // ─── Phase 2.3 — resolve scene tree ───
    // Apply scene config to root scene attrs.
    let scene_attrs = match split.scene_config {
        Some(cfg) => {
            let resolved = resolve_attrs(&cfg.items, &styles_table, &vars)?;
            collapse(&resolved)
        }
        None => default_scene_attrs(&vars),
    };

    let mut id_seen: HashMap<String, Span> = HashMap::new();
    let mut scene_nodes = Vec::new();
    let mut internal_wires_lifted: Vec<LiftedWire> = Vec::new();

    // The scene config seeds the cascade for inheritable text attrs.
    let mut root_text_ctx = AttrMap::new();
    for name in INHERITED_TEXT_ATTRS {
        if let Some(v) = scene_attrs.get(name) {
            root_text_ctx.insert(*name, v.clone());
        }
    }

    for inst in &root_nodes {
        let resolved = resolve_inst(
            inst,
            &shapes_table,
            &styles_table,
            &vars,
            &mut id_seen,
            &[],
            &mut internal_wires_lifted,
            &root_text_ctx,
        )?;
        scene_nodes.push(resolved);
    }
    // ─── Phase 2.4 — auto-create, against the expanded tree ───
    // SPEC section 5: a root wire's single-segment endpoint naming an id that
    // exists nowhere in the expanded tree auto-creates an empty |rect| at the
    // scene root. Ids that exist deeper get the did-you-mean error instead.
    let mut path_index = build_path_index(&scene_nodes);
    let mut auto_seen: HashSet<String> = HashSet::new();
    let mut auto_created: Vec<ShapeInst> = Vec::new();
    for wire in &root_wires {
        for group in &wire.chain {
            for ep in &group.endpoints {
                if ep.path.len() != 1 {
                    // Multi-segment paths are navigations, never new nodes.
                    continue;
                }
                let id = &ep.path[0];
                if path_index.has_final_segment(id) || auto_seen.contains(id) {
                    continue;
                }
                auto_seen.insert(id.clone());
                auto_created.push(auto_created_inst(id, ep.span));
            }
        }
    }
    if !auto_created.is_empty() {
        for inst in &auto_created {
            let resolved = resolve_inst(
                inst,
                &shapes_table,
                &styles_table,
                &vars,
                &mut id_seen,
                &[],
                &mut internal_wires_lifted,
                &root_text_ctx,
            )?;
            scene_nodes.push(resolved);
        }
        path_index = build_path_index(&scene_nodes);
    }

    // ─── Phase 2.6 — resolve wires (root + lifted internal) ───
    // Pre-resolve |wire| defaults once — layered as lowest specificity under
    // styles and per-wire attrs.
    let wires_defaults = match split.wire_config {
        Some(cfg) => resolve_attrs(&cfg.items, &styles_table, &vars)?,
        None => Vec::new(),
    };
    let mut wires = Vec::new();
    for w in &root_wires {
        for resolved in resolve_wire(w, &styles_table, &vars, &path_index, &[], &wires_defaults)? {
            wires.push(resolved);
        }
    }
    for lifted in &internal_wires_lifted {
        for resolved in resolve_wire(
            &lifted.wire,
            &styles_table,
            &vars,
            &path_index,
            &lifted.prefix,
            &wires_defaults,
        )? {
            wires.push(resolved);
        }
    }

    // ─── Phase 2.7 — stylesheet inputs for the renderer (SPEC §14) ───
    let sheet = SheetInputs {
        styles: styles_table
            .in_order()
            .into_iter()
            .map(|(name, attrs)| (name, collapse(&attrs)))
            .collect(),
        type_defaults: split
            .type_defaults
            .iter()
            .filter_map(|td| {
                shapes_table
                    .type_default_attrs(&td.name)
                    .map(|attrs| (td.name.clone(), collapse(attrs)))
            })
            .collect(),
        shape_defs: split
            .shape_defs
            .iter()
            .filter_map(|sd| {
                shapes_table
                    .own_attrs(&sd.name)
                    .map(|attrs| (sd.name.clone(), collapse(attrs)))
            })
            .collect(),
        templates: shapes::TEMPLATES
            .iter()
            .map(|(name, _)| (name.to_string(), collapse(&shapes::template_attrs(name))))
            .filter(|(_, attrs)| !attrs.map.is_empty())
            .collect(),
        wire_defaults: collapse(&wires_defaults),
    };

    Ok(Program {
        vars,
        scene: ResolvedScene {
            attrs: scene_attrs,
            nodes: scene_nodes,
        },
        wires,
        sheet,
    })
}

// ─────────────────────────── Defs partitioning ───────────────────────────

struct SplitDefs<'a> {
    scene_config: Option<&'a SceneConfig>,
    wire_config: Option<&'a WireConfig>,
    type_defaults: Vec<&'a TypeDefaults>,
    var_overrides: Vec<&'a VarOverride>,
    style_defs: Vec<&'a StyleDef>,
    shape_defs: Vec<&'a ShapeDef>,
}

fn split_defs(defs: &Option<DefsBlock>) -> Result<SplitDefs<'_>, Error> {
    let mut scene_config: Option<&SceneConfig> = None;
    let mut wire_config: Option<&WireConfig> = None;
    let mut type_defaults = Vec::new();
    let mut var_overrides = Vec::new();
    let mut style_defs = Vec::new();
    let mut shape_defs = Vec::new();
    if let Some(block) = defs {
        for entry in &block.entries {
            match entry {
                DefsEntry::SceneConfig(s) => {
                    if scene_config.is_some() {
                        return Err(Error::at(
                            s.span,
                            "'|scene|' may appear at most once in the defs block",
                        ));
                    }
                    scene_config = Some(s);
                }
                DefsEntry::WireConfig(w) => {
                    if wire_config.is_some() {
                        return Err(Error::at(
                            w.span,
                            "'|wire|' may appear at most once in the defs block",
                        ));
                    }
                    wire_config = Some(w);
                }
                DefsEntry::TypeDefaults(t) => type_defaults.push(t),
                DefsEntry::VarOverride(v) => var_overrides.push(v),
                DefsEntry::StyleDef(s) => style_defs.push(s),
                DefsEntry::ShapeDef(s) => shape_defs.push(s),
            }
        }
    }
    Ok(SplitDefs {
        scene_config,
        wire_config,
        type_defaults,
        var_overrides,
        style_defs,
        shape_defs,
    })
}

fn default_scene_attrs(vars: &VarTable) -> AttrMap {
    // SPEC §4 default when |scene| is omitted: `layout:row gap:20 padding:20`.
    let mut m = AttrMap::new();
    m.insert("layout", ResolvedValue::Ident("row".into()));
    if let Some(e) = vars.get("gap") {
        m.insert(
            "gap",
            ResolvedValue::LiveVar {
                name: "gap".into(),
                raw: false,
                baked: Some(Box::new(e.value.clone())),
            },
        );
    }
    if let Some(e) = vars.get("canvas-pad") {
        m.insert(
            "padding",
            ResolvedValue::LiveVar {
                name: "canvas-pad".into(),
                raw: false,
                baked: Some(Box::new(e.value.clone())),
            },
        );
    }
    m
}

// ─────────────────────────── Stmt partitioning ───────────────────────────

fn partition_stmts(stmts: &[crate::ast::Stmt]) -> (Vec<ShapeInst>, Vec<WireDecl>) {
    let mut nodes = Vec::new();
    let mut wires = Vec::new();
    for s in stmts {
        match s {
            crate::ast::Stmt::Node(n) => nodes.push(n.clone()),
            crate::ast::Stmt::Wire(w) => wires.push(w.clone()),
        }
    }
    (nodes, wires)
}

// ─────────────────────────── Auto-create ───────────────────────────

fn auto_created_inst(id: &str, span: Span) -> ShapeInst {
    ShapeInst {
        id: Some(id.to_string()),
        ty: TypeRef {
            name: "rect".to_string(),
            span,
        },
        label: Some(id.to_string()),
        href: None,
        items: Vec::new(),
        body: None,
        span,
    }
}

// ─────────────────────────── Reserved names ───────────────────────────

/// The reserved-identifier error, with the always-available out: idents are
/// case-sensitive, so the capitalized variant is never reserved.
pub(super) fn reserved_error(span: Span, name: &str) -> Error {
    let mut cap = name.to_string();
    if let Some(first) = cap.get_mut(0..1) {
        first.make_ascii_uppercase();
    }
    Error::at(
        span,
        format!(
            "'{}' is reserved (ids are case-sensitive — '{}' is free)",
            name, cap
        ),
    )
}

pub(super) fn is_reserved(name: &str) -> bool {
    matches!(
        name,
        // Layout values
        "row" | "column" | "grid"
        | "start" | "center" | "end" | "stretch" | "between" | "around" | "evenly"
        // Anchors / endpoint sides
        | "top" | "bottom" | "left" | "right"
        | "top-left" | "top-right" | "bottom-left" | "bottom-right"
        | "out-top" | "out-bottom" | "out-left" | "out-right"
        | "out-top-left" | "out-top-right" | "out-bottom-left" | "out-bottom-right"
        | "mid"
        // Primitives
        | "rect" | "oval" | "line" | "path" | "poly" | "text"
        | "hex" | "slant" | "cyl" | "diamond" | "cloud" | "icon" | "image"
        // Templates
        | "group" | "badge" | "button" | "card" | "note"
        | "table" | "cell"
        // Defs-only specials
        | "scene" | "wire"
        // Constants
        | "true" | "false" | "none" | "auto"
        // Functions
        | "var" | "rgb" | "rgba" | "hsl"
    )
}

// ─────────────────────────── Attr resolution ───────────────────────────

fn resolve_attrs(
    items: &[AttrItem],
    styles: &styles::StyleTable,
    vars: &VarTable,
) -> Result<Vec<ResolvedAttr>, Error> {
    // SPEC §13: style classes merge in defs-block definition order — listing
    // order is irrelevant, as with CSS classes — and inline attrs merge after
    // every style, regardless of where they sit on the line.
    let mut style_refs: Vec<(usize, &str)> = Vec::new();
    for item in items {
        if let AttrItem::Style(s) = item {
            let idx = styles
                .index(&s.name)
                .ok_or_else(|| Error::at(s.span, format!("unknown style '.{}'", s.name)))?;
            style_refs.push((idx, s.name.as_str()));
        }
    }
    style_refs.sort_by_key(|(idx, _)| *idx);
    style_refs.dedup_by_key(|(idx, _)| *idx);

    let mut out = Vec::new();
    for (_, name) in &style_refs {
        let inner = styles.lookup(name).expect("indexed style expands");
        out.extend(inner.iter().cloned());
    }
    for item in items {
        if let AttrItem::Attr(a) = item {
            out.push(ResolvedAttr {
                name: a.name.clone(),
                value: vars::resolve_value(&a.value, vars)?,
                span: a.span,
            });
        }
    }
    Ok(out)
}

fn collapse(items: &[ResolvedAttr]) -> AttrMap {
    let mut map = AttrMap::new();
    for item in items {
        if is_marker_attr(&item.name) {
            continue;
        }
        map.insert(item.name.clone(), item.value.clone());
    }
    map
}

fn is_marker_attr(name: &str) -> bool {
    matches!(name, "marker" | "marker-start" | "marker-end")
}

// ─────────────────────────── Markers ───────────────────────────

fn resolve_markers(
    items: &[ResolvedAttr],
    default_start: MarkerKind,
    default_end: MarkerKind,
) -> Result<Markers, Error> {
    let mut start = default_start;
    let mut end = default_end;
    for item in items {
        match item.name.as_str() {
            "marker" => {
                let m = expect_marker(&item.value, item.span)?;
                start = m;
                end = m;
            }
            "marker-start" => {
                start = expect_marker(&item.value, item.span)?;
            }
            "marker-end" => {
                end = expect_marker(&item.value, item.span)?;
            }
            _ => {}
        }
    }
    Ok(Markers { start, end })
}

fn expect_marker(value: &ResolvedValue, span: Span) -> Result<MarkerKind, Error> {
    match value {
        ResolvedValue::Ident(s) => MarkerKind::parse(s)
            .ok_or_else(|| Error::at(span, format!("invalid marker value '{}'", s))),
        _ => Err(Error::at(span, "marker attr requires an identifier value")),
    }
}

fn op_markers(op: WireOp) -> Markers {
    Markers {
        start: MarkerKind::from_marker(op.start),
        end: MarkerKind::from_marker(op.end),
    }
}

// ─────────────────────────── Scene tree resolution ───────────────────────────

/// One internal wire (from a shape def body) lifted up to the program level
/// after instantiation, with its endpoint paths prefixed by the instance path.
struct LiftedWire {
    wire: WireDecl,
    /// Dot-path of the host instance (e.g. ["garden"]) — gets prefixed onto
    /// every endpoint path inside the wire at resolution time.
    prefix: Vec<String>,
}

/// Text attrs that cascade from any container to descendant `|text|` nodes —
/// nearest ancestor wins, the node's own attrs win over all (SPEC §11 Text).
const INHERITED_TEXT_ATTRS: &[&str] = &["font", "text-size", "weight", "align"];

fn size_on_text_error(span: Span) -> Error {
    Error::at(span, "'size' is not a text attr; use 'text-size'")
}

#[allow(clippy::too_many_arguments)]
fn resolve_inst(
    inst: &ShapeInst,
    shapes: &shapes::ShapesTable,
    styles_table: &styles::StyleTable,
    vars: &VarTable,
    id_seen: &mut HashMap<String, Span>,
    path_prefix: &[String],
    lifted: &mut Vec<LiftedWire>,
    text_ctx: &AttrMap,
) -> Result<ResolvedInst, Error> {
    let resolved_shape = shapes.resolve(&inst.ty.name, inst.ty.span)?;

    let applied_styles: Vec<String> = inst
        .items
        .iter()
        .filter_map(|i| match i {
            AttrItem::Style(s) => Some(s.name.clone()),
            AttrItem::Attr(_) => None,
        })
        .collect();

    // ID uniqueness + reserved-name check, keyed by full path: siblings in any
    // scope must be distinct (the path index requires it), but the same local
    // id across distinct instances (a.inlet vs b.inlet) has distinct paths and
    // legitimately coexists.
    if let Some(id) = &inst.id {
        if is_reserved(id) {
            return Err(reserved_error(inst.span, id));
        }
        let full = if path_prefix.is_empty() {
            id.clone()
        } else {
            format!("{}.{}", path_prefix.join("."), id)
        };
        if let Some(prev) = id_seen.get(&full) {
            return Err(Error::at(inst.span, format!("duplicate id '{}'", id)).with_related(*prev));
        }
        id_seen.insert(full, inst.span);
    }

    let inline = resolve_attrs(&inst.items, styles_table, vars)?;
    let mut ordered = resolved_shape.attrs.clone();
    ordered.extend(inline);

    // No primitive carries default markers; an "arrow" is just a
    // `|line| marker-end:arrow`. Wires get theirs from the operator.
    let markers = resolve_markers(&ordered, MarkerKind::None, MarkerKind::None)?;
    let mut attrs = collapse(&ordered);

    if resolved_shape.kind == ShapeKind::Text {
        if attrs.get("size").is_some() {
            return Err(size_on_text_error(inst.span));
        }
        for name in INHERITED_TEXT_ATTRS {
            if attrs.get(name).is_none()
                && let Some(v) = text_ctx.get(name)
            {
                attrs.insert(*name, v.clone());
            }
        }
    }
    // SPEC §8: a slant's skew must stay in the open interval (-89, 89) — at the
    // bounds tan() explodes, shifting the top edge off to infinity.
    if resolved_shape.kind == ShapeKind::Slant
        && let Some(skew) = attrs.number("skew")
        && (skew <= -89.0 || skew >= 89.0)
    {
        return Err(Error::at(
            inst.span,
            format!("skew:{} must be in (-89, 89)", skew),
        ));
    }
    let mut child_text_ctx = text_ctx.clone();
    for name in INHERITED_TEXT_ATTRS {
        if let Some(v) = attrs.get(name) {
            child_text_ctx.insert(*name, v.clone());
        }
    }

    // Compute the dot-path of this inst for nested children.
    let mut child_prefix = path_prefix.to_vec();
    if let Some(id) = &inst.id {
        child_prefix.push(id.clone());
    }

    // Body assembly: shape-def intrinsic children, then label sugar (non-text),
    // then explicit body items from the source.
    let mut body_items: Vec<BodyItem> = resolved_shape.body_items.clone();
    let own_label = if resolved_shape.kind == ShapeKind::Text {
        inst.label.clone()
    } else {
        if let Some(label) = &inst.label {
            body_items.push(BodyItem::Inst(label_sugar_text(label, inst.span)));
        }
        None
    };
    if let Some(b) = &inst.body {
        body_items.extend(b.iter().cloned());
    }

    let mut children = Vec::new();
    for item in &body_items {
        match item {
            BodyItem::Inst(child) => {
                children.push(resolve_inst(
                    child,
                    shapes,
                    styles_table,
                    vars,
                    id_seen,
                    &child_prefix,
                    lifted,
                    &child_text_ctx,
                )?);
            }
            BodyItem::Wire(wire) => {
                lifted.push(LiftedWire {
                    wire: wire.clone(),
                    prefix: child_prefix.clone(),
                });
            }
        }
    }

    Ok(ResolvedInst {
        id: inst.id.clone(),
        shape: resolved_shape.kind,
        type_chain: resolved_shape.type_chain,
        applied_styles,
        label: own_label,
        attrs,
        markers,
        children,
        span: inst.span,
    })
}

fn label_sugar_text(text: &str, span: Span) -> ShapeInst {
    ShapeInst {
        id: None,
        ty: TypeRef {
            name: "text".to_string(),
            span,
        },
        label: Some(text.to_string()),
        href: None,
        items: Vec::new(),
        body: None,
        span,
    }
}

// ─────────────────────────── Path index ───────────────────────────

/// Maps fully-qualified dot-paths to their place in the scene tree.
struct PathIndex {
    paths: Vec<String>,
}

impl PathIndex {
    fn contains(&self, path: &str) -> bool {
        self.paths.iter().any(|p| p == path)
    }

    /// SPEC section 10: an endpoint is an exact path walked from the wire's
    /// scope — the caller prepends the scope prefix. There is no search.
    fn resolve(&self, query: &[String]) -> Option<String> {
        let qjoined = query.join(".");
        self.contains(&qjoined).then_some(qjoined)
    }

    /// Whether any node anywhere in the tree carries this id — the
    /// auto-create gate (only ids absent everywhere materialize).
    fn has_final_segment(&self, seg: &str) -> bool {
        self.paths.iter().any(|p| final_segment(p) == seg)
    }

    /// Full paths of same-named nodes, for did-you-mean errors. Sorted,
    /// capped at 3.
    /// Same-named paths to propose in a wire's scope. For a body wire (non-empty
    /// `scope`) only paths inside that subtree are reachable, and they are
    /// stripped to the form the user types there (`shelf.bowl`, not the
    /// root-absolute `garden.shelf.bowl`). Sorted, deduped, capped at 3.
    fn suggest(&self, seg: &str, scope: &[String]) -> Vec<String> {
        let prefix = if scope.is_empty() {
            String::new()
        } else {
            format!("{}.", scope.join("."))
        };
        let mut hits: Vec<String> = self
            .paths
            .iter()
            .filter(|p| final_segment(p) == seg)
            .filter_map(|p| {
                if prefix.is_empty() {
                    Some(p.clone())
                } else {
                    p.strip_prefix(&prefix).map(str::to_string)
                }
            })
            .collect();
        hits.sort();
        hits.dedup();
        hits.truncate(3);
        hits
    }
}

fn final_segment(path: &str) -> &str {
    path.rsplit('.').next().unwrap_or(path)
}

fn build_path_index(nodes: &[ResolvedInst]) -> PathIndex {
    let mut paths = Vec::new();
    for n in nodes {
        walk_paths(n, &mut Vec::new(), &mut paths);
    }
    PathIndex { paths }
}

fn walk_paths(n: &ResolvedInst, stack: &mut Vec<String>, out: &mut Vec<String>) {
    if let Some(id) = &n.id {
        stack.push(id.clone());
        out.push(stack.join("."));
    }
    for c in &n.children {
        walk_paths(c, stack, out);
    }
    if n.id.is_some() {
        stack.pop();
    }
}

// ─────────────────────────── Wires ───────────────────────────

fn resolve_wire(
    w: &WireDecl,
    styles_table: &styles::StyleTable,
    vars: &VarTable,
    paths: &PathIndex,
    path_prefix: &[String],
    wires_defaults: &[ResolvedAttr],
) -> Result<Vec<ResolvedWire>, Error> {
    let inline = resolve_attrs(&w.items, styles_table, vars)?;
    // Style names ride the wire as `lini-style-*` classes (resolve_attrs above
    // already validated them); their paint comes from the class rules, exactly
    // like a node.
    let applied_styles: Vec<String> = w
        .items
        .iter()
        .filter_map(|i| match i {
            AttrItem::Style(s) => Some(s.name.clone()),
            AttrItem::Attr(_) => None,
        })
        .collect();
    // SPEC section 13 application order: `|wire|` defaults are lowest specificity,
    // styles and per-wire attrs override (the latter are already merged into
    // `inline` left-to-right by `resolve_attrs`).
    let mut ordered: Vec<ResolvedAttr> = Vec::with_capacity(wires_defaults.len() + inline.len());
    ordered.extend(wires_defaults.iter().cloned());
    ordered.extend(inline);

    let op_marks = op_markers(w.op);
    let markers = resolve_markers(&ordered, op_marks.start, op_marks.end)?;
    let mut attrs = collapse(&ordered);

    // Synthesize the line attr for operator variants per SPEC section 10.
    inject_line_style(&mut attrs, w.op.line);

    // Text children: label sugar + explicit body texts.
    let mut texts: Vec<ResolvedText> = Vec::new();
    if let Some(label) = &w.label {
        texts.push(ResolvedText {
            text: label.clone(),
            at: WireAt::Mid,
            attrs: AttrMap::new(),
        });
    }
    if let Some(body) = &w.body {
        for t in body {
            let t_attrs = resolve_attrs(&t.items, styles_table, vars)?;
            let mut at = WireAt::Mid;
            let mut t_map = AttrMap::new();
            for item in &t_attrs {
                if item.name == "size" {
                    return Err(size_on_text_error(item.span));
                }
                if item.name == "at" {
                    at = WireAt::parse(&item.value).ok_or_else(|| {
                        Error::at(
                            item.span,
                            "|text| anchor on a wire must be start/mid/end or 0..1",
                        )
                    })?;
                } else {
                    t_map.insert(item.name.clone(), item.value.clone());
                }
            }
            texts.push(ResolvedText {
                text: t.text.clone(),
                at,
                attrs: t_map,
            });
        }
    }

    // Cartesian fan expansion: each group's endpoints fan out independently.
    // For chain [{a}, {b,c}, {d}] with op `->`, we get a→b→d, a→c→d (each as
    // its own wire). Per spec section 10 wire fan grammar.
    let expanded = expand_chain(&w.chain);

    let mut out = Vec::with_capacity(expanded.len());
    for (fan_index, chain_path) in expanded.into_iter().enumerate() {
        let mut endpoints = Vec::with_capacity(chain_path.len());
        for ep in chain_path {
            let qualified: Vec<String> = if path_prefix.is_empty() {
                ep.path.clone()
            } else {
                // For internal wires lifted from a shape body, prefix the
                // endpoint with the host inst's id-path before resolution.
                let mut p = path_prefix.to_vec();
                p.extend(ep.path.iter().cloned());
                p
            };
            let resolved_path = match paths.resolve(&qualified) {
                Some(p) => p,
                None => {
                    let scope = if path_prefix.is_empty() {
                        "at scene root".to_string()
                    } else {
                        format!("in '{}'", path_prefix.join("."))
                    };
                    let mut msg =
                        format!("wire endpoint '{}' not found {}", ep.path.join("."), scope);
                    let suggestions =
                        paths.suggest(ep.path.last().expect("non-empty path"), path_prefix);
                    if !suggestions.is_empty() {
                        let quoted: Vec<String> =
                            suggestions.iter().map(|s| format!("'{}'", s)).collect();
                        msg.push_str(&format!("; did you mean {}?", quoted.join(", ")));
                    }
                    return Err(Error::at(ep.span, msg));
                }
            };
            endpoints.push(ResolvedEndpoint {
                path: resolved_path,
                side: ep.side,
                span: ep.span,
            });
        }
        out.push(ResolvedWire {
            endpoints,
            attrs: attrs.clone(),
            applied_styles: applied_styles.clone(),
            markers: markers.clone(),
            // A fan declaration's label is written once; cartesian expansion
            // would otherwise copy it onto every sibling.
            texts: if fan_index == 0 {
                texts.clone()
            } else {
                Vec::new()
            },
            span: w.span,
        });
    }
    Ok(out)
}

fn inject_line_style(attrs: &mut AttrMap, line: LineStyle) {
    let style = match line {
        LineStyle::Solid => return,
        LineStyle::Dashed => "dashed",
        LineStyle::Dotted => "dotted",
        // wavy isn't first-class in the renderer yet — tagged so render can
        // branch later.
        LineStyle::Wavy => "wavy",
    };
    // Don't override an explicit line attr.
    if attrs.get("line").is_none() {
        attrs.insert("line", ResolvedValue::Ident(style.into()));
    }
}

/// Take a wire chain and expand the cartesian fan-out across endpoint groups.
/// Result: each entry is one fully-flattened endpoint sequence (one wire).
fn expand_chain(chain: &[EndpointGroup]) -> Vec<Vec<WireEndpoint>> {
    let mut acc: Vec<Vec<WireEndpoint>> = vec![Vec::new()];
    for group in chain {
        let mut next: Vec<Vec<WireEndpoint>> =
            Vec::with_capacity(acc.len() * group.endpoints.len());
        for trail in &acc {
            for ep in &group.endpoints {
                let mut t = trail.clone();
                t.push(ep.clone());
                next.push(t);
            }
        }
        acc = next;
    }
    acc
}

// ─────────────────────────── Tests ───────────────────────────

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

    fn resolve_str(src: &str) -> Program {
        let tokens = crate::lexer::lex(src).expect("lex");
        let file = crate::parser::parse(&tokens).expect("parse");
        resolve(file).expect("resolve")
    }

    fn resolve_err(src: &str) -> Error {
        let tokens = crate::lexer::lex(src).expect("lex");
        let file = crate::parser::parse(&tokens).expect("parse");
        match resolve(file) {
            Ok(_) => panic!("expected resolve error"),
            Err(e) => e,
        }
    }

    #[test]
    fn single_letter_ids_are_legal() {
        let p = resolve_str("a -> b\n");
        let ids: Vec<&str> = p
            .scene
            .nodes
            .iter()
            .filter_map(|n| n.id.as_deref())
            .collect();
        assert!(ids.contains(&"a") && ids.contains(&"b"));
    }

    #[test]
    fn short_side_forms_are_plain_segments() {
        let e = resolve_err("p |rect|\nq |rect|\np.r -> q\n");
        assert!(e.message.contains("not found"), "got: {}", e.message);
    }

    #[test]
    fn long_side_forms_parse() {
        let p = resolve_str("p |rect|\nq |rect|\np -> q.left\n");
        assert_eq!(p.wires[0].endpoints[1].side, Some(crate::ast::Side::Left));
    }

    #[test]
    fn bare_name_no_longer_reaches_into_containers() {
        let e = resolve_err("kitchen |group| { inlet |rect|\noutlet |rect| }\noutlet -> inlet\n");
        assert!(
            e.message.contains("did you mean 'kitchen.outlet'"),
            "got: {}",
            e.message
        );
    }

    #[test]
    fn template_internals_error_with_suggestions_not_phantoms() {
        let e = resolve_err(
            "{ |room:group| { inlet |rect|\noutlet |rect| } }\n\
             closet |room|\nfridge |room|\noutlet -> inlet\n",
        );
        assert!(
            e.message.contains("closet.outlet") && e.message.contains("fridge.outlet"),
            "got: {}",
            e.message
        );
    }

    #[test]
    fn full_paths_resolve() {
        let p = resolve_str(
            "{ |room:group| { inlet |rect|\noutlet |rect| } }\n\
             closet |room|\nfridge |room|\ncloset.outlet -> fridge.inlet\n",
        );
        assert_eq!(p.wires[0].endpoints[0].path, "closet.outlet");
        assert_eq!(p.wires[0].endpoints[1].path, "fridge.inlet");
    }

    #[test]
    fn body_wire_sees_siblings() {
        let p = resolve_str("garden |group| { a1 |rect|\nb1 |rect|\na1 -> b1 }\n");
        assert_eq!(p.wires[0].endpoints[0].path, "garden.a1");
        assert_eq!(p.wires[0].endpoints[1].path, "garden.b1");
    }

    #[test]
    fn body_wire_cannot_see_out() {
        let e = resolve_err("outsider |rect|\ngarden |group| { a1 |rect|\na1 -> outsider }\n");
        assert!(e.message.contains("not found"), "got: {}", e.message);
    }

    #[test]
    fn body_wires_never_autocreate() {
        let e = resolve_err("garden |group| { a1 |rect|\na1 -> ghost }\n");
        assert!(e.message.contains("not found"), "got: {}", e.message);
    }

    #[test]
    fn typo_autocreates_when_absent_everywhere() {
        let p = resolve_str("alpha |rect|\nalpha -> betta\n");
        assert!(
            p.scene
                .nodes
                .iter()
                .any(|n| n.id.as_deref() == Some("betta"))
        );
    }

    #[test]
    fn deep_grandchild_needs_full_path_from_scope() {
        let e = resolve_err(
            "kitchen |group| { counter |group| { bowl |rect| } }\nkitchen.bowl -> kitchen\n",
        );
        assert!(
            e.message.contains("kitchen.counter.bowl"),
            "got: {}",
            e.message
        );
    }

    #[test]
    fn style_definition_order_decides() {
        for node in ["x |rect| .a .b\n", "x |rect| .b .a\n"] {
            let src = format!("{{ .a stroke:red\n  .b stroke:blue }}\n{}", node);
            let p = resolve_str(&src);
            let got = format!("{:?}", p.scene.nodes[0].attrs.get("stroke"));
            assert!(got.contains("blue"), "node {:?} → {}", node, got);
        }
    }

    #[test]
    fn inline_attrs_beat_styles_regardless_of_position() {
        let p = resolve_str("{ .a stroke:red }\nx |rect| stroke:green .a\n");
        let got = format!("{:?}", p.scene.nodes[0].attrs.get("stroke"));
        assert!(got.contains("green"), "got {}", got);
    }

    #[test]
    fn text_size_cascades_from_container() {
        let p = resolve_str("g |group| text-size:10 { t |text| \"hi\" }\n");
        let txt = &p.scene.nodes[0].children[0];
        assert_eq!(txt.attrs.number("text-size"), Some(10.0));
    }

    #[test]
    fn nearest_text_size_wins() {
        let p =
            resolve_str("g |group| text-size:10 { h |group| text-size:20 { t |text| \"hi\" } }\n");
        let txt = &p.scene.nodes[0].children[0].children[0];
        assert_eq!(txt.attrs.number("text-size"), Some(20.0));
    }

    #[test]
    fn own_text_attrs_beat_inherited() {
        let p = resolve_str("g |group| text-size:10 { t |text| \"hi\" text-size:8 }\n");
        let txt = &p.scene.nodes[0].children[0];
        assert_eq!(txt.attrs.number("text-size"), Some(8.0));
    }

    #[test]
    fn font_cascades_to_label_sugar() {
        let p = resolve_str("box |rect| \"Label\" font:serif\n");
        let txt = &p.scene.nodes[0].children[0];
        match txt.attrs.get("font") {
            Some(ResolvedValue::Ident(s)) => assert_eq!(s, "serif"),
            other => panic!("expected font=serif on sugar text, got {:?}", other),
        }
    }

    #[test]
    fn scene_text_size_reaches_all_text() {
        let p = resolve_str("{ |scene| text-size:15 }\nt |text| \"hi\"\n");
        let txt = &p.scene.nodes[0];
        assert_eq!(txt.attrs.number("text-size"), Some(15.0));
    }

    #[test]
    fn size_on_text_errors_with_hint() {
        let e = resolve_err("t |text| \"x\" size:11\n");
        assert!(e.message.contains("use 'text-size'"), "got: {}", e.message);
    }

    #[test]
    fn size_on_wire_text_errors_with_hint() {
        let e = resolve_err("a |rect|\nz |rect|\na -> z { |text| \"x\" size:9 }\n");
        assert!(e.message.contains("use 'text-size'"), "got: {}", e.message);
    }

    #[test]
    fn wire_text_accepts_style_refs() {
        let p = resolve_str(
            "{ .small text-size:9 }\na |rect|\nz |rect|\na -> z { |text| \"hi\" .small }\n",
        );
        match p.wires[0].texts[0].attrs.get("text-size") {
            Some(ResolvedValue::Number(n)) => assert_eq!(*n, 9.0),
            other => panic!(
                "expected text-size=9 from the .small style, got {:?}",
                other
            ),
        }
    }

    #[test]
    fn dashed_op_injects_line_attr() {
        let p = resolve_str("a |rect|\nz |rect|\na --> z\n");
        match p.wires[0].attrs.get("line") {
            Some(ResolvedValue::Ident(s)) => assert_eq!(s, "dashed"),
            other => panic!("expected line=dashed, got {:?}", other),
        }
    }

    #[test]
    fn explicit_line_attr_beats_operator() {
        let p = resolve_str("a |rect|\nz |rect|\na --> z line:dotted\n");
        match p.wires[0].attrs.get("line") {
            Some(ResolvedValue::Ident(s)) => assert_eq!(s, "dotted"),
            other => panic!("expected line=dotted, got {:?}", other),
        }
    }

    #[test]
    fn reserved_id_error_hints_capitalized_variant() {
        let e = resolve_err("start |rect|\n");
        assert!(e.message.contains("'Start' is free"), "got: {}", e.message);
    }

    #[test]
    fn marker_order_marker_before_marker_end() {
        let p = resolve_str(
            "cat |rect| \"Cat\"\n\
             dog |rect| \"Dog\"\n\
             cat -> dog marker:arrow marker-end:dot\n",
        );
        let w = &p.wires[0];
        assert_eq!(w.markers.start, MarkerKind::Arrow);
        assert_eq!(w.markers.end, MarkerKind::Dot);
    }

    #[test]
    fn wire_op_default_markers() {
        let p = resolve_str(
            "cat |rect| \"Cat\"\n\
             dog |rect| \"Dog\"\n\
             cat <-> dog\n",
        );
        let w = &p.wires[0];
        assert_eq!(w.markers.start, MarkerKind::Arrow);
        assert_eq!(w.markers.end, MarkerKind::Arrow);
    }

    #[test]
    fn defaults_override_layout_var_keeps_kind_and_bakes_value() {
        let p = resolve_str("{ --gap:30 }\nx |rect|\n");
        let entry = p.vars.get("gap").expect("gap present");
        assert_eq!(entry.kind, VarKind::Layout);
        match &entry.value {
            ResolvedValue::Number(n) => assert_eq!(*n, 30.0),
            other => panic!("expected Number(30), got {:?}", other),
        }
    }

    #[test]
    fn label_sugar_creates_text_child_on_non_text_shape() {
        let p = resolve_str("cat |rect| \"hello\"\n");
        let r = &p.scene.nodes[0];
        assert_eq!(r.shape, ShapeKind::Rect);
        assert!(r.label.is_none(), "non-text shape keeps no label");
        assert_eq!(r.children.len(), 1);
        let t = &r.children[0];
        assert_eq!(t.shape, ShapeKind::Text);
        assert_eq!(t.label.as_deref(), Some("hello"));
    }

    #[test]
    fn text_label_stays_on_text_inst() {
        let p = resolve_str("cat |text| \"hello\"\n");
        let t = &p.scene.nodes[0];
        assert_eq!(t.shape, ShapeKind::Text);
        assert_eq!(t.label.as_deref(), Some("hello"));
        assert!(t.children.is_empty());
    }

    #[test]
    fn shape_inheritance_resolves_to_primitive_kind() {
        let p = resolve_str("{ |treat:rect| radius:5 }\ncat |treat| \"Cat\"\n");
        let n = &p.scene.nodes[0];
        assert_eq!(n.shape, ShapeKind::Rect);
        assert!(n.attrs.get("radius").is_some());
    }

    #[test]
    fn wire_auto_creates_undeclared_endpoints() {
        let p = resolve_str("cat -> dog\n");
        // Both `cat` and `dog` auto-created as rects.
        assert_eq!(p.scene.nodes.len(), 2);
        let ids: Vec<&str> = p
            .scene
            .nodes
            .iter()
            .filter_map(|n| n.id.as_deref())
            .collect();
        assert!(ids.contains(&"cat"));
        assert!(ids.contains(&"dog"));
    }

    #[test]
    fn wire_fan_expands_cartesian() {
        let p = resolve_str("cat & fox -> bird & mouse\n");
        assert_eq!(p.wires.len(), 4);
    }

    #[test]
    fn fan_label_is_not_duplicated_across_siblings() {
        // `a -> b & c "shared"` expands to two wires; the one declared label
        // rides a single sibling (E2 — drawn once), not each of them.
        let p = resolve_str(
            "src |rect|\n\
             one |rect|\n\
             two |rect|\n\
             src -> one & two \"shared\"\n",
        );
        assert_eq!(p.wires.len(), 2);
        let labelled = p.wires.iter().filter(|w| !w.texts.is_empty()).count();
        assert_eq!(labelled, 1, "the fan label rides one sibling, not each");
    }
}