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
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
//! Code-block reformat and assertion-paragraph transforms.
//!
//! elm-format re-runs Elm code inside doc comments through its own parser
//! and printer. These helpers decide whether a block needs to be reformatted,
//! rewrite chains of `expr == value` assertions into the elm-format vertical
//! layout, and drive the full reparse+reindent pipeline for the block.

use super::*;

pub(in crate::print) fn transform_assertion_paragraphs(block_lines: &[&str]) -> String {
    // Pre-process: merge standalone `...` lines into the previous assertion
    // as a trailing ` ...`. elm-format treats
    //     expr1 == val1
    //     ...
    //     expr2 == val2
    // identically to
    //     expr1 == val1 ...
    //     expr2 == val2
    // The existing chain logic handles the trailing-dots form.
    let merged_owned: Vec<String>;
    let block_lines: Vec<&str> = {
        let mut out: Vec<String> = Vec::with_capacity(block_lines.len());
        let mut i = 0;
        let orig = block_lines;
        while i < orig.len() {
            let line = orig[i];
            let trimmed = line.trim();
            if trimmed == "..." && !out.is_empty() {
                // Find the last non-blank line in `out` and append ` ...`.
                let mut last_idx = out.len();
                while last_idx > 0 && out[last_idx - 1].trim().is_empty() {
                    last_idx -= 1;
                }
                if last_idx > 0 {
                    let last = &out[last_idx - 1];
                    let last_trimmed = last.trim();
                    if !last_trimmed.is_empty()
                        && !last_trimmed.starts_with("--")
                        && !last_trimmed.ends_with(" ...")
                        // A case arm (`Pat ->`) that's followed by `...` is
                        // using `...` as a body placeholder, not as a chain
                        // continuation. Preserve the line break.
                        && !last_trimmed.ends_with("->")
                        // Only merge `...` into a preceding line that looks
                        // like an Elm assertion or simple expression.
                        // Without this, non-Elm content (e.g. CSS keyframes
                        // `}` closing braces) inside a doc code block gets
                        // silently joined with the placeholder.
                        && super::predicates::looks_like_assertion(last_trimmed)
                    {
                        out[last_idx - 1] = format!("{} ...", last.trim_end());
                        // Drop any blank lines between assertion and `...`, and
                        // drop any blank lines between `...` and the next line,
                        // so the three lines become one. Skip trailing blanks
                        // after the `...` line.
                        while out.len() > last_idx
                            && out.last().is_some_and(|l| l.trim().is_empty())
                        {
                            out.pop();
                        }
                        let mut j = i + 1;
                        while j < orig.len() && orig[j].trim().is_empty() {
                            j += 1;
                        }
                        i = j;
                        continue;
                    }
                }
            }
            out.push(line.to_string());
            i += 1;
        }
        merged_owned = out;
        merged_owned.iter().map(|s| s.as_str()).collect()
    };
    let block_lines: &[&str] = &block_lines;

    // If the block contains anything other than pure assertion lines,
    // elm-format does not split adjacent assertions in this block. Emit
    // the block unchanged in that case.
    if block_has_non_assertion_content(block_lines) {
        return block_lines.join("\n");
    }
    // Column-aligned assertion tables are preserved verbatim by elm-format.
    if block_has_column_aligned_assertions(block_lines) {
        return block_lines.join("\n");
    }
    let mut out = String::new();
    let mut i = 0;
    while i < block_lines.len() {
        let line = block_lines[i];
        if line.trim().is_empty() {
            if i > 0 {
                out.push('\n');
            }
            out.push_str(line);
            i += 1;
            continue;
        }

        // Collect a run of adjacent non-blank lines. Extend across blank lines
        // when the current last line is an assertion ending with ` ...` and the
        // next non-blank line is also an assertion — elm-format treats this as
        // a single multi-line operator chain.
        let run_start = i;
        let mut run_end = i;
        loop {
            let next = run_end + 1;
            if next >= block_lines.len() {
                break;
            }
            if !block_lines[next].trim().is_empty() {
                run_end = next;
                continue;
            }
            let last_trimmed = block_lines[run_end].trim();
            if !last_trimmed.ends_with(" ...") {
                break;
            }
            let mut j = next;
            while j < block_lines.len() && block_lines[j].trim().is_empty() {
                j += 1;
            }
            if j >= block_lines.len() {
                break;
            }
            let next_trimmed = block_lines[j].trim();
            if next_trimmed.starts_with("--") || !looks_like_assertion(next_trimmed) {
                break;
            }
            run_end = j;
        }

        // Check if every line in this run is either a top-level assertion
        // (`expr == value` / `expr -- comment`) or a line-comment (`-- ...`),
        // all at the same leading indent, and the run ends in an assertion.
        // Comments stay attached to the following assertion; assertions are
        // separated from one another by blank lines.
        let first_indent = block_lines[run_start].len() - block_lines[run_start].trim_start().len();
        let mut all_valid = true;
        let mut assertion_count = 0usize;
        let mut has_eq_or_comment_shape = false;
        #[allow(clippy::needless_range_loop)]
        for k in run_start..=run_end {
            let l = block_lines[k];
            if l.trim().is_empty() {
                continue;
            }
            let indent = l.len() - l.trim_start().len();
            if indent != first_indent {
                all_valid = false;
                break;
            }
            let trimmed = l.trim();
            if trimmed.starts_with("--") {
                // comment line — ok in between assertions
            } else if looks_like_assertion(trimmed) {
                assertion_count += 1;
                if trimmed.contains(" == ") || trimmed.contains(" -- ") {
                    has_eq_or_comment_shape = true;
                }
            } else {
                all_valid = false;
                break;
            }
        }
        let last_is_assertion = {
            let trimmed = block_lines[run_end].trim();
            !trimmed.starts_with("--") && looks_like_assertion(trimmed)
        };
        // elm-format only splits runs that contain at least one `==` or
        // `-- comment` shaped assertion. Runs of pure standalone
        // expressions are preserved verbatim.
        let is_assertion_run =
            all_valid && assertion_count >= 1 && last_is_assertion && has_eq_or_comment_shape;

        // If the run's last non-blank line ends with ` ...`, the chain would
        // be incomplete. elm-format preserves such blocks without chain
        // reformatting.
        let run_last_ends_with_dots = {
            let mut idx = run_end;
            while idx > run_start && block_lines[idx].trim().is_empty() {
                idx -= 1;
            }
            block_lines[idx].trim().ends_with(" ...")
        };
        if is_assertion_run && run_last_ends_with_dots {
            for (k, idx) in (run_start..=run_end).enumerate() {
                if i > 0 || k > 0 {
                    out.push('\n');
                }
                out.push_str(block_lines[idx]);
            }
            i = run_end + 1;
            continue;
        }
        if is_assertion_run {
            // Group lines into chains. A chain contains an optional run of
            // comment lines, one assertion, plus any continuation assertions
            // triggered by a trailing ` ...` on the prior assertion. Chains
            // are separated by blank lines; within a chain, a single-line
            // assertion is emitted normally, while a multi-line chain is
            // joined and split at ` == ` / ` ... ` operators into the
            // elm-format multi-line form.
            let mut chains: Vec<(Vec<usize>, Vec<usize>)> = Vec::new();
            let mut cur_comments: Vec<usize> = Vec::new();
            let mut cur_assertions: Vec<usize> = Vec::new();
            #[allow(clippy::needless_range_loop)]
            for k in run_start..=run_end {
                let trimmed = block_lines[k].trim();
                if trimmed.is_empty() {
                    continue;
                }
                if trimmed.starts_with("--") {
                    cur_comments.push(k);
                } else {
                    cur_assertions.push(k);
                    if !trimmed.ends_with(" ...") {
                        chains.push((
                            std::mem::take(&mut cur_comments),
                            std::mem::take(&mut cur_assertions),
                        ));
                    }
                }
            }
            if !cur_comments.is_empty() || !cur_assertions.is_empty() {
                chains.push((cur_comments, cur_assertions));
            }

            for (chain_idx, (comments, assertions)) in chains.iter().enumerate() {
                if chain_idx == 0 && i > 0 {
                    out.push('\n');
                } else if chain_idx > 0 {
                    out.push_str("\n\n");
                }
                for &ci in comments {
                    out.push_str(block_lines[ci]);
                    out.push('\n');
                }
                if assertions.len() == 1 {
                    let l = block_lines[assertions[0]];
                    let indent_str = &l[..first_indent];
                    let content = &l[first_indent..];
                    let normalized = collapse_spaces_outside_strings(content);
                    let normalized = space_tight_binary_ops(&normalized);
                    let normalized = space_tight_tuples_lists(&normalized);
                    out.push_str(indent_str);
                    out.push_str(&normalized);
                } else if !assertions.is_empty() {
                    let joined = assertions
                        .iter()
                        .map(|&idx| block_lines[idx].trim())
                        .collect::<Vec<_>>()
                        .join(" ");
                    let joined = collapse_spaces_outside_strings(&joined);
                    let joined = space_tight_binary_ops(&joined);
                    let joined = space_tight_tuples_lists(&joined);
                    let segments = split_at_chain_operators(&joined);
                    let indent_str = &block_lines[assertions[0]][..first_indent];
                    let cont_indent: String = std::iter::repeat_n(' ', first_indent + 4).collect();
                    out.push_str(indent_str);
                    if let Some(first) = segments.first() {
                        out.push_str(first);
                    }
                    for seg in segments.iter().skip(1) {
                        out.push('\n');
                        out.push_str(&cont_indent);
                        out.push_str(seg);
                    }
                }
            }
        } else {
            for (k, idx) in (run_start..=run_end).enumerate() {
                if i > 0 || k > 0 {
                    out.push('\n');
                }
                out.push_str(block_lines[idx]);
            }
        }
        i = run_end + 1;
    }
    out
}

