arity-formatter 0.7.1

Deterministic, rule-based formatter for the R language
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
use rowan::{Language, NodeOrToken, SyntaxElement, TextRange};

use super::context::FormatContext;
use super::ir::Ir;
use super::printer::Printer;
use super::render::format_atom_token;
use super::rules::control_flow::{
    ir_for_expr, ir_if_expr, ir_repeat_expr, ir_while_expr, should_insert_comment_for_gap,
    try_format_for_with_external_body, try_format_if_with_external_body,
    try_format_repeat_with_external_body, try_format_while_with_external_body,
};
use super::rules::expressions::{
    ir_assignment_expr, ir_binary_expr, ir_paren_expr, ir_subset_expr, ir_unary_expr,
};
use super::rules::functions::{ir_call_expr, ir_function_expr};
use super::style::{FormatStyle, apply_line_ending};
use super::trivia::{is_trivia as is_trivia_kind, split_lines};
use crate::ast::{
    AssignmentExpr, AstNode, BinaryExpr, BlockExpr, CallExpr, ForExpr, FunctionExpr, IfExpr,
    ParenExpr, UnaryExpr, WhileExpr,
};
use crate::parser::{ParseOptions, parse_with_options};
use crate::syntax::{RLanguage, SyntaxKind, SyntaxNode};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FormatError {
    ParseErrors {
        count: usize,
    },
    UnsupportedConstruct {
        kind: SyntaxKind,
        snippet: String,
    },
    AmbiguousConstruct {
        context: &'static str,
        snippet: String,
    },
}

impl std::fmt::Display for FormatError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ParseErrors { count } => write!(
                f,
                "input contains {count} parser diagnostic(s); formatter only supports parseable input"
            ),
            Self::UnsupportedConstruct { kind, snippet } => {
                write!(
                    f,
                    "unsupported construct for formatter: {kind:?} near {snippet:?}"
                )
            }
            Self::AmbiguousConstruct { context, snippet } => {
                write!(
                    f,
                    "ambiguous construct for formatter ({context}): {snippet:?}"
                )
            }
        }
    }
}

impl std::error::Error for FormatError {}

pub fn format(input: &str) -> Result<String, FormatError> {
    format_with_style(input, FormatStyle::default())
}

pub fn format_with_style(input: &str, style: FormatStyle) -> Result<String, FormatError> {
    format_with_options(input, style, &ParseOptions::default())
}

/// [`format_with_style`] with caller-supplied [`ParseOptions`] for the parse.
/// The one option that matters to the formatter is the roxygen markdown
/// default: a package that enables markdown package-wide
/// (`Roxygen: list(markdown = TRUE)` in `DESCRIPTION`) writes no per-block
/// `@md`, and its doc comments only format correctly — markdown lists, code
/// blocks, and tables preserved as atomic units instead of reflowed as prose —
/// when the parse resolves them in markdown mode. The mode lives entirely in
/// the parsed tree; the formatting rules themselves key off node kinds and
/// need no flag.
pub fn format_with_options(
    input: &str,
    style: FormatStyle,
    options: &ParseOptions,
) -> Result<String, FormatError> {
    let parse_output = parse_with_options(input, options);
    if !parse_output.diagnostics.is_empty() {
        return Err(FormatError::ParseErrors {
            count: parse_output.diagnostics.len(),
        });
    }

    format_node(&parse_output.cst, style, input)
}

/// Formatter output together with check-only facts discovered by comparing
/// alternate formatter decisions over the same parsed tree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormatAnalysis {
    pub formatted: String,
    pub outdated_directives: Vec<TextRange>,
}

/// Format once and identify honored directives that no longer affect output.
///
/// This is a formatter fact rather than a lint fact: each candidate is disabled
/// in turn and the formatter outputs are compared. Closing `on` directives and
/// directives in inert positions are not candidates. The parsed tree and
/// ordinary formatted output are each computed only once.
pub fn analyze_format_with_options(
    input: &str,
    style: FormatStyle,
    options: &ParseOptions,
) -> Result<FormatAnalysis, FormatError> {
    let parse_output = parse_with_options(input, options);
    if !parse_output.diagnostics.is_empty() {
        return Err(FormatError::ParseErrors {
            count: parse_output.diagnostics.len(),
        });
    }

    let root = &parse_output.cst;
    let formatted = format_node(root, style, input)?;
    let candidates = root.descendants_with_tokens().filter_map(|element| {
        let NodeOrToken::Token(token) = element else {
            return None;
        };
        if token.kind() != SyntaxKind::COMMENT {
            return None;
        }
        let arity_parser::directive::Parsed::Directive(directive) =
            arity_parser::directive::parse(token.text())?
        else {
            return None;
        };
        if !directive.tool.affects_format()
            || directive.verb == arity_parser::directive::Verb::On
            || !super::directive::is_honored_directive(&token, directive.verb)
        {
            return None;
        }
        Some(token.text_range())
    });

    let mut outdated = Vec::new();
    for range in candidates {
        if format_node_ignoring_directive(root, style, input, range)? == formatted {
            outdated.push(range);
        }
    }
    Ok(FormatAnalysis {
        formatted,
        outdated_directives: outdated,
    })
}

