elint 0.1.1

Erlang code linter
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
//! Per-file tokenize / preprocess / parse pipeline.
//!
//! [`Context::analyze`] runs the three-stage pipeline for one source text:
//! tokenize with `erl_tokenize`, preprocess with `erl_pp` (responding to
//! every `Awaiting*` event: include, conditional, macro expansion), and parse
//! the preprocessed lexical tokens with `erl_parse` (`ParseMode::Module`).
//!
//! [`Context::analyze`] is an API that takes a path and a source string; it
//! does not collect files. Recursively collecting `.erl` / `.hrl` under a
//! file or directory is [`crate::fs::collect_erlang_files`].
//!
//! ## Branch exploration
//!
//! The driver explores several preprocessor states for one file. At each
//! `AwaitingConditional` event the current `Fork` is cloned into a mainline
//! side (`Branch::Then`) and a non-mainline side (`Branch::Else`). The
//! mainline continues past the `-endif`; a non-mainline fork stops at the
//! `-endif` that closes the conditional it was forked from, tracked with
//! `Fork::depth` / `Fork::stop_depth`. Each source region is therefore
//! scanned by exactly one fork, so findings do not duplicate across branches
//! and the work stays linear in the input size instead of growing with the
//! product of independent conditionals.
//!
//! Each explored state becomes a [`BranchContext`], which holds the branch's
//! token origin data (`source_tokens`), its syntax tree, and its
//! preprocessor diagnostics. [`BranchContext::span_of_range`] and
//! `span_in_original_file` map tokens back to byte spans in the original
//! file, so findings from any branch can be reported at the original source
//! location.
//!
//! ## Error handling
//!
//! - A tokenize error aborts the file: [`Context::analyze`] returns
//!   `Err(erl_tokenize::Error)` and no branch is linted.
//! - A preprocessor structural error (stray `-else`, unclosed conditional,
//!   macro arity mismatch, ...) is collected as a [`PreprocessDiagnostic`]
//!   on the branch; the branch's lint still runs if the file parses.
//! - A parse diagnostic is attached to the branch's tree; that branch's lint
//!   is skipped, while other branches still contribute findings.
//! - A preprocessor protocol error (a `step` / `resume_*` call outside the
//!   expected event flow) is a driver bug and panics with
//!   `preprocessor protocol`.

use std::path::{Path, PathBuf};

use crate::Span;

/// Diagnostic recorded while driving the preprocessor.
#[derive(Debug, Clone)]
pub struct PreprocessDiagnostic {
    /// Location in the original file when it can be mapped; otherwise [`Span::ZERO`].
    pub span: Span,
    /// Human-readable description.
    pub message: String,
}

/// A `-include` / `-include_lib` directive skipped by the preprocessor.
///
/// Includes are not resolved, so they never appear in [`BranchContext::tree`].
/// Rules that care about directive placement (for example attribute order)
/// read these retained sites instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SkippedInclude {
    /// Byte range of the attribute name (`include` or `include_lib`).
    pub name_span: Span,
    /// Whether the directive was `-include_lib`.
    pub is_lib: bool,
}

/// A `-define` directive consumed by the preprocessor.
///
/// Macro definitions are registered by `erl_pp` and do not remain in
/// [`BranchContext::tree`]. Rules that care about attribute placement read
/// these retained sites instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SkippedDefine {
    /// Byte range of the attribute name `define`.
    pub name_span: Span,
}

/// One explored conditional-arm path through the file.
#[derive(Debug)]
pub struct BranchContext {
    /// Side table parallel to `tree.tokens()`: origin and source span of each
    /// token, in the same order as the parse tree's token slice.
    pub source_tokens: Vec<erl_pp::SourceToken>,
    /// Parse forest for the preprocessed token stream.
    pub tree: erl_parse::SyntaxTree,
    /// Preprocessor diagnostics (`-error` / `-warning`, input errors).
    pub preprocess_diagnostics: Vec<PreprocessDiagnostic>,
    /// `-include` / `-include_lib` sites consumed while skipping headers.
    pub skipped_includes: Vec<SkippedInclude>,
    /// `-define` sites consumed while registering macros.
    pub skipped_defines: Vec<SkippedDefine>,
}

