elm-ast 0.2.1

A syn-quality Rust library for parsing and constructing Elm 0.19.1 ASTs
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
#![cfg(not(target_arch = "wasm32"))]

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use elm_ast::declaration::Declaration;
use elm_ast::expr::Expr;
use elm_ast::file::ElmModule;
use elm_ast::pattern::Pattern;
use elm_ast::type_annotation::TypeAnnotation;
use elm_ast::{parse, pretty_print, pretty_print_converged, print};

// ── Regression watchlist ─────────────────────────────────────────────
//
// These files were the hardest to get right and are the most likely to
// regress. If a parser or printer change breaks the suite, check these first.
//
// 1. elm-community/typed-svg — Examples/GradientsPatterns.elm
//    Problem: Inside list literals like `[ linearGradient [...] [...], ... ]`,
//    function application args can appear at the *same* column as the function
//    name (both indented to the bracket's column). The standard application_loop
//    column check (`arg_col <= func_col`) rejected these as not-indented-enough.
//    Fix: `app_context_col` — list/record parsers set the opening bracket's
//    column as the reference for application_loop, relaxing the check to
//    `arg_col <= bracket_col` instead of `arg_col <= func_col`.
//
// 2. mdgriffith/elm-animator — src/Animator.elm
//    Problem: The printer output multiline function applications inline
//    (space-separated), causing subsequent args to land at columns far below
//    the function name after a multiline lambda/parenthesized arg. On re-parse,
//    application_loop rejected those args.
//    Fix: Vertical application layout — when any non-function arg is multiline,
//    each arg is emitted on its own indented line. Also, multiline record setter
//    values are placed on new indented lines so function names within them start
//    near the indent column.
//
// Other packages with non-trivial coverage (complex patterns, deep nesting,
// heavy operator use, GLSL blocks, large files):
//   - folkertdev/elm-flate (large generated decompression tables)
//   - dillonkearns/elm-markdown (deep nesting, complex case expressions)
//   - rtfeldman/elm-css (heavy operator use, many record updates)
//   - elm-explorations/webgl (GLSL shader blocks)
//   - elm/core (infix declarations, wide variety of patterns)

// ── Fixture discovery ────────────────────────────────────────────────

