graphcal-compiler 0.0.1-alpha.14

Type-safe, unit-aware, Git-friendly reactive programming language for engineering calculations
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
use super::*;
use crate::syntax::parser::Parser;

fn make_src(source: &str) -> NamedSource<Arc<String>> {
    NamedSource::new("test", Arc::new(source.to_string()))
}

fn parse_and_desugar(source: &str) -> crate::desugar::desugared_ast::File {
    let raw_file = Parser::new(source).parse_file().unwrap();
    crate::syntax::desugar::desugar_multi_decls_in_file(raw_file)
}

fn parse_and_resolve(source: &str) -> Result<ResolvedFile, GraphcalError> {
    let file = parse_and_desugar(source);
    resolve(&file, &make_src(source))
}

/// Run the full per-file pipeline (desugar → IR → HIR/TIR) so tests can
/// observe reference resolution and the HIR-derived dependency graph.
fn compile_to_tir(source: &str) -> Result<crate::tir::typed::TIR, GraphcalError> {
    let file = parse_and_desugar(source);
    let src = NamedSource::new("test.gcl", Arc::new(source.to_string()));
    let dag_id =
        crate::dag_id::DagId::from_relative_path(std::path::Path::new("test.gcl")).unwrap();
    let ir = crate::ir::lower::lower(&file, &src)?;
    let mut resolver = crate::syntax::module_resolve::ModuleResolver::default();
    resolver
        .add_module(dag_id.clone(), &file.declarations)
        .unwrap();
    let mut module_types = crate::tir::typed::ModuleTypeRegistry::default();
    module_types.insert_graphcal_prelude().unwrap();
    module_types.insert_registry(&dag_id, &ir.registry);
    crate::tir::typed::type_resolve_with_modules(ir, dag_id, &src, &resolver, &module_types)
}

/// Dependency names of `decl` in `map`, as leaf strings.
fn dep_names_of<'a>(
    map: &'a std::collections::HashMap<
        crate::syntax::names::ResolvedName<crate::syntax::names::namespace::Decl>,
        std::collections::BTreeSet<
            crate::syntax::names::ResolvedName<crate::syntax::names::namespace::Decl>,
        >,
    >,
    decl: &str,
) -> Vec<&'a str> {
    map.iter()
        .find(|(key, _)| key.as_str() == decl)
        .map(|(_, deps)| {
            deps.iter()
                .map(crate::syntax::names::ResolvedName::as_str)
                .collect()
        })
        .unwrap_or_default()
}

#[test]
fn resolve_rocket_ksr() {
    let source = include_str!("../../../../../tests/fixtures/valid/rocket.gcl");
    let file = parse_and_desugar(source);
    let resolved = resolve(&file, &make_src(source)).unwrap();
    assert_eq!(resolved.consts.len(), 1);
    assert_eq!(resolved.params.len(), 3);
    assert_eq!(resolved.nodes.len(), 3);
}

#[test]
fn resolve_constants_ksr() {
    let source = include_str!("../../../../../tests/fixtures/valid/constants.gcl");
    let file = parse_and_desugar(source);
    let resolved = resolve(&file, &make_src(source)).unwrap();
    assert_eq!(resolved.consts.len(), 4);
    assert_eq!(resolved.params.len(), 1);
    assert_eq!(resolved.nodes.len(), 2);
}

#[test]
fn resolve_duplicate_name() {
    let err = parse_and_resolve("param x: Dimensionless = 1.0;\nnode x: Dimensionless = 2.0;")
        .unwrap_err();
    assert!(matches!(err, GraphcalError::DuplicateName { .. }));
}

#[test]
fn resolve_rejects_type_index_name_collision() {
    let err =
        parse_and_resolve("type M { Mk(v: Dimensionless) }\npub index M = { A, B };").unwrap_err();
    assert!(matches!(
        err,
        GraphcalError::DuplicateName { ref name, .. } if name == "M"
    ));
}