/// Analyzed Erlang file: original source and one analysis per explored
/// conditional-arm path.
#[derive(Debug)]
pub struct Context {
    /// Path used as the preprocessor display name (and for CLI output).
    pub path: PathBuf,
    /// Original file text.
    pub text: String,
    /// Tokens scanned from [`Context::text`], including comments and whitespace.
    pub original_tokens: Vec<erl_tokenize::Token>,
    /// Per-branch analyses. `branches[0]` is the mainline (`Branch::Then`
    /// taken at every conditional).
    pub branches: Vec<BranchContext>,
}

impl Context {
    /// Tokenizes, preprocesses, and parses `text` as a module.
    ///
    /// Returns [`erl_tokenize::Error`] when the original file cannot be scanned.
    /// Preprocessor protocol mistakes panic: they are driver bugs.
    pub fn analyze<P: AsRef<Path>>(path: P, text: String) -> Result<Self, erl_tokenize::Error> {
        let path = path.as_ref().to_path_buf();
        let original_tokens = erl_tokenize::scan_tokens(&text)?;
        let source = erl_pp::Source::new(
            path.to_string_lossy().as_ref(),
            text.clone(),
            original_tokens.clone(),
        );
        let branches = preprocess(source)
            .into_iter()
            .map(
                |(source_tokens, preprocess_diagnostics, skipped_includes, skipped_defines)| {
                    let tokens: Vec<_> = source_tokens.iter().map(|t| *t.token()).collect();
                    let tree = erl_parse::parse(tokens, erl_parse::ParseMode::Module);
                    BranchContext {
                        source_tokens,
                        tree,
                        preprocess_diagnostics,
                        skipped_includes,
                        skipped_defines,
                    }
                },
            )
            .collect();
        Ok(Self {
            path,
            text,
            original_tokens,
            branches,
        })
    }
}

impl BranchContext {
    /// Maps a token-buffer range to a byte range in the original file.
    ///
    /// Empty ranges (missing tokens / EOF) map to the end of the preceding
    /// original-file token, or to offset 0 when there is no preceding token.
    pub fn span_of_range(&self, range: erl_parse::TokenRange) -> Option<Span> {
        if range.is_empty() {
            let i = range.start().get();
            if i == 0 {
                return Some(Span::new(0, 0));
            }
            return self.span_of_token(i - 1).map(|s| Span::new(s.end, s.end));
        }

        let mut start = None;
        let mut end = None;
        for i in range {
            let Some(s) = self.span_of_token(i.get()) else {
                continue;
            };
            start = Some(start.map_or(s.start, |t: usize| t.min(s.start)));
            end = Some(end.map_or(s.end, |t: usize| t.max(s.end)));
        }
        Some(Span::new(start?, end?))
    }

    fn span_of_token(&self, index: usize) -> Option<Span> {
        let token = self.source_tokens.get(index)?;
        span_in_original_file(token.origin(), token.source_span())
    }

    /// Returns the `Name/Arity` of the function enclosing `node`, e.g.
    /// `foo/2`, when the node lies inside a [`erl_parse::SyntaxKind::FunctionDecl`].
    ///
    /// Walks `node`'s ancestors to the nearest `FunctionDecl`, reads the
    /// name atom and argument-list arity from its first
    /// [`erl_parse::SyntaxKind::FunctionClause`], and returns `None` when
    /// there is no enclosing function (top-level or attribute context) or
    /// the name cannot be resolved.
    pub fn enclosing_function_name(&self, node: erl_parse::NodeId) -> Option<String> {
        let view = self.tree.view(node)?;
        let decl = view
            .ancestors()
            .find(|a| a.kind() == erl_parse::SyntaxKind::FunctionDecl)?;
        let clause = decl
            .children()
            .find(|c| c.kind() == erl_parse::SyntaxKind::FunctionClause)?;
        let name = clause_name(self, clause)?;
        let arity = clause_arity(clause)?;
        Some(format!("{name}/{arity}"))
    }
}