fn all_fixture_dirs() -> Vec<(&'static str, &'static str)> {
    vec![
        // ── elm/* ───────────────────────────────────────────────
        ("elm/core", "test-fixtures/core/src"),
        ("elm/html", "test-fixtures/html/src"),
        ("elm/browser", "test-fixtures/browser/src"),
        ("elm/json", "test-fixtures/json/src"),
        ("elm/http", "test-fixtures/http/src"),
        ("elm/url", "test-fixtures/url/src"),
        ("elm/parser", "test-fixtures/parser/src"),
        ("elm/virtual-dom", "test-fixtures/virtual-dom/src"),
        ("elm/bytes", "test-fixtures/bytes/src"),
        ("elm/file", "test-fixtures/file/src"),
        ("elm/time", "test-fixtures/time/src"),
        ("elm/regex", "test-fixtures/regex/src"),
        ("elm/random", "test-fixtures/random/src"),
        ("elm/svg", "test-fixtures/svg/src"),
        ("elm/compiler", "test-fixtures/compiler/reactor/src"),
        (
            "elm/project-metadata-utils",
            "test-fixtures/project-metadata-utils/src",
        ),
        // ── elm-explorations/* ──────────────────────────────────
        ("elm-explorations/test", "test-fixtures/test/src"),
        ("elm-explorations/markdown", "test-fixtures/markdown/src"),
        (
            "elm-explorations/linear-algebra",
            "test-fixtures/linear-algebra/src",
        ),
        ("elm-explorations/webgl", "test-fixtures/webgl/src"),
        ("elm-explorations/benchmark", "test-fixtures/benchmark/src"),
        // ── elm-community/* ─────────────────────────────────────
        ("elm-community/list-extra", "test-fixtures/list-extra/src"),
        ("elm-community/maybe-extra", "test-fixtures/maybe-extra/src"),
        (
            "elm-community/string-extra",
            "test-fixtures/string-extra/src",
        ),
        ("elm-community/dict-extra", "test-fixtures/dict-extra/src"),
        ("elm-community/array-extra", "test-fixtures/array-extra/src"),
        (
            "elm-community/result-extra",
            "test-fixtures/result-extra/src",
        ),
        ("elm-community/html-extra", "test-fixtures/html-extra/src"),
        ("elm-community/json-extra", "test-fixtures/json-extra/src"),
        ("elm-community/typed-svg", "test-fixtures/typed-svg/src"),
        // ── NoRedInk/* ──────────────────────────────────────────
        (
            "NoRedInk/elm-json-decode-pipeline",
            "test-fixtures/elm-json-decode-pipeline/src",
        ),
        (
            "NoRedInk/elm-sweet-poll",
            "test-fixtures/elm-sweet-poll/src",
        ),
        ("NoRedInk/elm-compare", "test-fixtures/elm-compare/src"),
        (
            "NoRedInk/elm-string-conversions",
            "test-fixtures/elm-string-conversions/src",
        ),
        (
            "NoRedInk/elm-sortable-table",
            "test-fixtures/elm-sortable-table/src",
        ),
        // ── rtfeldman/* ─────────────────────────────────────────
        ("rtfeldman/elm-css", "test-fixtures/elm-css/src"),
        ("rtfeldman/elm-hex", "test-fixtures/elm-hex/src"),
        (
            "rtfeldman/elm-iso8601-date-strings",
            "test-fixtures/elm-iso8601-date-strings/src",
        ),
        // ── Other widely-used packages ──────────────────────────
        ("mdgriffith/elm-ui", "test-fixtures/elm-ui/src"),
        ("mdgriffith/elm-animator", "test-fixtures/elm-animator/src"),
        (
            "dillonkearns/elm-markdown",
            "test-fixtures/elm-markdown/src",
        ),
        ("krisajenkins/remotedata", "test-fixtures/remotedata/src"),
        ("robinheghan/murmur3", "test-fixtures/murmur3/src"),
        ("myrho/elm-round", "test-fixtures/elm-round/src"),
        ("truqu/elm-base64", "test-fixtures/elm-base64/src"),
        ("folkertdev/elm-flate", "test-fixtures/elm-flate/src"),
        ("BrianHicks/elm-csv", "test-fixtures/elm-csv/src"),
        ("zwilias/elm-rosetree", "test-fixtures/elm-rosetree/src"),
        ("pzp1997/assoc-list", "test-fixtures/assoc-list/src"),
        (
            "Chadtech/elm-bool-extra",
            "test-fixtures/elm-bool-extra/src",
        ),
    ]
}

fn find_elm_files(dir: &str) -> Vec<PathBuf> {
    let mut files = Vec::new();
    let dir = PathBuf::from(dir);
    if !dir.exists() {
        return files;
    }
    collect_elm_files(&dir, &mut files);
    files.sort();
    files
}

fn collect_elm_files(dir: &PathBuf, files: &mut Vec<PathBuf>) {
    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                collect_elm_files(&path, files);
            } else if path.extension().is_some_and(|ext| ext == "elm") {
                files.push(path);
            }
        }
    }
}

// ── Helpers ──────────────────────────────────────────────────────────

fn try_parse_file(path: &PathBuf) -> Result<ElmModule, String> {
    let source =
        fs::read_to_string(path).map_err(|e| format!("failed to read {}: {e}", path.display()))?;

    parse(&source).map_err(|errors| {
        let error_msgs: Vec<String> = errors.iter().map(|e| format!("  {e}")).collect();
        format!(
            "failed to parse {}:\n{}",
            path.display(),
            error_msgs.join("\n")
        )
    })
}