#[test]
fn resolve_rejects_dimension_index_name_collision() {
    let err = parse_and_resolve("dim M = Length;\npub index M = { A, B };").unwrap_err();
    assert!(matches!(
        err,
        GraphcalError::DuplicateName { ref name, .. } if name == "M"
    ));
}

#[test]
fn resolve_rejects_dimension_type_name_collision() {
    let err = parse_and_resolve("dim M = Length;\ntype M { Mk(v: Dimensionless) }").unwrap_err();
    assert!(matches!(
        err,
        GraphcalError::DuplicateName { ref name, .. } if name == "M"
    ));
}

#[test]
fn resolve_rejects_value_index_name_collision() {
    let err =
        parse_and_resolve("param M: Dimensionless = 1.0;\npub index M = { A, B };").unwrap_err();
    assert!(matches!(
        err,
        GraphcalError::DuplicateName { ref name, .. } if name == "M"
    ));
}

#[test]
fn resolve_allows_index_name_matching_prelude_unit_name() {
    let tir = compile_to_tir(
        "pub index s = { A };
         param sample: Time[s] = { s.A: 1.0 s };",
    )
    .unwrap();

    assert_eq!(tir.root().params.len(), 1);
}

#[test]
fn resolve_rejects_builtin_dimension_shadowing() {
    let err = parse_and_resolve("dim Velocity = Length / Time;").unwrap_err();
    assert!(matches!(err, GraphcalError::BuiltinNameShadowed { name, .. } if name == "Velocity"));
}

#[test]
fn resolve_rejects_builtin_unit_shadowing() {
    let err = parse_and_resolve("unit m: Length = 1.0 m;").unwrap_err();
    assert!(matches!(err, GraphcalError::BuiltinNameShadowed { name, .. } if name == "m"));
}

#[test]
fn resolve_unknown_graph_ref() {
    // Unknown `@` targets are rejected by HIR lowering during type
    // resolution — the IR collection pass no longer classifies references.
    let err = compile_to_tir("node x: Dimensionless = @nonexistent + 1.0;").unwrap_err();
    assert!(
        err.to_string().contains("nonexistent"),
        "unexpected error: {err}"
    );
}

#[test]
fn resolve_unknown_bare_name_is_rejected_in_hir_lowering() {
    // A bare name that matches nothing in scope is rejected by HIR lowering
    // with an unknown-name diagnostic; there is no fallback classification.
    let err = compile_to_tir("node x: Dimensionless = NONEXISTENT + 1.0;").unwrap_err();
    assert!(
        err.to_string().contains("NONEXISTENT"),
        "unexpected error: {err}"
    );
}

#[test]
fn resolve_at_in_const() {
    let err =
        compile_to_tir("param p: Dimensionless = 1.0;\nconst node bad: Dimensionless = @p * 2.0;")
            .unwrap_err();
    assert!(matches!(err, GraphcalError::GraphRefInConst { .. }));
}

#[test]
fn parser_accepts_any_const_casing() {
    let file = Parser::new("const node BAD_NAME: Dimensionless = 42.0;")
        .parse_file()
        .unwrap();
    assert_eq!(file.declarations.len(), 1);
}

#[test]
fn parser_accepts_any_param_casing() {
    let file = Parser::new("param BAD: Dimensionless = 42.0;")
        .parse_file()
        .unwrap();
    assert_eq!(file.declarations.len(), 1);
}

#[test]
fn resolve_builtin_const_recognized() {
    let resolved = parse_and_resolve("node x: Dimensionless = PI * 2.0;").unwrap();
    assert_eq!(resolved.nodes.len(), 1);
}

#[test]
fn resolve_builtin_function_recognized() {
    let resolved =
        parse_and_resolve("param x: Dimensionless = 4.0;\nnode y: Dimensionless = sqrt(@x);")
            .unwrap();
    assert_eq!(resolved.nodes.len(), 1);
}

#[test]
fn resolve_unknown_function() {
    let err = compile_to_tir("node x: Dimensionless = unknown_fn(1.0);").unwrap_err();
    assert!(matches!(err, GraphcalError::UnknownFunction { .. }));
}