/// Detect "mixed" code blocks: blocks containing BOTH a decl-like line
/// (type, type alias, value decl, or type annotation) AND a bare expression
/// at base indent. elm-format treats such blocks as verbatim examples and
/// leaves them untouched instead of re-running the module-body formatter.
pub(in crate::print) fn block_mixes_decls_and_bare_exprs(block_lines: &[&str]) -> bool {
    let mut has_decl = false;
    let mut has_bare = false;
    // Track whether we are currently inside a triple-quoted string so lines
    // within it (which may look like bare expressions or decls syntactically)
    // don't trigger the predicate.
    let mut in_triple = false;
    for &line in block_lines {
        let was_in_triple = in_triple;
        let triple_count = line.matches("\"\"\"").count();
        if triple_count % 2 == 1 {
            in_triple = !in_triple;
        }
        // A line that is interior content of a multi-line triple-string is
        // skipped. A line that opens/closes one on the same position still
        // gets classified by its leading code (e.g. `name = """..."""`).
        if was_in_triple {
            continue;
        }
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        let leading = line.len() - line.trim_start().len();
        if leading != 4 {
            continue;
        }
        if trimmed.starts_with("--") {
            continue;
        }
        if trimmed.starts_with("module ")
            || trimmed.starts_with("import ")
            || trimmed.starts_with("port module ")
            || trimmed.starts_with("effect module ")
        {
            continue;
        }
        if looks_like_code_block_decl(trimmed) {
            has_decl = true;
        } else if line_looks_like_bare_expression(trimmed) {
            has_bare = true;
        }
        if has_decl && has_bare {
            return true;
        }
    }
    false
}