/// Reads the name atom of a function clause: its first lexical token.
pub(crate) fn clause_name(branch: &BranchContext, node: erl_parse::NodeView<'_>) -> Option<String> {
    node.indexed_tokens().find_map(|(i, _)| {
        let token = branch.source_tokens.get(i.get())?;
        if !token.token().kind().is_lexical() {
            return None;
        }
        match token.value() {
            erl_tokenize::TokenValue::Atom(name) => Some(name.into_owned()),
            _ => None,
        }
    })
}

/// Counts the arguments of a function clause's `ArgumentList`.
pub(crate) fn clause_arity(node: erl_parse::NodeView<'_>) -> Option<u64> {
    let args = node
        .children()
        .find(|c| c.kind() == erl_parse::SyntaxKind::ArgumentList)?;
    Some(args.children().count() as u64)
}

/// One in-progress exploration fork of the preprocessor.
struct Fork {
    pp: erl_pp::Preprocessor,
    /// Number of conditional directives currently open in this fork.
    depth: usize,
    /// Depth at which a non-mainline fork stops (its own `-endif`).
    stop_depth: Option<usize>,
    source_tokens: Vec<erl_pp::SourceToken>,
    diagnostics: Vec<PreprocessDiagnostic>,
    skipped_includes: Vec<SkippedInclude>,
    skipped_defines: Vec<SkippedDefine>,
}

/// One explored preprocessor fork's outputs.
type PreprocessBranch = (
    Vec<erl_pp::SourceToken>,
    Vec<PreprocessDiagnostic>,
    Vec<SkippedInclude>,
    Vec<SkippedDefine>,
);