/// Format an already-parsed CST. The caller is responsible for rejecting input
/// that failed to parse (the diagnostics live next to the green tree in the
/// salsa cache, not on the node); this entry only guards against stray `ERROR`
/// tokens. `source` is the original text the CST was parsed from: its trailing
/// newline is preserved, and (for `line-ending = "auto"`) its first line ending
/// selects the output's newline style.
///
/// Used by the language server's read path, which formats off the cached parse
/// tree in its salsa database rather than re-parsing the buffer.
pub fn format_node(
    root: &SyntaxNode,
    style: FormatStyle,
    source: &str,
) -> Result<String, FormatError> {
    format_node_with_ignored_directive(root, style, source, None)
}

fn format_node_ignoring_directive(
    root: &SyntaxNode,
    style: FormatStyle,
    source: &str,
    ignored_directive: TextRange,
) -> Result<String, FormatError> {
    format_node_with_ignored_directive(root, style, source, Some(ignored_directive))
}

fn format_node_with_ignored_directive(
    root: &SyntaxNode,
    style: FormatStyle,
    source: &str,
    ignored_directive: Option<TextRange>,
) -> Result<String, FormatError> {
    // `# arity-format skip-file` is answered here and nowhere else: ordinary
    // formatting hands the file back byte for byte, so idempotence holds
    // trivially. Not even the line ending is normalized — the point of the
    // directive is that nothing is decided. Check analysis separately asks
    // whether the same bytes emerge when one such directive is ignored.
    if scan_tokens(root, ignored_directive)?.skipped {
        return Ok(source.to_string());
    }
    let ctx = match ignored_directive {
        Some(range) => FormatContext::ignoring_directive(style, range),
        None => FormatContext::new(style),
    };
    let mut formatted = format_root(root, ctx)?;
    if source.ends_with('\n') && !formatted.ends_with('\n') {
        formatted.push('\n');
    }
    Ok(apply_line_ending(
        &formatted,
        style.line_ending.resolve(source),
    ))
}

/// A region reformatted by [`format_range`]: the byte range to replace and the
/// text to replace it with. The range is the union of the selected statements'
/// non-whitespace spans (so the first line's existing indentation is left
/// untouched), and `text` carries no leading indent on its first line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RangeFormatted {
    pub range: TextRange,
    pub text: String,
}

/// Format only the statements overlapping `range`, leaving the rest of the
/// document untouched. Mirrors air: the selection is widened to whole statements
/// of the deepest enclosing statement list (ROOT or a block body), those
/// statements are formatted at their structural indent, and the first line's
/// existing indentation is preserved (only continuation lines are reindented).
///
/// Returns `Ok(None)` when the selection covers no statement (empty, whitespace,
/// or comment-gap only). Like [`format_node`], the caller must reject input that
/// failed to parse; this only guards against stray `ERROR` tokens.
pub fn format_range(
    root: &SyntaxNode,
    range: TextRange,
    style: FormatStyle,
    source: &str,
) -> Result<Option<RangeFormatted>, FormatError> {
    if scan_tokens(root, None)?.skipped {
        return Ok(None);
    }
    let ctx = FormatContext::new(style);

    let container = statement_container(root, range);
    let in_block = container.kind() == SyntaxKind::BLOCK_EXPR;
    let elements: Vec<SyntaxElement<RLanguage>> = if in_block {
        super::render::block_statement_elements(&container)?
    } else {
        container.children_with_tokens().collect()
    };
    let lines = split_lines(elements, "range")?;
    if lines.is_empty() {
        return Ok(None);
    }

    // Statements inside `n` nested blocks sit at indent level `n`; ROOT is 0.
    let base_indent = container
        .ancestors()
        .filter(|n| n.kind() == SyntaxKind::BLOCK_EXPR)
        .count();

    // Widen the selection to every statement line whose span touches `range`.
    let mut window_start: Option<usize> = None;
    let mut window_end = 0usize;
    for (idx, line) in lines.iter().enumerate() {
        if let Some(span) = line_significant_span(line)
            && span.start() <= range.end()
            && range.start() <= span.end()
        {
            window_start.get_or_insert(idx);
            window_end = idx + 1;
        }
    }
    let Some(window_start) = window_start else {
        return Ok(None);
    };
    let window = expand_comment_alignment_window(&lines, window_start..window_end);

    let rendered = if in_block {
        ir_block_statements(&lines, window, base_indent, ctx)?
    } else {
        ir_statements(&lines, window, base_indent, ctx)?
    };
    let (Some(first_line), Some(last_line)) = (rendered.first_line, rendered.last_line) else {
        return Ok(None);
    };

    let start = line_significant_span(&lines[first_line])
        .expect("emitted line has a significant span")
        .start();
    let end = line_significant_span(&lines[last_line])
        .expect("consumed line has a significant span")
        .end();

    let mut text = Printer::new(style).print_at(&rendered.ir, base_indent);
    while text.ends_with('\n') {
        text.pop();
    }
    let text = apply_line_ending(&text, style.line_ending.resolve(source));

    Ok(Some(RangeFormatted {
        range: TextRange::new(start, end),
        text,
    }))
}