#[test]
fn resolve_wrong_arity() {
    let err = compile_to_tir("node x: Dimensionless = sqrt(1.0, 2.0);").unwrap_err();
    assert!(matches!(err, GraphcalError::WrongArity { .. }));
}

#[test]
fn resolve_const_deps_extracted() {
    let tir = compile_to_tir(
        "const node a: Dimensionless = 1.0;\nconst node b: Dimensionless = @a + 2.0;",
    )
    .unwrap();
    let deps = &tir.root().semantic.dependencies;
    assert_eq!(dep_names_of(&deps.const_deps, "b"), ["a"]);
}

#[test]
fn resolve_runtime_deps_extracted() {
    let tir =
        compile_to_tir("param a: Dimensionless = 1.0;\nparam b: Dimensionless = 2.0;\nnode c: Dimensionless = @a + @b;").unwrap();
    let deps = &tir.root().semantic.dependencies;
    assert_eq!(dep_names_of(&deps.runtime_deps, "c"), ["a", "b"]);
}

// --- Additional error path tests ---

#[test]
fn resolve_duplicate_param_name() {
    let err = parse_and_resolve("param x: Dimensionless = 1.0;\nparam x: Dimensionless = 2.0;")
        .unwrap_err();
    assert!(matches!(err, GraphcalError::DuplicateName { .. }));
}

#[test]
fn resolve_duplicate_const_name() {
    let err =
        parse_and_resolve("const node a: Dimensionless = 1.0;\nconst node a: Dimensionless = 2.0;")
            .unwrap_err();
    assert!(matches!(err, GraphcalError::DuplicateName { .. }));
}

#[test]
fn resolve_duplicate_node_name() {
    let err = parse_and_resolve(
        "param x: Dimensionless = 1.0;\nnode y: Dimensionless = @x;\nnode y: Dimensionless = @x + 1.0;",
    )
    .unwrap_err();
    assert!(matches!(err, GraphcalError::DuplicateName { .. }));
}

#[test]
fn resolve_constructor_collision_with_node() {
    let err = parse_and_resolve(
        "type Student { Student(mass: Dimensionless), }\nnode Student: Dimensionless = 1.0;",
    )
    .unwrap_err();
    assert!(matches!(
        err,
        GraphcalError::DuplicateName { ref name, .. } if name == "Student"
    ));
}

#[test]
fn resolve_const_collision_with_param() {
    // const and param both use lower_snake_case — different names → no collision
    let resolved =
        parse_and_resolve("const node a: Dimensionless = 1.0;\nparam b: Dimensionless = 2.0;")
            .unwrap();
    assert_eq!(resolved.consts.len(), 1);
    assert_eq!(resolved.params.len(), 1);
}

#[test]
fn resolve_unknown_bare_name_in_const_becomes_local_ref() {
    // After lifting casing requirements, bare `NONEXISTENT` is parsed as an unresolved path
    // and resolved to LocalRef (fallback). The resolve pass no longer rejects it;
    // the error is caught later in the TIR dim-check phase as UnknownLocalRef.
    let resolved = parse_and_resolve("const node a: Dimensionless = NONEXISTENT + 1.0;").unwrap();
    assert_eq!(resolved.consts.len(), 1);
}

#[test]
fn resolve_unknown_function_in_const() {
    let err = compile_to_tir("const node a: Dimensionless = unknown_fn(1.0);").unwrap_err();
    assert!(matches!(err, GraphcalError::UnknownFunction { .. }));
}

#[test]
fn resolve_wrong_arity_in_const() {
    let err = compile_to_tir("const node a: Dimensionless = sqrt(1.0, 2.0);").unwrap_err();
    assert!(matches!(err, GraphcalError::WrongArity { .. }));
}

#[test]
fn resolve_unknown_graph_ref_in_node() {
    let err = compile_to_tir("param x: Dimensionless = 1.0;\nnode y: Dimensionless = @z + 1.0;")
        .unwrap_err();
    assert!(err.to_string().contains('z'), "unexpected error: {err}");
}