fn try_round_trip_file(path: &PathBuf) -> Result<(), String> {
    let source =
        fs::read_to_string(path).map_err(|e| format!("failed to read {}: {e}", path.display()))?;

    let ast1 =
        parse(&source).map_err(|_errors| format!("first parse failed for {}", path.display()))?;

    let printed = print::print(&ast1);

    let ast2 = parse(&printed).map_err(|errors| {
        let error_msgs: Vec<String> = errors.iter().map(|e| format!("  {e}")).collect();
        format!(
            "round-trip reparse failed for {}:\n{}\n--- printed (first 500 chars) ---\n{}",
            path.display(),
            error_msgs.join("\n"),
            &printed[..printed.len().min(500)]
        )
    })?;

    // Deep structural equality check (ignoring spans).
    assert_module_eq(&ast1, &ast2, path)?;

    Ok(())
}

fn try_idempotent_print(path: &PathBuf) -> Result<(), String> {
    let source =
        fs::read_to_string(path).map_err(|e| format!("failed to read {}: {e}", path.display()))?;

    let ast1 = parse(&source).map_err(|_| format!("parse failed for {}", path.display()))?;
    let print1 = print::print(&ast1);

    let ast2 = parse(&print1).map_err(|_| format!("reparse failed for {}", path.display()))?;
    let print2 = print::print(&ast2);

    if print1 != print2 {
        // Find first difference.
        let lines1: Vec<&str> = print1.lines().collect();
        let lines2: Vec<&str> = print2.lines().collect();
        for (i, (l1, l2)) in lines1.iter().zip(lines2.iter()).enumerate() {
            if l1 != l2 {
                return Err(format!(
                    "printer not idempotent for {} at line {}:\n  print1: {}\n  print2: {}",
                    path.display(),
                    i + 1,
                    l1,
                    l2
                ));
            }
        }
        if lines1.len() != lines2.len() {
            return Err(format!(
                "printer not idempotent for {}: {} vs {} lines",
                path.display(),
                lines1.len(),
                lines2.len()
            ));
        }
    }

    Ok(())
}

// ── Deep AST equality (ignoring spans) ───────────────────────────────

fn assert_module_eq(a: &ElmModule, b: &ElmModule, path: &Path) -> Result<(), String> {
    if a.imports.len() != b.imports.len() {
        return Err(format!(
            "import count mismatch for {}: {} vs {}",
            path.display(),
            a.imports.len(),
            b.imports.len()
        ));
    }

    if a.declarations.len() != b.declarations.len() {
        return Err(format!(
            "declaration count mismatch for {}: {} vs {}",
            path.display(),
            a.declarations.len(),
            b.declarations.len()
        ));
    }

    // Check comment count (round-trip should preserve comments).
    if a.comments.len() != b.comments.len() {
        return Err(format!(
            "comment count mismatch for {}: {} vs {}",
            path.display(),
            a.comments.len(),
            b.comments.len()
        ));
    }

    // Check each declaration structurally.
    for (i, (da, db)) in a.declarations.iter().zip(b.declarations.iter()).enumerate() {
        if !decl_eq(&da.value, &db.value) {
            return Err(format!(
                "declaration {} differs for {}: {:?} vs {:?}",
                i,
                path.display(),
                decl_kind(&da.value),
                decl_kind(&db.value),
            ));
        }
    }

    Ok(())
}

fn decl_kind(d: &Declaration) -> &'static str {
    match d {
        Declaration::FunctionDeclaration(_) => "Function",
        Declaration::AliasDeclaration(_) => "TypeAlias",
        Declaration::CustomTypeDeclaration(_) => "CustomType",
        Declaration::PortDeclaration(_) => "Port",
        Declaration::InfixDeclaration(_) => "Infix",
        Declaration::Destructuring { .. } => "Destructuring",
    }
}

