Skip to main content

lang_parsing_substrate/
dead_code_csharp.rs

1//! Dead-code region detection for C#'s `#if`/`#elif`/`#else`/`#endif`
2//! conditional compilation.
3//!
4//! Tree-sitter-based, like [`crate::dead_code_swift`] and unlike
5//! [`crate::dead_code`]'s C/C++ line scanner — but structurally closer to
6//! C/C++'s *problem shape* than to Swift's. Verified directly against
7//! tree-sitter-c-sharp 0.23's grammar and a parse dump (not assumed):
8//! `preproc_if`/`preproc_elif` are real nested nodes with a `condition`
9//! field and an `alternative` field (chaining to the next `preproc_elif` or
10//! a trailing `preproc_else`), and the guarded content is nested as
11//! ordinary children *underneath* them — not spliced in as flat siblings
12//! the way Swift's `directive` nodes are. That's possible because C#, like
13//! Swift, requires each branch's content to be syntactically complete
14//! (`repeat($.declaration)`-shaped in the grammar), so there's no
15//! `extern "C" {`-style brace-imbalance failure mode to work around; a
16//! proper AST walk following `condition`/`alternative` fields is
17//! straightforward and doesn't need Swift's flat-sibling depth-tracking
18//! trick either, since nesting is real here.
19//!
20//! Unlike Swift, C# *does* have `#define`/`#undef` — real top-level nodes
21//! (confirmed: `preproc_define` appears as a direct child of
22//! `compilation_unit`, sibling to `using_directive`/`class_declaration`),
23//! so locally-provable symbol definedness ports over: a symbol
24//! `#define`d on every path to a condition is always-defined there, and one
25//! `#undef`d on every path is never-defined. The evidence follows the paths
26//! through each conditional, as in [`crate::dead_code`]: after `#endif` a
27//! symbol keeps a value only if every branch that may compile, and the path
28//! that skips the conditional when it has no `#else`, agree on it. A branch
29//! of `#if FOO` or `#if !FOO` also knows `FOO` from the test, so `#if !FOO` /
30//! `#define FOO` / `#endif` leaves `FOO` defined on both paths. A dead
31//! branch's `#define` counts on no path. A commented-out `#define` is no
32//! evidence, as in [`crate::dead_code`]: the build can still define the
33//! symbol (`-define:`, `DefineConstants`).
34//!
35//! C# also has no `#ifdef`/`#ifndef` — only `#if`/`#elif` with a boolean
36//! condition expression (`identifier`, `true`/`false` literals, `!`, `&&`,
37//! `||`, `==`, `!=`, and parens; confirmed against the grammar), so
38//! `!SYMBOL` covers what C spells `#ifndef SYMBOL`. Because each operand of
39//! `&&`/`||` is a real sub-tree (not a flat token stream like Swift's),
40//! short-circuit evaluation falls out for free: `false && SYMBOL` is
41//! provably dead even though `SYMBOL` alone isn't classifiable.
42
43use std::collections::{HashMap, HashSet};
44
45use tree_sitter::{Node, Parser};
46
47/// A C# preprocessor-dead region: an `#if`/`#elif`/`#else` branch proven
48/// unreachable by a compile-time-constant condition or locally-provable
49/// symbol definedness. See the module documentation for exactly what is and
50/// isn't recognized.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct CSharpDeadCodeRegion {
53    /// 1-based, inclusive first line of the dead region.
54    pub start_line: usize,
55    /// 1-based, inclusive last line of the dead region.
56    pub end_line: usize,
57}
58
59/// Computes the dead-code regions of `source`, a C# file. See the module
60/// documentation for exactly what is and isn't recognized.
61pub fn csharp_dead_code_regions(source: &[u8]) -> Vec<CSharpDeadCodeRegion> {
62    let mut parser = Parser::new();
63    if parser
64        .set_language(&tree_sitter_c_sharp::LANGUAGE.into())
65        .is_err()
66    {
67        return Vec::new();
68    }
69    let Some(tree) = parser.parse(source, None) else {
70        return Vec::new();
71    };
72
73    let mut defined = Symbols::default();
74    let mut regions = Vec::new();
75    walk(tree.root_node(), source, &mut defined, &mut regions);
76    regions
77}
78
79/// What the file itself proves about each symbol at the current point of
80/// the walk, `true` defined and `false` undefined (no entry: no evidence),
81/// with an undo log so a branch can be walked in place and rolled back.
82#[derive(Default)]
83struct Symbols {
84    values: HashMap<String, bool>,
85    /// Each write since the start, with the value it replaced.
86    log: Vec<(String, Option<bool>)>,
87}
88
89impl Symbols {
90    fn get(&self, name: &str) -> Option<bool> {
91        self.values.get(name).copied()
92    }
93
94    /// Sets `name` (`None`: no evidence), logging the value it replaces.
95    fn set(&mut self, name: &str, value: Option<bool>) {
96        let old = match value {
97            Some(v) => self.values.insert(name.to_string(), v),
98            None => self.values.remove(name),
99        };
100        self.log.push((name.to_string(), old));
101    }
102
103    /// The value at this point of each name written since `mark`.
104    fn written_since(&self, mark: usize) -> HashMap<String, Option<bool>> {
105        let mut writes = HashMap::new();
106        for (name, _) in &self.log[mark..] {
107            if !writes.contains_key(name) {
108                writes.insert(name.clone(), self.get(name));
109            }
110        }
111        writes
112    }
113
114    /// Undoes every write since `mark`.
115    fn rollback(&mut self, mark: usize) {
116        for (name, old) in self.log.drain(mark..).rev() {
117            match old {
118                Some(v) => self.values.insert(name, v),
119                None => self.values.remove(&name),
120            };
121        }
122    }
123}
124
125/// Recurses through `node`'s named children in document order. A dead
126/// branch is never recursed into at all, so a `#define`/`#undef` reached
127/// here is on some path that may compile.
128fn walk(node: Node, source: &[u8], defined: &mut Symbols, out: &mut Vec<CSharpDeadCodeRegion>) {
129    let mut cursor = node.walk();
130    let children: Vec<Node> = node.named_children(&mut cursor).collect();
131    walk_siblings(&children, source, defined, out);
132}
133
134/// Same as [`walk`], but over an arbitrary already-collected slice of
135/// siblings (used for the body of a live/unknown branch, which is a
136/// sub-slice of some ancestor's children — not a node's own
137/// `named_children()`). Dispatches each sibling by its own kind, since a
138/// sibling might itself be a `preproc_if` chain that needs [`walk_chain`],
139/// not a plain container to recurse into via [`walk`].
140fn walk_siblings(
141    children: &[Node],
142    source: &[u8],
143    defined: &mut Symbols,
144    out: &mut Vec<CSharpDeadCodeRegion>,
145) {
146    for child in children {
147        match child.kind() {
148            "preproc_define" | "preproc_undef" => {
149                if let Some(name) = preproc_arg_name(*child, source) {
150                    defined.set(&name, Some(child.kind() == "preproc_define"));
151                }
152            }
153            "preproc_if" => walk_chain(*child, source, defined, out),
154            _ => walk(*child, source, defined, out),
155        }
156    }
157}
158
159/// Walks one `#if`/`#elif`/`#else` chain, following the `alternative` field
160/// from `#if` through any `#elif`s to a trailing `#else`, and leaves in
161/// `defined` what every path through the chain agrees on.
162fn walk_chain(
163    node: Node,
164    source: &[u8],
165    defined: &mut Symbols,
166    out: &mut Vec<CSharpDeadCodeRegion>,
167) {
168    // The symbol a bare `#if FOO` / `#if !FOO` tests, and its value in the
169    // first branch. Every later branch, and the path that skips the chain,
170    // has the opposite.
171    let tested = node
172        .child_by_field_name("condition")
173        .and_then(|cond| tested_symbol(cond, source));
174    // Whether an earlier branch in this chain was proven to always run —
175    // if so, every later branch (elif/else) is dead regardless of its own
176    // condition.
177    let mut chain_resolved_true = false;
178    let mut has_else = false;
179    // What each branch that may compile wrote, with each name's value at
180    // `#endif` on that path.
181    let mut paths: Vec<HashMap<String, Option<bool>>> = Vec::new();
182    let branches = chain_branches(node);
183    let mut first = true;
184
185    for (condition, body) in branches {
186        has_else |= condition.is_none();
187        // Every condition is evaluated against the chain's entry state: an
188        // earlier branch's writes were rolled back.
189        let live = !chain_resolved_true
190            && match condition.map(|cond| eval_condition(cond, source, defined)) {
191                Some(Some(false)) => false,
192                Some(Some(true)) => {
193                    chain_resolved_true = true;
194                    true
195                }
196                Some(None) | None => true,
197            };
198        if live {
199            let mark = defined.log.len();
200            if let Some((name, value_in_first)) = &tested {
201                defined.set(name, Some(*value_in_first == first));
202            }
203            walk_siblings(&body, source, defined, out);
204            paths.push(defined.written_since(mark));
205            defined.rollback(mark);
206        } else {
207            push_dead_range(&body, out);
208        }
209        first = false;
210    }
211
212    // A missing `#else` is an empty branch, taken whenever every condition
213    // is false; no path skips a chain with a proven-true branch.
214    if !has_else && !chain_resolved_true {
215        let skip = tested
216            .iter()
217            .map(|(name, value_in_first)| (name.clone(), Some(!value_in_first)));
218        paths.push(skip.collect());
219    }
220    // Join each written name over the paths that wrote it, then with its
221    // entry value if some path did not: a name keeps a value only if every
222    // path agrees. Linear in the writes, so a long `#elif` chain stays cheap.
223    let total = paths.len();
224    let mut joined: HashMap<String, (Option<bool>, usize)> = HashMap::new();
225    for (name, value) in paths.into_iter().flatten() {
226        joined
227            .entry(name)
228            .and_modify(|(acc, n)| {
229                *acc = agree(*acc, value);
230                *n += 1;
231            })
232            .or_insert((value, 1));
233    }
234    for (name, (value, n)) in joined {
235        let value = if n < total {
236            agree(value, defined.get(&name))
237        } else {
238            value
239        };
240        if value != defined.get(&name) {
241            defined.set(&name, value);
242        }
243    }
244}
245
246/// Two paths' values for one symbol joined: the value if they agree, no
247/// evidence otherwise.
248fn agree(a: Option<bool>, b: Option<bool>) -> Option<bool> {
249    if a == b {
250        a
251    } else {
252        None
253    }
254}
255
256/// The symbol whose definedness alone decides a `#if FOO` or `#if !FOO`
257/// condition (parentheses allowed), and whether the condition is true when
258/// it is defined. `None` for any other condition.
259fn tested_symbol(node: Node, source: &[u8]) -> Option<(String, bool)> {
260    match node.kind() {
261        "identifier" => Some((node.utf8_text(source).ok()?.to_string(), true)),
262        "parenthesized_expression" => tested_symbol(node.named_child(0)?, source),
263        "unary_expression" if node.child_by_field_name("operator")?.kind() == "!" => {
264            let (name, when) = tested_symbol(node.child_by_field_name("argument")?, source)?;
265            Some((name, !when))
266        }
267        _ => None,
268    }
269}
270
271/// Each branch of the chain starting at `node`, in order: its condition
272/// (`None` for `#else`) and its guarded content.
273///
274/// The content is assigned by line, not by tree parent. tree-sitter-c-sharp
275/// parses directives as extras, so a branch's trailing `#define`/`#undef`
276/// can hang off an outer node of the chain (an `#else` holding only
277/// `#undef FOO` comes out empty, with the `#undef` a child of the `#if`
278/// after its `alternative`). A branch owns everything from its own
279/// directive's line to the next branch's.
280fn chain_branches(node: Node) -> Vec<(Option<Node>, Vec<Node>)> {
281    let mut heads = Vec::new();
282    let mut fields = HashSet::new();
283    let mut current = Some(node);
284    while let Some(n) = current {
285        let condition = n.child_by_field_name("condition");
286        current = n.child_by_field_name("alternative");
287        fields.extend(condition.iter().chain(current.iter()).map(|f| f.id()));
288        heads.push((n, condition));
289    }
290    let mut content: Vec<Node> = heads
291        .iter()
292        .flat_map(|(n, _)| {
293            let mut cursor = n.walk();
294            n.named_children(&mut cursor).collect::<Vec<_>>()
295        })
296        .filter(|c| !fields.contains(&c.id()))
297        .collect();
298    content.sort_by_key(|c| c.start_byte());
299    let mut branches: Vec<(Option<Node>, Vec<Node>)> = heads
300        .iter()
301        .map(|(_, condition)| (*condition, Vec::new()))
302        .collect();
303    let starts: Vec<usize> = heads.iter().map(|(n, _)| n.start_position().row).collect();
304    // Rows only grow along `content`, so one pass assigns every node.
305    let mut i = 0;
306    for c in content {
307        let row = c.start_position().row;
308        while starts.get(i + 1).is_some_and(|&next| next <= row) {
309            i += 1;
310        }
311        if row >= starts[0] {
312            branches[i].1.push(c);
313        }
314    }
315    branches
316}
317
318fn push_dead_range(body: &[Node], out: &mut Vec<CSharpDeadCodeRegion>) {
319    let (Some(first), Some(last)) = (body.first(), body.last()) else {
320        return;
321    };
322    out.push(CSharpDeadCodeRegion {
323        start_line: first.start_position().row + 1,
324        end_line: last_line(*last),
325    });
326}
327
328/// The 1-based last line of `node`'s own text. A directive node's range
329/// takes in its line ending, so it ends at column 0 of the next line.
330fn last_line(node: Node) -> usize {
331    let end = node.end_position();
332    if end.column == 0 && end.row > node.start_position().row {
333        end.row
334    } else {
335        end.row + 1
336    }
337}
338
339/// Evaluates a `#if`/`#elif` condition expression node to a constant
340/// boolean, if locally provable — `None` as soon as any operand can't be
341/// resolved (an unrecognized construct, or a symbol with no local
342/// evidence), except where `&&`/`||` short-circuits past it.
343fn eval_condition(node: Node, source: &[u8], defined: &Symbols) -> Option<bool> {
344    match node.kind() {
345        "boolean_literal" => match node.utf8_text(source) {
346            Ok("true") => Some(true),
347            Ok("false") => Some(false),
348            _ => None,
349        },
350        "identifier" => {
351            let name = node.utf8_text(source).ok()?;
352            defined.get(name)
353        }
354        "parenthesized_expression" => eval_condition(node.named_child(0)?, source, defined),
355        "unary_expression" => {
356            if node.child_by_field_name("operator")?.kind() != "!" {
357                return None;
358            }
359            let arg = node.child_by_field_name("argument")?;
360            Some(!eval_condition(arg, source, defined)?)
361        }
362        "binary_expression" => {
363            let op = node.child_by_field_name("operator")?.kind();
364            let left = node.child_by_field_name("left")?;
365            let right = node.child_by_field_name("right")?;
366            let l = eval_condition(left, source, defined);
367            let r = eval_condition(right, source, defined);
368            match op {
369                "&&" => match (l, r) {
370                    (Some(false), _) | (_, Some(false)) => Some(false),
371                    (Some(a), Some(b)) => Some(a && b),
372                    _ => None,
373                },
374                "||" => match (l, r) {
375                    (Some(true), _) | (_, Some(true)) => Some(true),
376                    (Some(a), Some(b)) => Some(a || b),
377                    _ => None,
378                },
379                "==" => Some(l? == r?),
380                "!=" => Some(l? != r?),
381                _ => None,
382            }
383        }
384        _ => None,
385    }
386}
387
388/// Extracts the leading identifier from a `preproc_define`/`preproc_undef`
389/// node's `preproc_arg` child (which matches arbitrary trailing text, not
390/// just an identifier, so this trims to the symbol name itself).
391fn preproc_arg_name(node: Node, source: &[u8]) -> Option<String> {
392    let arg = node.named_child(0)?;
393    let text = arg.utf8_text(source).ok()?.trim_start();
394    let end = text
395        .find(|c: char| !(c.is_alphanumeric() || c == '_'))
396        .unwrap_or(text.len());
397    if end == 0 {
398        None
399    } else {
400        Some(text[..end].to_string())
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407
408    fn ranges(source: &str) -> Vec<(usize, usize)> {
409        csharp_dead_code_regions(source.as_bytes())
410            .into_iter()
411            .map(|r| (r.start_line, r.end_line))
412            .collect()
413    }
414
415    #[test]
416    fn if_false_is_dead() {
417        let src = "class C {\n#if false\n    int x = 1;\n#endif\n}\n";
418        assert_eq!(ranges(src), vec![(3, 3)]);
419    }
420
421    #[test]
422    fn if_true_else_branch_dead() {
423        let src = "#if true\nint x = 1;\n#else\nint y = 2;\n#endif\n";
424        assert_eq!(ranges(src), vec![(4, 4)]);
425    }
426
427    #[test]
428    fn negated_false_makes_branch_live() {
429        let src = "#if !false\nint x = 1;\n#endif\n";
430        assert!(ranges(src).is_empty());
431    }
432
433    #[test]
434    fn elif_true_kills_trailing_else() {
435        let src = concat!(
436            "#if false\n",  // 1
437            "int a = 1;\n", // 2
438            "#elif true\n", // 3
439            "int b = 2;\n", // 4
440            "#else\n",      // 5
441            "int c = 3;\n", // 6
442            "#endif\n",     // 7
443        );
444        assert_eq!(ranges(src), vec![(2, 2), (6, 6)]);
445    }
446
447    #[test]
448    fn always_defined_symbol_else_branch_dead() {
449        let src = concat!(
450            "#define FOO\n", // 1
451            "#if FOO\n",     // 2
452            "int a = 1;\n",  // 3
453            "#else\n",       // 4
454            "int b = 2;\n",  // 5
455            "#endif\n",      // 6
456        );
457        assert_eq!(ranges(src), vec![(5, 5)]);
458    }
459
460    #[test]
461    fn commented_out_define_is_not_evidence() {
462        // The build can still define FOO (`-define:FOO`, `DefineConstants`).
463        for comment in ["//#define FOO\n", "// #define FOO\n", "/* #define FOO */\n"] {
464            let src = format!("{comment}#if FOO\nint a = 1;\n#else\nint b = 2;\n#endif\n");
465            assert!(ranges(&src).is_empty(), "{comment}");
466        }
467    }
468
469    #[test]
470    fn real_define_still_decides_next_to_a_commented_one() {
471        let src = concat!(
472            "// #define BAR\n", // 1
473            "#define FOO\n",    // 2
474            "#if FOO\n",        // 3
475            "int a = 1;\n",     // 4
476            "#else\n",          // 5
477            "int b = 2;\n",     // 6
478            "#endif\n",         // 7
479            "#if !FOO\n",       // 8
480            "int c = 3;\n",     // 9
481            "#endif\n",         // 10
482        );
483        assert_eq!(ranges(src), vec![(6, 6), (9, 9)]);
484    }
485
486    #[test]
487    fn undef_with_no_later_define_makes_if_dead() {
488        let src = "#define FOO\n#undef FOO\n#if FOO\nint a = 1;\n#endif\n";
489        assert_eq!(ranges(src), vec![(4, 4)]);
490    }
491
492    #[test]
493    fn undef_inside_an_undecided_branch_leaves_the_symbol_undecided() {
494        // With X defined, FOO is undefined at line 5, so the #else compiles.
495        let src = concat!(
496            "#define FOO\n", // 1
497            "#if X\n",       // 2
498            "#undef FOO\n",  // 3
499            "#endif\n",      // 4
500            "#if FOO\n",     // 5
501            "int a = 1;\n",  // 6
502            "#else\n",       // 7
503            "int b = 2;\n",  // 8
504            "#endif\n",      // 9
505        );
506        assert!(ranges(src).is_empty());
507    }
508
509    #[test]
510    fn undef_nested_two_branches_deep_leaves_the_symbol_undecided() {
511        let src = concat!(
512            "#define FOO\n", // 1
513            "#if X\n",       // 2
514            "#if Y\n",       // 3
515            "#undef FOO\n",  // 4
516            "#endif\n",      // 5
517            "#endif\n",      // 6
518            "#if !FOO\n",    // 7
519            "int a = 1;\n",  // 8
520            "#endif\n",      // 9
521        );
522        assert!(ranges(src).is_empty());
523    }
524
525    #[test]
526    fn a_define_on_every_branch_holds_after_endif() {
527        let src = concat!(
528            "#if X\n",       // 1
529            "#define FOO\n", // 2
530            "#elif Y\n",     // 3
531            "#define FOO\n", // 4
532            "#else\n",       // 5
533            "#define FOO\n", // 6
534            "#endif\n",      // 7
535            "#if FOO\n",     // 8
536            "int a = 1;\n",  // 9
537            "#else\n",       // 10
538            "int b = 2;\n",  // 11
539            "#endif\n",      // 12
540        );
541        assert_eq!(ranges(src), vec![(11, 11)]);
542    }
543
544    #[test]
545    fn a_define_on_some_branches_is_undecided_after_endif() {
546        let src = concat!(
547            "#if X\n",       // 1
548            "#define FOO\n", // 2
549            "#elif Y\n",     // 3
550            "#define FOO\n", // 4
551            "#endif\n",      // 5
552            "#if FOO\n",     // 6
553            "int a = 1;\n",  // 7
554            "#else\n",       // 8
555            "int b = 2;\n",  // 9
556            "#endif\n",      // 10
557        );
558        assert!(ranges(src).is_empty());
559    }
560
561    #[test]
562    fn the_default_value_idiom_defines_the_symbol_on_both_paths() {
563        for (test, write) in [("!FOO", "#define FOO"), ("(FOO)", "#undef BAR")] {
564            let src = format!(
565                "#if {test}\n{write}\n#endif\n#if FOO\nint a = 1;\n#else\nint b = 2;\n#endif\n"
566            );
567            let expected = if test == "!FOO" { vec![(7, 7)] } else { vec![] };
568            assert_eq!(ranges(&src), expected, "{test}");
569        }
570    }
571
572    #[test]
573    fn an_undef_in_the_else_of_a_tested_symbol_leaves_it_undefined() {
574        let src = concat!(
575            "#if FOO\n",    // 1
576            "#undef FOO\n", // 2
577            "#else\n",      // 3
578            "#endif\n",     // 4
579            "#if FOO\n",    // 5
580            "int a = 1;\n", // 6
581            "#endif\n",     // 7
582        );
583        assert_eq!(ranges(src), vec![(6, 6)]);
584    }
585
586    #[test]
587    fn a_define_in_a_proven_branch_holds_after_endif() {
588        let src = concat!(
589            "#if true\n",    // 1
590            "#define FOO\n", // 2
591            "#else\n",       // 3
592            "#undef FOO\n",  // 4
593            "#endif\n",      // 5
594            "#if !FOO\n",    // 6
595            "int a = 1;\n",  // 7
596            "#endif\n",      // 8
597        );
598        assert_eq!(ranges(src), vec![(4, 4), (7, 7)]);
599    }
600
601    #[test]
602    fn a_define_in_a_dead_branch_counts_on_no_path() {
603        let src = concat!(
604            "#if false\n",   // 1
605            "#define FOO\n", // 2
606            "#endif\n",      // 3
607            "#if FOO\n",     // 4
608            "int a = 1;\n",  // 5
609            "#else\n",       // 6
610            "int b = 2;\n",  // 7
611            "#endif\n",      // 8
612        );
613        assert_eq!(ranges(src), vec![(2, 2)]);
614    }
615
616    #[test]
617    fn a_later_branch_condition_ignores_an_earlier_branch_define() {
618        let src = concat!(
619            "#if X\n",       // 1
620            "#define FOO\n", // 2
621            "#elif FOO\n",   // 3
622            "int a = 1;\n",  // 4
623            "#endif\n",      // 5
624        );
625        assert!(ranges(src).is_empty());
626    }
627
628    #[test]
629    fn an_else_holding_only_a_directive_is_found_dead() {
630        let src = concat!(
631            "#if true\n",   // 1
632            "int a = 1;\n", // 2
633            "#else\n",      // 3
634            "#undef FOO\n", // 4
635            "#endif\n",     // 5
636        );
637        assert_eq!(ranges(src), vec![(4, 4)]);
638    }
639
640    #[test]
641    fn a_dead_branch_ending_in_a_directive_stops_before_the_next_branch() {
642        let src = concat!(
643            "#if false\n",   // 1
644            "int a = 1;\n",  // 2
645            "#define FOO\n", // 3
646            "#elif BAR\n",   // 4
647            "#define BAZ\n", // 5
648            "#endif\n",      // 6
649            "#if !BAZ\n",    // 7
650            "int b = 2;\n",  // 8
651            "#endif\n",      // 9
652        );
653        assert_eq!(ranges(src), vec![(2, 3)]);
654    }
655
656    /// Whether scanning `shape(4 * n)` costs well under 16 times
657    /// `shape(n)`, as a quadratic scan would.
658    fn scales_linearly(shape: impl Fn(usize) -> String) -> bool {
659        crate::scaling_check::costs_under(
660            &shape(2_500),
661            &shape(10_000),
662            crate::scaling_check::LINEAR_BOUND,
663            |source| {
664                csharp_dead_code_regions(source.as_bytes());
665            },
666        )
667    }
668
669    #[test]
670    fn many_defines_and_chains_scan_in_linear_time() {
671        let shape = |n: usize| {
672            let defines: String = (0..n).map(|i| format!("#define S{i}\n")).collect();
673            let chains: String = (0..n / 2)
674                .map(|i| format!("#if X{i}\nint a{i};\n#endif\n"))
675                .collect();
676            defines + &chains
677        };
678        assert!(scales_linearly(shape));
679    }
680
681    #[test]
682    fn a_long_elif_chain_scans_in_linear_time() {
683        let shape = |n: usize| {
684            let arms: String = (1..n)
685                .map(|i| format!("#elif X{i}\n#define D{i}\nint b{i};\n"))
686                .collect();
687            format!("#if X0\nint a;\n{arms}#endif\n")
688        };
689        assert!(scales_linearly(shape));
690    }
691
692    #[test]
693    fn symbol_never_mentioned_is_neutral() {
694        let src = "#if DEBUG\nint a = 1;\n#endif\n";
695        assert!(ranges(src).is_empty());
696    }
697
698    #[test]
699    fn short_circuit_and_with_false_literal_is_dead() {
700        let src = "#if false && DEBUG\nint a = 1;\n#endif\n";
701        assert_eq!(ranges(src), vec![(2, 2)]);
702    }
703
704    #[test]
705    fn short_circuit_or_with_true_literal_makes_else_dead() {
706        let src = "#if true || DEBUG\nint a = 1;\n#else\nint b = 2;\n#endif\n";
707        assert_eq!(ranges(src), vec![(4, 4)]);
708    }
709
710    #[test]
711    fn define_inside_conditional_does_not_count_as_unconditional() {
712        let src = "#if BAR\n#define FOO\n#endif\n#if FOO\nint a = 1;\n#endif\n";
713        assert!(ranges(src).is_empty());
714    }
715
716    #[test]
717    fn nested_dead_chain_inside_dead_branch_does_not_split_region() {
718        let src = concat!(
719            "#if false\n",  // 1
720            "int a = 1;\n", // 2
721            "#if true\n",   // 3
722            "int b = 2;\n", // 4
723            "#endif\n",     // 5
724            "int c = 3;\n", // 6
725            "#endif\n",     // 7
726        );
727        assert_eq!(ranges(src), vec![(2, 6)]);
728    }
729
730    #[test]
731    fn nested_dead_chain_inside_live_branch_is_still_found() {
732        let src = concat!(
733            "#if true\n",   // 1
734            "int a = 1;\n", // 2
735            "#if false\n",  // 3
736            "int b = 2;\n", // 4
737            "#endif\n",     // 5
738            "int c = 3;\n", // 6
739            "#endif\n",     // 7
740        );
741        assert_eq!(ranges(src), vec![(4, 4)]);
742    }
743
744    #[test]
745    fn empty_dead_branch_yields_no_region() {
746        let src = "#if false\n#endif\n";
747        assert!(ranges(src).is_empty());
748    }
749
750    #[test]
751    fn no_directives_yields_no_regions() {
752        assert!(ranges("class C {}\n").is_empty());
753    }
754
755    #[test]
756    fn empty_source_yields_no_regions() {
757        assert!(ranges("").is_empty());
758    }
759}