/// Classify a single code block by whether its base-indent (4-space) lines
/// are all declaration-flavored (type/value binding/type annotation/module/
/// import) with at least one such line. Ignores blank lines, comment-only
/// lines, and continuation lines past the base indent.
pub(in crate::print) fn block_looks_decl_only(block_lines: &[&str]) -> bool {
    let mut has_decl = false;
    let mut has_bare = false;
    let mut in_triple = false;
    for &line in block_lines {
        let was_in_triple = in_triple;
        let triple_count = line.matches("\"\"\"").count();
        if triple_count % 2 == 1 {
            in_triple = !in_triple;
        }
        if was_in_triple {
            continue;
        }
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with("--") {
            continue;
        }
        let leading = line.len() - line.trim_start().len();
        if leading != 4 {
            continue;
        }
        let is_header = trimmed.starts_with("module ")
            || trimmed.starts_with("import ")
            || trimmed.starts_with("port module ")
            || trimmed.starts_with("effect module ");
        if is_header || looks_like_code_block_decl(trimmed) {
            has_decl = true;
        } else if line_looks_like_bare_expression(trimmed) {
            has_bare = true;
        }
    }
    has_decl && !has_bare
}

/// Mirror of `block_looks_decl_only`, but for blocks consisting only of
/// bare expressions at base indent. Used to detect "sample code" docs where
/// decl-flavored blocks sit alongside bare-expression blocks; elm-format
/// preserves every block in such docs verbatim.
pub(in crate::print) fn block_looks_bare_only(block_lines: &[&str]) -> bool {
    let mut has_decl = false;
    let mut has_bare = false;
    let mut in_triple = false;
    for &line in block_lines {
        let was_in_triple = in_triple;
        let triple_count = line.matches("\"\"\"").count();
        if triple_count % 2 == 1 {
            in_triple = !in_triple;
        }
        if was_in_triple {
            continue;
        }
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with("--") {
            continue;
        }
        let leading = line.len() - line.trim_start().len();
        if leading != 4 {
            continue;
        }
        let is_header = trimmed.starts_with("module ")
            || trimmed.starts_with("import ")
            || trimmed.starts_with("port module ")
            || trimmed.starts_with("effect module ");
        if is_header || looks_like_code_block_decl(trimmed) {
            has_decl = true;
        } else if line_looks_like_bare_expression(trimmed) {
            has_bare = true;
        }
    }
    has_bare && !has_decl
}