#[test]
fn resolve_unknown_function_in_node() {
    let err = compile_to_tir("param x: Dimensionless = 1.0;\nnode y: Dimensionless = bad_fn(@x);")
        .unwrap_err();
    assert!(matches!(err, GraphcalError::UnknownFunction { .. }));
}

#[test]
fn resolve_wrong_arity_in_node() {
    let err =
        compile_to_tir("param x: Dimensionless = 1.0;\nnode y: Dimensionless = sqrt(@x, @x);")
            .unwrap_err();
    assert!(matches!(err, GraphcalError::WrongArity { .. }));
}

#[test]
fn resolve_const_with_if_else() {
    let resolved =
        parse_and_resolve("const node a: Dimensionless = if 1.0 > 0.0 { 1.0 } else { 0.0 };")
            .unwrap();
    assert_eq!(resolved.consts.len(), 1);
}

#[test]
fn resolve_const_with_unary_op() {
    let resolved = parse_and_resolve("const node a: Dimensionless = -42.0;").unwrap();
    assert_eq!(resolved.consts.len(), 1);
}

#[test]
fn resolve_node_with_struct() {
    let resolved = parse_and_resolve(
        r"
        type Pair { Pair(a: Dimensionless, b: Dimensionless) }
        param x: Dimensionless = 1.0;
        node p: Pair = Pair(a: @x, b: @x + 1.0);
    ",
    )
    .unwrap();
    assert_eq!(resolved.nodes.len(), 1);
}

#[test]
fn resolve_node_with_field_access() {
    let resolved = parse_and_resolve(
        r"
        type Pair { Pair(a: Dimensionless, b: Dimensionless) }
        param x: Dimensionless = 1.0;
        node p: Pair = Pair(a: @x, b: @x + 1.0);
        node val: Dimensionless = @p.a;
    ",
    )
    .unwrap();
    assert_eq!(resolved.nodes.len(), 2);
}

#[test]
fn resolve_node_with_convert() {
    let resolved =
        parse_and_resolve("param x: Length = 1000.0 m;\nnode y: Length = @x -> km;").unwrap();
    assert_eq!(resolved.nodes.len(), 1);
}

#[test]
fn resolve_import_decl_skipped() {
    // import declarations should not be treated as param/node/const
    let source = "import helper.{something};";
    let file = parse_and_desugar(source);
    let resolved = resolve(&file, &make_src(source)).unwrap();
    assert!(resolved.params.is_empty());
    assert!(resolved.nodes.is_empty());
    assert!(resolved.consts.is_empty());
}

#[test]
fn resolve_indexed_param() {
    let resolved = parse_and_resolve(
        r"
        pub index Color = { Red, Green, Blue };
        param values: Dimensionless[Color] = {
            Color.Red: 1.0,
            Color.Green: 2.0,
            Color.Blue: 3.0,
        };
    ",
    )
    .unwrap();
    assert_eq!(resolved.params.len(), 1);
}

#[test]
fn resolve_for_comprehension() {
    let resolved = parse_and_resolve(
        r"
        pub index Color = { Red, Green, Blue };
        param values: Dimensionless[Color] = {
            Color.Red: 1.0,
            Color.Green: 2.0,
            Color.Blue: 3.0,
        };
        node doubled: Dimensionless[Color] = for c: Color { @values[c] * 2.0 };
    ",
    )
    .unwrap();
    assert_eq!(resolved.nodes.len(), 1);
}

#[test]
fn resolve_scan_expression() {
    let resolved = parse_and_resolve(
        r"
        pub index Step = { First, Second, Third };
        param vals: Dimensionless[Step] = {
            Step.First: 1.0,
            Step.Second: 2.0,
            Step.Third: 3.0,
        };
        node cumul: Dimensionless[Step] = scan(@vals, 0.0, |acc, val| acc + val);
    ",
    )
    .unwrap();
    assert_eq!(resolved.nodes.len(), 1);
}