fn decl_eq(a: &Declaration, b: &Declaration) -> bool {
    match (a, b) {
        (Declaration::FunctionDeclaration(fa), Declaration::FunctionDeclaration(fb)) => {
            fa.declaration.value.name.value == fb.declaration.value.name.value
                && fa.declaration.value.args.len() == fb.declaration.value.args.len()
                && fa.signature.is_some() == fb.signature.is_some()
                && expr_eq(
                    &fa.declaration.value.body.value,
                    &fb.declaration.value.body.value,
                )
        }
        (Declaration::AliasDeclaration(aa), Declaration::AliasDeclaration(ab)) => {
            aa.name.value == ab.name.value
                && aa.generics.len() == ab.generics.len()
                && type_eq(&aa.type_annotation.value, &ab.type_annotation.value)
        }
        (Declaration::CustomTypeDeclaration(ca), Declaration::CustomTypeDeclaration(cb)) => {
            ca.name.value == cb.name.value
                && ca.generics.len() == cb.generics.len()
                && ca.constructors.len() == cb.constructors.len()
                && ca
                    .constructors
                    .iter()
                    .zip(cb.constructors.iter())
                    .all(|(a, b)| {
                        a.value.name.value == b.value.name.value
                            && a.value.args.len() == b.value.args.len()
                    })
        }
        (Declaration::PortDeclaration(sa), Declaration::PortDeclaration(sb)) => {
            sa.name.value == sb.name.value
        }
        (Declaration::InfixDeclaration(ia), Declaration::InfixDeclaration(ib)) => {
            ia.operator.value == ib.operator.value
                && ia.function.value == ib.function.value
                && ia.precedence.value == ib.precedence.value
                && ia.direction.value == ib.direction.value
        }
        (
            Declaration::Destructuring { pattern: pa, .. },
            Declaration::Destructuring { pattern: pb, .. },
        ) => pattern_eq(&pa.value, &pb.value),
        _ => false,
    }
}

fn expr_eq(a: &Expr, b: &Expr) -> bool {
    match (a, b) {
        (Expr::Unit, Expr::Unit) => true,
        (Expr::Literal(la), Expr::Literal(lb)) => la == lb,
        (
            Expr::FunctionOrValue {
                module_name: ma,
                name: na,
            },
            Expr::FunctionOrValue {
                module_name: mb,
                name: nb,
            },
        ) => ma == mb && na == nb,
        (Expr::PrefixOperator(a), Expr::PrefixOperator(b)) => a == b,
        (
            Expr::OperatorApplication {
                operator: oa,
                left: la,
                right: ra,
                ..
            },
            Expr::OperatorApplication {
                operator: ob,
                left: lb,
                right: rb,
                ..
            },
        ) => oa == ob && expr_eq(&la.value, &lb.value) && expr_eq(&ra.value, &rb.value),
        (Expr::Application(aa), Expr::Application(ab)) => {
            aa.len() == ab.len()
                && aa
                    .iter()
                    .zip(ab.iter())
                    .all(|(a, b)| expr_eq(&a.value, &b.value))
        }
        (
            Expr::IfElse {
                branches: ba,
                else_branch: ea,
            },
            Expr::IfElse {
                branches: bb,
                else_branch: eb,
            },
        ) => {
            ba.len() == bb.len()
                && ba.iter().zip(bb.iter()).all(|(a, b)| {
                    expr_eq(&a.condition.value, &b.condition.value)
                        && expr_eq(&a.then_branch.value, &b.then_branch.value)
                })
                && expr_eq(&ea.value, &eb.value)
        }
        (Expr::Negation(a), Expr::Negation(b)) => expr_eq(&a.value, &b.value),
        (Expr::Tuple(aa), Expr::Tuple(ab)) => {
            aa.len() == ab.len()
                && aa
                    .iter()
                    .zip(ab.iter())
                    .all(|(a, b)| expr_eq(&a.value, &b.value))
        }
        (Expr::List { elements: aa, .. }, Expr::List { elements: ab, .. }) => {
            aa.len() == ab.len()
                && aa
                    .iter()
                    .zip(ab.iter())
                    .all(|(a, b)| expr_eq(&a.value, &b.value))
        }
        (Expr::Parenthesized { expr: a, .. }, Expr::Parenthesized { expr: b, .. }) => {
            expr_eq(&a.value, &b.value)
        }
        // For deep comparison of case/let/lambda/record, check structural shape.
        (Expr::CaseOf { branches: ba, .. }, Expr::CaseOf { branches: bb, .. }) => {
            ba.len() == bb.len()
        }
        (
            Expr::LetIn {
                declarations: da, ..
            },
            Expr::LetIn {
                declarations: db, ..
            },
        ) => da.len() == db.len(),
        (Expr::Lambda { args: aa, .. }, Expr::Lambda { args: ab, .. }) => aa.len() == ab.len(),
        (Expr::Record(fa), Expr::Record(fb)) => fa.len() == fb.len(),
        (
            Expr::RecordUpdate {
                base: ba,
                updates: ua,
            },
            Expr::RecordUpdate {
                base: bb,
                updates: ub,
            },
        ) => ba.value == bb.value && ua.len() == ub.len(),
        (Expr::RecordAccess { field: fa, .. }, Expr::RecordAccess { field: fb, .. }) => {
            fa.value == fb.value
        }
        (Expr::RecordAccessFunction(a), Expr::RecordAccessFunction(b)) => a == b,
        (Expr::GLSLExpression(a), Expr::GLSLExpression(b)) => a == b,
        // Parenthesized in one but not the other is OK if the inner matches.
        // The printer may add parens that weren't in the original.
        (Expr::Parenthesized { expr: inner, .. }, other)
        | (other, Expr::Parenthesized { expr: inner, .. }) => expr_eq(&inner.value, other),
        _ => false,
    }
}