/// Accept any line that starts like an Elm expression: identifiers, literals,
/// opening brackets/braces/parens, backslash lambdas, or leading negation.
fn line_looks_like_bare_expression(trimmed: &str) -> bool {
    // Reject block comment markers — a line like `{-| pair of values -}`
    // starts with `{` but is not an expression.
    if trimmed.starts_with("{-") {
        return false;
    }
    let first = match trimmed.chars().next() {
        Some(c) => c,
        None => return false,
    };
    let starter_ok = first.is_ascii_alphabetic()
        || first.is_ascii_digit()
        || first == '_'
        || first == '('
        || first == '['
        || first == '{'
        || first == '\''
        || first == '"'
        || first == '\\'
        || first == '-';
    if !starter_ok {
        return false;
    }
    // `-` only valid as leading negation when followed by a digit or paren.
    if first == '-' {
        let second = trimmed.chars().nth(1);
        match second {
            Some(c) if c.is_ascii_digit() || c == '(' => {}
            _ => return false,
        }
    }
    // Reject keyword-led lines that aren't expressions.
    let first_word_end = trimmed
        .find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '.')
        .unwrap_or(trimmed.len());
    let first_word = &trimmed[..first_word_end];
    match first_word {
        "type" | "port" | "module" | "import" | "exposing" | "effect" | "infix" => {
            return false;
        }
        _ => {}
    }
    true
}

/// Returns true if the trimmed line matches `ident = """..."""` with both
/// triple-quote delimiters on this same line. elm-format preserves such lines
/// verbatim inside doc comments, so we treat them as non-reformat signals.
fn has_same_line_triple_string_rhs(trimmed: &str) -> bool {
    if trimmed.matches("\"\"\"").count() < 2 {
        return false;
    }
    // The RHS must open with `"""` right after `= `. Anything else (e.g.
    // `"""`-triples embedded deep in an expression) is treated conservatively
    // as "not this pattern" so normal reformat rules apply.
    let Some(eq) = trimmed.find("= \"\"\"") else {
        return false;
    };
    // Make sure the `=` isn't part of `==`, `/=`, etc.
    if eq == 0 {
        return false;
    }
    let prev = trimmed.as_bytes()[eq - 1];
    if prev != b' ' {
        return false;
    }
    true
}