/// Include the complete adjacent run when a range touches an alignable trailing
/// comment. Otherwise formatting one member could choose a column that its
/// untouched neighbors do not share, diverging from whole-document formatting.
fn expand_comment_alignment_window(
    lines: &[Vec<SyntaxElement<RLanguage>>],
    mut window: std::ops::Range<usize>,
) -> std::ops::Range<usize> {
    let plan = super::directive::plan(lines, None);
    let participates = |idx: usize| {
        !plan.contains(idx)
            && lines.get(idx).is_some_and(|line| {
                let significant: Vec<_> = line
                    .iter()
                    .filter(|el| !is_trivia_kind(el.kind()))
                    .collect();
                significant.len() >= 2
                    && significant
                        .last()
                        .is_some_and(|el| super::trivia::is_inline_trailing_comment(el))
            })
    };

    if participates(window.start) {
        while window.start > 0 && participates(window.start - 1) {
            window.start -= 1;
        }
    }
    if window.end > 0 && participates(window.end - 1) {
        while window.end < lines.len() && participates(window.end) {
            window.end += 1;
        }
    }
    window
}

/// The deepest ROOT/BLOCK_EXPR node whose statement list fully contains `range`.
/// `covering_element` already yields the smallest element spanning the whole
/// range, so its nearest statement-list ancestor is the deepest common one.
fn statement_container(root: &SyntaxNode, range: TextRange) -> SyntaxNode {
    let is_container = |kind: SyntaxKind| matches!(kind, SyntaxKind::ROOT | SyntaxKind::BLOCK_EXPR);
    let found = match root.covering_element(range) {
        NodeOrToken::Node(node) => node.ancestors().find(|n| is_container(n.kind())),
        NodeOrToken::Token(token) => token.parent_ancestors().find(|n| is_container(n.kind())),
    };
    found.unwrap_or_else(|| root.clone())
}

/// The span of a line from its first to its last non-trivia element (comments
/// included). `None` for a blank line, which has no significant element.
fn line_significant_span(line: &[SyntaxElement<RLanguage>]) -> Option<TextRange> {
    let mut significant = line.iter().filter(|el| !is_trivia_kind(el.kind()));
    let first = significant.next()?;
    let last = significant.next_back().unwrap_or(first);
    Some(TextRange::new(
        first.text_range().start(),
        last.text_range().end(),
    ))
}