fn pattern_eq(a: &Pattern, b: &Pattern) -> bool {
    match (a, b) {
        (Pattern::Anything, Pattern::Anything) => true,
        (Pattern::Unit, Pattern::Unit) => true,
        (Pattern::Var(a), Pattern::Var(b)) => a == b,
        (Pattern::Literal(a), Pattern::Literal(b)) => a == b,
        (Pattern::Hex(a), Pattern::Hex(b)) => a == b,
        (Pattern::Tuple(aa), Pattern::Tuple(ab)) | (Pattern::List(aa), Pattern::List(ab)) => {
            aa.len() == ab.len()
                && aa
                    .iter()
                    .zip(ab.iter())
                    .all(|(a, b)| pattern_eq(&a.value, &b.value))
        }
        (
            Pattern::Constructor {
                name: na, args: aa, ..
            },
            Pattern::Constructor {
                name: nb, args: ab, ..
            },
        ) => na == nb && aa.len() == ab.len(),
        (Pattern::Record(fa), Pattern::Record(fb)) => {
            fa.len() == fb.len() && fa.iter().zip(fb.iter()).all(|(a, b)| a.value == b.value)
        }
        (Pattern::Cons { .. }, Pattern::Cons { .. }) => true,
        (Pattern::As { name: na, .. }, Pattern::As { name: nb, .. }) => na.value == nb.value,
        (Pattern::Parenthesized(a), Pattern::Parenthesized(b)) => pattern_eq(&a.value, &b.value),
        (Pattern::Parenthesized(inner), other) | (other, Pattern::Parenthesized(inner)) => {
            pattern_eq(&inner.value, other)
        }
        _ => false,
    }
}

fn type_eq(a: &TypeAnnotation, b: &TypeAnnotation) -> bool {
    match (a, b) {
        (TypeAnnotation::GenericType(a), TypeAnnotation::GenericType(b)) => a == b,
        (TypeAnnotation::Unit, TypeAnnotation::Unit) => true,
        (
            TypeAnnotation::Typed {
                name: na, args: aa, ..
            },
            TypeAnnotation::Typed {
                name: nb, args: ab, ..
            },
        ) => {
            na.value == nb.value
                && aa.len() == ab.len()
                && aa
                    .iter()
                    .zip(ab.iter())
                    .all(|(a, b)| type_eq(&a.value, &b.value))
        }
        (TypeAnnotation::Tupled(aa), TypeAnnotation::Tupled(ab)) => {
            aa.len() == ab.len()
                && aa
                    .iter()
                    .zip(ab.iter())
                    .all(|(a, b)| type_eq(&a.value, &b.value))
        }
        (TypeAnnotation::Record(fa), TypeAnnotation::Record(fb)) => {
            fa.len() == fb.len()
                && fa.iter().zip(fb.iter()).all(|(a, b)| {
                    a.value.name.value == b.value.name.value
                        && type_eq(
                            &a.value.type_annotation.value,
                            &b.value.type_annotation.value,
                        )
                })
        }
        (
            TypeAnnotation::GenericRecord {
                base: ba,
                fields: fa,
            },
            TypeAnnotation::GenericRecord {
                base: bb,
                fields: fb,
            },
        ) => ba.value == bb.value && fa.len() == fb.len(),
        (
            TypeAnnotation::FunctionType { from: fa, to: ta },
            TypeAnnotation::FunctionType { from: fb, to: tb },
        ) => type_eq(&fa.value, &fb.value) && type_eq(&ta.value, &tb.value),
        _ => false,
    }
}