/// Check whether a code block needs reformatting.
///
/// Returns true if the block contains:
/// - lines with non-4-aligned indentation (2-space indent), OR
/// - compact list/tuple syntax that elm-format would space out
///   (e.g., `[1,2]` -> `[ 1, 2 ]`, `(0,"a")` -> `( 0, "a" )`)
pub(in crate::print) fn code_block_needs_reformat(block_lines: &[&str]) -> bool {
    // When a block mixes declarations with bare expressions, elm-format
    // preserves the block verbatim. Mirror that to keep compact tuples and
    // single-line value decls inside examples.
    if block_mixes_decls_and_bare_exprs(block_lines) {
        return false;
    }
    let mut count_non_4_aligned = 0usize;
    let mut has_compact_syntax = false;
    let mut has_single_line_decl = false;
    let mut has_unsorted_import = false;
    for &line in block_lines {
        if line.trim().is_empty() {
            continue;
        }
        let leading = line.len() - line.trim_start().len();
        if leading > 4 && (leading - 4) % 4 != 0 {
            count_non_4_aligned += 1;
        }
        // Imports with an out-of-order `exposing` list get re-sorted by
        // elm-format. Flag the block for reformat so the import re-parses
        // through the module parser which normalizes exposing order.
        if leading == 4 && import_has_unsorted_exposing(line.trim()) {
            has_unsorted_import = true;
        }
        // Check for compact list syntax [x,y] or [x] or tuple syntax (x,y)
        // that elm-format would normalize to [ x, y ] / [ x ] / ( x, y ).
        let trimmed = line.trim();
        if trimmed.contains('[') && trimmed.contains(']') {
            // Look for `[` immediately followed by a literal or identifier
            // start — the distinguishing marker of a compact list/tuple.
            if trimmed.contains("[\"")
                || trimmed.contains("[(")
                || trimmed.contains("['")
                || trimmed.contains("[0")
                || trimmed.contains("[1")
                || trimmed.contains("[2")
                || trimmed.contains("[3")
                || trimmed.contains("[4")
                || trimmed.contains("[5")
                || trimmed.contains("[6")
                || trimmed.contains("[7")
                || trimmed.contains("[8")
                || trimmed.contains("[9")
            {
                has_compact_syntax = true;
            }
        }
        if trimmed.contains('(') && trimmed.contains(',') && trimmed.contains(')') {
            // Match `(X` where X is a literal/identifier start — the
            // distinguishing marker of a compact tuple. A space after `(`
            // means the tuple is already normalized; skip in that case.
            if has_compact_tuple(trimmed) {
                has_compact_syntax = true;
            }
        }
        // Single-line value declaration at the block base-indent (4 spaces):
        // `name = expr` fits on one line. elm-format always expands these
        // to two lines (`name =\n    expr`), so flag for reformat. Exception:
        // `name = """..."""` with the triple-string fully on the same line is
        // left alone by elm-format inside doc comments.
        if leading == 4
            && is_single_line_value_decl(trimmed)
            && !has_same_line_triple_string_rhs(trimmed)
        {
            has_single_line_decl = true;
        }
        // Single-line type / type-alias declaration at base indent. elm-format
        // always expands these to multi-line form.
        if leading == 4
            && (trimmed.starts_with("type alias ") || trimmed.starts_with("type "))
            && trimmed.contains(" = ")
        {
            has_single_line_decl = true;
        }
        // Single-line doc-comment `{-| ... -}` on its own line inside a code
        // block. elm-format splits these into multi-line form.
        if leading == 4
            && trimmed.starts_with("{-|")
            && trimmed.ends_with("-}")
            && trimmed.len() > 5
        {
            has_single_line_decl = true;
        }
        // Tight operator (no space around) like `3^2`. elm-format always
        // inserts spaces around infix operators.
        if has_tight_binary_op(trimmed) {
            has_compact_syntax = true;
        }
        // A line that is a single parenthesized operator expression with no
        // commas, like `(true || false)`. elm-format strips the redundant
        // outer parens on reformat.
        if leading == 4 && is_redundant_paren_expr(trimmed) {
            has_compact_syntax = true;
        }
        // A hex literal whose width doesn't match elm-format's padding (2, 4,
        // 8, or 16 digits). Flag for reformat so the literal gets normalized.
        if line_has_unpadded_hex(trimmed) {
            has_compact_syntax = true;
        }
        // A float literal in scientific form with no decimal point (e.g.
        // `1e-42`). elm-format normalizes to `1.0e-42`.
        if line_has_sci_float_without_dot(trimmed) {
            has_compact_syntax = true;
        }
    }
    let has_indent_issues = count_non_4_aligned > 0;
    let has_unseparated_assertions = block_has_unseparated_assertions(block_lines);
    let has_single_line_if = block_has_single_line_if(block_lines);
    // Column-aligned assertion tables (e.g. `foo "a"  == 1` / `foo "bb" == 2`)
    // are preserved verbatim by elm-format when the alignment has a clear
    // "intent" signal (incomplete marker or compact+padding). The predicate
    // already rejects blocks that only have op-alignment without intent, so
    // if it fires we can skip reformat even with sibling reformat signals.
    if has_unseparated_assertions && block_has_column_aligned_assertions(block_lines) {
        return false;
    }
    let other_reformat_signal = has_indent_issues
        || has_compact_syntax
        || has_single_line_decl
        || has_unsorted_import
        || has_single_line_if;
    other_reformat_signal || has_unseparated_assertions
}

/// Narrower variant of `code_block_needs_reformat` for use by the
/// "sample-code doc" detector: checks for 2-space-style indent (leading 2/6
/// at base indent) but ignores alignment artifacts past a list/tuple open
/// bracket column, which legitimately produce non-4-aligned leading.
pub(in crate::print) fn code_block_has_narrow_indent(block_lines: &[&str]) -> bool {
    for &line in block_lines {
        if line.trim().is_empty() {
            continue;
        }
        let leading = line.len() - line.trim_start().len();
        if leading > 0 && leading < 4 {
            return true;
        }
        if leading > 4 && leading < 8 && (leading - 4) % 4 != 0 {
            return true;
        }
    }
    false
}