#[test]
fn resolve_unfold_self_edge_excluded() {
    // The unfold body references @x[prev_t], which creates a self-reference.
    // extract_all_refs should exclude this self-edge from runtime_deps.
    let source = r"
        index TimeStep = { First, Second, Third };
        node x: Dimensionless[TimeStep] = unfold(1.0, |prev_t, t| @x[prev_t] * 2.0);
    ";
    let tir = compile_to_tir(source).unwrap();
    let deps = &tir.root().semantic.dependencies;
    assert!(
        !dep_names_of(&deps.runtime_deps, "x").contains(&"x"),
        "unfold self-reference should be excluded from runtime_deps"
    );
}

// --- Visibility tests ---

#[test]
fn resolve_required_param_is_implicitly_bindable() {
    // Post-A5: `param` never carries `pub`; a bare required param is
    // implicitly visible + bindable at the include site.
    let source = r"
        param x: Dimensionless;
    ";
    parse_and_resolve(source).unwrap();
}

// `pub param` / `pub(bind) param` are rejected at parse time; see
// `syntax::parser::decl::tests` for parser-level coverage.

#[test]
fn resolve_required_index_must_be_bindable() {
    let source = r"
        index Phase;
    ";
    let err = parse_and_resolve(source).unwrap_err();
    assert!(
        matches!(err, GraphcalError::RequiredItemMustBeBindable { kind, .. } if kind == "index")
    );
}

#[test]
fn resolve_required_pub_index_still_needs_bind() {
    // `pub index Phase;` is now rejected: required indexes must be
    // `pub(bind)` because A4 forces bindability.
    let source = r"
        pub index Phase;
    ";
    let err = parse_and_resolve(source).unwrap_err();
    assert!(
        matches!(err, GraphcalError::RequiredItemMustBeBindable { kind, .. } if kind == "index")
    );
}

#[test]
fn resolve_pub_bind_required_index_ok() {
    let source = r"
        pub(bind) index Phase;
    ";
    parse_and_resolve(source).unwrap();
}

#[test]
fn resolve_required_type_must_be_bindable() {
    let source = r"
        type Element;
    ";
    let err = parse_and_resolve(source).unwrap_err();
    assert!(
        matches!(err, GraphcalError::RequiredItemMustBeBindable { kind, .. } if kind == "type")
    );
}

#[test]
fn resolve_pub_bind_required_type_ok() {
    let source = r"
        pub(bind) type Element;
    ";
    parse_and_resolve(source).unwrap();
}

#[test]
fn resolve_required_dim_must_be_bindable() {
    let source = r"
        dim D;
    ";
    let err = parse_and_resolve(source).unwrap_err();
    assert!(matches!(err, GraphcalError::RequiredItemMustBeBindable { kind, .. } if kind == "dim"));
}

#[test]
fn resolve_pub_bind_required_dim_ok() {
    let source = r"
        pub(bind) dim D;
    ";
    parse_and_resolve(source).unwrap();
}

#[test]
fn resolve_private_in_public_dim() {
    // V003 is triggered by a pub node (not pub param, which is rejected).
    let source = r"
        dim Speed = Length / Time;
        param kmh: Speed = 36.0 km/h;
        pub node speed: Speed = @kmh;
    ";
    let err = parse_and_resolve(source).unwrap_err();
    assert!(matches!(err, GraphcalError::PrivateInPublic { ref_name, .. } if ref_name == "Speed"));
}

#[test]
fn resolve_private_in_public_ok_when_dim_is_pub() {
    let source = r"
        pub dim Speed = Length / Time;
        param kmh: Speed = 36.0 km/h;
        pub node speed: Speed = @kmh;
    ";
    parse_and_resolve(source).unwrap();
}

#[test]
fn resolve_private_in_public_ok_for_builtin_dims() {
    // Built-in dimensions (Length, Time, etc.) don't need to be `pub`.
    let source = r"
        param origin: Length = 1.0 m;
        pub node distance: Length = @origin;
    ";
    parse_and_resolve(source).unwrap();
}