/// The two whole-tree facts every entry point needs before a single layout
/// decision: whether the parse left a stray `ERROR` token, and whether the file
/// carries a `# arity-format skip-file`.
///
/// Both are pure token predicates, so this walks the **green** tree rather than
/// taking two `descendants_with_tokens()` passes. A cursor walk allocates and
/// drops a `SyntaxNode` per element visited, and these prepasses touch every
/// element in the file before any work that could use one.
///
/// An `ERROR` token outranks the directive: `skip-file` declines to decide
/// layout, it does not certify that the tree is formattable.
fn scan_tokens(
    root: &SyntaxNode,
    ignored_directive: Option<TextRange>,
) -> Result<TokenScan, FormatError> {
    if let Some(ignored) = ignored_directive {
        let mut skipped = false;
        for element in root.descendants_with_tokens() {
            let NodeOrToken::Token(token) = element else {
                continue;
            };
            if token.kind() == SyntaxKind::ERROR {
                return Err(FormatError::UnsupportedConstruct {
                    kind: token.kind(),
                    snippet: token.text().to_string(),
                });
            }
            if token.text_range() != ignored
                && token.kind() == SyntaxKind::COMMENT
                && super::directive::is_skip_file(token.text())
            {
                skipped = true;
            }
        }
        return Ok(TokenScan { skipped });
    }

    let mut scan = TokenScan { skipped: false };
    // An explicit stack, not recursion: nesting depth is the input's, and a
    // prepass must not be the thing that overflows on a tree the parser built.
    let mut stack: Vec<rowan::Children<'_>> = vec![root.green().children()];
    while let Some(children) = stack.last_mut() {
        let Some(child) = children.next() else {
            stack.pop();
            continue;
        };
        match child {
            NodeOrToken::Node(node) => stack.push(node.children()),
            NodeOrToken::Token(token) => {
                let kind = RLanguage::kind_from_raw(token.kind());
                if kind == SyntaxKind::ERROR {
                    return Err(FormatError::UnsupportedConstruct {
                        kind,
                        snippet: token.text().to_string(),
                    });
                }
                if !scan.skipped
                    && kind == SyntaxKind::COMMENT
                    && super::directive::is_skip_file(token.text())
                {
                    scan.skipped = true;
                }
            }
        }
    }
    Ok(scan)
}

/// What [`scan_tokens`] found. An `ERROR` token is reported as the `Err`, so
/// reaching this means the tree is formattable.
struct TokenScan {
    /// The file is `# arity-format skip-file`.
    skipped: bool,
}

fn format_root(root: &SyntaxNode, ctx: FormatContext) -> Result<String, FormatError> {
    let ir = ir_root(root, ctx)?;
    Ok(Printer::new(ctx.style()).print(&ir))
}

/// IR builder for the whole document. Mirrors [`legacy_format_root`]: statements
/// are separated by hard breaks (a blank line where a gap should be preserved),
/// control-flow forms whose body is on a following line are rendered via the
/// (bridged) external-body handlers, and everything else is an [`ir_line`].
fn ir_root(root: &SyntaxNode, ctx: FormatContext) -> Result<Ir, FormatError> {
    let lines = split_lines(root.children_with_tokens().collect(), "root")?;
    if lines.is_empty() {
        return Ok(Ir::nil());
    }
    Ok(ir_statements(&lines, 0..lines.len(), 0, ctx)?.ir)
}

/// IR built for a sub-window of a statement list, plus the bounds of the lines it
/// actually emitted. `first_line`/`last_line` are line indices into `lines`:
/// `last_line` accounts for control-flow bodies pulled in from following lines,
/// so callers can compute the exact text span the IR replaces.
pub(super) struct StatementsIr {
    pub(super) ir: Ir,
    pub(super) first_line: Option<usize>,
    pub(super) last_line: Option<usize>,
}

/// Sequence the statements of a ROOT-style list (blank-line gaps preserved,
/// control-flow forms whose body sits on a following line rejoined) emitting only
/// the lines whose index falls in `window`. Iterating the full `lines` (not a
/// sub-slice) keeps the external-body lookahead and the blank-line gap context
/// (`should_insert_comment_for_gap`, which inspects preceding lines) correct at
/// the window's edges. `ir_root` passes `0..lines.len()`.
pub(super) fn ir_statements(
    lines: &[Vec<SyntaxElement<RLanguage>>],
    window: std::ops::Range<usize>,
    indent: usize,
    ctx: FormatContext,
) -> Result<StatementsIr, FormatError> {
    let plan = super::directive::plan(lines, ctx.ignored_directive());
    let mut items: Vec<Ir> = Vec::new();
    let mut first_line: Option<usize> = None;
    let mut last_line: Option<usize> = None;
    let mut idx = 0usize;
    while idx < lines.len() {
        if !window.contains(&idx) {
            idx += 1;
            continue;
        }

        if first_line.is_some() {
            if should_insert_comment_for_gap(lines, idx, indent, ctx)? {
                items.push(Ir::empty_line());
            } else {
                items.push(Ir::hard_line());
            }
        }

        let consumed =
            if let Some((skipped, last)) = super::directive::skipped_at(lines, &plan, idx) {
                // The author asked for these lines back exactly as written; the
                // layout engine gets no say, including over the indent.
                items.push(skipped);
                last - idx
            } else if let Some((body_ir, consumed)) =
                try_format_for_with_external_body(lines, idx, indent, ctx)?
            {
                items.push(body_ir);
                consumed
            } else if let Some((body_ir, consumed)) =
                try_format_while_with_external_body(lines, idx, indent, ctx)?
            {
                items.push(body_ir);
                consumed
            } else if let Some((body_ir, consumed)) =
                try_format_if_with_external_body(lines, idx, indent, ctx)?
            {
                items.push(body_ir);
                consumed
            } else if let Some((body_ir, consumed)) =
                try_format_repeat_with_external_body(lines, idx, indent, ctx)?
            {
                items.push(body_ir);
                consumed
            } else {
                items.push(ir_line(&lines[idx], indent, ctx)?);
                0
            };

        if first_line.is_none() {
            first_line = Some(idx);
        }
        last_line = Some(idx + consumed);
        idx += consumed + 1;
    }
    Ok(StatementsIr {
        ir: Ir::concat(items),
        first_line,
        last_line,
    })
}