// ── Run suite helpers ────────────────────────────────────────────────

fn run_parse_suite(dirs: &[(&str, &str)]) -> (usize, usize, Vec<String>) {
    let mut total = 0;
    let mut passed = 0;
    let mut failures = Vec::new();

    for (pkg, dir) in dirs {
        let files = find_elm_files(dir);
        for file in &files {
            total += 1;
            match try_parse_file(file) {
                Ok(_) => passed += 1,
                Err(msg) => failures.push(format!("[{pkg}] {msg}")),
            }
        }
    }

    (total, passed, failures)
}

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

#[test]
fn parse_all_packages() {
    let dirs = all_fixture_dirs();
    let (total, passed, failures) = run_parse_suite(&dirs);

    eprintln!("\n=== Parse results ===");
    eprintln!("{passed}/{total} files parsed successfully");
    for f in &failures {
        eprintln!("\n{f}");
    }

    assert!(total > 0, "no .elm files found in test-fixtures/");
    let pass_rate = (passed as f64 / total as f64) * 100.0;
    eprintln!("\nParse pass rate: {pass_rate:.1}%");
    assert_eq!(
        passed,
        total,
        "{} of {} files failed to parse:\n{}",
        total - passed,
        total,
        failures.join("\n")
    );
}

#[test]
fn round_trip_all_packages() {
    let dirs = all_fixture_dirs();

    let mut total = 0;
    let mut passed = 0;
    let mut failures = Vec::new();

    for (pkg, dir) in &dirs {
        let files = find_elm_files(dir);
        for file in &files {
            if try_parse_file(file).is_err() {
                continue;
            }
            total += 1;
            match try_round_trip_file(file) {
                Ok(()) => passed += 1,
                Err(msg) => failures.push(format!("[{pkg}] {msg}")),
            }
        }
    }

    eprintln!("\n=== Round-trip results (with deep AST equality) ===");
    eprintln!("{passed}/{total} files round-tripped successfully");
    for f in &failures {
        eprintln!("\n{f}");
    }
    if total > 0 {
        let pass_rate = (passed as f64 / total as f64) * 100.0;
        eprintln!("\nRound-trip pass rate: {pass_rate:.1}%");
    }
    assert_eq!(
        passed,
        total,
        "{} of {} files failed round-trip:\n{}",
        total - passed,
        total,
        failures.join("\n")
    );
}

#[test]
fn printer_idempotency() {
    let dirs = all_fixture_dirs();

    let mut total = 0;
    let mut passed = 0;
    let mut failures = Vec::new();

    for (pkg, dir) in &dirs {
        let files = find_elm_files(dir);
        for file in &files {
            if try_parse_file(file).is_err() {
                continue;
            }
            total += 1;
            match try_idempotent_print(file) {
                Ok(()) => passed += 1,
                Err(msg) => failures.push(format!("[{pkg}] {msg}")),
            }
        }
    }

    eprintln!("\n=== Printer idempotency results ===");
    eprintln!("{passed}/{total} files print idempotently");
    for f in &failures {
        eprintln!("\n{f}");
    }
    if total > 0 {
        let pass_rate = (passed as f64 / total as f64) * 100.0;
        eprintln!("\nIdempotency pass rate: {pass_rate:.1}%");
    }
    assert_eq!(
        passed,
        total,
        "{} of {} files failed idempotency:\n{}",
        total - passed,
        total,
        failures.join("\n")
    );
}