#[test]
fn resolve_private_in_public_index_in_type() {
    let source = r"
        pub index Phase = { Alpha, Beta };
        index Step = { Xray, Yankee };
        pub node costs: Dimensionless[Phase, Step] = { Phase.Alpha: { Step.Xray: 1.0, Step.Yankee: 2.0 }, Phase.Beta: { Step.Xray: 3.0, Step.Yankee: 4.0 } };
    ";
    let err = parse_and_resolve(source).unwrap_err();
    // May get PubIndexVariantLiteral before PrivateInPublic.
    assert!(
        matches!(err, GraphcalError::PrivateInPublic { ref ref_name, .. } if ref_name == "Step")
            || matches!(err, GraphcalError::PubIndexVariantLiteral { .. }),
        "expected PrivateInPublic or PubIndexVariantLiteral error, got: {err:?}"
    );
}

#[test]
fn resolve_pub_names_collected() {
    let source = r"
        pub dim Speed = Length / Time;
        pub dim GravityAccel = Length / Time^2;
        pub const node g0: GravityAccel = 9.80665 m/s^2;
        node speed: Speed = 10.0 m/s;
    ";
    let resolved = parse_and_resolve(source).unwrap();
    assert!(resolved.pub_names.contains("Speed"));
    assert!(resolved.pub_names.contains("GravityAccel"));
    assert!(resolved.pub_names.contains("g0"));
    assert!(!resolved.pub_names.contains("speed"));
}

#[test]
fn resolve_param_default_with_pub_bind_variant_literal_ok() {
    // A10(a): `param` is implicitly bindable, so a variant literal of a
    // `pub(bind)` index in a param default is allowed — V005 at the
    // include site will ensure the importer re-binds the param when it
    // rebinds the index.
    let source = r"
        pub(bind) index Phase = { Design, Build, Test };
        param cost: Dimensionless[Phase] = {
            Phase.Design: 100.0,
            Phase.Build: 200.0,
            Phase.Test: 50.0,
        };
    ";
    parse_and_resolve(source).unwrap();
}

#[test]
fn resolve_node_with_pub_bind_variant_literal_fires_v004() {
    // A10(c): `node` is non-bindable, so a variant literal of a
    // `pub(bind)` index in a node body would orphan under rebinding.
    let source = r"
        pub(bind) index Phase = { Design, Build, Test };
        param cost: Dimensionless[Phase] = {
            Phase.Design: 1.0,
            Phase.Build: 2.0,
            Phase.Test: 3.0,
        };
        node design_cost: Dimensionless = @cost[Phase.Design];
    ";
    let err = compile_to_tir(source).unwrap_err();
    assert!(matches!(err, GraphcalError::PubIndexVariantLiteral { .. }));
}

#[test]
fn resolve_const_with_pub_bind_variant_literal_fires_v004() {
    let source = r"
        pub(bind) index Phase = { Design, Build };
        pub const node costs: Dimensionless[Phase] = {
            Phase.Design: 1.0,
            Phase.Build: 2.0,
        };
    ";
    let err = compile_to_tir(source).unwrap_err();
    assert!(matches!(err, GraphcalError::PubIndexVariantLiteral { .. }));
}

#[test]
fn resolve_private_assert_with_pub_bind_variant_literal_ok() {
    // A10(b) carve-out: private sink kinds are pruned from the merged
    // IR when the file is used as a library, so literal mentions of
    // `Phase.v` cannot orphan anything under override.
    let source = r"
        pub(bind) index Phase = { Design, Build };
        param cost: Dimensionless[Phase] = {
            Phase.Design: 1.0,
            Phase.Build: 2.0,
        };
        assert design_cheap = @cost[Phase.Design] < 10.0;
    ";
    compile_to_tir(source).unwrap();
}