/// Drives the preprocessor across every conditional arm.
///
/// At each `AwaitingConditional` the fork is cloned into a mainline side
/// (`Branch::Then`) and a non-mainline side (`Branch::Else`). The mainline
/// continues past the `-endif`; non-mainline forks stop at the `-endif`
/// that closes the conditional they were forked from, tracked with
/// [`Fork::depth`] / [`Fork::stop_depth`]. Each source region is therefore
/// scanned by exactly one fork and work stays linear in the input size.
fn preprocess(source: erl_pp::Source) -> Vec<PreprocessBranch> {
    let mut pending = vec![Fork {
        pp: erl_pp::Preprocessor::new([source]),
        depth: 0,
        stop_depth: None,
        source_tokens: Vec::new(),
        diagnostics: Vec::new(),
        skipped_includes: Vec::new(),
        skipped_defines: Vec::new(),
    }];
    let mut done = Vec::new();

    while let Some(mut fork) = pending.pop() {
        loop {
            let event = fork.pp.step().expect("preprocessor protocol");
            match event {
                erl_pp::Event::Token(token) => fork.source_tokens.push(token),
                erl_pp::Event::AwaitingInclude(include) => {
                    if let Some(skipped) = skipped_include_from_directive(&include) {
                        fork.skipped_includes.push(skipped);
                    }
                    fork.pp
                        .resume_include(empty_source("<skipped-include>"))
                        .expect("preprocessor protocol");
                }
                erl_pp::Event::AwaitingConditional(conditional) => {
                    let opens_conditional = matches!(
                        conditional,
                        erl_pp::Conditional::Ifdef(_)
                            | erl_pp::Conditional::Ifndef(_)
                            | erl_pp::Conditional::If(_)
                    );
                    let (base_depth, next_depth) = if opens_conditional {
                        (fork.depth, fork.depth + 1)
                    } else {
                        (fork.depth.saturating_sub(1), fork.depth)
                    };
                    let mut main = fork.pp.clone();
                    let mut side = fork.pp.clone();
                    main.resume_conditional(erl_pp::Branch::Then)
                        .expect("preprocessor protocol");
                    side.resume_conditional(erl_pp::Branch::Else)
                        .expect("preprocessor protocol");
                    fork.pp = main;
                    fork.depth = next_depth;
                    pending.push(Fork {
                        pp: side,
                        depth: next_depth,
                        stop_depth: Some(base_depth),
                        source_tokens: Vec::new(),
                        diagnostics: Vec::new(),
                        skipped_includes: Vec::new(),
                        skipped_defines: Vec::new(),
                    });
                }
                erl_pp::Event::AwaitingMacroExpansion(_) => {
                    fork.pp
                        .resume_macro_expansion(dummy_macro_source())
                        .expect("preprocessor protocol");
                }
                erl_pp::Event::Diagnostic(_) => {
                    // `-error` / `-warning` directives are deliberately
                    // ignored: every conditional arm is scanned, so these
                    // directives would always be hit, and judging them is
                    // the compiler's job, not a linter's.
                }
                erl_pp::Event::PreprocessError(error) => {
                    fork.diagnostics.push(PreprocessDiagnostic {
                        span: source_span_to_span(error.span()),
                        message: preprocess_error_message(&error),
                    });
                }
                erl_pp::Event::MacroDefined(definition) => {
                    if let Some(skipped) = skipped_define_from_definition(&definition) {
                        fork.skipped_defines.push(skipped);
                    }
                }
                erl_pp::Event::MacroUndefined(_) => {}
                erl_pp::Event::BranchBoundary(boundary) => {
                    if matches!(boundary, erl_pp::BranchBoundary::Endif { .. }) {
                        fork.depth = fork.depth.saturating_sub(1);
                        if fork.stop_depth.is_some_and(|stop| fork.depth <= stop) {
                            break;
                        }
                    }
                }
                erl_pp::Event::Complete => break,
            }
        }
        done.push((
            fork.source_tokens,
            fork.diagnostics,
            fork.skipped_includes,
            fork.skipped_defines,
        ));
    }

    done
}

/// Maps a skipped include directive to its attribute-name span in the
/// original file.
fn skipped_include_from_directive(include: &erl_pp::IncludeDirective) -> Option<SkippedInclude> {
    let directive = span_in_original_file(&include.parent_origin, include.directive_span)?;
    let is_lib = matches!(include.kind, erl_pp::IncludeKind::IncludeLib);
    let name = if is_lib { "include_lib" } else { "include" };
    name_span_after_hyphen(directive, name).map(|name_span| SkippedInclude { name_span, is_lib })
}

/// Maps a consumed `-define` to its attribute-name span in the original file.
fn skipped_define_from_definition(definition: &erl_pp::MacroDefinition) -> Option<SkippedDefine> {
    let directive = span_in_original_file(&definition.origin, definition.directive_span)?;
    name_span_after_hyphen(directive, "define").map(|name_span| SkippedDefine { name_span })
}

fn name_span_after_hyphen(directive: Span, name: &str) -> Option<Span> {
    // Directives are written `-Name(...)`; the name starts one byte after `-`.
    let name_start = directive.start.checked_add(1)?;
    let name_end = name_start.checked_add(name.len())?;
    if name_end > directive.end {
        return None;
    }
    Some(Span::new(name_start, name_end))
}

/// Atom spliced in for an unknown macro so the file still parses.
/// Lowercase so it scans as an atom (valid wherever a macro's value
/// could appear), unlike efmt's uppercase `EFMT_DUMMY` which is a variable.
const DUMMY_MACRO_ATOM: &str = "elint_dummy";