/// Sequence the statements of a block body for a sub-window. Mirrors
/// [`super::render::ir_block_expr_with_prefixed_comments`]'s body rules (plain
/// hard breaks between statements, no blank-line preservation, no external-body
/// lookahead), but without the surrounding braces, so range formatting of a
/// block's interior matches whole-document block output.
pub(super) fn ir_block_statements(
    lines: &[Vec<SyntaxElement<RLanguage>>],
    window: std::ops::Range<usize>,
    indent: usize,
    ctx: FormatContext,
) -> Result<StatementsIr, FormatError> {
    let plan = super::directive::plan(lines, ctx.ignored_directive());
    let mut items: Vec<Ir> = Vec::new();
    let mut first_line: Option<usize> = None;
    let mut last_line: Option<usize> = None;
    let mut idx = window.start;
    while idx < window.end && idx < lines.len() {
        if first_line.is_some() {
            items.push(Ir::hard_line());
        }
        let consumed = match super::directive::skipped_at(lines, &plan, idx) {
            Some((skipped, last)) => {
                items.push(skipped);
                last - idx
            }
            None => {
                items.push(ir_line(&lines[idx], indent, ctx)?);
                0
            }
        };
        if first_line.is_none() {
            first_line = Some(idx);
        }
        last_line = Some(idx + consumed);
        idx += consumed + 1;
    }
    Ok(StatementsIr {
        ir: Ir::concat(items),
        first_line,
        last_line,
    })
}

pub(super) fn format_expr_segment(
    elements: &[SyntaxElement<RLanguage>],
    context: &'static str,
    indent: usize,
    ctx: FormatContext,
) -> Result<String, FormatError> {
    super::render::format_expr_segment(elements, context, indent, ctx, format_expr_element)
}

/// A single statement line as IR, without the leading indentation (the caller
/// supplies that structurally via [`Ir::Indent`] and line breaks). An empty
/// (blank) line yields [`Ir::Nil`].
pub(super) fn ir_line(
    line: &[SyntaxElement<RLanguage>],
    indent: usize,
    ctx: FormatContext,
) -> Result<Ir, FormatError> {
    let significant: Vec<_> = line
        .iter()
        .filter(|el| !is_trivia_kind(el.kind()))
        .cloned()
        .collect();
    if significant.is_empty() {
        return Ok(Ir::nil());
    }

    if let [NodeOrToken::Token(token)] = significant.as_slice()
        && token.kind() == SyntaxKind::COMMENT
    {
        return Ok(Ir::text(token.text().to_string()));
    }

    if let [NodeOrToken::Node(node)] = significant.as_slice()
        && node.kind() == SyntaxKind::ROXYGEN_BLOCK
    {
        return Ok(super::roxygen::ir_roxygen_block(node, indent, ctx));
    }

    if significant.len() == 2
        && let Some(comment) = super::trivia::inline_trailing_comment_text(&significant[1])
    {
        let expr = ir_expr_element(&significant[0], indent, ctx)?;
        // The trailing comment is a zero-width line suffix so it never forces the
        // expression's own groups to break (matching air); the statement
        // separator supplies the newline that ends its line.
        return Ok(Ir::concat([
            expr,
            super::trivia::ir_inline_trailing_comment(&comment),
        ]));
    }

    ir_expr_segment(&significant, "line expression", indent, ctx)
}