#[test]
fn resolve_public_assert_with_pub_bind_variant_literal_fires_v004() {
    // A10(b): public sinks travel with the include and must abstract
    // over pub(bind) indexes.
    let source = r"
        pub(bind) index Phase = { Design, Build };
        param cost: Dimensionless[Phase] = {
            Phase.Design: 1.0,
            Phase.Build: 2.0,
        };
        pub assert design_cheap = @cost[Phase.Design] < 10.0;
    ";
    let err = compile_to_tir(source).unwrap_err();
    assert!(matches!(err, GraphcalError::PubIndexVariantLiteral { .. }));
}

#[test]
fn resolve_node_with_plain_pub_variant_literal_ok() {
    // Plain `pub` (fixed) indexes are not bindable, so A10 does not
    // fire on their variant literals; importers cannot override them.
    let source = r"
        pub index Phase = { Design, Build };
        pub const node costs: Dimensionless[Phase] = {
            Phase.Design: 1.0,
            Phase.Build: 2.0,
        };
    ";
    parse_and_resolve(source).unwrap();
}

#[test]
fn resolve_param_with_private_dim_fires_v003() {
    // `param` is implicitly visible (A5 §4.0), so a private dim in a
    // param's signature is V003 (A9 case 1).
    let source = r"
        dim Speed = Length / Time;
        param speed: Speed = 10.0 m/s;
    ";
    let err = parse_and_resolve(source).unwrap_err();
    assert!(matches!(err, GraphcalError::PrivateInPublic { ref_name, .. } if ref_name == "Speed"));
}

#[test]
fn resolve_param_with_pub_dim_ok() {
    let source = r"
        pub dim Speed = Length / Time;
        param speed: Speed = 10.0 m/s;
    ";
    parse_and_resolve(source).unwrap();
}

#[test]
fn resolve_pub_dim_with_private_dim_fires_v003() {
    // A9 case 1 also applies to dim/unit/type/index signatures.
    let source = r"
        dim Inner = Length;
        pub dim Outer = Inner / Time;
    ";
    let err = parse_and_resolve(source).unwrap_err();
    assert!(
        matches!(err, GraphcalError::PrivateInPublic { pub_kind, ref_name, .. }
            if pub_kind == "dim" && ref_name == "Inner")
    );
}

#[test]
fn resolve_pub_type_with_private_field_type_fires_v003() {
    let source = r"
        type Inner { Inner }
        pub type Outer { Outer(inner: Inner) }
    ";
    let err = parse_and_resolve(source).unwrap_err();
    assert!(
        matches!(err, GraphcalError::PrivateInPublic { pub_kind, ref_name, .. }
            if pub_kind == "type" && ref_name == "Inner")
    );
}

#[test]
fn resolve_pub_union_type_with_private_payload_type_fires_v003() {
    // Under the constructor-list union design, variants no longer
    // reference other types by name in the union signature. The A9
    // dependency from a `pub` union to a private type now flows through
    // a variant's payload field type. (See issue #601.)
    let source = r"
        type Inner { Inner }
        pub type Result {
          Ok,
          Err(detail: Inner),
        }
    ";
    let err = parse_and_resolve(source).unwrap_err();
    assert!(
        matches!(err, GraphcalError::PrivateInPublic { pub_kind, ref_name, .. }
            if pub_kind == "type" && ref_name == "Inner")
    );
}

#[test]
fn resolve_pub_bind_index_with_private_dim_fires_v003() {
    // A required range index carries a dim constraint that participates
    // in A9 case 1.
    let source = r"
        dim Rate = Time^-1;
        pub(bind) index Channel: Rate;
    ";
    let err = parse_and_resolve(source).unwrap_err();
    assert!(
        matches!(err, GraphcalError::PrivateInPublic { pub_kind, ref_name, .. }
            if pub_kind == "index" && ref_name == "Rate")
    );
}

#[test]
fn resolve_pub_unit_with_private_dim_fires_v003() {
    let source = r"
        dim Currency = Length;
        pub const unit usd: Currency = 1.0 m;
    ";
    let err = parse_and_resolve(source).unwrap_err();
    assert!(
        matches!(err, GraphcalError::PrivateInPublic { pub_kind, ref_name, .. }
            if pub_kind == "unit" && ref_name == "Currency")
    );
}