fn empty_source(name: &str) -> erl_pp::Source {
    erl_pp::Source::new(name, "", Vec::new())
}

fn dummy_macro_source() -> erl_pp::Source {
    erl_pp::Source::new(
        "<elint-dummy-macro>",
        DUMMY_MACRO_ATOM,
        erl_tokenize::scan_tokens(DUMMY_MACRO_ATOM).expect("dummy atom always tokenizes"),
    )
}

fn source_span_to_span(span: erl_pp::SourceSpan) -> Span {
    Span::new(span.start.offset(), span.end.offset())
}

/// Human-readable description of a preprocessor structural error.
fn preprocess_error_message(error: &erl_pp::PreprocessError) -> String {
    match error {
        erl_pp::PreprocessError::ParseUnexpectedToken { expected, .. } => {
            format!("unexpected token in directive; expected {expected}")
        }
        erl_pp::PreprocessError::ParseUnexpectedEof { expected, .. } => {
            format!("unexpected end of file in directive; expected {expected}")
        }
        erl_pp::PreprocessError::DuplicateParameter { name, .. } => {
            format!("duplicate macro parameter: {}", name.as_str())
        }
        erl_pp::PreprocessError::ArityMismatch { name, .. } => {
            format!("macro arity mismatch: {}", name.as_str())
        }
        erl_pp::PreprocessError::UnclosedArgument { .. } => "unclosed macro argument".into(),
        erl_pp::PreprocessError::LeadingEmptyArgument { .. } => {
            "leading empty macro argument".into()
        }
        erl_pp::PreprocessError::TrailingEmptyArgument { .. } => {
            "trailing empty macro argument".into()
        }
        erl_pp::PreprocessError::InvalidStringificationTarget { .. } => {
            "invalid stringification target".into()
        }
        erl_pp::PreprocessError::CircularExpansion { name, .. } => {
            format!("circular macro expansion: {name}")
        }
        erl_pp::PreprocessError::StrayElse { .. } => "stray -else".into(),
        erl_pp::PreprocessError::StrayEndif { .. } => "stray -endif".into(),
        erl_pp::PreprocessError::DoubleElse { .. } => "double -else".into(),
        erl_pp::PreprocessError::UnclosedConditional { .. } => "unclosed conditional".into(),
        erl_pp::PreprocessError::StrayElif { .. } => "stray -elif".into(),
        erl_pp::PreprocessError::ElifAfterElse { .. } => "-elif after -else".into(),
    }
}