pub(super) fn format_expr_element(
    element: &SyntaxElement<RLanguage>,
    indent: usize,
    ctx: FormatContext,
) -> Result<String, FormatError> {
    let ir = ir_expr_element(element, indent, ctx)?;
    Ok(Printer::new(ctx.style()).print_at(&ir, indent))
}

/// IR dispatch for an element. Migrated constructs build real IR; the rest fall
/// back to the legacy string formatter wrapped as a `Verbatim` node (Bridge A).
pub(super) fn ir_expr_element(
    element: &SyntaxElement<RLanguage>,
    indent: usize,
    ctx: FormatContext,
) -> Result<Ir, FormatError> {
    match element {
        NodeOrToken::Node(node) => ir_expr_node(node, indent, ctx),
        NodeOrToken::Token(token) => ir_atom_token(token),
    }
}

fn ir_expr_node(node: &SyntaxNode, indent: usize, ctx: FormatContext) -> Result<Ir, FormatError> {
    if let Some(expr) = AssignmentExpr::cast(node.clone()) {
        return ir_assignment_expr(expr.syntax(), indent, ctx);
    }
    if let Some(expr) = UnaryExpr::cast(node.clone()) {
        return ir_unary_expr(expr.syntax(), indent, ctx);
    }
    if let Some(expr) = BinaryExpr::cast(node.clone()) {
        return ir_binary_expr(expr.syntax(), indent, ctx);
    }
    if let Some(expr) = ParenExpr::cast(node.clone()) {
        return ir_paren_expr(expr.syntax(), indent, ctx);
    }
    if let Some(expr) = BlockExpr::cast(node.clone()) {
        return ir_block_expr(expr.syntax(), indent, ctx);
    }
    if let Some(expr) = ForExpr::cast(node.clone()) {
        return ir_for_expr(expr.syntax(), indent, ctx);
    }
    if let Some(expr) = WhileExpr::cast(node.clone()) {
        return ir_while_expr(expr.syntax(), indent, ctx);
    }
    if node.kind() == SyntaxKind::REPEAT_EXPR {
        return ir_repeat_expr(node, indent, ctx);
    }
    if let Some(expr) = IfExpr::cast(node.clone()) {
        return ir_if_expr(expr.syntax(), indent, ctx);
    }
    // Subset, call, and function arg lists are rendered natively on the IR.
    // Calls and function definitions fall back to the legacy string renderer
    // (inside `ir_call_expr` / `ir_function_expr`) for the cases that involve
    // comment relocation not yet ported to the IR.
    if matches!(
        node.kind(),
        SyntaxKind::SUBSET_EXPR | SyntaxKind::SUBSET2_EXPR
    ) {
        return ir_subset_expr(node, indent, ctx);
    }
    if let Some(expr) = CallExpr::cast(node.clone()) {
        return ir_call_expr(expr.syntax(), indent, ctx);
    }
    if let Some(expr) = FunctionExpr::cast(node.clone()) {
        return ir_function_expr(expr.syntax(), indent, ctx);
    }
    // A `#'` line inside an argument list parses as a comment-only `ROXYGEN_BLOCK`
    // (roxygen2 does not treat it as documentation there, but the CST shape
    // matches the block/root parsers). Lay it out like any other roxygen block.
    if node.kind() == SyntaxKind::ROXYGEN_BLOCK {
        return Ok(super::roxygen::ir_roxygen_block(node, indent, ctx));
    }

    Err(FormatError::UnsupportedConstruct {
        kind: node.kind(),
        snippet: node.text().to_string(),
    })
}

/// Atom tokens (identifiers, literals, `!`) become plain text. Reuses the legacy
/// token validation so unsupported tokens keep raising `UnsupportedConstruct`.
fn ir_atom_token(token: &rowan::SyntaxToken<RLanguage>) -> Result<Ir, FormatError> {
    Ok(Ir::text(format_atom_token(token)?))
}

/// IR counterpart of [`format_expr_segment`]: a run of elements that must reduce
/// to exactly one significant expression.
pub(super) fn ir_expr_segment(
    elements: &[SyntaxElement<RLanguage>],
    context: &'static str,
    indent: usize,
    ctx: FormatContext,
) -> Result<Ir, FormatError> {
    let significant: Vec<_> = elements
        .iter()
        .filter(|el| !is_trivia_kind(el.kind()))
        .cloned()
        .collect();
    if significant.len() != 1 {
        return Err(FormatError::AmbiguousConstruct {
            context,
            snippet: snippet_from_elements(elements),
        });
    }
    ir_expr_element(&significant[0], indent, ctx)
}