// ── pretty_print vs elm-format ──────────────────────────────────────
//
// Round-trip through elm-format: pretty-print a file, feed the result back
// through elm-format, and check nothing changes. Confirms our output is a
// form elm-format accepts as canonical, so downstream tooling that runs
// elm-format won't mutate our output.
//
// The test is skipped when elm-format is not found on the system.
// Set ELM_FORMAT to a custom path if it's not in PATH.

/// Try to locate elm-format. Checks `$ELM_FORMAT`, then `$PATH`.
fn find_elm_format() -> Option<PathBuf> {
    if let Ok(path) = std::env::var("ELM_FORMAT") {
        let p = PathBuf::from(&path);
        if p.exists() {
            return Some(p);
        }
    }
    // Check PATH
    Command::new("elm-format")
        .arg("--help")
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|_| PathBuf::from("elm-format"))
}

/// Run elm-format on the given source string. Returns the formatted output.
fn run_elm_format(elm_format: &Path, source: &str) -> Result<String, String> {
    use std::io::Write;
    let mut child = Command::new(elm_format)
        .args(["--stdin", "--elm-version=0.19"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .map_err(|e| format!("failed to spawn elm-format: {e}"))?;

    child
        .stdin
        .as_mut()
        .expect("elm-format stdin piped")
        .write_all(source.as_bytes())
        .map_err(|e| format!("failed to write to elm-format stdin: {e}"))?;

    let output = child
        .wait_with_output()
        .map_err(|e| format!("elm-format failed: {e}"))?;

    if !output.status.success() {
        return Err(format!(
            "elm-format exited with {}: {}",
            output.status,
            String::from_utf8_lossy(&output.stderr)
        ));
    }
    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

#[test]
#[ignore] // Run explicitly: cargo test pretty_print_matches_elm_format -- --ignored --nocapture
fn pretty_print_matches_elm_format() {
    let elm_format = match find_elm_format() {
        Some(path) => path,
        None => {
            eprintln!("elm-format not found — skipping pretty_print_matches_elm_format test");
            eprintln!("Install elm-format or set ELM_FORMAT=/path/to/elm-format to enable");
            return;
        }
    };

    let dirs = all_fixture_dirs();

    let mut total = 0;
    let mut passed = 0;
    let mut failures = Vec::new();

    for (pkg, dir) in &dirs {
        let files = find_elm_files(dir);
        for file in &files {
            // Only test files we can parse.
            if try_parse_file(file).is_err() {
                continue;
            }
            let source = fs::read_to_string(file).expect("read fixture file");
            let ast = match parse(&source) {
                Ok(ast) => ast,
                Err(_) => continue,
            };

            // This test checks the round-trip property: does our output
            // survive an elm-format pass unchanged? Use the converged
            // variant so we stay stable even on inputs where elm-format
            // itself is non-idempotent (e.g. Task.elm's
            // `-- comment → import` pattern inside doc code blocks).
            let pretty = pretty_print_converged(&ast);

            // Feed pretty-printed output to elm-format.
            let formatted = match run_elm_format(&elm_format, &pretty) {
                Ok(f) => f,
                Err(msg) => {
                    // elm-format couldn't parse our output — that's a failure.
                    failures.push(format!(
                        "[{pkg}] elm-format rejected pretty_print output for {}: {msg}",
                        file.display()
                    ));
                    total += 1;
                    continue;
                }
            };

            total += 1;
            if pretty == formatted {
                passed += 1;
            } else {
                // Find first differing line for diagnostics.
                let pretty_lines: Vec<&str> = pretty.lines().collect();
                let fmt_lines: Vec<&str> = formatted.lines().collect();
                let mut diff_msg = String::new();
                for (i, (p, f)) in pretty_lines.iter().zip(fmt_lines.iter()).enumerate() {
                    if p != f {
                        diff_msg = format!(
                            "first diff at line {}:\n  pretty_print: {}\n  elm-format:   {}",
                            i + 1,
                            p,
                            f
                        );
                        break;
                    }
                }
                if diff_msg.is_empty() && pretty_lines.len() != fmt_lines.len() {
                    diff_msg = format!(
                        "line count differs: pretty_print={} vs elm-format={}",
                        pretty_lines.len(),
                        fmt_lines.len()
                    );
                }
                failures.push(format!(
                    "[{pkg}] pretty_print differs from elm-format for {}:\n  {diff_msg}",
                    file.display()
                ));
            }
        }
    }

    eprintln!("\n=== pretty_print vs elm-format results ===");
    eprintln!("{passed}/{total} files match elm-format exactly");
    for f in &failures {
        eprintln!("\n{f}");
    }
    if total > 0 {
        let pass_rate = (passed as f64 / total as f64) * 100.0;
        eprintln!("\nMatch rate: {pass_rate:.1}%");
    }
    assert_eq!(
        passed,
        total,
        "{} of {} files differ from elm-format:\n{}",
        total - passed,
        total,
        failures.join("\n")
    );
}

/// Direct parity test: our `pretty_print` output on parsed source is
/// byte-identical to what `elm-format` produces from the same source.
///
/// This is the strictest elm-format parity check — it asserts that we
/// match elm-format's exact layout decisions, not just that elm-format
/// would accept our output unchanged (that's what
/// `pretty_print_matches_elm_format` checks).
#[test]
#[ignore] // Run explicitly: cargo test pretty_print_equals_elm_format_on_source -- --ignored --nocapture
fn pretty_print_equals_elm_format_on_source() {
    let elm_format = match find_elm_format() {
        Some(path) => path,
        None => {
            eprintln!(
                "elm-format not found — skipping pretty_print_equals_elm_format_on_source test"
            );
            eprintln!("Install elm-format or set ELM_FORMAT=/path/to/elm-format to enable");
            return;
        }
    };

    let dirs = all_fixture_dirs();

    let mut total = 0;
    let mut passed = 0;
    let mut failures = Vec::new();

    for (pkg, dir) in &dirs {
        let files = find_elm_files(dir);
        for file in &files {
            if try_parse_file(file).is_err() {
                continue;
            }
            let source = fs::read_to_string(file).expect("read fixture file");
            let ast = match parse(&source) {
                Ok(ast) => ast,
                Err(_) => continue,
            };

            let pretty = pretty_print(&ast);

            // Feed ORIGINAL source (not our pretty output) to elm-format.
            let formatted_from_source = match run_elm_format(&elm_format, &source) {
                Ok(f) => f,
                Err(msg) => {
                    failures.push(format!(
                        "[{pkg}] elm-format rejected original source for {}: {msg}",
                        file.display()
                    ));
                    total += 1;
                    continue;
                }
            };

            total += 1;
            if pretty == formatted_from_source {
                passed += 1;
            } else {
                let pretty_lines: Vec<&str> = pretty.lines().collect();
                let fmt_lines: Vec<&str> = formatted_from_source.lines().collect();
                let mut diff_msg = String::new();
                for (i, (p, f)) in pretty_lines.iter().zip(fmt_lines.iter()).enumerate() {
                    if p != f {
                        diff_msg = format!(
                            "first diff at line {}:\n  pretty_print: {}\n  elm-format:   {}",
                            i + 1,
                            p,
                            f
                        );
                        break;
                    }
                }
                if diff_msg.is_empty() && pretty_lines.len() != fmt_lines.len() {
                    diff_msg = format!(
                        "line count differs: pretty_print={} vs elm-format={}",
                        pretty_lines.len(),
                        fmt_lines.len()
                    );
                }
                failures.push(format!(
                    "[{pkg}] pretty_print differs from elm-format(source) for {}:\n  {diff_msg}",
                    file.display()
                ));
            }
        }
    }

    eprintln!("\n=== pretty_print vs elm-format(source) results ===");
    eprintln!("{passed}/{total} files match elm-format(source) exactly");
    for f in &failures {
        eprintln!("\n{f}");
    }
    if total > 0 {
        let pass_rate = (passed as f64 / total as f64) * 100.0;
        eprintln!("\nMatch rate: {pass_rate:.1}%");
    }
    assert_eq!(
        passed,
        total,
        "{} of {} files differ from elm-format(source):\n{}",
        total - passed,
        total,
        failures.join("\n")
    );
}