fn span_in_original_file(origin: &erl_pp::Origin, span: erl_pp::SourceSpan) -> Option<Span> {
    match origin {
        erl_pp::Origin::Source => Some(source_span_to_span(span)),
        erl_pp::Origin::Include {
            parent,
            include_site,
            ..
        } => span_in_original_file(parent, *include_site),
        erl_pp::Origin::MacroBody {
            parent, call_site, ..
        }
        | erl_pp::Origin::MacroArgument {
            parent, call_site, ..
        }
        | erl_pp::Origin::Stringification {
            parent, call_site, ..
        }
        | erl_pp::Origin::SourceInfo {
            parent, call_site, ..
        }
        | erl_pp::Origin::CallerExpansion {
            parent, call_site, ..
        } => span_in_original_file(parent, *call_site),
    }
}

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

    fn analyze_ok(src: &str) -> Context {
        Context::analyze("t.erl", src.to_string()).expect("test source must scan")
    }

    #[test]
    fn analyze_module_yields_mainline_branch() {
        let ctx = analyze_ok("-module(foo).\n");
        let branch = &ctx.branches[0];
        assert!(branch.tree.diagnostics().is_empty());
        assert_eq!(branch.tree.tokens().len(), branch.source_tokens.len());
        assert!(!branch.tree.tokens().is_empty());
        assert_eq!(branch.tree.roots().count(), 1);
    }

    #[test]
    fn unknown_macro_expands_to_dummy_atom_without_diagnostic() {
        let ctx = analyze_ok("-module(foo).\nfoo() -> ?BAR.\n");
        let branch = &ctx.branches[0];
        assert!(branch.preprocess_diagnostics.is_empty());
        assert!(branch.tree.diagnostics().is_empty());
        assert!(branch.source_tokens.iter().any(|token| matches!(
            token.value(),
            erl_tokenize::TokenValue::Atom(name) if name == DUMMY_MACRO_ATOM
        )));
    }

    #[test]
    fn include_is_skipped_without_leaving_the_file() {
        let ctx = analyze_ok("-module(foo).\n-include(\"missing.hrl\").\n");
        let branch = &ctx.branches[0];
        assert!(branch.tree.diagnostics().is_empty());
        // The include directive is consumed by the preprocessor, so only `-module` remains.
        assert_eq!(branch.tree.roots().count(), 1);
        assert_eq!(branch.skipped_includes.len(), 1);
        assert!(!branch.skipped_includes[0].is_lib);
        assert_eq!(
            branch.skipped_includes[0].name_span.text(&ctx.text),
            "include"
        );
    }

    #[test]
    fn tokenize_error_is_returned() {
        let err = Context::analyze("t.erl", "\"unterminated\n".to_string())
            .expect_err("unclosed string must fail");
        assert!(err.position.offset() < 20);
    }

    #[test]
    fn explores_every_arm_and_keeps_mainline_first() {
        let ctx = analyze_ok(
            "\
-module(foo).
-ifdef(A).
foo() -> then_arm.
-else.
foo() -> else_arm.
-endif.
bar() -> ok.
",
        );
        // Then arm and Else arm.
        assert_eq!(ctx.branches.len(), 2);
        let mainline = &ctx.branches[0];
        let mainline_text: String = mainline
            .tree
            .tokens()
            .iter()
            .map(|t| t.text(&ctx.text))
            .collect();
        assert!(mainline_text.contains("then_arm"));
        assert!(mainline_text.contains("bar()"));
        let side_text: String = ctx.branches[1]
            .tree
            .tokens()
            .iter()
            .map(|t| t.text(&ctx.text))
            .collect();
        assert!(side_text.contains("else_arm"));
        assert!(!side_text.contains("bar()"));
        // Every branch's tokens must map back to original-file text.
        for branch in &ctx.branches {
            for (i, _token) in branch.tree.tokens().iter().enumerate() {
                let Some(span) = branch
                    .span_of_range(erl_parse::TokenRange::single(erl_parse::TokenIndex::new(i)))
                else {
                    continue;
                };
                assert!(span.start < span.end);
            }
        }
    }

    #[test]
    fn side_branch_stops_at_its_own_endif() {
        // The Else arm's `case` must be linted, but code after the outer
        // `-endif` must not appear in the side branch (mainline only).
        let ctx = analyze_ok(
            "\
-module(foo).
-ifdef(A).
ok.
-else.
foo() -> ok.
-endif.
bar() -> ok.
",
        );
        let side = &ctx.branches[1];
        let side_text: String = side
            .tree
            .tokens()
            .iter()
            .map(|t| t.text(&ctx.text))
            .collect();
        assert!(side_text.contains("foo()"));
        assert!(!side_text.contains("bar()"));
    }

    #[test]
    fn consecutive_ifdefs_do_not_form_cartesian_product() {
        // With the stop-at-`-endif` rule the number of branches stays
        // linear: 2 independent ifdefs yield 3 forks (mainline plus one
        // side per conditional), not the 4 of a full product.
        let ctx = analyze_ok(
            "\
-module(foo).
-ifdef(A).
a1.
-else.
a2.
-endif.
-ifdef(B).
b1.
-else.
b2.
-endif.
",
        );
        assert_eq!(ctx.branches.len(), 3);
    }

    #[test]
    fn nested_conditionals_explore_inner_arms() {
        // Each arm's nested conditional is explored by the fork that made
        // that arm active, so every marker appears in exactly one branch.
        let ctx = analyze_ok(
            "\
-module(foo).
-ifdef(A).
    -ifdef(B).
    n1.
    -else.
    n2.
    -endif.
-else.
    -ifdef(C).
    n3.
    -else.
    n4.
    -endif.
-endif.
",
        );
        assert_eq!(ctx.branches.len(), 4);
        let marker = |branch: &BranchContext, m: &str| {
            branch.tree.tokens().iter().any(|t| t.text(&ctx.text) == m)
        };
        assert!(marker(&ctx.branches[0], "n1"));
        let mut seen = std::collections::HashSet::new();
        for branch in &ctx.branches {
            let present: Vec<_> = ["n1", "n2", "n3", "n4"]
                .into_iter()
                .filter(|m| marker(branch, m))
                .collect();
            assert_eq!(
                present.len(),
                1,
                "branch must contain exactly one marker: {present:?}"
            );
            seen.insert(present[0]);
        }
        assert_eq!(seen.len(), 4);
    }

    #[test]
    fn if_elif_chain_explores_every_arm() {
        let ctx = analyze_ok(
            "\
-module(foo).
-if(true). c1. -elif(false). c2. -elif(true). c3. -else. c4. -endif.
",
        );
        assert_eq!(ctx.branches.len(), 4);
        let mut seen = std::collections::HashSet::new();
        for branch in &ctx.branches {
            let present: Vec<_> = ["c1", "c2", "c3", "c4"]
                .into_iter()
                .filter(|m| branch.tree.tokens().iter().any(|t| t.text(&ctx.text) == *m))
                .collect();
            assert_eq!(
                present.len(),
                1,
                "branch must contain exactly one marker: {present:?}"
            );
            seen.insert(present[0]);
        }
        assert_eq!(seen.len(), 4);
    }

    #[test]
    fn findings_in_a_side_branch_are_reachable() {
        let ctx = analyze_ok(
            "\
-module(foo).
-ifdef(A).
ok.
-else.
foo(T) -> element(1, T).
-endif.
",
        );
        let branch = &ctx.branches[1];
        let rule = crate::rules::RULES
            .iter()
            .find(|rule| rule.name == "element_bif")
            .expect("element_bif rule");
        let findings = (rule.check)(&ctx, branch);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].span.text(&ctx.text), "element(1, T)");
    }

    #[test]
    fn enclosing_function_name_resolves_function() {
        let ctx = analyze_ok("-module(t).\nfoo(A, B) ->\n    element(1, A).\n");
        let branch = &ctx.branches[0];
        let call = branch
            .tree
            .nodes()
            .find(|n| n.kind() == erl_parse::SyntaxKind::CallExpr)
            .expect("call expr");
        assert_eq!(
            branch.enclosing_function_name(call.node_id()).as_deref(),
            Some("foo/2")
        );
    }

    #[test]
    fn enclosing_function_name_resolves_for_clause_node() {
        let ctx = analyze_ok("-module(t).\nfoo() -> ok.\n");
        let branch = &ctx.branches[0];
        let clause = branch
            .tree
            .nodes()
            .find(|n| n.kind() == erl_parse::SyntaxKind::FunctionClause)
            .expect("function clause");
        assert_eq!(
            branch.enclosing_function_name(clause.node_id()).as_deref(),
            Some("foo/0")
        );
    }

    #[test]
    fn enclosing_function_name_is_none_outside_function() {
        let ctx = analyze_ok("-module(t).\nfoo() -> ok.\n");
        let branch = &ctx.branches[0];
        let attribute = branch
            .tree
            .nodes()
            .find(|n| n.kind() == erl_parse::SyntaxKind::Attribute)
            .expect("attribute");
        assert_eq!(branch.enclosing_function_name(attribute.node_id()), None);
    }
}