/// Does the block contain structural signals that definitely require
/// reformatting (compact syntax, single-line decls, unsorted imports, etc.),
/// excluding the broad "non-4-aligned indent" check that the primary
/// `code_block_needs_reformat` uses — that one has false positives from
/// legitimate deep-alignment artifacts in sample code. Use this as a gate
/// for the cross-block "sample code doc" detector.
pub(in crate::print) fn code_block_has_structural_reformat_signal(block_lines: &[&str]) -> bool {
    if block_mixes_decls_and_bare_exprs(block_lines) {
        return false;
    }
    if code_block_has_narrow_indent(block_lines) {
        return true;
    }
    for &line in block_lines {
        if line.trim().is_empty() {
            continue;
        }
        let leading = line.len() - line.trim_start().len();
        let trimmed = line.trim();
        if leading == 4 && import_has_unsorted_exposing(trimmed) {
            return true;
        }
        // Import/module/port header lines can contain exposing `(x, y)` lists
        // that look like compact tuples to the lexical checks below; skip them.
        let is_header_line = trimmed.starts_with("import ")
            || trimmed.starts_with("module ")
            || trimmed.starts_with("port module ")
            || trimmed.starts_with("effect module ");
        if is_header_line {
            continue;
        }
        if trimmed.contains('[')
            && trimmed.contains(']')
            && (trimmed.contains("[\"")
                || trimmed.contains("[(")
                || trimmed.contains("['")
                || trimmed.contains("[0")
                || trimmed.contains("[1")
                || trimmed.contains("[2")
                || trimmed.contains("[3")
                || trimmed.contains("[4")
                || trimmed.contains("[5")
                || trimmed.contains("[6")
                || trimmed.contains("[7")
                || trimmed.contains("[8")
                || trimmed.contains("[9"))
        {
            return true;
        }
        if trimmed.contains('(')
            && trimmed.contains(',')
            && trimmed.contains(')')
            && has_compact_tuple(trimmed)
        {
            return true;
        }
        if leading == 4
            && is_single_line_value_decl(trimmed)
            && !has_same_line_triple_string_rhs(trimmed)
        {
            return true;
        }
        if leading == 4
            && (trimmed.starts_with("type alias ") || trimmed.starts_with("type "))
            && trimmed.contains(" = ")
        {
            return true;
        }
        if leading == 4
            && trimmed.starts_with("{-|")
            && trimmed.ends_with("-}")
            && trimmed.len() > 5
        {
            return true;
        }
        if has_tight_binary_op(trimmed) {
            return true;
        }
        if leading == 4 && is_redundant_paren_expr(trimmed) {
            return true;
        }
        if line_has_unpadded_hex(trimmed) {
            return true;
        }
        if line_has_sci_float_without_dot(trimmed) {
            return true;
        }
    }
    if block_has_unseparated_assertions(block_lines) {
        return true;
    }
    if block_has_single_line_if(block_lines) {
        return true;
    }
    false
}

