Skip to main content

lang_parsing_substrate/
dead_code.rs

1//! Preprocessor dead-code region detection for C/C++.
2//!
3//! Also compiled under `lang-csharp` alone (see this module's `cfg` in
4//! `lib.rs`), which keeps its public functions available to a C#-only
5//! build. It has no grammar dependency: it is pure text scanning.
6//!
7//! Computes the 1-based inclusive line ranges of a C/C++ translation unit
8//! that a preprocessor would strip before the compiler ever sees them. This
9//! module covers two sub-problems in one pass, sharing a
10//! single nesting/depth state machine so they don't disagree at edge cases
11//! (e.g. a `#if 0` nested inside a dead `#ifdef MACRO` region, or vice
12//! versa):
13//!
14//! 1. `#if 0` and `#elif 0` arms, the arms after a literal-true `#if 1` or
15//!    `#elif 1`, and `__cplusplus`-gated branches — dead when the
16//!    translation unit is compiled as C.
17//! 2. `#ifdef MACRO` / `#if defined(MACRO)` where `MACRO`'s definedness is
18//!    locally provable from this file: `#define`d on every path to this
19//!    point (branch always live, its `#else` dead), or `#undef`d on every
20//!    path (branch always dead). A macro this file never mentions at all
21//!    (e.g. a build-system flag like `_WIN32`) is left unclassified — there's
22//!    no local evidence either way, and guessing would turn every such branch
23//!    into a false positive. A commented-out `#define` is not evidence either:
24//!    the build can still pass `-DNAME`.
25//!
26//! Deliberately line-based, not tree-sitter-based: a header shaped like
27//!
28//! ```c
29//! #ifdef __cplusplus
30//! extern "C" {
31//! #endif
32//! /* ... C declarations ... */
33//! #ifdef __cplusplus
34//! }
35//! #endif
36//! ```
37//!
38//! has an unbalanced `{` when parsed as C (the opening brace's `#ifdef` is
39//! invisible to the parser, but the brace itself is real text) — tree-sitter
40//! error recovery then mis-nests everything that follows, which is exactly
41//! the construct this feature exists to handle. A plain-text line scanner
42//! sidesteps that entirely, the same way [`mod@crate::suppressions`] and
43//! [`mod@crate::regions`] do.
44//!
45//! `#define`/`#undef` evidence follows the paths through each conditional,
46//! not literal nesting depth. Inside an arm, the arm's own `#define` holds
47//! for the rest of that arm — so a file wrapped in one module guard
48//! (`#if SUPPORT_MODULE_X`) that this scanner can't decide still has its
49//! `#define`s counted inside the guard, since nothing inside it compiles
50//! unless the guard is taken. At the `#endif` the arms meet again: a name
51//! keeps a value only if every arm that may be compiled, and the implicit
52//! empty `#else` when there is none, agree on it. So a `#define` under an
53//! undecided `#ifdef _WIN32` leaves the name undecided after the `#endif`
54//! (the POSIX build never ran it), while one in both arms of an `#if`/`#else`
55//! holds. A conditional that tests one macro alone also tells each path
56//! about that macro: the path that skips `#ifndef X` / `#define X 1` /
57//! `#endif` had X defined already, so X is defined after it either way. An
58//! arm this scanner has proven dead contributes nothing, and an arm proven
59//! taken (the C side of `#ifndef __cplusplus`, the first arm of `#if 1`) is
60//! the only path.
61//! Directives inside comments, including multi-line `/* */` comments, are
62//! not directives.
63
64use std::borrow::Cow;
65use std::collections::{HashMap, HashSet};
66
67use BranchKind::{ElseDead, Neutral, ThenDead};
68
69/// Why a [`DeadCodeRegion`] is provably never compiled.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum DeadCodeReason {
72    /// A literal constant condition: the first arm of `#if 0`, a reached
73    /// `#elif 0` arm, and every arm after a literal-true one (the
74    /// `#elif`/`#else` arms of `#if 1`, or those after an `#elif 1` that is
75    /// reached).
76    IfZero,
77    /// C++-only branch, dead when the translation unit is built as C.
78    /// Covers `#ifdef __cplusplus`, `#if defined(__cplusplus) [&&...]`, and
79    /// the dead `#else` of `#ifndef __cplusplus` / `#if !defined(__cplusplus)`.
80    CppOnly,
81    /// The macro is `#define`d on every path to this point with no later
82    /// `#undef`, so the `#ifdef`/`#if defined(MACRO)` branch is always
83    /// live and its `#else` is dead. Also produced, under
84    /// [`dead_code_ranges_with_assumptions`], when the macro has no local
85    /// `#define`/`#undef` of its own but the caller's [`PlatformAssumptions`]
86    /// asserts it defined.
87    AlwaysDefined,
88    /// The macro is `#undef`d on every path to this point with no later
89    /// `#define`, so the
90    /// `#ifdef`/`#if defined(MACRO)` branch itself is dead. Also produced,
91    /// under [`dead_code_ranges_with_assumptions`], when the macro has no
92    /// local `#define`/`#undef` of its own but the caller's
93    /// [`PlatformAssumptions`] asserts it undefined.
94    NeverDefined,
95}
96
97/// A preprocessor-dead region: source that a C/C++ preprocessor strips
98/// before the compiler ever sees it.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub struct DeadCodeRegion {
101    /// 1-based, inclusive first line of the dead region.
102    pub start_line: usize,
103    /// 1-based, inclusive last line of the dead region.
104    pub end_line: usize,
105    /// Why this region is dead.
106    pub reason: DeadCodeReason,
107}
108
109/// Which branch of a preprocessor conditional is never compiled.
110#[derive(Clone, Copy)]
111enum BranchKind {
112    /// The then-branch is dead; the `#else` branch (if any) is live.
113    ThenDead(DeadCodeReason),
114    /// The then-branch is live; the `#else` branch is dead.
115    ElseDead(DeadCodeReason),
116    /// Not a recognized dead conditional — both branches are live as far as
117    /// this scanner knows.
118    Neutral,
119}
120
121struct Frame {
122    kind: BranchKind,
123    /// Whether the dead region currently open (if any) was opened by this
124    /// frame itself, as opposed to inherited from an enclosing dead frame
125    /// (in which case this frame's own classification is moot — everything
126    /// in it is already dead).
127    self_caused: bool,
128    /// The `#if` itself is proven true (its `#else` is proven dead, or it is
129    /// a literal `#if 1`), so its first arm is the only path through the
130    /// conditional: no `#elif`/`#else` arm and no skipping path joins it.
131    then_taken: bool,
132    has_else: bool,
133    /// A live arm with a literal-true condition (`#if 1`, `#elif 1`) has
134    /// begun: every later arm is dead.
135    true_arm_seen: bool,
136    /// The arms from here to `#endif` are dead because of such an arm.
137    rest_dead: bool,
138    /// The current arm alone is dead for this reason (`#elif 0`), apart from
139    /// the conditional's own `kind`.
140    arm_dead_reason: Option<DeadCodeReason>,
141    /// Whether an `#elif`/`#else` has been reached, so the current arm is no
142    /// longer the first.
143    left_first_arm: bool,
144    /// Whether the current arm can be compiled at all, as far as this
145    /// scanner knows. An arm inside a dead region writes nothing.
146    arm_live: bool,
147    /// Each name any arm of this conditional has written so far, with its
148    /// value at the `#if` (`None`: no evidence).
149    entry: HashMap<String, Option<Def>>,
150    /// The names the current arm has written.
151    arm_writes: HashSet<String>,
152    /// The macro a bare `#ifdef`/`#ifndef`/`#if [!]defined(NAME)` tests, and
153    /// whether the first arm is the one where it is defined. Every later arm,
154    /// and the path that skips the conditional, has the opposite.
155    tested: Option<(String, bool)>,
156    /// What each finished live arm left behind.
157    live_arms: Vec<Arm>,
158}
159
160/// One finished, live arm of a conditional.
161struct Arm {
162    /// The value at the arm's end of each name the arm wrote.
163    writes: HashMap<String, Option<Def>>,
164    /// Whether the tested macro (if any) is defined throughout this arm.
165    tested_defined: bool,
166}
167
168impl Frame {
169    /// The branch kind that names the reason of the region this frame has
170    /// open: the current arm's own (`#elif 0`) if it has one.
171    fn region_kind(&self) -> BranchKind {
172        self.arm_dead_reason.map_or(self.kind, ThenDead)
173    }
174
175    /// The value `name` has at the end of a path through this conditional
176    /// that wrote `writes` and on which the tested macro's definedness is
177    /// `tested_defined`; `before` is its value at the `#if`.
178    fn path_value(
179        &self,
180        name: &str,
181        before: Option<Def>,
182        writes: Option<&HashMap<String, Option<Def>>>,
183        tested_defined: bool,
184    ) -> Option<Def> {
185        if let Some(value) = writes.and_then(|w| w.get(name)) {
186            return *value;
187        }
188        match &self.tested {
189            Some((tested, _)) if tested == name => Some(Def::from(tested_defined)),
190            _ => before,
191        }
192    }
193}
194
195/// Assumed defined/undefined state for macros this file will never itself
196/// settle — typically compiler- or build-system-predefined platform flags
197/// (`_MSC_VER`, `_WIN32`, `__APPLE__`, `__vxworks`, ...) that no portable
198/// source file `#define`s or `#undef`s itself. Distinct from the
199/// locally-inferred `#define`/`#undef` evidence [`dead_code_ranges`] already
200/// tracks: a caller-supplied fact standing in for evidence the file itself
201/// will never contain, not something inferred from it. See
202/// [`dead_code_ranges_with_assumptions`].
203pub type PlatformAssumptions = HashMap<String, bool>;
204
205/// A suggested starting point for [`PlatformAssumptions`]: "POSIX/Linux, no
206/// Windows/vxworks compatibility shims active" — assumes `_WIN32`,
207/// `_MSC_VER`, `__CYGWIN__`, and `__vxworks` undefined, and `__linux__` and
208/// `__unix__` defined. A convenience default for the common case, not a
209/// universal one — a caller targeting a different platform profile should
210/// build its own table instead of starting from this one.
211pub fn posix_default_assumptions() -> PlatformAssumptions {
212    [
213        ("_WIN32", false),
214        ("_MSC_VER", false),
215        ("__CYGWIN__", false),
216        ("__vxworks", false),
217        ("__linux__", true),
218        ("__unix__", true),
219    ]
220    .into_iter()
221    .map(|(name, value)| (name.to_string(), value))
222    .collect()
223}
224
225/// Computes the dead-code regions of `source`, a C or C++ translation unit.
226/// See the module documentation for exactly what is and isn't recognized.
227pub fn dead_code_ranges(source: &str) -> Vec<DeadCodeRegion> {
228    dead_code_ranges_impl(source, None)
229}
230
231/// Like [`dead_code_ranges`], but seeds macro definedness with a
232/// caller-supplied [`PlatformAssumptions`] table before walking the file —
233/// standing in for evidence a compiler-predefined platform macro (e.g.
234/// `_MSC_VER`, `__vxworks`) will never leave in the file's own text, which
235/// [`dead_code_ranges`] correctly declines to guess about (see the module
236/// documentation on sub-problem 2).
237///
238/// **Precedence:** a local `#define`/`#undef` for an assumed name overrides
239/// the assumption from the point it takes effect onward — this is the same
240/// `defined` map either way, and local evidence is simply written into it
241/// after the assumption seeds it. This is a deliberate choice, not an
242/// accident of implementation order: for the compiler-predefined platform
243/// flags this is aimed at, a portable file that itself `#define`s
244/// `_MSC_VER` or the like is unusual enough that it's more likely a bug in
245/// the caller's assumption table than a real signal worth suppressing —
246/// but since the file *did* say something concrete, trust it over an
247/// external guess.
248pub fn dead_code_ranges_with_assumptions(
249    source: &str,
250    assumed: &PlatformAssumptions,
251) -> Vec<DeadCodeRegion> {
252    dead_code_ranges_impl(source, Some(assumed))
253}
254
255fn dead_code_ranges_impl(
256    source: &str,
257    assumed: Option<&PlatformAssumptions>,
258) -> Vec<DeadCodeRegion> {
259    // This scanner doesn't know whether the file is C or C++, and a raw
260    // string can be misread (`#define R "x"` then `R"(";` in C, or
261    // ill-formed source). One still open at end of file has hidden
262    // everything after it, so read the file again with raw strings off from
263    // the line it opened on. Every line before that reads exactly as in the
264    // first pass, so earlier, closed raw strings still protect their text.
265    match scan_lines(source, assumed, usize::MAX) {
266        Ok(regions) => regions,
267        Err(open_line) => scan_lines(source, assumed, open_line).unwrap_or_default(),
268    }
269}
270
271/// One pass over `source`, reading raw strings only on lines before index
272/// `raw_strings_until`. `Err` gives the index of the line where a raw string
273/// still open at end of file began.
274fn scan_lines(
275    source: &str,
276    assumed: Option<&PlatformAssumptions>,
277    raw_strings_until: usize,
278) -> Result<Vec<DeadCodeRegion>, usize> {
279    let mut scan = Scan {
280        defined: assumed
281            .map(|a| a.iter().map(|(k, &v)| (k.clone(), Def::from(v))).collect())
282            .unwrap_or_default(),
283        ..Scan::default()
284    };
285    let mut lex = Lex::Code;
286    let mut total_lines = 0;
287    let mut raw_opened_at = 0;
288
289    for (idx, raw) in source.lines().enumerate() {
290        total_lines = idx + 1;
291        let mut opened_raw = false;
292        let line = strip_comments(raw, &mut lex, idx < raw_strings_until, &mut opened_raw);
293        if opened_raw {
294            raw_opened_at = idx;
295        }
296        if let Some((directive, rest)) = parse_directive(&line) {
297            scan.directive(idx + 1, directive, rest);
298        }
299    }
300
301    if matches!(lex, Lex::Raw(_)) {
302        return Err(raw_opened_at);
303    }
304    Ok(scan.finish(total_lines))
305}
306
307/// What this file proves about one macro name at a point in the scan.
308#[derive(Clone, Copy, PartialEq, Eq, Debug)]
309enum Def {
310    Defined,
311    Undefined,
312    /// Defined on some path to this point and not on another: an arm this
313    /// scanner can't decide wrote it. Unlike a name with no entry at all,
314    /// this also overrides a caller's [`PlatformAssumptions`].
315    Unknown,
316}
317
318impl From<bool> for Def {
319    fn from(defined: bool) -> Self {
320        if defined {
321            Def::Defined
322        } else {
323            Def::Undefined
324        }
325    }
326}
327
328/// The value a name has on each of two paths that meet again: equal values
329/// survive, anything else is [`Def::Unknown`].
330fn join(a: Option<Def>, b: Option<Def>) -> Option<Def> {
331    if a == b {
332        a
333    } else {
334        Some(Def::Unknown)
335    }
336}
337
338#[derive(Default)]
339struct Scan {
340    defined: HashMap<String, Def>,
341    regions: Vec<DeadCodeRegion>,
342    stack: Vec<Frame>,
343    dead_start: Option<usize>,
344}
345
346impl Scan {
347    fn directive(&mut self, line_no: usize, directive: &str, rest: &str) {
348        match directive {
349            "if" | "ifdef" | "ifndef" => self.open(line_no, directive, rest),
350            "elif" => self.next_arm(line_no, Some(rest)),
351            "else" => self.next_arm(line_no, None),
352            "endif" => self.close(line_no),
353            "define" | "undef" if self.dead_start.is_none() => {
354                if let Some(name) = first_ident(rest) {
355                    self.set(name, Some(Def::from(directive == "define")));
356                }
357            }
358            _ => {}
359        }
360    }
361
362    fn open(&mut self, line_no: usize, directive: &str, rest: &str) {
363        let kind = if self.dead_start.is_some() {
364            Neutral
365        } else {
366            classify_conditional(directive, rest, &self.defined)
367        };
368        let self_caused = self.dead_start.is_none() && matches!(kind, ThenDead(_));
369        if self_caused {
370            self.dead_start = Some(line_no + 1);
371        }
372        self.stack.push(Frame {
373            kind,
374            self_caused,
375            then_taken: matches!(kind, ElseDead(_))
376                || (self.dead_start.is_none() && directive == "if" && is_one_condition(rest)),
377            has_else: false,
378            true_arm_seen: self.dead_start.is_none() && directive == "if" && is_one_condition(rest),
379            rest_dead: false,
380            arm_dead_reason: None,
381            left_first_arm: false,
382            arm_live: self.dead_start.is_none(),
383            entry: HashMap::new(),
384            arm_writes: HashSet::new(),
385            tested: tested_macro(directive, rest).map(|(n, d)| (n.to_string(), d)),
386            live_arms: Vec::new(),
387        });
388    }
389
390    /// `#elif` (`elif_condition` is its condition) or `#else`: closes the
391    /// current arm and opens the next.
392    fn next_arm(&mut self, line_no: usize, elif_condition: Option<&str>) {
393        if self.stack.is_empty() {
394            return;
395        }
396        self.end_arm();
397        let Some(frame) = self.stack.last_mut() else {
398            return;
399        };
400        let is_else = elif_condition.is_none();
401        frame.has_else |= is_else;
402        if frame.rest_dead {
403            // Still inside the dead run that follows a literal-true arm.
404            frame.arm_live = false;
405            return;
406        }
407        // An `#elif 0` arm's own region ends here, and the conditional
408        // carries on as if that arm were never there; any other region this
409        // frame opened (the first arm of `#if 0`) ends with the arm too, and
410        // the next arm is then live.
411        let decide_next = !frame.self_caused || frame.arm_dead_reason.is_some();
412        if frame.self_caused {
413            let kind = frame.region_kind();
414            frame.arm_dead_reason = None;
415            frame.self_caused = false;
416            close_region(&mut self.regions, &mut self.dead_start, line_no - 1, kind);
417        }
418        // Whether this boundary can open a region for the arms that follow.
419        let open_next = decide_next && self.dead_start.is_none();
420        if open_next && frame.true_arm_seen && !matches!(frame.kind, ElseDead(_)) {
421            // An arm with a literal-true condition (`#if 1`, or an `#elif 1`
422            // reached) is taken whenever it is reached, so no later arm is.
423            // A conditional whose first arm is already proven taken keeps its
424            // own reason for the dead `#else` (the branch below).
425            self.dead_start = Some(line_no + 1);
426            frame.self_caused = true;
427            frame.rest_dead = true;
428            frame.kind = ElseDead(DeadCodeReason::IfZero);
429        } else if open_next && is_else && matches!(frame.kind, ElseDead(_)) {
430            self.dead_start = Some(line_no + 1);
431            frame.self_caused = true;
432        }
433        if self.dead_start.is_none() && elif_condition.is_some_and(is_one_condition) {
434            frame.true_arm_seen = true;
435        }
436        if self.dead_start.is_none() && elif_condition.is_some_and(is_zero_condition) {
437            // A reached `#elif 0` arm is never taken. Its region carries its
438            // own reason, so `frame.kind` (read by a later `#else`) is kept.
439            self.dead_start = Some(line_no + 1);
440            frame.self_caused = true;
441            frame.arm_dead_reason = Some(DeadCodeReason::IfZero);
442        }
443        frame.arm_live = self.dead_start.is_none();
444    }
445
446    fn close(&mut self, line_no: usize) {
447        if self.stack.is_empty() {
448            return;
449        }
450        self.end_arm();
451        let Some(frame) = self.stack.pop() else {
452            return;
453        };
454        if frame.self_caused {
455            close_region(
456                &mut self.regions,
457                &mut self.dead_start,
458                line_no - 1,
459                frame.region_kind(),
460            );
461        }
462        // A missing `#else` is an empty arm, taken whenever the condition
463        // is false: on that path every name keeps its value from the `#if`,
464        // except that a tested macro has the definedness that skipped the
465        // arm (`#ifndef X` / `#define X 1` / `#endif` leaves X defined on
466        // both paths).
467        // No path skips a conditional with a literal-true arm.
468        let implicit_else = !frame.has_else && !frame.then_taken && !frame.true_arm_seen;
469        let paths = frame.live_arms.len() + usize::from(implicit_else);
470        let tested = frame.tested.as_ref().map(|(name, _)| name.as_str());
471        // Join each written name over the paths that wrote it, then with its
472        // value at the `#if` if some path did not. Linear in the writes, so
473        // a long `#elif` chain stays cheap.
474        let mut joined: HashMap<&str, (Option<Def>, usize)> = HashMap::new();
475        for arm in &frame.live_arms {
476            for (name, value) in &arm.writes {
477                if Some(name.as_str()) == tested {
478                    continue;
479                }
480                joined
481                    .entry(name)
482                    .and_modify(|(acc, n)| {
483                        *acc = join(*acc, *value);
484                        *n += 1;
485                    })
486                    .or_insert((*value, 1));
487            }
488        }
489        let mut after: Vec<(String, Option<Def>)> = joined
490            .into_iter()
491            .map(|(name, (value, n))| {
492                let before = frame.entry.get(name).copied().flatten();
493                let value = if n < paths {
494                    join(value, before)
495                } else {
496                    value
497                };
498                (name.to_string(), value)
499            })
500            .collect();
501        // The tested macro: a path that did not write it still knows its
502        // definedness from the test (`#ifndef X` / `#define X 1` / `#endif`
503        // leaves X defined on both paths).
504        if let Some(name) = tested.filter(|n| frame.entry.contains_key(*n)) {
505            let before = frame.entry[name];
506            let skip_defined = frame.tested.as_ref().is_some_and(|(_, first)| !first);
507            let mut values: Vec<Option<Def>> = frame
508                .live_arms
509                .iter()
510                .map(|arm| frame.path_value(name, before, Some(&arm.writes), arm.tested_defined))
511                .collect();
512            if implicit_else {
513                values.push(frame.path_value(name, before, None, skip_defined));
514            }
515            after.push((
516                name.to_string(),
517                values.into_iter().reduce(join).unwrap_or(before),
518            ));
519        }
520        for (name, value) in after {
521            self.set(&name, value);
522        }
523    }
524
525    /// Records the current arm's writes (if it can be compiled at all) and
526    /// rewinds every name it wrote to its value at the
527    /// `#if`, so the next arm starts where the conditional did.
528    fn end_arm(&mut self) {
529        let Some(frame) = self.stack.last_mut() else {
530            return;
531        };
532        let first_arm = !frame.left_first_arm;
533        frame.left_first_arm = true;
534        let written: Vec<String> = frame.arm_writes.drain().collect();
535        if frame.arm_live && (first_arm || !frame.then_taken) {
536            let writes = written
537                .iter()
538                .map(|name| (name.clone(), self.defined.get(name).copied()))
539                .collect();
540            let tested_defined = frame.tested.as_ref().is_some_and(|(_, d)| *d == first_arm);
541            frame.live_arms.push(Arm {
542                writes,
543                tested_defined,
544            });
545        }
546        // Only this arm's writes can differ from the `#if`'s values: every
547        // arm starts from them.
548        for name in written {
549            match frame.entry.get(&name).copied().flatten() {
550                Some(value) => self.defined.insert(name, value),
551                None => self.defined.remove(&name),
552            };
553        }
554    }
555
556    /// Writes `name`'s value, first noting what it was at the innermost
557    /// open conditional's `#if` so that conditional can rewind and join it.
558    fn set(&mut self, name: &str, value: Option<Def>) {
559        if let Some(frame) = self.stack.last_mut() {
560            if !frame.entry.contains_key(name) {
561                frame
562                    .entry
563                    .insert(name.to_string(), self.defined.get(name).copied());
564            }
565            frame.arm_writes.insert(name.to_string());
566        }
567        match value {
568            Some(value) => self.defined.insert(name.to_string(), value),
569            None => self.defined.remove(name),
570        };
571    }
572
573    fn finish(mut self, total_lines: usize) -> Vec<DeadCodeRegion> {
574        if let Some(start) = self.dead_start {
575            let reason = self
576                .stack
577                .iter()
578                .rev()
579                .find(|f| f.self_caused)
580                .and_then(|f| match f.region_kind() {
581                    ThenDead(r) | ElseDead(r) => Some(r),
582                    Neutral => None,
583                })
584                .unwrap_or(DeadCodeReason::IfZero);
585            push_region(&mut self.regions, start, total_lines, reason);
586        }
587        self.regions
588    }
589}
590
591fn close_region(
592    regions: &mut Vec<DeadCodeRegion>,
593    dead_start: &mut Option<usize>,
594    end_line: usize,
595    kind: BranchKind,
596) {
597    if let Some(start) = dead_start.take() {
598        if let ThenDead(reason) | ElseDead(reason) = kind {
599            push_region(regions, start, end_line, reason);
600        }
601    }
602}
603
604fn push_region(
605    regions: &mut Vec<DeadCodeRegion>,
606    start: usize,
607    end: usize,
608    reason: DeadCodeReason,
609) {
610    if start <= end {
611        regions.push(DeadCodeRegion {
612            start_line: start,
613            end_line: end,
614            reason,
615        });
616    }
617}
618
619/// Classifies an `#if`/`#ifdef`/`#ifndef` line. `rest` is everything after
620/// the directive keyword, unparsed.
621fn classify_conditional(directive: &str, rest: &str, defined: &HashMap<String, Def>) -> BranchKind {
622    match directive {
623        "ifdef" => first_ident(rest).map_or(Neutral, |n| classify_name(n, false, defined)),
624        "ifndef" => first_ident(rest).map_or(Neutral, |n| classify_name(n, true, defined)),
625        "if" => {
626            if is_zero_condition(rest) {
627                ThenDead(DeadCodeReason::IfZero)
628            } else {
629                classify_if_condition(rest, defined)
630            }
631        }
632        _ => Neutral,
633    }
634}
635
636/// Classifies a bare macro name from `#ifdef`/`#ifndef` (`is_ifndef` tells
637/// which) or from `defined(NAME)`/`!defined(NAME)` inside `#if`.
638fn classify_name(name: &str, is_ifndef: bool, defined: &HashMap<String, Def>) -> BranchKind {
639    if name == "__cplusplus" {
640        return if is_ifndef {
641            ElseDead(DeadCodeReason::CppOnly)
642        } else {
643            ThenDead(DeadCodeReason::CppOnly)
644        };
645    }
646    match defined.get(name) {
647        Some(Def::Defined) => {
648            if is_ifndef {
649                ThenDead(DeadCodeReason::AlwaysDefined)
650            } else {
651                ElseDead(DeadCodeReason::AlwaysDefined)
652            }
653        }
654        Some(Def::Undefined) => {
655            if is_ifndef {
656                ElseDead(DeadCodeReason::NeverDefined)
657            } else {
658                ThenDead(DeadCodeReason::NeverDefined)
659            }
660        }
661        Some(Def::Unknown) | None => Neutral,
662    }
663}
664
665/// Classifies an `#if` condition that isn't the literal `0` — looks for
666/// `defined(NAME)` / `defined NAME`, optionally negated with a leading `!`,
667/// optionally followed by `&& ...` (only the `ThenDead` side survives a
668/// trailing `&&`, since a live-but-unproven first clause can't prove the
669/// whole condition either way).
670fn classify_if_condition(rest: &str, defined: &HashMap<String, Def>) -> BranchKind {
671    let trimmed = strip_trailing_comment(rest).trim();
672
673    if let Some(after_bang) = trimmed.strip_prefix('!') {
674        return match parse_defined(after_bang.trim_start()) {
675            Some((name, remainder)) if remainder.trim().is_empty() => {
676                classify_name(name, true, defined)
677            }
678            _ => Neutral,
679        };
680    }
681
682    match parse_defined(trimmed) {
683        Some((name, remainder)) => {
684            let kind = classify_name(name, false, defined);
685            let remainder = remainder.trim_start();
686            let bare = remainder.is_empty();
687            // `defined(X) && ...` is false whenever X is undefined, unless an
688            // `||` lets the rest be true on its own.
689            let leading_and = remainder.starts_with("&&")
690                && !remainder.contains("||")
691                && matches!(kind, ThenDead(_));
692            if bare || leading_and {
693                kind
694            } else {
695                Neutral
696            }
697        }
698        None => Neutral,
699    }
700}
701
702/// The macro whose definedness alone decides an `#ifdef NAME`, `#ifndef
703/// NAME`, `#if defined(NAME)` or `#if !defined(NAME)`, and whether the first
704/// arm is the one where it is defined. `None` for any other condition.
705fn tested_macro<'a>(directive: &str, rest: &'a str) -> Option<(&'a str, bool)> {
706    match directive {
707        "ifdef" => first_ident(rest).map(|n| (n, true)),
708        "ifndef" => first_ident(rest).map(|n| (n, false)),
709        "if" => {
710            let trimmed = strip_trailing_comment(rest).trim();
711            let (negated, cond) = match trimmed.strip_prefix('!') {
712                Some(after) => (true, after.trim_start()),
713                None => (false, trimmed),
714            };
715            match parse_defined(cond) {
716                Some((name, after)) if after.trim().is_empty() => Some((name, !negated)),
717                _ => None,
718            }
719        }
720        _ => None,
721    }
722}
723
724/// Parses a leading `defined(NAME)` or `defined NAME` off `s`, returning the
725/// name and whatever text follows it.
726fn parse_defined(s: &str) -> Option<(&str, &str)> {
727    let s = s.trim_start();
728    let rest = s.strip_prefix("defined")?;
729    let rest = rest.trim_start();
730    if let Some(inner) = rest.strip_prefix('(') {
731        let close = inner.find(')')?;
732        let name = inner[..close].trim();
733        if name.is_empty() {
734            return None;
735        }
736        Some((name, &inner[close + 1..]))
737    } else {
738        let name = first_ident(rest)?;
739        Some((name, &rest[name.len()..]))
740    }
741}
742
743/// A literal-true `#if 1` or `#elif 1` condition: that arm is taken whenever
744/// it is reached, so every later arm of the conditional is dead.
745fn is_one_condition(rest: &str) -> bool {
746    let stripped: String = strip_trailing_comment(rest)
747        .chars()
748        .filter(|c| !c.is_whitespace() && *c != '(' && *c != ')')
749        .collect();
750    stripped == "1"
751}
752
753fn is_zero_condition(rest: &str) -> bool {
754    let stripped: String = strip_trailing_comment(rest)
755        .chars()
756        .filter(|c| !c.is_whitespace() && *c != '(' && *c != ')')
757        .collect();
758    stripped == "0"
759}
760
761fn strip_trailing_comment(s: &str) -> &str {
762    let line_pos = s.find("//");
763    let block_pos = s.find("/*");
764    match (line_pos, block_pos) {
765        (Some(a), Some(b)) => &s[..a.min(b)],
766        (Some(a), None) => &s[..a],
767        (None, Some(b)) => &s[..b],
768        (None, None) => s,
769    }
770}
771
772fn first_ident(s: &str) -> Option<&str> {
773    let s = s.trim_start();
774    let end = s
775        .find(|c: char| !(c.is_alphanumeric() || c == '_'))
776        .unwrap_or(s.len());
777    if end == 0 {
778        None
779    } else {
780        Some(&s[..end])
781    }
782}
783
784/// Where a line starts, lexically, given the lines before it.
785#[derive(Default, Clone, PartialEq, Eq, Debug)]
786enum Lex {
787    #[default]
788    Code,
789    /// Inside a `/* */` comment.
790    Block,
791    /// A `//` comment continued onto this line by a trailing backslash.
792    LineComment,
793    /// A string or character literal (its quote) continued onto this line
794    /// by a trailing backslash.
795    Quote(u8),
796    /// A C++ raw string `R"delim( ... )delim"`, closed by `)delim"`.
797    Raw(String),
798}
799
800/// Removes the comments from one line of C or C++ source, replacing each
801/// with a space as the preprocessor does. `state` carries a comment or
802/// literal left open at the end of one line into the next, so text wholly
803/// inside a block comment, a raw string or a backslash-continued literal
804/// comes back blank, and a `#define` or `#if` written inside one is never
805/// read as a directive. Literals that open on this line are kept as written,
806/// and the `/*` in `"/*"` opens nothing. With `raw_strings` off, `R"` opens
807/// an ordinary string. `opened_raw` is set when a raw string opens on this
808/// line.
809fn strip_comments<'a>(
810    line: &'a str,
811    state: &mut Lex,
812    raw_strings: bool,
813    opened_raw: &mut bool,
814) -> Cow<'a, str> {
815    if *state == Lex::Code && !line.contains(['/', '"', '\'']) {
816        return Cow::Borrowed(line);
817    }
818    let bytes = line.as_bytes();
819    let continued = line.ends_with('\\');
820    let mut out = String::with_capacity(line.len());
821    // A literal carried in from an earlier line is blanked up to its close.
822    let mut carried = matches!(state, Lex::Quote(_) | Lex::Raw(_));
823    // Start of the text not yet copied (or skipped). Every index it takes
824    // sits next to an ASCII byte, so it is a char boundary.
825    let mut keep_from = if carried || *state != Lex::Code {
826        line.len()
827    } else {
828        0
829    };
830    let mut i = 0;
831    while i < bytes.len() {
832        let c = bytes[i];
833        let next = bytes.get(i + 1).copied();
834        match state {
835            Lex::LineComment => break,
836            Lex::Block => {
837                if c == b'*' && next == Some(b'/') {
838                    *state = Lex::Code;
839                    out.push(' ');
840                    keep_from = i + 2;
841                    i += 1;
842                }
843            }
844            Lex::Quote(q) => {
845                if c == b'\\' {
846                    i += 1;
847                } else if c == *q {
848                    *state = Lex::Code;
849                    if carried {
850                        carried = false;
851                        out.push(' ');
852                        keep_from = i + 1;
853                    }
854                }
855            }
856            Lex::Raw(delim) => {
857                let close = i + 1 + delim.len();
858                if c == b')'
859                    && line.get(i + 1..close) == Some(delim.as_str())
860                    && bytes.get(close) == Some(&b'"')
861                {
862                    *state = Lex::Code;
863                    if carried {
864                        carried = false;
865                        out.push(' ');
866                        keep_from = close + 1;
867                    }
868                    i = close;
869                }
870            }
871            Lex::Code => {
872                if c == b'"' {
873                    let raw = raw_strings.then(|| raw_string_delimiter(line, i)).flatten();
874                    *state = match raw {
875                        Some((delim, open)) => {
876                            i = open;
877                            *opened_raw = true;
878                            Lex::Raw(delim.to_string())
879                        }
880                        None => Lex::Quote(c),
881                    };
882                } else if c == b'\'' && !follows_a_number(bytes, i) {
883                    // (A `'` inside a number is a C23/C++14 digit separator.)
884                    *state = Lex::Quote(c);
885                } else if c == b'/' && (next == Some(b'/') || next == Some(b'*')) {
886                    out.push_str(&line[keep_from..i]);
887                    out.push(' ');
888                    keep_from = line.len();
889                    *state = if next == Some(b'/') {
890                        Lex::LineComment
891                    } else {
892                        Lex::Block
893                    };
894                    i += 1;
895                }
896            }
897        }
898        i += 1;
899    }
900    if keep_from < line.len() && !carried {
901        out.push_str(&line[keep_from..]);
902    }
903    // A literal or `//` comment ends with its line unless a backslash
904    // splices the next line on; a block comment or raw string does not.
905    if matches!(state, Lex::LineComment | Lex::Quote(_)) && !continued {
906        *state = Lex::Code;
907    }
908    Cow::Owned(out)
909}
910
911/// Whether the `'` at `at` continues a number (`1'000`, `0xFF'FF`): the token
912/// before it starts with a digit. After an identifier such as the `u8` of
913/// `u8'a'`, it opens a character literal.
914fn follows_a_number(bytes: &[u8], at: usize) -> bool {
915    let mut start = at;
916    while start > 0 && (bytes[start - 1].is_ascii_alphanumeric() || bytes[start - 1] == b'_') {
917        start -= 1;
918    }
919    start < at && bytes[start].is_ascii_digit()
920}
921
922/// If the `"` at `quote` opens a C++ raw string (`R"`, `LR"`, `uR"`, `UR"`
923/// or `u8R"`, then a delimiter and `(`), returns the delimiter and the
924/// index of that `(`. A delimiter longer than the standard's 16 characters
925/// is ill-formed but still read as one: reading it as an ordinary string
926/// would let a `"` inside end it early.
927fn raw_string_delimiter(line: &str, quote: usize) -> Option<(&str, usize)> {
928    let bytes = line.as_bytes();
929    let mut start = quote;
930    while start > 0 && (bytes[start - 1].is_ascii_alphanumeric() || bytes[start - 1] == b'_') {
931        start -= 1;
932    }
933    if !matches!(&line[start..quote], "R" | "LR" | "uR" | "UR" | "u8R") {
934        return None;
935    }
936    let rest = &line[quote + 1..];
937    let open = rest.find('(')?;
938    let delim = &rest[..open];
939    let valid = delim
940        .bytes()
941        .all(|b| b.is_ascii_graphic() && !matches!(b, b'(' | b')' | b'\\' | b'"'));
942    valid.then_some((delim, quote + 1 + open))
943}
944
945/// Splits `line` into a leading `#`-directive keyword and the rest of the
946/// line, if `line` is a preprocessor directive at all.
947fn parse_directive(line: &str) -> Option<(&str, &str)> {
948    let trimmed = line.trim_start();
949    let after_hash = trimmed.strip_prefix('#')?;
950    let after_hash = after_hash.trim_start();
951    let word_end = after_hash
952        .find(|c: char| !c.is_ascii_alphabetic())
953        .unwrap_or(after_hash.len());
954    if word_end == 0 {
955        return None;
956    }
957    Some((&after_hash[..word_end], &after_hash[word_end..]))
958}
959
960#[cfg(test)]
961mod tests {
962    use super::*;
963
964    fn ranges(source: &str) -> Vec<(usize, usize, DeadCodeReason)> {
965        dead_code_ranges(source)
966            .into_iter()
967            .map(|r| (r.start_line, r.end_line, r.reason))
968            .collect()
969    }
970
971    #[test]
972    fn if_zero_is_dead() {
973        let src = "a();\n#if 0\nb();\nc();\n#endif\nd();\n";
974        assert_eq!(ranges(src), vec![(3, 4, DeadCodeReason::IfZero)]);
975    }
976
977    #[test]
978    fn if_zero_with_trailing_comment() {
979        let src = "#if 0 // disabled\nx();\n#endif\n";
980        assert_eq!(ranges(src), vec![(2, 2, DeadCodeReason::IfZero)]);
981    }
982
983    #[test]
984    fn if_parenthesized_zero_is_dead() {
985        let src = "#if (0)\nx();\n#endif\n";
986        assert_eq!(ranges(src), vec![(2, 2, DeadCodeReason::IfZero)]);
987    }
988
989    #[test]
990    fn ifdef_cplusplus_then_branch_dead() {
991        let src = "#ifdef __cplusplus\nextern \"C\" {\n#endif\nint f(void);\n";
992        assert_eq!(ranges(src), vec![(2, 2, DeadCodeReason::CppOnly)]);
993    }
994
995    #[test]
996    fn extern_c_header_pair_produces_two_separate_regions() {
997        let src = concat!(
998            "#ifdef __cplusplus\n", // 1
999            "extern \"C\" {\n",     // 2
1000            "#endif\n",             // 3
1001            "int f(void);\n",       // 4
1002            "#ifdef __cplusplus\n", // 5
1003            "}\n",                  // 6
1004            "#endif\n",             // 7
1005        );
1006        assert_eq!(
1007            ranges(src),
1008            vec![
1009                (2, 2, DeadCodeReason::CppOnly),
1010                (6, 6, DeadCodeReason::CppOnly),
1011            ]
1012        );
1013    }
1014
1015    #[test]
1016    fn ifndef_cplusplus_else_branch_dead() {
1017        let src = "#ifndef __cplusplus\nlive();\n#else\ndead();\n#endif\n";
1018        assert_eq!(ranges(src), vec![(4, 4, DeadCodeReason::CppOnly)]);
1019    }
1020
1021    #[test]
1022    fn if_defined_cplusplus_with_and_is_dead() {
1023        let src = "#if defined(__cplusplus) && SOMETHING\nx();\n#endif\n";
1024        assert_eq!(ranges(src), vec![(2, 2, DeadCodeReason::CppOnly)]);
1025    }
1026
1027    #[test]
1028    fn if_not_defined_cplusplus_else_branch_dead() {
1029        let src = "#if !defined(__cplusplus)\nlive();\n#else\ndead();\n#endif\n";
1030        assert_eq!(ranges(src), vec![(4, 4, DeadCodeReason::CppOnly)]);
1031    }
1032
1033    // Raylib rtext.c-shaped case 1: macro unconditionally
1034    // #define'd two lines above the #if defined(...) — the #else is dead.
1035    #[test]
1036    fn always_defined_macro_else_branch_dead() {
1037        let src = concat!(
1038            "#define SUPPORT_COMPRESSED_FONT_ATLAS\n",      // 1
1039            "void f(void) {\n",                             // 2
1040            "#if defined(SUPPORT_COMPRESSED_FONT_ATLAS)\n", // 3
1041            "    live_call();\n",                           // 4
1042            "#else\n",                                      // 5
1043            "    sprintf(buf, \"%d\", n);\n",               // 6
1044            "#endif\n",                                     // 7
1045            "}\n",                                          // 8
1046        );
1047        assert_eq!(ranges(src), vec![(6, 6, DeadCodeReason::AlwaysDefined)]);
1048    }
1049
1050    // A commented-out `#define` is not evidence: `-DSUPPORT_FONT_DATA_COPY`
1051    // still compiles the branch.
1052    #[test]
1053    fn commented_out_define_is_not_evidence() {
1054        let src = concat!(
1055            "//#define SUPPORT_FONT_DATA_COPY\n",    // 1
1056            "void f(void) {\n",                      // 2
1057            "#if defined(SUPPORT_FONT_DATA_COPY)\n", // 3
1058            "    sprintf(buf, \"%d\", n);\n",        // 4
1059            "#endif\n",                              // 5
1060            "}\n",                                   // 6
1061        );
1062        assert!(ranges(src).is_empty());
1063    }
1064
1065    #[test]
1066    fn block_commented_define_is_not_evidence() {
1067        let src = "/* #define HAVE_FOO */\n#ifdef HAVE_FOO\n#include \"foo.h\"\n#endif\n";
1068        assert!(ranges(src).is_empty());
1069    }
1070
1071    #[test]
1072    fn directives_inside_a_multi_line_comment_are_ignored() {
1073        let src = concat!(
1074            "/*\n",                 // 1
1075            "#define HAVE_FOO\n",   // 2
1076            "#if 0\n",              // 3
1077            "*/\n",                 // 4
1078            "#ifdef HAVE_FOO\n",    // 5
1079            "#include \"foo.h\"\n", // 6
1080            "#else\n",              // 7
1081            "bar();\n",             // 8
1082            "#endif\n",             // 9
1083        );
1084        assert!(ranges(src).is_empty());
1085    }
1086
1087    #[test]
1088    fn string_literal_holding_comment_or_define_text_changes_nothing() {
1089        let src = concat!(
1090            "const char *s = \"/*\";\n",          // 1
1091            "const char *t = \"#define FOO\";\n", // 2
1092            "#define FOO\n",                      // 3
1093            "#ifdef FOO\n",                       // 4
1094            "live();\n",                          // 5
1095            "#else\n",                            // 6
1096            "dead();\n",                          // 7
1097            "#endif\n",                           // 8
1098        );
1099        assert_eq!(ranges(src), vec![(7, 7, DeadCodeReason::AlwaysDefined)]);
1100    }
1101
1102    #[test]
1103    fn define_after_trailing_block_comment_close_still_counts() {
1104        let src = "/* note\n */ #define FOO\n#ifndef FOO\ndead();\n#endif\n";
1105        assert_eq!(ranges(src), vec![(4, 4, DeadCodeReason::AlwaysDefined)]);
1106    }
1107
1108    #[test]
1109    fn ifdef_macro_never_mentioned_is_neutral() {
1110        let src = "#ifdef _WIN32\nmaybe_dead();\n#endif\n";
1111        assert!(ranges(src).is_empty());
1112    }
1113
1114    #[test]
1115    fn undef_with_no_later_define_makes_ifdef_dead() {
1116        let src = "#define FOO\n#undef FOO\n#ifdef FOO\ndead();\n#endif\n";
1117        assert_eq!(ranges(src), vec![(4, 4, DeadCodeReason::NeverDefined)]);
1118    }
1119
1120    #[test]
1121    fn undef_with_no_later_define_makes_ifndef_live() {
1122        let src = "#define FOO\n#undef FOO\n#ifndef FOO\nlive();\n#else\ndead();\n#endif\n";
1123        assert_eq!(ranges(src), vec![(6, 6, DeadCodeReason::NeverDefined)]);
1124    }
1125
1126    #[test]
1127    fn define_inside_dead_branch_does_not_count() {
1128        // FOO is only #define'd inside a *proven-dead* `#if 0` branch, which
1129        // never executes — it must not be treated as having defined FOO.
1130        // Line 2 (the #define itself) is legitimately dead as part of the
1131        // `#if 0` block; the later `#ifdef FOO` block (lines 4-6) must NOT
1132        // additionally be reported as dead just because it saw the #define.
1133        let src = "#if 0\n#define FOO\n#endif\n#ifdef FOO\nx();\n#endif\n";
1134        assert_eq!(ranges(src), vec![(2, 2, DeadCodeReason::IfZero)]);
1135    }
1136
1137    // A #define inside an arm this scanner can't decide holds only on the
1138    // path through that arm: after the #endif, the path that skipped the arm
1139    // has FOO undefined, so neither branch of `#ifdef FOO` is dead.
1140    #[test]
1141    fn define_inside_unproven_branch_is_undecided_after_it() {
1142        let src = "#ifndef BAR\n#define FOO\n#endif\n\
1143                   #ifdef FOO\nlive();\n#else\nlive_too();\n#endif\n";
1144        assert!(ranges(src).is_empty());
1145    }
1146
1147    #[test]
1148    fn define_under_platform_arm_leaves_posix_else_live() {
1149        let src = concat!(
1150            "#ifdef _WIN32\n",        // 1
1151            "#define USE_W\n",        // 2
1152            "#endif\n",               // 3
1153            "#ifdef USE_W\n",         // 4
1154            "#include <windows.h>\n", // 5
1155            "#else\n",                // 6
1156            "#include \"posix.h\"\n", // 7
1157            "#endif\n",               // 8
1158        );
1159        assert!(ranges(src).is_empty());
1160    }
1161
1162    #[test]
1163    fn define_in_every_arm_of_an_undecided_conditional_counts() {
1164        let src = concat!(
1165            "#ifdef _WIN32\n",      // 1
1166            "#define SEP '\\\\'\n", // 2
1167            "#else\n",              // 3
1168            "#define SEP '/'\n",    // 4
1169            "#endif\n",             // 5
1170            "#ifndef SEP\n",        // 6
1171            "dead();\n",            // 7
1172            "#endif\n",             // 8
1173        );
1174        assert_eq!(ranges(src), vec![(7, 7, DeadCodeReason::AlwaysDefined)]);
1175    }
1176
1177    #[test]
1178    fn define_in_one_elif_arm_only_is_undecided() {
1179        let src = concat!(
1180            "#if defined(A)\n",   // 1
1181            "#define X\n",        // 2
1182            "#elif defined(B)\n", // 3
1183            "#define X\n",        // 4
1184            "#else\n",            // 5
1185            "#endif\n",           // 6
1186            "#ifdef X\n",         // 7
1187            "x();\n",             // 8
1188            "#endif\n",           // 9
1189        );
1190        assert!(ranges(src).is_empty());
1191    }
1192
1193    #[test]
1194    fn define_inside_proven_live_arm_counts_after_it() {
1195        // `#ifndef __cplusplus` is proven taken when built as C, so its
1196        // #define holds after the #endif.
1197        let src = concat!(
1198            "#ifndef __cplusplus\n", // 1
1199            "#define C_ONLY\n",      // 2
1200            "#endif\n",              // 3
1201            "#ifdef C_ONLY\n",       // 4
1202            "live();\n",             // 5
1203            "#else\n",               // 6
1204            "dead();\n",             // 7
1205            "#endif\n",              // 8
1206        );
1207        assert_eq!(ranges(src), vec![(7, 7, DeadCodeReason::AlwaysDefined)]);
1208    }
1209
1210    #[test]
1211    fn define_inside_live_else_of_if_zero_counts_after_it() {
1212        let src = "#if 0\n#define X 1\n#else\n#define Y\n#endif\n\
1213                   #ifdef Y\nlive();\n#else\ndead();\n#endif\n\
1214                   #ifdef X\nx();\n#endif\n";
1215        assert_eq!(
1216            ranges(src),
1217            vec![
1218                (2, 2, DeadCodeReason::IfZero),
1219                (9, 9, DeadCodeReason::AlwaysDefined),
1220            ]
1221        );
1222    }
1223
1224    #[test]
1225    fn undef_inside_undecided_arm_is_undecided_after_it() {
1226        let src = "#define FOO\n#ifdef _WIN32\n#undef FOO\n#endif\n\
1227                   #ifdef FOO\nmaybe();\n#else\nmaybe_too();\n#endif\n";
1228        assert!(ranges(src).is_empty());
1229    }
1230
1231    #[test]
1232    fn undef_inside_an_undecided_if_leaves_every_later_test_undecided() {
1233        // With X true, FOO is undefined after line 4, so both arms of each
1234        // later test compile: C spellings, and C++ code under them.
1235        for test in [
1236            "#ifdef FOO",
1237            "#if defined(FOO)",
1238            "#ifndef FOO",
1239            "#if !defined FOO",
1240        ] {
1241            for (cond, body) in [("#if X", "f();"), ("#if X > 1", "class A {};")] {
1242                let src = format!(
1243                    "#define FOO\n{cond}\n#undef FOO\n#endif\n{test}\n{body}\n#else\n{body}\n#endif\n"
1244                );
1245                assert!(ranges(&src).is_empty(), "{src}");
1246            }
1247        }
1248    }
1249
1250    #[test]
1251    fn undef_two_levels_deep_leaves_the_macro_undecided() {
1252        let src = "#define FOO\n#if X\n#ifdef Y\n#undef FOO\n#endif\n#endif\n\
1253                   #ifdef FOO\nmaybe();\n#else\nmaybe_too();\n#endif\n";
1254        assert!(ranges(src).is_empty());
1255    }
1256
1257    #[test]
1258    fn include_guard_defines_hold_inside_the_guard() {
1259        let src = concat!(
1260            "#ifndef FOO_H\n", // 1
1261            "#define FOO_H\n", // 2
1262            "#define USE_X\n", // 3
1263            "#ifdef USE_X\n",  // 4
1264            "live();\n",       // 5
1265            "#else\n",         // 6
1266            "dead();\n",       // 7
1267            "#endif\n",        // 8
1268            "#ifndef FOO_H\n", // 9
1269            "dead_too();\n",   // 10
1270            "#endif\n",        // 11
1271            "#endif\n",        // 12
1272        );
1273        assert_eq!(
1274            ranges(src),
1275            vec![
1276                (7, 7, DeadCodeReason::AlwaysDefined),
1277                (10, 10, DeadCodeReason::AlwaysDefined),
1278            ]
1279        );
1280    }
1281
1282    /// The `#else` of `#ifdef FAST ... #else ... #endif` after `default`.
1283    fn else_of_fast_after(default: &str) -> Vec<(usize, usize, DeadCodeReason)> {
1284        let src = format!("{default}#ifdef FAST\nfast();\n#else\nslow();\n#endif\n");
1285        let slow = default.lines().count() + 4;
1286        // Only the region at the `#else` matters here; the default itself
1287        // may sit in a conditional with dead arms of its own.
1288        ranges(&src)
1289            .into_iter()
1290            .filter(|&(a, _, _)| a == slow)
1291            .collect()
1292    }
1293
1294    #[test]
1295    fn default_value_guard_leaves_the_macro_defined_on_every_path() {
1296        for default in [
1297            "#ifndef FAST\n#define FAST 1\n#endif\n",
1298            "#if !defined(FAST)\n#define FAST\n#endif\n",
1299            "#if ! defined FAST /* default */\n#define FAST 1\n#endif\n",
1300            "#ifndef FAST\n#define FAST 1\n#else\n#endif\n",
1301            "#ifdef FAST\n#else\n#define FAST 1\n#endif\n",
1302            "#ifdef WIN\n#define FAST 1\n#endif\n#ifndef FAST\n#define FAST 1\n#endif\n",
1303            "#if 0\n#else\n#ifndef FAST\n#define FAST 1\n#endif\n#endif\n",
1304            "#ifndef FAST\n#if 1\n#define FAST 1\n#endif\n#endif\n",
1305            "#if 1\n#ifndef FAST\n#define FAST 1\n#endif\n#elif defined(WIN)\n#define W 1\n#endif\n",
1306            "#ifndef __cplusplus\n#define FAST 1\n#elif defined(X)\n#undef FAST\n#endif\n",
1307            "#ifndef FAST\n#define FAST 1\n#endif\n#ifdef WIN\n#undef FAST\n#define FAST 2\n#endif\n",
1308        ] {
1309            let slow = default.lines().count() + 4;
1310            assert_eq!(
1311                else_of_fast_after(default),
1312                vec![(slow, slow, DeadCodeReason::AlwaysDefined)],
1313                "{default}"
1314            );
1315        }
1316    }
1317
1318    #[test]
1319    fn a_guard_that_does_not_always_define_the_macro_proves_nothing() {
1320        for default in [
1321            // Defined only under an unrelated undecided macro.
1322            "#ifndef OTHER\n#define FAST 1\n#endif\n",
1323            // A default that a platform then removes.
1324            "#ifndef FAST\n#define FAST 1\n#endif\n#ifdef WIN\n#undef FAST\n#endif\n",
1325            // Defined in the arm where it already was, absent in the other.
1326            "#ifdef FAST\n#define FAST 2\n#else\n#endif\n#ifdef WIN\n#undef FAST\n#endif\n",
1327            // `#elif`: the default holds only in one arm.
1328            "#ifndef FAST\n#elif defined(X)\n#undef FAST\n#endif\n",
1329        ] {
1330            assert!(else_of_fast_after(default).is_empty(), "{default}");
1331        }
1332    }
1333
1334    #[test]
1335    fn a_quote_inside_a_raw_string_does_not_open_a_comment() {
1336        let src = concat!(
1337            "#ifdef __cplusplus\n",                  // 1
1338            "const char *r = R\"x(a \" /* b)x\";\n", // 2
1339            "#endif\n",                              // 3
1340            "int live(void);\n",                     // 4
1341            "#if 0\n",                               // 5
1342            "dead();\n",                             // 6
1343            "#endif\n",                              // 7
1344        );
1345        assert_eq!(
1346            ranges(src),
1347            vec![
1348                (2, 2, DeadCodeReason::CppOnly),
1349                (6, 6, DeadCodeReason::IfZero)
1350            ]
1351        );
1352    }
1353
1354    #[test]
1355    fn a_continued_string_does_not_open_a_comment_on_its_next_line() {
1356        let src = concat!(
1357            "#ifdef __cplusplus\n",     // 1
1358            "const char *s = \"a \\\n", // 2
1359            "/* b\";\n",                // 3
1360            "#endif\n",                 // 4
1361            "int live(void);\n",        // 5
1362        );
1363        assert_eq!(ranges(src), vec![(2, 3, DeadCodeReason::CppOnly)]);
1364    }
1365
1366    #[test]
1367    fn a_define_inside_a_multi_line_raw_string_is_not_a_directive() {
1368        let src = concat!(
1369            "const char *r = R\"sql(\n", // 1
1370            "#define FOO\n",             // 2
1371            "#if 0\n",                   // 3
1372            ")sql\";\n",                 // 4
1373            "#ifdef FOO\n",              // 5
1374            "maybe();\n",                // 6
1375            "#else\n",                   // 7
1376            "maybe_too();\n",            // 8
1377            "#endif\n",                  // 9
1378        );
1379        assert!(ranges(src).is_empty());
1380    }
1381
1382    #[test]
1383    fn a_define_inside_a_continued_string_is_not_a_directive() {
1384        let src = "const char *s = \"a \\\n#define FOO\";\n\
1385                   #ifdef FOO\nmaybe();\n#else\nmaybe_too();\n#endif\n";
1386        assert!(ranges(src).is_empty());
1387    }
1388
1389    #[test]
1390    fn a_continued_line_comment_hides_the_next_line() {
1391        let src = "// note \\\n#define FOO\n#ifdef FOO\nmaybe();\n#else\nmaybe_too();\n#endif\n";
1392        assert!(ranges(src).is_empty());
1393    }
1394
1395    #[test]
1396    fn a_digit_separator_does_not_open_a_char_literal() {
1397        let src = "int n = 1'000; /* c */\n#define FOO\n#ifndef FOO\ndead();\n#endif\n";
1398        assert_eq!(ranges(src), vec![(4, 4, DeadCodeReason::AlwaysDefined)]);
1399    }
1400
1401    #[test]
1402    fn defined_and_rest_with_an_or_decides_nothing() {
1403        let src = "#define A\n#undef A\n#if defined(A) && B || C\nmaybe();\n#endif\n";
1404        assert!(ranges(src).is_empty());
1405        let and_only = "#define A\n#undef A\n#if defined(A) && B\ndead();\n#endif\n";
1406        assert_eq!(ranges(and_only), vec![(4, 4, DeadCodeReason::NeverDefined)]);
1407    }
1408
1409    #[test]
1410    fn a_long_elif_chain_of_distinct_defines_joins_to_undecided() {
1411        let mut src = String::from("#if A0\n#define X0\n");
1412        for i in 1..5000 {
1413            src.push_str(&format!("#elif A{i}\n#define X{i}\n"));
1414        }
1415        src.push_str("#endif\n#ifdef X4999\nmaybe();\n#endif\n#ifndef X0\nmaybe_too();\n#endif\n");
1416        assert!(ranges(&src).is_empty());
1417    }
1418
1419    #[test]
1420    fn a_long_elif_chain_of_distinct_defines_scans_in_linear_time() {
1421        let shape = |n: usize| {
1422            let mut src = String::from("#if A0\n#define X0\n");
1423            for i in 1..n {
1424                src.push_str(&format!("#elif A{i}\n#define X{i}\n"));
1425            }
1426            src + "#endif\n#ifdef X0\nmaybe();\n#endif\n"
1427        };
1428        assert!(crate::scaling_check::costs_under(
1429            &shape(1_250),
1430            &shape(5_000),
1431            crate::scaling_check::LINEAR_BOUND,
1432            |source| {
1433                dead_code_ranges(source);
1434            },
1435        ));
1436    }
1437
1438    #[test]
1439    fn a_u8_char_literal_is_not_a_digit_separator() {
1440        let src = concat!(
1441            "#if 0\n",                                        // 1
1442            "char a[] = {u8'\"'}; const char *s = \"/*\";\n", // 2
1443            "#endif\n",                                       // 3
1444            "int LIVE;\n",                                    // 4
1445        );
1446        assert_eq!(ranges(src), vec![(2, 2, DeadCodeReason::IfZero)]);
1447    }
1448
1449    #[test]
1450    fn a_hex_digit_separator_is_still_a_separator() {
1451        let src = "int n = 0xFF'FF; /* c */\n#define FOO\n#ifndef FOO\ndead();\n#endif\n";
1452        assert_eq!(ranges(src), vec![(4, 4, DeadCodeReason::AlwaysDefined)]);
1453    }
1454
1455    #[test]
1456    fn an_overlong_raw_string_delimiter_is_still_a_raw_string() {
1457        let src = concat!(
1458            "#if 0\n",                                                     // 1
1459            "auto r = R\"abcdefghijklmnopq(\" /* )abcdefghijklmnopq\";\n", // 2
1460            "#endif\n",                                                    // 3
1461            "int LIVE;\n",                                                 // 4
1462        );
1463        assert_eq!(ranges(src), vec![(2, 2, DeadCodeReason::IfZero)]);
1464    }
1465
1466    #[test]
1467    fn a_raw_string_open_at_end_of_file_is_read_again_as_plain_strings() {
1468        // In C, `R"(";` is the macro R followed by a string, not a raw string.
1469        let in_if_zero = concat!(
1470            "#define R \"x\"\n", // 1
1471            "#if 0\n",           // 2
1472            "R\"(\";\n",         // 3
1473            "#endif\n",          // 4
1474            "int LIVE;\n",       // 5
1475        );
1476        assert_eq!(ranges(in_if_zero), vec![(3, 3, DeadCodeReason::IfZero)]);
1477        let outside = concat!(
1478            "#define R \"x\"\n",         // 1
1479            "const char *s = R\"(\";\n", // 2
1480            "#if 0\n",                   // 3
1481            "dead();\n",                 // 4
1482            "#endif\n",                  // 5
1483        );
1484        assert_eq!(ranges(outside), vec![(4, 4, DeadCodeReason::IfZero)]);
1485    }
1486
1487    #[test]
1488    fn a_closed_raw_string_before_an_unclosed_one_still_hides_its_text() {
1489        let src = concat!(
1490            "const char *ok = R\"(\n",      // 1
1491            "#if 0\n",                      // 2
1492            ")\";\n",                       // 3
1493            "int LIVE;\n",                  // 4
1494            "#ifdef A\n",                   // 5
1495            "int LIVE;\n",                  // 6
1496            "#endif\n",                     // 7
1497            "int LIVE;\n",                  // 8
1498            "const char *bad = R\"(oops\n", // 9
1499        );
1500        assert!(ranges(src).is_empty());
1501    }
1502
1503    #[test]
1504    fn an_unclosed_raw_string_after_a_closed_one_leaves_later_directives() {
1505        let src = concat!(
1506            "const char *ok = R\"(a \" /* b)\";\n", // 1
1507            "const char *bad = R\"(oops\n",         // 2
1508            "#if 0\n",                              // 3
1509            "dead();\n",                            // 4
1510            "#endif\n",                             // 5
1511        );
1512        assert_eq!(ranges(src), vec![(4, 4, DeadCodeReason::IfZero)]);
1513    }
1514
1515    #[test]
1516    fn the_else_of_if_1_is_dead() {
1517        assert_eq!(
1518            ranges("#if 1\na();\n#else\nb();\n#endif\n"),
1519            vec![(4, 4, DeadCodeReason::IfZero)]
1520        );
1521        assert_eq!(
1522            ranges("#if (1) // on\na();\n#else\nb();\n#endif\n"),
1523            vec![(4, 4, DeadCodeReason::IfZero)]
1524        );
1525    }
1526
1527    #[test]
1528    fn every_arm_after_if_1_is_dead() {
1529        let src = concat!(
1530            "#if 1\n",   // 1
1531            "a();\n",    // 2
1532            "#elif X\n", // 3
1533            "b();\n",    // 4
1534            "#elif 1\n", // 5
1535            "c();\n",    // 6
1536            "#else\n",   // 7
1537            "d();\n",    // 8
1538            "#endif\n",  // 9
1539            "e();\n",    // 10
1540        );
1541        assert_eq!(ranges(src), vec![(4, 8, DeadCodeReason::IfZero)]);
1542    }
1543
1544    #[test]
1545    fn the_else_after_a_reached_elif_1_is_dead() {
1546        let src = concat!(
1547            "#if 0\n",   // 1
1548            "a();\n",    // 2
1549            "#elif 1\n", // 3
1550            "b();\n",    // 4
1551            "#else\n",   // 5
1552            "c();\n",    // 6
1553            "#endif\n",  // 7
1554        );
1555        assert_eq!(
1556            ranges(src),
1557            vec![
1558                (2, 2, DeadCodeReason::IfZero),
1559                (6, 6, DeadCodeReason::IfZero)
1560            ]
1561        );
1562        // After an undecided arm, `#elif 1` still makes the `#else` dead.
1563        let after_x = "#if X\na();\n#elif 1\nb();\n#else\nc();\n#endif\n";
1564        assert_eq!(ranges(after_x), vec![(6, 6, DeadCodeReason::IfZero)]);
1565    }
1566
1567    #[test]
1568    fn elif_1_after_a_proven_first_arm_keeps_the_else_reason() {
1569        let defined = concat!(
1570            "#define F\n", // 1
1571            "#ifdef F\n",  // 2
1572            "a();\n",      // 3
1573            "#elif 1\n",   // 4
1574            "b();\n",      // 5
1575            "#else\n",     // 6
1576            "c();\n",      // 7
1577            "#endif\n",    // 8
1578        );
1579        assert_eq!(ranges(defined), vec![(7, 7, DeadCodeReason::AlwaysDefined)]);
1580        let c_only = concat!(
1581            "#ifndef __cplusplus\n", // 1
1582            "a();\n",                // 2
1583            "#elif 1\n",             // 3
1584            "b();\n",                // 4
1585            "#else\n",               // 5
1586            "c();\n",                // 6
1587            "#endif\n",              // 7
1588        );
1589        assert_eq!(ranges(c_only), vec![(6, 6, DeadCodeReason::CppOnly)]);
1590    }
1591
1592    #[test]
1593    fn elif_0_after_an_undecided_if_is_dead() {
1594        let src = concat!(
1595            "#if X\n",            // 1
1596            "a();\n",             // 2
1597            "#elif (0) // off\n", // 3
1598            "b();\n",             // 4
1599            "#else\n",            // 5
1600            "c();\n",             // 6
1601            "#endif\n",           // 7
1602        );
1603        assert_eq!(ranges(src), vec![(4, 4, DeadCodeReason::IfZero)]);
1604        let no_else = "#if X\na();\n#elif 0\nb();\n#endif\nd();\n";
1605        assert_eq!(ranges(no_else), vec![(4, 4, DeadCodeReason::IfZero)]);
1606    }
1607
1608    #[test]
1609    fn elif_0_after_a_dead_arm_leaves_the_else_live() {
1610        let src = concat!(
1611            "#if 0\n",   // 1
1612            "a();\n",    // 2
1613            "#elif 0\n", // 3
1614            "b();\n",    // 4
1615            "#else\n",   // 5
1616            "c();\n",    // 6
1617            "#endif\n",  // 7
1618        );
1619        assert_eq!(
1620            ranges(src),
1621            vec![
1622                (2, 2, DeadCodeReason::IfZero),
1623                (4, 4, DeadCodeReason::IfZero)
1624            ]
1625        );
1626    }
1627
1628    #[test]
1629    fn elif_0_nested_in_a_live_arm_and_inside_a_dead_one() {
1630        let live = "#ifdef X\n#if Y\na();\n#elif 0\nb();\n#endif\n#endif\n";
1631        assert_eq!(ranges(live), vec![(5, 5, DeadCodeReason::IfZero)]);
1632        let dead = "#if 0\n#if Y\na();\n#elif 0\nb();\n#endif\n#endif\n";
1633        assert_eq!(ranges(dead), vec![(2, 6, DeadCodeReason::IfZero)]);
1634    }
1635
1636    #[test]
1637    fn elif_0_inside_a_proven_chain_keeps_the_else_reason() {
1638        let src = concat!(
1639            "#define F\n", // 1
1640            "#ifdef F\n",  // 2
1641            "a();\n",      // 3
1642            "#elif 0\n",   // 4
1643            "b();\n",      // 5
1644            "#else\n",     // 6
1645            "c();\n",      // 7
1646            "#endif\n",    // 8
1647        );
1648        assert_eq!(
1649            ranges(src),
1650            vec![
1651                (5, 5, DeadCodeReason::IfZero),
1652                (7, 7, DeadCodeReason::AlwaysDefined)
1653            ]
1654        );
1655        let c_only = "#ifndef __cplusplus\na();\n#elif 0\nb();\n#else\nc();\n#endif\n";
1656        assert_eq!(
1657            ranges(c_only),
1658            vec![
1659                (4, 4, DeadCodeReason::IfZero),
1660                (6, 6, DeadCodeReason::CppOnly)
1661            ]
1662        );
1663    }
1664
1665    #[test]
1666    fn elif_0_then_elif_1_makes_the_rest_dead() {
1667        let src = "#if X\na();\n#elif 0\nb();\n#elif 1\nc();\n#else\nd();\n#endif\n";
1668        assert_eq!(
1669            ranges(src),
1670            vec![
1671                (4, 4, DeadCodeReason::IfZero),
1672                (8, 8, DeadCodeReason::IfZero)
1673            ]
1674        );
1675    }
1676
1677    #[test]
1678    fn an_unterminated_elif_0_runs_to_end_of_file() {
1679        let src = "#if X\na();\n#elif 0\nb();\nc();\n";
1680        assert_eq!(ranges(src), vec![(4, 5, DeadCodeReason::IfZero)]);
1681    }
1682
1683    #[test]
1684    fn a_define_in_an_elif_0_arm_does_not_count() {
1685        let src = "#if X\n#define F\n#elif 0\n#define G\n#else\n#define F\n#endif\n\
1686                   #ifndef F\ndead();\n#endif\n#ifdef G\ng();\n#endif\n";
1687        assert_eq!(
1688            ranges(src),
1689            vec![
1690                (4, 4, DeadCodeReason::IfZero),
1691                (9, 9, DeadCodeReason::AlwaysDefined)
1692            ]
1693        );
1694    }
1695
1696    #[test]
1697    fn if_1_inside_a_dead_region_adds_nothing() {
1698        let src = "#if 0\n#if 1\na();\n#else\nb();\n#endif\n#endif\n";
1699        assert_eq!(ranges(src), vec![(2, 6, DeadCodeReason::IfZero)]);
1700    }
1701
1702    #[test]
1703    fn nested_if_1_else_inside_a_live_arm_is_dead() {
1704        let src = "#ifdef X\n#if 1\na();\n#else\nb();\n#endif\n#endif\n";
1705        assert_eq!(ranges(src), vec![(5, 5, DeadCodeReason::IfZero)]);
1706    }
1707
1708    #[test]
1709    fn a_define_after_elif_1_without_else_holds_after_endif() {
1710        // No path skips `#if X ... #elif 1 ... #endif`, and both arms define
1711        // FOO, so FOO is defined after it.
1712        let src = "#if X\n#define FOO\n#elif 1\n#define FOO\n#endif\n\
1713                   #ifndef FOO\ndead();\n#endif\n";
1714        assert_eq!(ranges(src), vec![(7, 7, DeadCodeReason::AlwaysDefined)]);
1715    }
1716
1717    #[test]
1718    fn a_tested_macro_nobody_writes_keeps_its_assumption() {
1719        // `#ifdef _MSC_VER ... #else ... #endif` writes nothing, so the
1720        // caller's assumption about _MSC_VER still decides a later test.
1721        let src = "#ifdef _MSC_VER\nx();\n#else\ny();\n#endif\n\
1722                   #ifdef _MSC_VER\nwin();\n#endif\n";
1723        let mut assumed = PlatformAssumptions::new();
1724        assumed.insert("_MSC_VER".to_string(), false);
1725        assert_eq!(
1726            ranges_with(src, &assumed),
1727            vec![
1728                (2, 2, DeadCodeReason::NeverDefined),
1729                (7, 7, DeadCodeReason::NeverDefined),
1730            ]
1731        );
1732    }
1733
1734    #[test]
1735    fn nested_if_zero_inside_live_arm_is_dead() {
1736        let src = "#ifdef _WIN32\na();\n#if 0\nb();\n#endif\nc();\n#endif\n";
1737        assert_eq!(ranges(src), vec![(4, 4, DeadCodeReason::IfZero)]);
1738    }
1739
1740    #[test]
1741    fn local_undecided_define_overrides_assumption() {
1742        // An assumption is a stand-in for missing evidence; once an undecided
1743        // arm writes the name, the file has said something and it is unknown.
1744        let src = "#ifdef CONFIG_X\n#define _MSC_VER 1900\n#endif\n\
1745                   #ifdef _MSC_VER\nmaybe();\n#endif\n";
1746        let mut assumed = PlatformAssumptions::new();
1747        assumed.insert("_MSC_VER".to_string(), false);
1748        assert!(ranges_with(src, &assumed).is_empty());
1749    }
1750
1751    // Raylib rtext.c's actual shape: the whole file is
1752    // wrapped in a single top-level `#if SUPPORT_MODULE_RTEXT` module guard
1753    // this scanner can't prove either way, so the unconditional #define
1754    // inside it sits at preprocessor-nesting depth 1, not 0.
1755    #[test]
1756    fn always_defined_macro_under_unprovable_module_guard_else_is_dead() {
1757        let src = concat!(
1758            "#if SUPPORT_MODULE_RTEXT\n",                   // 1
1759            "#define SUPPORT_COMPRESSED_FONT_ATLAS\n",      // 2
1760            "void f(void) {\n",                             // 3
1761            "#if defined(SUPPORT_COMPRESSED_FONT_ATLAS)\n", // 4
1762            "    live_call();\n",                           // 5
1763            "#else\n",                                      // 6
1764            "    sprintf(buf, \"%d\", n);\n",               // 7
1765            "#endif\n",                                     // 8
1766            "}\n",                                          // 9
1767            "#endif\n",                                     // 10
1768        );
1769        assert_eq!(ranges(src), vec![(7, 7, DeadCodeReason::AlwaysDefined)]);
1770    }
1771
1772    #[test]
1773    fn nested_if_zero_inside_dead_region_does_not_split_it() {
1774        let src = concat!(
1775            "#if 0\n",              // 1
1776            "a();\n",               // 2
1777            "#ifdef __cplusplus\n", // 3
1778            "b();\n",               // 4
1779            "#endif\n",             // 5
1780            "c();\n",               // 6
1781            "#endif\n",             // 7
1782            "d();\n",               // 8
1783        );
1784        assert_eq!(ranges(src), vec![(2, 6, DeadCodeReason::IfZero)]);
1785    }
1786
1787    #[test]
1788    fn unterminated_dead_block_runs_to_eof() {
1789        let src = "a();\n#if 0\nb();\nc();\n";
1790        assert_eq!(ranges(src), vec![(3, 4, DeadCodeReason::IfZero)]);
1791    }
1792
1793    #[test]
1794    fn empty_if_zero_block_yields_no_region() {
1795        let src = "#if 0\n#endif\n";
1796        assert!(ranges(src).is_empty());
1797    }
1798
1799    #[test]
1800    fn no_directives_yields_no_regions() {
1801        assert!(ranges("int x = 0;\nint y = 1;\n").is_empty());
1802    }
1803
1804    #[test]
1805    fn empty_source_yields_no_regions() {
1806        assert!(ranges("").is_empty());
1807    }
1808
1809    fn ranges_with(
1810        source: &str,
1811        assumed: &PlatformAssumptions,
1812    ) -> Vec<(usize, usize, DeadCodeReason)> {
1813        dead_code_ranges_with_assumptions(source, assumed)
1814            .into_iter()
1815            .map(|r| (r.start_line, r.end_line, r.reason))
1816            .collect()
1817    }
1818
1819    // hostap's src/utils/common.h shape:
1820    // an #ifdef on a macro the file never itself defines is Neutral without
1821    // an assumption, but resolves once the caller supplies one.
1822    #[test]
1823    fn assumption_makes_never_mentioned_macro_dead() {
1824        let src = "#ifdef _MSC_VER\ntypedef UINT16 u16;\n#endif\n";
1825        assert!(ranges(src).is_empty());
1826
1827        let mut assumed = PlatformAssumptions::new();
1828        assumed.insert("_MSC_VER".to_string(), false);
1829        assert_eq!(
1830            ranges_with(src, &assumed),
1831            vec![(2, 2, DeadCodeReason::NeverDefined)]
1832        );
1833    }
1834
1835    #[test]
1836    fn assumption_true_keeps_ifdef_branch_live_and_else_dead() {
1837        let src = "#ifdef __linux__\nlive();\n#else\ndead();\n#endif\n";
1838        let mut assumed = PlatformAssumptions::new();
1839        assumed.insert("__linux__".to_string(), true);
1840        assert_eq!(
1841            ranges_with(src, &assumed),
1842            vec![(4, 4, DeadCodeReason::AlwaysDefined)]
1843        );
1844    }
1845
1846    #[test]
1847    fn local_define_overrides_assumption() {
1848        // The file itself #defines _MSC_VER despite the caller assuming it
1849        // undefined — local evidence wins from that point on.
1850        let src = "#define _MSC_VER\n#ifdef _MSC_VER\nlive();\n#endif\n";
1851        let mut assumed = PlatformAssumptions::new();
1852        assumed.insert("_MSC_VER".to_string(), false);
1853        assert!(ranges_with(src, &assumed).is_empty());
1854    }
1855
1856    #[test]
1857    fn posix_default_assumptions_resolves_hostap_style_platform_split() {
1858        let src = concat!(
1859            "#ifdef _MSC_VER\n",             // 1
1860            "typedef UINT16 u16;\n",         // 2
1861            "#endif\n",                      // 3
1862            "#ifdef __vxworks\n",            // 4
1863            "typedef UINT16 u16;\n",         // 5
1864            "#endif\n",                      // 6
1865            "#ifndef WPA_TYPES_DEFINED\n",   // 7
1866            "typedef unsigned short u16;\n", // 8
1867            "#endif\n",                      // 9
1868        );
1869        assert_eq!(
1870            ranges_with(src, &posix_default_assumptions()),
1871            vec![
1872                (2, 2, DeadCodeReason::NeverDefined),
1873                (5, 5, DeadCodeReason::NeverDefined),
1874            ]
1875        );
1876    }
1877}