/// A single expression optionally followed by a trailing comment on the same
/// line.
pub(super) fn ir_expr_with_optional_comment(
    elements: &[SyntaxElement<RLanguage>],
    context: &'static str,
    indent: usize,
    ctx: FormatContext,
) -> Result<Ir, FormatError> {
    let significant: Vec<_> = elements
        .iter()
        .filter(|el| !is_trivia_kind(el.kind()))
        .cloned()
        .collect();

    if significant.len() == 2
        && let Some(comment) = super::trivia::inline_trailing_comment_text(&significant[1])
    {
        let expr = ir_expr_element(&significant[0], indent, ctx)?;
        // Zero-width line suffix: the trailing comment must not force the
        // expression to break (matching air). A break always follows it in
        // context (statement separator, or the enclosing list that a comment
        // forces open).
        return Ok(Ir::concat([
            expr,
            super::trivia::ir_inline_trailing_comment(&comment),
        ]));
    }

    ir_expr_segment(elements, context, indent, ctx)
}

fn ir_block_expr(node: &SyntaxNode, indent: usize, ctx: FormatContext) -> Result<Ir, FormatError> {
    ir_block_expr_with_prefixed_comments(node, indent, ctx, &[])
}

pub(super) fn ir_block_expr_with_prefixed_comments(
    node: &SyntaxNode,
    indent: usize,
    ctx: FormatContext,
    prefixed_comments: &[String],
) -> Result<Ir, FormatError> {
    super::render::ir_block_expr_with_prefixed_comments(
        node,
        indent,
        ctx,
        prefixed_comments,
        &[],
        ir_line,
    )
}

pub(super) fn ir_block_expr_with_trailing_comments(
    node: &SyntaxNode,
    indent: usize,
    ctx: FormatContext,
    trailing_comments: &[String],
) -> Result<Ir, FormatError> {
    super::render::ir_block_expr_with_prefixed_comments(
        node,
        indent,
        ctx,
        &[],
        trailing_comments,
        ir_line,
    )
}

pub(super) fn ir_block_expr_with_surrounding_comments(
    node: &SyntaxNode,
    indent: usize,
    ctx: FormatContext,
    prefixed_comments: &[String],
    trailing_comments: &[String],
) -> Result<Ir, FormatError> {
    super::render::ir_block_expr_with_prefixed_comments(
        node,
        indent,
        ctx,
        prefixed_comments,
        trailing_comments,
        ir_line,
    )
}

pub(super) fn snippet_from_elements(elements: &[SyntaxElement<RLanguage>]) -> String {
    super::render::snippet_from_elements(elements)
}

pub(super) fn reparse_snippet_from_elements(elements: &[SyntaxElement<RLanguage>]) -> String {
    super::render::reparse_snippet_from_elements(elements)
}