/// Detect a code block containing a line with a single-line `if ... then ... else ...`
/// expression. elm-format always breaks `if-then-else` across multiple lines, so
/// such blocks need reformat.
pub(in crate::print) fn try_reformat_code_block(block_lines: &[&str]) -> Option<String> {
    // If every non-blank line's leading exceeds 4, this is an indented-code
    // block with deeper-than-base indent (e.g. ASCII art, box drawings,
    // poetry). elm-format preserves these verbatim rather than treating them
    // as parse-able Elm code.
    let min_leading = block_lines
        .iter()
        .filter(|l| !l.trim().is_empty())
        .map(|l| l.len() - l.trim_start().len())
        .min();
    if matches!(min_leading, Some(n) if n > 4) {
        return None;
    }
    // A block with an assertion followed by a trailing comment-only
    // paragraph is left verbatim by elm-format. Skip reparse so we don't
    // rewrite compact lists/tuples inside it.
    if block_has_assertion_then_comment_paragraph(block_lines) {
        return None;
    }
    // Strip the 4-space prefix from each line to get raw Elm code.
    let mut raw_lines: Vec<String> = Vec::new();
    for &line in block_lines {
        if line.trim().is_empty() {
            raw_lines.push(String::new());
        } else if let Some(stripped) = line.strip_prefix("    ") {
            raw_lines.push(stripped.to_string());
        } else {
            return None;
        }
    }

    let raw_code = raw_lines.join("\n");

    // If the block already begins with a `module` declaration, use it
    // directly as the wrapper (don't double-wrap).
    let trimmed_raw = raw_code.trim_start();
    if (trimmed_raw.starts_with("module ")
        || trimmed_raw.starts_with("port module ")
        || trimmed_raw.starts_with("effect module "))
        && let Some(result) = try_parse_and_format_full_module(&raw_code)
    {
        // Re-indent every non-blank line with the 4-space doc-code prefix.
        // Inside a markdown code block, elm-format's Cheapskate renderer
        // collapses runs of blank lines to a single blank line, so skip
        // consecutive blank lines as we reindent.
        let mut out_lines: Vec<String> = Vec::new();
        let mut prev_blank = false;
        for l in result.split('\n') {
            if l.is_empty() {
                if prev_blank {
                    continue;
                }
                prev_blank = true;
                out_lines.push(String::new());
            } else {
                prev_blank = false;
                out_lines.push(format!("    {}", l));
            }
        }
        return Some(out_lines.join("\n"));
    }

    // First try: parse as a full module with declarations.
    let wrapped = format!("module DocTemp__ exposing (..)\n\n\n{}\n", raw_code);
    if let Some(result) = try_parse_and_format_module(&wrapped) {
        return Some(result);
    }

    // Second try: split into paragraphs (separated by blank lines) and
    // try each paragraph individually. Some may be expressions, some
    // declarations.
    let paragraphs = split_into_paragraphs(&raw_lines);

    // If the block has an `import` paragraph and the module-parse path
    // above already failed, elm-format leaves the whole block verbatim
    // (it won't reformat expression paragraphs that co-exist with
    // imports inside a single code block). Mirror that here.
    if paragraphs.iter().any(|p| paragraph_is_all_imports(p)) {
        let mut out_lines: Vec<String> = Vec::new();
        let mut prev_blank = false;
        for l in raw_lines.iter() {
            if l.trim().is_empty() {
                if prev_blank {
                    continue;
                }
                prev_blank = true;
                out_lines.push(String::new());
            } else {
                prev_blank = false;
                out_lines.push(format!("    {}", l));
            }
        }
        return Some(out_lines.join("\n"));
    }

    let mut formatted_paragraphs: Vec<String> = Vec::new();

    for para in &paragraphs {
        let para_text = para.join("\n");

        // Try as declaration(s) first.
        let wrapped_decl = format!("module DocTemp__ exposing (..)\n\n\n{}\n", para_text);
        if let Some(result) = try_parse_and_format_module_raw(&wrapped_decl) {
            formatted_paragraphs.push(result);
            continue;
        }

        // A single bare expression followed by `-- comment` lines is left
        // verbatim by elm-format when it can't parse the paragraph as
        // declarations. Mirror that to avoid adding unrelated spacing inside
        // example code.
        if paragraph_is_single_expr_with_line_comment(para) {
            formatted_paragraphs.push(para_text);
            continue;
        }

        // Triple-quoted strings are rarely re-printable safely (the parser
        // loses attached line comments and interior formatting). Preserve
        // the paragraph verbatim if it contains one.
        if para.iter().any(|l| l.contains("\"\"\"")) {
            formatted_paragraphs.push(para_text);
            continue;
        }

        // If the paragraph consists entirely of assertion-shaped lines, parse
        // each line as its own expression and render them as separate top-level
        // expressions. This must run BEFORE whole-paragraph expression parsing
        // because consecutive assertion lines like `1 == 1\n0 == 0` would
        // otherwise parse as function application (`1 == 1` applied to
        // `0 == 0`) and render as a single expression.
        //
        // A line starting with `-<digit/paren>` is a binary-subtraction
        // continuation of the previous expression, so it is *appended* to the
        // current accumulator rather than starting a new standalone expression.
        // This matches elm-format's behavior: `14 / 4 == 3.5\n-1 / 4 == -0.25`
        // parses as one expression `14 / 4 == 3.5 - 1 / 4 == -0.25`.
        let try_per_line = is_assertion_only_paragraph(para) && {
            let mut per_line_results: Vec<String> = Vec::new();
            let mut pending_comments: Vec<String> = Vec::new();
            let mut current_accum: Option<String> = None;
            let mut all_ok = true;
            let flush_accum = |accum: Option<String>,
                               results: &mut Vec<String>,
                               pending: &mut Vec<String>|
             -> bool {
                let Some(text) = accum else {
                    return true;
                };
                let wrapped = format!(
                    "module DocTemp__ exposing (..)\n\n\ndocTemp__ =\n{}\n",
                    text
                );
                match try_parse_and_format_expr(&wrapped) {
                    Some(r) => {
                        let combined = if pending.is_empty() {
                            r
                        } else {
                            let mut s = pending.join("\n");
                            s.push('\n');
                            s.push_str(&r);
                            pending.clear();
                            s
                        };
                        results.push(combined);
                        true
                    }
                    None => false,
                }
            };
            for line in para {
                if line.trim().is_empty() {
                    continue;
                }
                let trimmed = line.trim();
                if trimmed.starts_with("--") {
                    pending_comments.push(trimmed.to_string());
                    continue;
                }
                let is_minus_cont = trimmed.strip_prefix('-').is_some_and(|r| {
                    r.chars()
                        .next()
                        .is_some_and(|c| c.is_ascii_digit() || c == '(')
                });
                if let Some(cur) = current_accum.as_mut().filter(|_| is_minus_cont) {
                    cur.push('\n');
                    cur.push_str("    ");
                    cur.push_str(trimmed);
                } else {
                    if !flush_accum(
                        current_accum.take(),
                        &mut per_line_results,
                        &mut pending_comments,
                    ) {
                        all_ok = false;
                        break;
                    }
                    current_accum = Some(format!("    {}", trimmed));
                }
            }
            if all_ok && !flush_accum(current_accum, &mut per_line_results, &mut pending_comments) {
                all_ok = false;
            }
            if !pending_comments.is_empty() {
                per_line_results.push(pending_comments.join("\n"));
            }
            if all_ok && !per_line_results.is_empty() {
                formatted_paragraphs.push(per_line_results.join("\n\n"));
                true
            } else {
                false
            }
        };
        if try_per_line {
            continue;
        }

        // Try as expression by wrapping in a dummy function.
        let indented: Vec<String> = para
            .iter()
            .map(|line| {
                if line.is_empty() {
                    String::new()
                } else {
                    format!("    {}", line)
                }
            })
            .collect();
        let wrapped_expr = format!(
            "module DocTemp__ exposing (..)\n\n\ndocTemp__ =\n{}\n",
            indented.join("\n")
        );
        if let Some(result) = try_parse_and_format_expr(&wrapped_expr) {
            formatted_paragraphs.push(result);
            continue;
        }

        // Third try: if every non-empty line in this paragraph looks like an
        // independent assertion (`expr == value`), parse each line as its own
        // expression and join with blank lines. elm-format renders these as
        // separate "top-level" expressions. A leading `-- comment` line
        // attaches to the following assertion (no blank between them).
        if is_assertion_only_paragraph(para) {
            let mut per_line_results: Vec<String> = Vec::new();
            let mut pending_comments: Vec<String> = Vec::new();
            let mut all_ok = true;
            for line in para {
                if line.trim().is_empty() {
                    continue;
                }
                let trimmed = line.trim();
                if trimmed.starts_with("--") {
                    // Queue the comment to attach to the next assertion.
                    pending_comments.push(trimmed.to_string());
                    continue;
                }
                let wrapped_line = format!(
                    "module DocTemp__ exposing (..)\n\n\ndocTemp__ =\n    {}\n",
                    line
                );
                match try_parse_and_format_expr(&wrapped_line) {
                    Some(r) => {
                        let combined = if pending_comments.is_empty() {
                            r
                        } else {
                            let mut s = pending_comments.join("\n");
                            s.push('\n');
                            s.push_str(&r);
                            pending_comments.clear();
                            s
                        };
                        per_line_results.push(combined);
                    }
                    None => {
                        all_ok = false;
                        break;
                    }
                }
            }
            // Any trailing orphan comments attach as their own block.
            if !pending_comments.is_empty() {
                per_line_results.push(pending_comments.join("\n"));
            }
            if all_ok && !per_line_results.is_empty() {
                formatted_paragraphs.push(per_line_results.join("\n\n"));
                continue;
            }
        }

        // If the paragraph contains a triple-quoted string, it's probably
        // hard to parse as a single decl/expr but is still valid Elm in situ.
        // Keep it verbatim and continue, so other paragraphs can still be
        // reformatted.
        if para.iter().any(|l| l.contains("\"\"\"")) {
            formatted_paragraphs.push(para_text);
            continue;
        }

        // Can't parse this paragraph — bail out entirely.
        return None;
    }

    // Join paragraphs with blank lines. When a paragraph begins with a line
    // comment (`--`) and the previous paragraph consists of imports, insert
    // an extra blank line between them — elm-format renders this as a loose
    // separation.
    let mut joined = String::new();
    for (idx, para_text) in formatted_paragraphs.iter().enumerate() {
        if idx > 0 {
            let prev_para = &paragraphs[idx - 1];
            let cur_para = &paragraphs[idx];
            let sep = if paragraph_is_all_imports(prev_para)
                && paragraph_starts_with_line_comment(cur_para)
            {
                "\n\n\n"
            } else {
                "\n\n"
            };
            joined.push_str(sep);
        }
        joined.push_str(para_text);
    }
    let mut output = String::new();
    for (idx, line) in joined.split('\n').enumerate() {
        if idx > 0 {
            output.push('\n');
        }
        if line.is_empty() {
            // Keep blank lines blank.
        } else {
            output.push_str("    ");
            output.push_str(line);
        }
    }

    Some(output)
}