fix(extract): blank C# preprocessor directives and #if branches that derail parsing

tree-sitter-c-sharp parses `#if`/`#elif`/`#else`/`#endif` with every branch
in place. Its error recovery around a directive can close the enclosing class
early, so every later member became a class-less node: it lost its `Type.`
owner, its field/receiver typing and same-class resolution, and its calls
were lost or wrong (e.g. `Writer.Flush -> Buffer.Append` was missing).

Before parsing, extract_csharp now blanks every directive line (including
#region, #pragma, #nullable and #define). The first branch of each #if group
is always kept. A later #elif/#else branch is kept as well, so members that
exist only there stay in the graph (#2631). It is blanked only when keeping
it would derail the parse:
- its `{}` or `()` do not net to zero on their own
  (`class A : B {` #else `class A {`), or
- it declares a member (name + arity) that a kept branch of the same group
  already declares (`void Write(Span<char>)` #else `void Write(string)`
  sharing one body).
Nested groups are decided first. The rewrite keeps the byte length the same
(removed bytes become spaces, CR/LF kept), so every remaining byte keeps its
line and column. A `#` line inside a comment or a multi-line string is not
treated as a directive.

Measured against the Roslyn answer key on Newtonsoft.Json, Dapper and
AutoMapper: 5544/7349 links (75.4%, was 70.8%), and 264 wrong `calls` edges
(was 288). No kind loses recall except `ctor` (-4): five `new JValue(...)`
calls inside JValue. Those methods now correctly belong to JValue, and the
graph keeps one edge per node pair, so the JValue -> method edge replaces
the calls edge. Keeping only the first branch scores 5545 but drops #else-only
members.

Bumps the AST cache schema to 38 so cached C# extractions re-run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit e1668ed0c6)
This commit is contained in:
rohit-jsfreaky authored and safishamsi committed 2026-11-04 20:48:49 +00:00
1 parent 92622867d1
commit 52a7acb602
3 files changed
+490 -3

No files matched your search

+1 -1
View File
@@ -38,7 +38,7 @@ except Exception:
_EXTRACTOR_VERSION = "unknown"
# Bump when AST cache-key semantics change independently of the package version.
_AST_CACHE_SCHEMA = 37 # Solidity `import "../x/Y.sol"` resolves the `..` to the real file instead of a dangling stub that kept the importer's own folder (#4985); a Python module-level singleton (`g = Service()` then `g.method()`) resolves its member calls through the instance's type, gated by an exact-spelling and lexical-shadow guard (#4972); Kotlin resolves a call to an overloaded method and attributes calls inside an `init {}` block to the class, and a bare call no longer binds to a class the caller cannot reach (#4935, #4956); a Go same-file member call resolves through the receiver's type instead of a declaration-order-dependent same-named method (#4962, #4966); a Go member call on a receiver typed from another package (`pkg.T`) binds only to the `T` declared at the path the file imports `pkg` from (#3368, #4853); and a Go interface method call additively dispatches to the interface's implicit implementers (#4934), so cached Solidity, Python, Kotlin and Go extractions re-run; prior (36): C++ extraction changes: a type-alias reference (`using Foo = Bar;` then `Foo x;`) binds by exact spelling so it no longer loses to a same-normalized function, and a salted alias keeps its own `contains` edge (#4951); a member call `x.m()` binds by the receiver's type, now typed from parameters and class fields and not just locals, with untyped receivers kept bound in-file (#3215, #4946); an out-of-line/split-header definition attaches to the unique owner whose class file is in its include set via a `_cpp_qualified` identity marker, instead of file-containing or cross-binding to an unrelated same-named function (#4916, #4920); and a local callable value (a lambda or `std::function` local) is kept out of global call resolution by byte-range binding lifetimes so it no longer mints a spurious INFERRED call to a same-named global (#4917, #4921), so cached C++ extractions re-run; prior (35): A Rust module-qualified call like `crate::b::helper()` resolves to the function it names via qualifier-verified cross-file resolution, kept inside the caller's crate and out of local names (#2135, #4944); a Rust call written inside an expression macro's arguments (`println!`, `vec!`, ...) is linked, with a parsed call winning the dedupe (#4945); and cache keys keep their written case (file I/O through os_long_path, cache identity via normpath not normcase, and the digest salt no longer lowercased) so README.md and readme.md stop sharing one digest on a case-sensitive filesystem, which also changes the salt digest for any relative path carrying an uppercase char (#4925, #4937), so cached Rust extractions and any uppercase-path cache entries re-run; prior (34): A bare call inside a Python method no longer self-binds to a same-named method, so it resolves to the imported/module function instead (#4933); a Go method value reached through a receiver field is linked as an indirect_call (#4931); and a Go package-level `var` initialiser references the types it names (#4932), so cached Python and Go extractions re-run; prior (33): A Scala `extension (x: T)` method is scoped to its receiver type T (#2044, #4856); and a Terraform node carries its original scope so ids stay portable when the cached project is moved to a new directory (#4858, #4861), so cached Scala and Terraform extractions re-run; prior (32): A type and a function whose names differ only in case get separate node ids (#4904, #4908); and a PHP `Scope::MEMBER` access in a class-level initializer (const value, property/parameter default) emits a references_constant edge (#4648, #4895); R `setClass`/`setRefClass` `contains=` superclasses get inherits edges (#4902); an Elixir bare call resolves to the caller's own module first (#4900); a Dart mixin `on A, B` clause resolves every constraint (#4899); and a Fortran derived-type `extends` emits an inherits edge (#4897), so cached extractions for those languages re-run (#4904); Go credits a call in a package-level `var` initialiser (and its closures) to the file node (#4867); a Go method value passed as an argument is linked as an `indirect_call` (#4868); a Go receiver's field whose struct is declared in a sibling file of the same package is typed so its member calls resolve (#4866); and a Python dispatch table's `module.func` values resolve to the referenced functions as `indirect_call`s (#4773), so cached Go and Python extractions re-run; prior (30): File and per-declaration ids are kept distinct so a top-level declaration sharing the file's name is not dropped (#4854); a SystemVerilog `function new(...)` constructor gets its own node, `method` edge and parameter refs (#4848); a Go `var x = T{}`/`var x = &T{}` types `x` as `T` for receiver resolution like `x := T{}` (#4843); a PowerShell `using module`/`using assembly` name drops its file extension (#4847); a Solidity free-function `using {a, b} for T` set emits `uses` edges (#4846); a CommonLisp forward-referenced superclass binds to its local node instead of a sourceless stub (#4845)Line truncated
_AST_CACHE_SCHEMA = 38 # C# preprocessor directives are blanked before parsing, and an `#if` branch that would derail tree-sitter-c-sharp is blanked too (byte-length preserving, so lines and columns do not move); its error recovery around `#if`/`#else` could close the enclosing class early, leaving every later member class-less with its calls lost, so cached C# extractions re-run; prior (37): Solidity `import "../x/Y.sol"` resolves the `..` to the real file instead of a dangling stub that kept the importer's own folder (#4985); a Python module-level singleton (`g = Service()` then `g.method()`) resolves its member calls through the instance's type, gated by an exact-spelling and lexical-shadow guard (#4972); Kotlin resolves a call to an overloaded method and attributes calls inside an `init {}` block to the class, and a bare call no longer binds to a class the caller cannot reach (#4935, #4956); a Go same-file member call resolves through the receiver's type instead of a declaration-order-dependent same-named method (#4962, #4966); a Go member call on a receiver typed from another package (`pkg.T`) binds only to the `T` declared at the path the file imports `pkg` from (#3368, #4853); and a Go interface method call additively dispatches to the interface's implicit implementers (#4934), so cached Solidity, Python, Kotlin and Go extractions re-run; prior (36): C++ extraction changes: a type-alias reference (`using Foo = Bar;` then `Foo x;`) binds by exact spelling so it no longer loses to a same-normalized function, and a salted alias keeps its own `contains` edge (#4951); a member call `x.m()` binds by the receiver's type, now typed from parameters and class fields and not just locals, with untyped receivers kept bound in-file (#3215, #4946); an out-of-line/split-header definition attaches to the unique owner whose class file is in its include set via a `_cpp_qualified` identity marker, instead of file-containing or cross-binding to an unrelated same-named function (#4916, #4920); and a local callable value (a lambda or `std::function` local) is kept out of global call resolution by byte-range binding lifetimes so it no longer mints a spurious INFERRED call to a same-named global (#4917, #4921), so cached C++ extractions re-run; prior (35): A Rust module-qualified call like `crate::b::helper()` resolves to the function it names via qualifier-verified cross-file resolution, kept inside the caller's crate and out of local names (#2135, #4944); a Rust call written inside an expression macro's arguments (`println!`, `vec!`, ...) is linked, with a parsed call winning the dedupe (#4945); and cache keys keep their written case (file I/O through os_long_path, cache identity via normpath not normcase, and the digest salt no longer lowercased) so README.md and readme.md stop sharing one digest on a case-sensitive filesystem, which also changes the salt digest for any relative path carrying an uppercase char (#4925, #4937), so cached Rust extractions and any uppercase-path cache entries re-run; prior (34): A bare call inside a Python method no longer self-binds to a same-named method, so it resolves to the imported/module function instead (#4933); a Go method value reached through a receiver field is linked as an indirect_call (#4931); and a Go package-level `var` initialiser references the types it names (#4932), so cached Python and Go extractions re-run; prior (33): A Scala `extension (x: T)` method is scoped to its receiver type T (#2044, #4856); and a Terraform node carries its original scope so ids stay portable when the cached project is moved to a new directory (#4858, #4861), so cached Scala and Terraform extractions re-run; prior (32): A type and a function whose names differ only in case get separate node ids (#4904, #4908); and a PHP `Scope::MEMBER` access in a class-level initializer (const value, property/parameter default) emits a references_constant edge (#4648, #4895); R `setClass`/`setRefClass` `contains=` superclasses get inherits edges (#4902); an Elixir bare call resolves to the caller's own module first (#4900); a Dart mixin `on A, B` clause resolves every constraint (#4899); and a Fortran derived-type `extends` emits an inherits edge (#4897), so cached extractions for those languages re-run (#4904); Go credits a call in a package-level `var` initialiser (and its closures) to the file node (#4867); a Go method value passed as an argument is linked as an `indirect_call` (#4868); a Go receiver's field whose struct is declared in a sibling file of the same package is typed so its member calls resolve (#4866); and a Python dispatch table's `module.func` values resolve to the referenced functions as `indirect_call`s (#4773), so cached Go and Python extractions re-run; prior (30): File and per-declaration ids are kept distinct so a top-level declaration sharing the file's name is not dropped (#4854); a SystemVerilog `function new(...)` constructor gets its own node, `method` edge and parameter refs (#4Line truncated
# Per-process memo: distributions() scans site-packages metadata, which is
+275 -2
View File
@@ -3721,13 +3721,286 @@ def _normalize_csharp_verbatim_interpolation(source: bytes) -> bytes | None:
return out
# Maps every byte but CR and LF to a space: blanking keeps lines and columns.
_CSHARP_BLANK_TABLE = bytes(b if b in (0x0A, 0x0D) else 0x20 for b in range(256))
def _csharp_token_end(source: bytes, i: int) -> int:
"""End (exclusive) of the comment, char or string literal opening at ``i``.
Returns ``i`` when no such token opens there. A line-bounded token (a ``//``
comment, a char literal, a regular string) stops *before* its newline, so
the caller still sees the next line start. Holes of interpolated strings
are walked as code, so a quote inside ``{...}`` does not end the string.
"""
n = len(source)
if source.startswith(b"//", i):
nl = source.find(b"\n", i)
return n if nl == -1 else nl
if source.startswith(b"/*", i):
end = source.find(b"*/", i + 2)
return n if end == -1 else end + 2
if source[i:i + 1] == b"'":
j = i + 1
while j < n and source[j:j + 1] not in (b"'", b"\n"):
j += 2 if source[j:j + 1] == b"\\" else 1
return j + 1 if source[j:j + 1] == b"'" else min(j, n)
quote, run, interpolated, verbatim = _csharp_string_opener(source, i)
if run == 0:
return i
if run >= 3:
end = source.find(b'"' * run, quote + run)
return n if end == -1 else end + run
if run == 2:
return quote + 2
j = quote + 1
while j < n:
ch = source[j:j + 1]
if verbatim and source.startswith(b'""', j):
j += 2
elif ch == b"\\" and not verbatim:
j += 2
elif ch == b'"':
return j + 1
elif ch == b"\n" and not verbatim:
return j
elif interpolated and source.startswith(b"{{", j):
j += 2
elif interpolated and ch == b"{":
depth = 1
j += 1
while j < n and depth:
end = _csharp_token_end(source, j)
if end > j:
j = end
continue
c = source[j:j + 1]
depth += (c == b"{") - (c == b"}")
j += 1
else:
j += 1
return n
def _csharp_branch_balanced(text: bytearray, start: int, end: int) -> bool:
"""True when ``{}`` and ``()`` in ``text[start:end]`` each net to zero.
Comments, char and string literals are skipped.
"""
src = bytes(text[start:end])
brace = paren = 0
j = 0
while j < len(src):
tok = _csharp_token_end(src, j)
if tok > j:
j = tok
continue
ch = src[j:j + 1]
brace += (ch == b"{") - (ch == b"}")
paren += (ch == b"(") - (ch == b")")
j += 1
return brace == 0 and paren == 0
_CSHARP_NOT_A_TYPE = frozenset({
b"return", b"new", b"await", b"throw", b"if", b"while", b"for", b"foreach",
b"switch", b"case", b"using", b"lock", b"catch", b"when", b"is", b"as",
b"in", b"out", b"ref", b"else", b"yield", b"nameof", b"typeof", b"sizeof",
b"default", b"var", b"goto", b"fixed", b"checked", b"unchecked", b"and", b"or", b"not",
})
_CSHARP_MEMBER_DECL_RE = re.compile(
rb"([A-Za-z_][A-Za-z0-9_]*|[>\]?*])\s+([A-Za-z_][A-Za-z0-9_]*)"
rb"\s*(?:<[^<>(){};]*>)?\s*(\(|\{|=>)"
)
def _csharp_branch_member_sigs(text: bytearray, start: int, end: int) -> set[tuple[bytes, int]]:
"""(name, arity) of the members a branch declares at its own brace depth.
A heuristic, not a parse: a declaration is an identifier preceded by a
type-like token (an identifier that is not a statement keyword, or ``>``,
``]``, ``?``, ``*``) and followed by ``(`` (arity = top-level commas + 1, 0
for ``()``) or by ``{``/``=>`` (a property or type, arity -1). Both branches
of a group sit at the same place in the file, so a shared (name, arity)
means the same member of the same type is declared twice.
"""
src = bytes(text[start:end])
# Mask comments and literals so they never look like code.
masked = bytearray(src)
j = 0
while j < len(src):
tok = _csharp_token_end(src, j)
if tok > j:
masked[j:tok] = src[j:tok].translate(_CSHARP_BLANK_TABLE)
j = tok
else:
j += 1
code = bytes(masked)
depth_at = []
d = 0
for ch in code:
depth_at.append(d)
if ch == 0x7B:
d += 1
elif ch == 0x7D:
d -= 1
sigs: set[tuple[bytes, int]] = set()
for m in _CSHARP_MEMBER_DECL_RE.finditer(code):
if depth_at[m.start(2)] != 0 or m.group(1) in _CSHARP_NOT_A_TYPE:
continue
name = m.group(2)
if m.group(3) != b"(":
sigs.add((name, -1))
continue
k = m.end(3)
level, angle, commas, empty = 1, 0, 0, True
while k < len(code) and level:
c = code[k:k + 1]
if c in (b"(", b"[", b"{"):
level += 1
elif c in (b")", b"]", b"}"):
level -= 1
elif c == b"<":
angle += 1
elif c == b">":
angle = max(0, angle - 1)
elif c == b"," and level == 1 and angle == 0:
commas += 1
if level and not c.isspace():
empty = False
k += 1
sigs.add((name, 0 if empty else commas + 1))
return sigs
def _blank_csharp_preprocessor(source: bytes) -> bytes | None:
"""Blank C# preprocessor directives and the ``#if`` branches that derail parsing, or None.
tree-sitter-c-sharp parses the raw text, directives and all branches
together. Its error recovery around a directive can close the enclosing
class early, so every later member loses its type owner, its field typing
and its calls.
Every directive line (``#if``/``#elif``/``#else``/``#endif``, and also
``#region``, ``#pragma``, ``#nullable``, ``#define`` ...) is blanked. The
first branch of each ``#if`` group is always kept. A later ``#elif`` /
``#else`` branch is kept too, so members that exist only there (an
older-framework fallback) stay in the graph (#2631), unless keeping it
would derail the parse:
* its ``{}`` or ``()`` do not net to zero on their own (``class A : B {``
``#else`` ``class A {``), or
* it declares a member (name + arity) that a kept branch of the same group
already declares (``void Write(Span<char> s)`` ``#else``
``void Write(string s)`` sharing one body).
Nested groups are decided first, so an outer branch is judged on what is
left of it. No symbols are evaluated. Measured against the compiler on
Newtonsoft.Json, Dapper and AutoMapper.
The rewrite is **byte-length preserving**: removed bytes become spaces and
every ``\\n``/``\\r`` is kept, so every remaining byte keeps its line and
column and source locations stay accurate (the #2876 contract).
A ``#`` line inside a comment or a multi-line string is not a directive;
comments and string literals are skipped while looking for line starts.
Returns None when the file has no directive.
"""
n = len(source)
# (line_start, line_end, keyword) for every directive line.
directives: list[tuple[int, int, bytes]] = []
i = 0
while i < n:
# i is at a line start here.
p = i
while p < n and source[p:p + 1] in (b" ", b"\t", b"\v", b"\f"):
p += 1
if source[p:p + 1] == b"#":
nl = source.find(b"\n", p)
end = n if nl == -1 else nl
k = p + 1
while k < end and source[k:k + 1] in (b" ", b"\t"):
k += 1
w = k
while w < end and source[w:w + 1].isalpha():
w += 1
directives.append((i, end, source[k:w]))
i = end + 1
continue
# Walk the line as code; a comment or string may run past its end.
j = p
while j < n:
ch = source[j:j + 1]
if ch == b"\n":
break
end = _csharp_token_end(source, j)
if end > j:
j = end
elif ch in (b"$", b"@"):
# Resume past the whole `$`/`@` run (see _csharp_string_opener).
j = max(j + 1, _csharp_string_opener(source, j)[0])
else:
j += 1
i = j + 1
if not directives:
return None
out = bytearray(source)
def blank(start: int, end: int) -> None:
out[start:end] = source[start:end].translate(_CSHARP_BLANK_TABLE)
def keep(branch: int, bodies: list[tuple[int, int]], kept: list[int]) -> bool:
if branch == 0:
return True
start, end = bodies[branch]
if not _csharp_branch_balanced(out, start, end):
return False
sigs = _csharp_branch_member_sigs(out, start, end)
return not any(sigs & _csharp_branch_member_sigs(out, *bodies[k]) for k in kept)
# Each open #if group: the (directive start, directive end) of its #if and
# of every #elif/#else seen so far.
stack: list[list[tuple[int, int]]] = []
def close(heads: list[tuple[int, int]], endif_start: int) -> None:
bodies = [(heads[k][1], heads[k + 1][0] if k + 1 < len(heads) else endif_start)
for k in range(len(heads))]
kept: list[int] = []
for k in range(len(bodies)):
if keep(k, bodies, kept):
kept.append(k)
else:
blank(*bodies[k])
for start, end, word in directives:
blank(start, end)
if word == b"if":
stack.append([(start, end)])
elif word in (b"elif", b"else") and stack:
stack[-1].append((start, end))
elif word == b"endif" and stack:
close(stack.pop(), start)
# An unterminated #if runs to the end of the file.
while stack:
close(stack.pop(), n)
return bytes(out)
def extract_csharp(path: Path) -> dict:
"""Extract C# type declarations, methods, namespaces, and usings from a .cs file."""
source_override = None
try:
source_override = _normalize_csharp_verbatim_interpolation(path.read_bytes())
source = path.read_bytes()
except OSError:
pass
source = None
if source is not None:
source_override = _blank_csharp_preprocessor(source)
source_override = _normalize_csharp_verbatim_interpolation(
source_override or source
) or source_override
return _extract_generic(path, _CSHARP_CONFIG, source_override=source_override)
+214
View File
@@ -897,3 +897,217 @@ def test_struct_primary_constructor_parameter_emits_references_edge(tmp_path):
idep = _find(r, "IDep", "idep")
assert (holder, idep) in _refs(r), \
"a struct primary-constructor parameter type must produce a references edge"
# --- Preprocessor directives -------------------------------------------------
# tree-sitter-c-sharp parses `#if`/`#elif`/`#else`/`#endif` with every branch in
# place. Its error recovery can close the enclosing class early, so every later
# member lost its `Type.` owner, its field typing and its calls. The C# extractor
# now blanks directive lines, plus any later branch whose braces/parens do not
# balance or that redeclares a member the kept branch already declares, keeping
# each remaining byte on its line and column. Other `#elif`/`#else` branches are
# kept so members that exist only there stay in the graph (#2631).
_PP_BUFFER = (
"namespace Repro3;\n"
"\n"
"public class Buffer\n"
"{\n"
" public void Append(char c) { }\n"
"}\n"
)
_PP_WRITER = (
"namespace Repro3\n"
"{\n"
" public class Writer\n"
" {\n"
" private readonly Buffer _buffer = new Buffer();\n"
" private int _state;\n"
"\n"
" public int State\n"
" {\n"
" get\n"
" {\n"
" {\n"
" return _state;\n"
" }\n"
" }\n"
" }\n"
"\n"
" public string Path\n"
" {\n"
" get\n"
" {\n"
" {\n"
" return \"\";\n"
" }\n"
" }\n"
" }\n"
"\n"
" public void WriteValue(int typeCode)\n"
" {\n"
" {\n"
" switch (typeCode)\n"
" {\n"
"#if HAVE_DB_NULL\n"
" case 1:\n"
" break;\n"
"#endif\n"
" }\n"
" }\n"
" }\n"
"\n"
" public void Flush()\n"
" {\n"
" Prepare();\n"
" _buffer.Append('x');\n"
" }\n"
"\n"
" private void Prepare() { }\n"
" }\n"
"}\n"
)
def _member(r, owner: str, name: str):
"""The one method node `name` declared inside class `owner`."""
suffix = f"_{owner}_{name}".lower()
matches = [n for n in r["nodes"]
if n["label"] == f".{name}()" and n["id"].endswith(suffix)]
assert len(matches) == 1, (owner, name, [(n["id"], n["label"]) for n in r["nodes"]])
return matches[0]
def test_preprocessor_if_does_not_orphan_later_members(tmp_path):
calls, r = _calls(tmp_path, {"Writer.cs": _PP_WRITER, "Buffer.cs": _PP_BUFFER})
flush = _member(r, "Writer", "Flush")
prepare = _member(r, "Writer", "Prepare")
append = _member(r, "Buffer", "Append")
assert (flush["id"], prepare["id"]) in calls
assert (flush["id"], append["id"]) in calls, "_buffer.Append() must resolve through the field type"
def test_preprocessor_blanking_keeps_member_line_numbers(tmp_path):
_, r = _calls(tmp_path, {"Writer.cs": _PP_WRITER, "Buffer.cs": _PP_BUFFER})
lines = _PP_WRITER.splitlines()
for name, decl in (("WriteValue", "public void WriteValue("),
("Flush", "public void Flush()"),
("Prepare", "private void Prepare()")):
want = next(i for i, line in enumerate(lines, 1) if decl in line)
assert _member(r, "Writer", name)["source_location"] == f"L{want}", name
def test_preprocessor_nested_split_signature_keeps_one_header(tmp_path):
calls, r = _calls(tmp_path, {
"Sink.cs": (
"public class Fast { public void Run() {} }\n"
"public class Slow { public void Run() {} }\n"
"public class Old { public void Run() {} }\n"
),
"Host.cs": (
"public class Host\n"
"{\n"
" private Fast _fast = new Fast();\n"
" private Slow _slow = new Slow();\n"
" private Old _old = new Old();\n"
"#if NET\n"
" #if NET8_0_OR_GREATER\n"
" public void Write(System.ReadOnlySpan<char> s)\n"
" #else\n"
" public void Write(char[] s)\n"
" #endif\n"
"#else\n"
" public void Write(string s)\n"
"#endif\n"
" {\n"
"#if NET\n"
" _fast.Run();\n"
" #if DEBUG\n"
" _slow.Run();\n"
" #else\n"
" _old.Run();\n"
" #endif\n"
"#else\n"
" _old.Run();\n"
"#endif\n"
" }\n"
"\n"
" public void Flush() { _fast.Run(); }\n"
"}\n"
),
})
write = _member(r, "Host", "Write")
flush = _member(r, "Host", "Flush")
fast = _member(r, "Fast", "Run")["id"]
slow = _member(r, "Slow", "Run")["id"]
old = _member(r, "Old", "Run")["id"]
assert write["source_location"] == "L8"
assert flush["source_location"] == "L28"
assert (write["id"], fast) in calls
assert (write["id"], slow) in calls, "a nested #if keeps its first branch inside a kept branch"
assert (write["id"], old) in calls, "balanced #else statements are kept"
assert (flush["id"], fast) in calls
def test_preprocessor_elif_else_redeclaring_a_member_are_blanked(tmp_path):
calls, r = _calls(tmp_path, {
"Sink.cs": (
"public class A { public void Go() {} }\n"
"public class B { public void Go() {} }\n"
"public class C { public void Go() {} }\n"
),
"Host.cs": (
"public class Host\n"
"{\n"
" private A _a = new A();\n"
" private B _b = new B();\n"
" private C _c = new C();\n"
"#if HAVE_A\n"
" public void Run() { _a.Go(); }\n"
"#elif HAVE_B\n"
" public void Run() { _b.Go(); }\n"
"#else\n"
" public void Run() { _c.Go(); }\n"
"#endif\n"
"#region tail\n"
" public void Tail() { Run(); }\n"
"#endregion\n"
"}\n"
),
})
run = _member(r, "Host", "Run")
tail = _member(r, "Host", "Tail")
assert run["source_location"] == "L7"
assert tail["source_location"] == "L14"
assert (run["id"], _member(r, "A", "Go")["id"]) in calls
for other in ("B", "C"):
assert (run["id"], _member(r, other, "Go")["id"]) not in calls, (
f"the #elif/#else branch calling {other}.Go() must not be parsed")
assert (tail["id"], run["id"]) in calls
def test_preprocessor_unbalanced_else_type_header_is_blanked(tmp_path):
calls, r = _calls(tmp_path, {
"Base.cs": "public class Base { public void Ping() {} }\n",
"Host.cs": (
"public class Sink { public void Go() {} }\n"
"#if NET\n"
"public class Host : Base\n"
"{\n"
"#else\n"
"public class Host\n"
"{\n"
" public void OldOnly() { }\n"
"#endif\n"
" private Sink _sink = new Sink();\n"
" public void Run() { _sink.Go(); Ping(); }\n"
"}\n"
),
})
run = _member(r, "Host", "Run")
assert run["source_location"] == "L11"
assert (run["id"], _member(r, "Sink", "Go")["id"]) in calls
assert (run["id"], _member(r, "Base", "Ping")["id"]) in calls
assert not any(n["label"] == ".OldOnly()" for n in r["nodes"]), (
"an #else branch whose braces do not balance is blanked")