pub(super) fn is_trivia(kind: SyntaxKind) -> bool {
    is_trivia_kind(kind)
}

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

    /// Formatting an already-parsed CST must match formatting the same text,
    /// so the LSP read path (which formats off the cached parse tree) stays
    /// byte-identical to the text entry point.
    #[test]
    fn format_node_matches_format_with_style() {
        let style = FormatStyle::default();
        for input in [
            "x<-1\n",
            "x <- 1\n",
            "f(a,b ,c)\n",
            "if(x){y}else{z}\n",
            "x<-1", // no trailing newline
            "",
        ] {
            let via_text = format_with_style(input, style);
            let parsed = parse(input);
            let via_node = format_node(&parsed.cst, style, input);
            assert_eq!(via_text, via_node, "mismatch for {input:?}");
        }
    }

    /// A stray `ERROR` token is refused with the *first* one in document
    /// order, and it outranks a `skip-file` directive: the directive declines
    /// to decide layout, it does not certify that the tree is formattable.
    #[test]
    fn stray_error_token_is_refused_before_skip_file() {
        let style = FormatStyle::default();
        let source = "# arity-format skip-file\nx <- \u{1}\ny <- \u{2}\n";
        let parsed = parse(source);
        assert_eq!(
            format_node(&parsed.cst, style, source),
            Err(FormatError::UnsupportedConstruct {
                kind: SyntaxKind::ERROR,
                snippet: "\u{1}".to_string(),
            })
        );
        assert_eq!(
            format_range(&parsed.cst, TextRange::default(), style, source),
            Err(FormatError::UnsupportedConstruct {
                kind: SyntaxKind::ERROR,
                snippet: "\u{1}".to_string(),
            })
        );
    }

    /// `skip-file` hands the source back byte for byte, wherever the directive
    /// sits and whichever spelling addresses the formatter.
    #[test]
    fn skip_file_returns_source_byte_for_byte() {
        let style = FormatStyle::default();
        for source in [
            "# arity-format skip-file\nx<-1\n",
            "x<-1\n# arity-format skip-file\n",
            "f <- function() {\n  # arity-format skip-file\n  x<-1\n}\n",
            "# arity skip-file\r\nx<-1\r\n",
            "# arity-format skip-file\nx<-1", // no trailing newline
        ] {
            let parsed = parse(source);
            assert_eq!(
                format_node(&parsed.cst, style, source).as_deref(),
                Ok(source),
                "mismatch for {source:?}"
            );
            assert_eq!(
                format_range(&parsed.cst, TextRange::default(), style, source),
                Ok(None),
                "mismatch for {source:?}"
            );
        }
    }

    #[test]
    fn reports_only_format_directives_that_no_longer_change_output() {
        let source = concat!(
            "# arity-format skip: already canonical\n",
            "x <- 1\n",
            "# arity-format skip: still needed\n",
            "y<-2\n",
            "# arity-format off: already canonical region\n",
            "z <- 3\n",
            "# arity-format on\n",
        );

        let outdated =
            analyze_format_with_options(source, FormatStyle::default(), &ParseOptions::default())
                .expect("analyzes directives")
                .outdated_directives;

        assert_eq!(outdated.len(), 2);
        assert_eq!(
            &source[usize::from(outdated[0].start())..usize::from(outdated[0].end())],
            "# arity-format skip: already canonical"
        );
        assert_eq!(
            &source[usize::from(outdated[1].start())..usize::from(outdated[1].end())],
            "# arity-format off: already canonical region"
        );
    }

    #[test]
    fn does_not_report_inert_or_closing_directives_as_outdated() {
        let source = concat!(
            "f(\n",
            "  # arity-format skip: inert here\n",
            "  x = 1\n",
            ")\n",
            "# arity-format on\n",
        );

        assert!(
            analyze_format_with_options(source, FormatStyle::default(), &ParseOptions::default(),)
                .expect("analyzes directives")
                .outdated_directives
                .is_empty()
        );
    }

    #[test]
    fn skip_file_is_outdated_only_when_unprotected_output_is_unchanged() {
        for (source, expected) in [
            ("# arity-format skip-file\nx <- 1\n", 1),
            ("# arity-format skip-file\nx<-1\n", 0),
        ] {
            assert_eq!(
                analyze_format_with_options(
                    source,
                    FormatStyle::default(),
                    &ParseOptions::default(),
                )
                .expect("analyzes directives")
                .outdated_directives
                .len(),
                expected,
                "mismatch for {source:?}"
            );
        }
    }

    #[test]
    fn detects_outdated_directive_inside_block_statement_list() {
        let source = "f <- function() {\n  # arity-format skip\n  x <- 1\n}\n";
        assert_eq!(
            analyze_format_with_options(source, FormatStyle::default(), &ParseOptions::default(),)
                .expect("analyzes directives")
                .outdated_directives
                .len(),
            1
        );
    }

    #[test]
    fn line_ending_auto_mirrors_source() {
        use crate::formatter::LineEnding;
        let style = FormatStyle {
            line_ending: LineEnding::Auto,
            ..FormatStyle::default()
        };
        // A CRLF source round-trips to CRLF output; an LF source stays LF.
        assert_eq!(
            format_with_style("x<-1\r\ny<-2\r\n", style).unwrap(),
            "x <- 1\r\ny <- 2\r\n"
        );
        assert_eq!(
            format_with_style("x<-1\ny<-2\n", style).unwrap(),
            "x <- 1\ny <- 2\n"
        );
    }

    #[test]
    fn line_ending_explicit_overrides_source() {
        use crate::formatter::LineEnding;
        let crlf = FormatStyle {
            line_ending: LineEnding::Crlf,
            ..FormatStyle::default()
        };
        assert_eq!(
            format_with_style("x<-1\ny<-2\n", crlf).unwrap(),
            "x <- 1\r\ny <- 2\r\n"
        );
        let lf = FormatStyle {
            line_ending: LineEnding::Lf,
            ..FormatStyle::default()
        };
        assert_eq!(
            format_with_style("x<-1\r\ny<-2\r\n", lf).unwrap(),
            "x <- 1\ny <- 2\n"
        );
    }
}