From e65cbb3126b4b049d0fe496661dc04d6c43b8576 Mon Sep 17 00:00:00 2001 From: Scott Arciszewski <147527775+tob-scott-a@users.noreply.github.com> Date: Wed, 2 Dec 2026 05:10:20 -0500 Subject: [PATCH 1/2] Recover bounded conditional profiles with C-family declaration owners --- docs/parser-coverage.md | 34 +- .../parsers/_c_conditional_profiles.py | 108 ++++ .../parsers/_c_conditional_recovery.py | 365 ++++++++++++ src/trailmark/parsers/c/_conditional.py | 97 +-- src/trailmark/parsers/cpp/parser.py | 48 +- src/trailmark/parsers/objc/parser.py | 50 +- tests/mutation_baseline.json | 29 +- tests/test_c_conditional_profiles.py | 95 +++ tests/test_cpp_conditional_profiles.py | 559 ++++++++++++++++++ tests/test_docs.py | 5 +- 10 files changed, 1267 insertions(+), 123 deletions(-) create mode 100644 src/trailmark/parsers/_c_conditional_profiles.py create mode 100644 src/trailmark/parsers/_c_conditional_recovery.py create mode 100644 tests/test_c_conditional_profiles.py create mode 100644 tests/test_cpp_conditional_profiles.py diff --git a/docs/parser-coverage.md b/docs/parser-coverage.md index e061295..8ed0382 100644 --- a/docs/parser-coverage.md +++ b/docs/parser-coverage.md @@ -643,7 +643,7 @@ give it the wrong name: | Source pattern | Current limitation | Workaround | | --- | --- | --- | | C++ inline `bool Read(int n) REQUIRES(!mu) { ... }` | C++ and Objective-C recover bounded uppercase trailing annotations, including bare markers; arbitrary declaration macros remain unexpanded. | Check recovery provenance and original diagnostics; preprocess unsupported forms with the project's compiler configuration. | -| `#ifdef` and `#else` arms each open `{`, with a shared closing `}` | C++ and Objective-C can lose the enclosing function and all of its calls. | Preprocess and analyze each relevant build configuration separately. | +| `#ifdef` and `#else` arms each open `{`, with a shared closing `}` | C, C++, and Objective-C retain bounded syntactic profiles with uncertain calls; unvisited or opaque configurations remain unknown. | Review conditional provenance and diagnostics; preprocess unsupported configurations separately. | | `#define APP_MAIN int main(...)`, followed by `APP_MAIN { ... }` | C, C++, and Objective-C recover bounded object-like signatures; unavailable or unsupported expansions remain unresolved. | Review `signature_macro`, `expansion_alias` and original diagnostics; preprocess unsupported definitions with the project's compiler configuration. | These correspond to [#222](https://github.com/trailofbits/trailmark/issues/222), @@ -693,13 +693,31 @@ Recovered functions retain `syntax_recovered` and `parse_incomplete`, and origin diagnostics still cause strict-mode failure. Rebuild affected graphs to recover functions omitted by older versions. -C already recovers some split-brace functions through at most 64 syntactic -profiles, retaining `conditional_source`, uncertain calls, profile provenance, -and the original syntax diagnostics. This does not prove build feasibility or -cover every configuration. C++ and Objective-C do not currently share that -recovery. Adapting it requires preserving their additional literal forms and -declaration owners. C also retains the simple trailing-annotation free-function -example above; that does not establish support for arbitrary macro expansions. +C, C++, and Objective-C retain split-brace functions through at most 64 syntactic +profiles, without evaluating build conditions. C keeps its existing profile bytes. +C++ and Objective-C select groups whose arms have a net brace change or a negative +running brace depth. They use the first profile with fewer grammar errors for the +whole file, then union verified affected functions from the remaining profiles. +This preserves declarations inside alternative arms and their namespace or class +owners, including different owners for the same physical function. Independent +functions after the group retain their actual owner. + +Affected functions retain `conditional_source`, `parse_incomplete`, and +`syntax_recovered`. Their calls stay uncertain after directory linking and carry +`conditional_profiles` provenance; call-site records retain a `conditional_source` +gap. Conflicting operand interpretations remain unknown. Original syntax diagnostics +remain visible, and modules add a `syntax_recovery` diagnostic. Incomplete profile +enumeration also adds `unsupported_syntax`. File counts and physical locations do +not multiply across profiles. A clean parse or balanced arms do not trigger this +recovery; unrecognized literal or directive syntax fails closed. + +The cap permits at most 64 recovery profile parses in addition to the initial +parse; later annotation and signature recovery retain their separate bounds. +Repeated predicates share one assignment across the file. Profiles describe syntax, +not feasible compiler configurations, and do not make conditional signature-macro +definitions unconditional. Strict mode still rejects recovered source. Rebuild +affected graphs to remove bogus owners such as `n.After`. Preprocess unsupported +forms and analyze each relevant configuration separately. Agents should use this workflow: diff --git a/src/trailmark/parsers/_c_conditional_profiles.py b/src/trailmark/parsers/_c_conditional_profiles.py new file mode 100644 index 0000000..6e072fc --- /dev/null +++ b/src/trailmark/parsers/_c_conditional_profiles.py @@ -0,0 +1,108 @@ +"""Bounded, source-mapped syntactic profiles, without evaluating build conditions.""" + +from __future__ import annotations + +import itertools +import re +from collections.abc import Iterator, Sequence +from dataclasses import dataclass + +_DEFINED = re.compile(rb"(!?)\s*defined\s*(?:\(\s*(\w+)\s*\)|(\w+))\Z") +CONDITIONAL = re.compile(rb"\s*#\s*(if|ifdef|ifndef|else|elif|elifdef|elifndef|endif)\b") +_OPEN = frozenset({b"if", b"ifdef", b"ifndef"}) +LIMIT = 64 +type Directive = tuple[int, int, bytes, tuple[str, bool]] + + +@dataclass(frozen=True) +class SourceProfile: + """One assignment's physical bytes and spans excluded from later reparses.""" + + source: bytes + evidence: str + complete: bool + excluded: tuple[tuple[int, int], ...] + + +def condition(text: bytes, directive: bytes) -> tuple[str, bool]: + """Correlate repeated predicates, including negated defined tests.""" + expression = text.split(directive, 1)[1].strip() + if directive in {b"ifdef", b"ifndef", b"elifdef", b"elifndef"}: + return f"defined({expression.decode(errors='replace')})", directive in { + b"ifdef", + b"elifdef", + } + match = _DEFINED.fullmatch(expression) + if match: + name = (match[2] or match[3]).decode(errors="replace") + return f"defined({name})", not bool(match[1]) + return " ".join(expression.decode(errors="replace").split()), True + + +def _assignments(names: list[str]) -> Iterator[tuple[bool, ...]]: + if len(names) <= 6: + yield from itertools.product((False, True), repeat=len(names)) + return + yield tuple(False for _ in names) + yield tuple(True for _ in names) + yield from (tuple(i == selected for i in range(len(names))) for selected in range(len(names))) + yield from (tuple(i != selected for i in range(len(names))) for selected in range(len(names))) + + +def _selected(expression: str, positive: bool, profile: dict[str, bool]) -> bool: + return (expression == "1" or profile.get(expression, False)) == positive + + +def _excluded( + source: bytes, directives: Sequence[Directive], profile: dict[str, bool] +) -> tuple[tuple[int, int], ...] | None: + spans: list[tuple[int, int]] = [] + stack: list[tuple[bool, bool]] = [] + active, previous = True, 0 + for start, end, kind, (expression, positive) in directives: + if not active: + spans.append((previous, start)) + spans.append((start, end)) + selected = _selected(expression, positive, profile) + if kind in _OPEN: + stack.append((active, selected)) + active = active and selected + elif not stack: + return None + elif kind == b"endif": + active, _ = stack.pop() + else: + parent, taken = stack[-1] + selected = not taken if kind == b"else" else selected and not taken + active = parent and selected + stack[-1] = (parent, taken or selected) + previous = end + if stack: + return None + if not active: + spans.append((previous, len(source))) + return tuple(spans) + + +def profile_views(source: bytes, directives: Sequence[Directive]) -> Iterator[SourceProfile]: + """Yield at most 64 distinct views, retaining every byte offset and newline.""" + if not directives: + return + names = sorted({item[3][0] for item in directives} - {"", "0", "1"}) + seen: set[bytes] = set() + for values in itertools.islice(_assignments(names), LIMIT): + profile = dict(zip(names, values, strict=True)) + spans = _excluded(source, directives, profile) + if spans is None: + continue + masked = bytearray(source) + for start, end in spans: + for index in range(start, end): + if masked[index] not in (10, 13): + masked[index] = 32 + view = bytes(masked) + if view in seen: + continue + seen.add(view) + evidence = "; ".join(f"{name}={str(profile[name]).lower()}" for name in names) + yield SourceProfile(view, evidence, len(names) <= 6, spans) diff --git a/src/trailmark/parsers/_c_conditional_recovery.py b/src/trailmark/parsers/_c_conditional_recovery.py new file mode 100644 index 0000000..6ac3cc3 --- /dev/null +++ b/src/trailmark/parsers/_c_conditional_recovery.py @@ -0,0 +1,365 @@ +"""Retain conditional C-family callables and their syntactic owner alternatives.""" + +from __future__ import annotations + +import json +from bisect import bisect_right +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING + +from tree_sitter import Node, Parser, Range, Tree + +from trailmark.models._replace import replace +from trailmark.models.constraints import CallSite +from trailmark.models.diagnostics import ParseDiagnostic +from trailmark.models.edges import CodeEdge, EdgeConfidence, EdgeKind +from trailmark.models.graph import CodeGraph +from trailmark.models.nodes import NodeKind +from trailmark.parsers._binding_index import query_nodes +from trailmark.parsers._c_conditional_profiles import ( + CONDITIONAL, + Directive, + SourceProfile, + condition, + profile_views, +) +from trailmark.parsers._common import make_location + +_FUNCTIONS = frozenset( + {"function_definition", "method_definition", "lambda_expression", "block_literal"} +) +_OWNERS = frozenset( + { + "namespace_definition", + "class_specifier", + "struct_specifier", + "class_implementation", + "category_implementation", + "function_definition", + "method_definition", + } +) +type ParseView = Callable[[Tree, bytes], tuple[CodeGraph, Tree]] + +if TYPE_CHECKING: + from trailmark.parsers.cpp._block_macros import _Token + + +def _conditional_tokens(tokens: Sequence[_Token]) -> list[Directive]: + from trailmark.parsers.c._recovery import _directive_text + + result = [] + for token in tokens: + text = _directive_text(token.text) + match = CONDITIONAL.match(text) + if match is not None: + kind = match[1] + predicate = condition(text, kind) + result.append((token.start, token.end, kind, predicate)) + return result + + +def _brace_groups(tokens: Sequence[_Token]) -> list[tuple[int, int]] | None: + from trailmark.parsers.c._recovery import _directive_text + + stack: list[tuple[int, int, int, bool]] = [] + groups = [] + for token in tokens: + match = CONDITIONAL.match(_directive_text(token.text)) + if match is not None: + kind = match[1] + if kind in {b"if", b"ifdef", b"ifndef"}: + stack.append((token.start, 0, 0, False)) + elif not stack: + return None + else: + start, depth, minimum, changed = stack.pop() + changed |= depth != 0 or minimum < 0 + if kind == b"endif": + if changed: + groups.append((start, token.end)) + else: + stack.append((start, 0, 0, changed)) + elif token.text in {b"{", b"}"}: + delta = 1 if token.text == b"{" else -1 + stack = [(s, d + delta, min(m, d + delta), c) for s, d, m, c in stack] + return None if stack else groups + + +def _profile_tree(parser: Parser, source: bytes, profile: SourceProfile) -> Tree: + starts = [0, *(index + 1 for index, byte in enumerate(source) if byte == 10)] + + def point(offset: int) -> tuple[int, int]: + row = bisect_right(starts, offset) - 1 + return row, offset - starts[row] + + ranges = [] + left = 0 + for start, end in profile.excluded: + if left < start: + ranges.append(Range(point(left), point(start), left, start)) + left = max(left, end) + if left < len(source): + ranges.append(Range(point(left), point(len(source)), left, len(source))) + bounded = Parser(parser.language) + bounded.included_ranges = ranges + return bounded.parse(profile.source) + + +def _error_count(tree: Tree) -> int: + pending, count = [tree.root_node], 0 + while pending: + node = pending.pop() + count += node.is_error or node.is_missing + pending.extend(node.children) + return count + + +def _intersects(node: Node, groups: Sequence[tuple[int, int]]) -> bool: + return any(node.start_byte < end and start < node.end_byte for start, end in groups) + + +def _affected(node: Node, groups: Sequence[tuple[int, int]]) -> Node | None: + ancestor: Node | None = node + while ancestor is not None: + if ancestor.type in _FUNCTIONS and _intersects(ancestor, groups): + return ancestor + if ancestor.type in _OWNERS and any( + ancestor.start_byte in range(start, end) for start, end in groups + ): + return ancestor + ancestor = ancestor.parent + return None + + +def _affected_ids(graph: CodeGraph, tree: Tree, groups: Sequence[tuple[int, int]]) -> set[str]: + locations = { + make_location(node, graph.root_path) + for node in query_nodes(tree.root_node, None, _FUNCTIONS) + if not node.has_error and _affected(node, groups) is not None + } + return { + key + for key, unit in graph.nodes.items() + if unit.kind in {NodeKind.FUNCTION, NodeKind.METHOD} and unit.location in locations + } + + +def _mark(graph: CodeGraph, affected: set[str], profile: str) -> None: + for key in affected: + unit = graph.nodes[key] + attrs = dict(unit.attributes) + attrs.update(conditional_source=True, parse_incomplete=True, syntax_recovered=True) + graph.nodes[key] = replace(unit, attributes=tuple(attrs.items())) + graph.edges[:] = [ + replace( + edge, + confidence=EdgeConfidence.UNCERTAIN, + attributes=(*edge.attributes, ("conditional_profiles", json.dumps([profile]))), + ) + if edge.source_id in affected and edge.kind in {EdgeKind.CALLS, EdgeKind.REFERENCES} + else edge + for edge in graph.edges + ] + for sites in (graph.call_sites, graph._parse_state.call_sites): + for key, site in sites.items(): + if site.caller_id in affected: + sites[key] = replace(site, gaps=tuple(sorted({*site.gaps, "conditional_source"}))) + + +def _ancestors(graph: CodeGraph, seeds: set[str]) -> set[str]: + adjacent: dict[str, set[str]] = {} + for edge in graph.edges: + if edge.kind == EdgeKind.CONTAINS: + adjacent.setdefault(edge.target_id, set()).add(edge.source_id) + keep, pending = set(seeds), list(seeds) + while pending: + for key in adjacent.get(pending.pop(), ()): + if key not in keep: + keep.add(key) + pending.append(key) + return keep + + +def _profile_names(graph: CodeGraph, incoming: CodeGraph, keep: set[str]) -> dict[str, str]: + renamed = {} + for key in sorted(keep): + unit, previous = incoming.nodes.get(key), graph.nodes.get(key) + if ( + unit is not None + and previous is not None + and unit.location != previous.location + and unit.kind in {NodeKind.FUNCTION, NodeKind.METHOD} + ): + renamed[key] = f"{key}@{unit.location.start_line}_{unit.location.start_col or 0}" + return _owned_names(keep, renamed) + + +def _owned_names(keep: set[str], renamed: dict[str, str]) -> dict[str, str]: + for key in sorted(keep, key=lambda value: value.count(".")): + parent = key.rpartition(".")[0] + while parent: + if parent in renamed: + renamed[key] = renamed[parent] + renamed.get(key, key)[len(parent) :] + break + parent = parent.rpartition(".")[0] + return renamed + + +def _merge_profile(graph: CodeGraph, incoming: CodeGraph, affected: set[str]) -> None: + bodies = affected + edges = [ + edge + for edge in incoming.edges + if edge.source_id in bodies and edge.kind != EdgeKind.CONTAINS + ] + keep = _ancestors(incoming, bodies | {edge.target_id for edge in edges}) + renamed = _profile_names(graph, incoming, keep) + for key in keep: + if key in incoming.nodes: + unit = incoming.nodes[key] + ident = renamed.get(key, key) + graph.nodes.setdefault(ident, replace(unit, id=ident)) + edges.extend( + edge for edge in incoming.edges if edge.kind == EdgeKind.CONTAINS and edge.target_id in keep + ) + graph.edges.extend( + replace( + edge, + source_id=renamed.get(edge.source_id, edge.source_id), + target_id=renamed.get(edge.target_id, edge.target_id), + ) + for edge in edges + ) + _merge_sites(graph.call_sites, incoming.call_sites, bodies, renamed) + _merge_sites(graph._parse_state.call_sites, incoming._parse_state.call_sites, bodies, renamed) + graph._parse_state.references.update(incoming._parse_state.references) + graph._parse_state.arguments.update(incoming._parse_state.arguments) + + +def _merge_sites( + current: dict[str, CallSite], + incoming: dict[str, CallSite], + bodies: set[str], + renamed: dict[str, str], +) -> None: + for site in incoming.values(): + if site.caller_id in bodies: + site = replace(site, caller_id=renamed.get(site.caller_id, site.caller_id)) + previous = current.get(site.id) + if previous is not None and previous != site: + site = replace( + site, + arguments=(), + receiver=None, + execution="unknown", + gaps=tuple( + sorted({*site.gaps, *previous.gaps, "conditional_operands_unknown"}) + ), + ) + current[site.id] = site + + +def mark_conditional_calls(graph: CodeGraph) -> None: + """Keep conditional call evidence uncertain after directory linking.""" + conditional = { + key for key, unit in graph.nodes.items() if dict(unit.attributes).get("conditional_source") + } + graph.edges[:] = [ + replace(edge, confidence=EdgeConfidence.UNCERTAIN) + if edge.kind in {EdgeKind.CALLS, EdgeKind.REFERENCES} + and ( + edge.source_id in conditional + or edge.target_id in conditional + or "conditional_profiles" in dict(edge.attributes) + ) + else edge + for edge in graph.edges + ] + + +def _deduplicate(graph: CodeGraph) -> None: + merged: dict[CodeEdge, set[str]] = {} + for edge in graph.edges: + attrs = dict(edge.attributes) + profiles = json.loads(str(attrs.pop("conditional_profiles", "[]"))) + if profiles: + edge = replace(edge, confidence=EdgeConfidence.UNCERTAIN) + edge = replace(edge, attributes=tuple(attrs.items())) + merged.setdefault(edge, set()).update(profiles) + graph.edges[:] = [ + replace( + edge, + attributes=(*edge.attributes, ("conditional_profiles", json.dumps(sorted(profiles)))), + ) + if profiles + else edge + for edge, profiles in merged.items() + ] + + +def _diagnose(graph: CodeGraph, *, limited: bool, recovered: bool) -> None: + module = next(unit for unit in graph.nodes.values() if unit.kind == NodeKind.MODULE) + if recovered: + graph.parse_diagnostics.append( + ParseDiagnostic( + graph.language, + graph.language, + module.location, + "syntax_recovery", + "Recovered conditional callables and owner alternatives from bounded syntactic " + "profiles; build feasibility and preprocessor control flow remain unknown", + ) + ) + if limited: + graph.parse_diagnostics.append( + ParseDiagnostic( + graph.language, + graph.language, + module.location, + "unsupported_syntax", + "Conditional recovery stopped after at most 64 syntactic profiles; " + "unvisited conditional source remains unknown", + ) + ) + + +def recover_conditional_profiles( + parser: Parser, source: bytes, original: Tree, parse_view: ParseView +) -> CodeGraph: + """Use the first improving whole view, then union verified affected callables.""" + from trailmark.parsers.cpp._block_macros import _tokens + + if not original.root_node.has_error: + return parse_view(original, source)[0] + tokens = _tokens(source, original, parser.language) + if tokens is None: + return parse_view(original, source)[0] + groups = _brace_groups(tokens) + if not groups: + return parse_view(original, source)[0] + directives = _conditional_tokens(tokens) + views = [ + (_profile_tree(parser, source, view), view) for view in profile_views(source, directives) + ] + errors = _error_count(original) + primary = next( + (index for index, (tree, _) in enumerate(views) if _error_count(tree) < errors), None + ) + limited = any(not view.complete for _, view in views) + if primary is None: + graph = parse_view(original, source)[0] + _diagnose(graph, limited=limited, recovered=False) + return graph + tree, view = views.pop(primary) + graph, recovered = parse_view(tree, view.source) + _mark(graph, _affected_ids(graph, recovered, groups), view.evidence) + for tree, view in views: + incoming, recovered = parse_view(tree, view.source) + affected = _affected_ids(incoming, recovered, groups) + _mark(incoming, affected, view.evidence) + _merge_profile(graph, incoming, affected) + _deduplicate(graph) + mark_conditional_calls(graph) + _diagnose(graph, limited=limited, recovered=True) + return graph diff --git a/src/trailmark/parsers/c/_conditional.py b/src/trailmark/parsers/c/_conditional.py index 7f89bdf..38db0a6 100644 --- a/src/trailmark/parsers/c/_conditional.py +++ b/src/trailmark/parsers/c/_conditional.py @@ -1,106 +1,23 @@ -"""Bounded syntactic profiles for functions hidden by conditional C braces. +"""Preserve C's existing syntactic views through the shared profile generator.""" -These views select source arms, not compiler configurations. They never expand -macros, read build flags, or establish that a profile is buildable. Every byte -offset and newline is retained; extracted evidence must remain uncertain. -""" - -from __future__ import annotations - -import itertools -import re from collections.abc import Iterator from tree_sitter import Parser, Tree +from trailmark.parsers._c_conditional_profiles import condition, profile_views from trailmark.parsers.c._recovery import _CONDITIONAL, _TOKENS, _directive_text -_DEFINED = re.compile(rb"(!?)\s*defined\s*(?:\(\s*(\w+)\s*\)|(\w+))\Z") -_LIMIT = 64 - - -def _condition(text: bytes, directive: bytes) -> tuple[str, bool]: - expression = text.split(directive, 1)[1].strip() - if directive in {b"ifdef", b"ifndef", b"elifdef", b"elifndef"}: - return f"defined({expression.decode(errors='replace')})", directive in { - b"ifdef", - b"elifdef", - } - match = _DEFINED.fullmatch(expression) - if match: - name = (match[2] or match[3]).decode(errors="replace") - return f"defined({name})", not bool(match[1]) - return " ".join(expression.decode(errors="replace").split()), True - def conditional_views(source: bytes, parser: Parser) -> Iterator[tuple[Tree, str, bool]]: - """Yield at most 64 source-mapped profiles, reporting incomplete enumeration.""" + """Yield the same byte-mapped C views and the same 64-profile bound.""" directives = [] - atoms: set[str] = set() for token in _TOKENS.finditer(source): text = _directive_text(token[0]).strip() match = _CONDITIONAL.match(text) if match is None: continue kind = match[1] - condition = _condition(text, kind) if kind not in {b"else", b"endif"} else ("", True) - if condition[0] not in {"", "0", "1"}: - atoms.add(condition[0]) - directives.append((token.start(), token.end(), kind, condition)) - if not directives: - return - names = sorted(atoms) - complete = len(names) <= 6 - if complete: - assignments = itertools.product((False, True), repeat=len(names)) - else: - # Cover both extremes and individual predicates before stopping. The - # original errors and a coverage diagnostic keep the remainder unknown. - assignments = itertools.chain( - [tuple(False for _ in names), tuple(True for _ in names)], - (tuple(i == selected for i in range(len(names))) for selected in range(len(names))), - (tuple(i != selected for i in range(len(names))) for selected in range(len(names))), - ) - seen: set[bytes] = set() - for values in itertools.islice(assignments, _LIMIT): - profile = dict(zip(names, values, strict=True)) - masked = bytearray(source) - stack: list[tuple[bool, bool]] = [] - active = True - previous = 0 - valid = True - for start, end, kind, (expression, positive) in directives: - if not active: - _mask(masked, previous, start) - _mask(masked, start, end) - selected = (expression == "1" or profile.get(expression, False)) == positive - if kind in {b"if", b"ifdef", b"ifndef"}: - stack.append((active, selected)) - active = active and selected - elif not stack: - valid = False - break - elif kind == b"endif": - active, _ = stack.pop() - else: - parent, taken = stack[-1] - selected = not taken if kind == b"else" else selected and not taken - active = parent and selected - stack[-1] = (parent, taken or selected) - previous = end - if not active: - _mask(masked, previous, len(source)) - if not valid or stack: - continue - view = bytes(masked) - if view in seen: - continue - seen.add(view) - evidence = "; ".join(f"{name}={str(profile[name]).lower()}" for name in names) - yield parser.parse(view), evidence, complete - - -def _mask(source: bytearray, start: int, end: int) -> None: - for index in range(start, end): - if source[index] not in (10, 13): - source[index] = 32 + predicate = condition(text, kind) + directives.append((token.start(), token.end(), kind, predicate)) + for view in profile_views(source, directives): + yield parser.parse(view.source), view.evidence, view.complete diff --git a/src/trailmark/parsers/cpp/parser.py b/src/trailmark/parsers/cpp/parser.py index b7f8c02..37824bd 100644 --- a/src/trailmark/parsers/cpp/parser.py +++ b/src/trailmark/parsers/cpp/parser.py @@ -3,6 +3,7 @@ from __future__ import annotations import re +from collections.abc import Callable from pathlib import Path from tree_sitter import Node, Parser, Tree @@ -20,6 +21,10 @@ ) from trailmark.parsers._binding_index import binding_scope, index_tree, units_at from trailmark.parsers._bindings import guard_call, scope_syntax +from trailmark.parsers._c_conditional_recovery import ( + mark_conditional_calls, + recover_conditional_profiles, +) from trailmark.parsers._c_exports import CALLABLE_NODES, index_c_declarations from trailmark.parsers._c_headers import header_facts from trailmark.parsers._c_signature_macros import ( @@ -156,18 +161,35 @@ def __init__(self) -> None: @binding_scope def parse_file(self, file_path: str) -> CodeGraph: - """Parse a single C++ file into a CodeGraph.""" + """Parse one file, retaining bounded conditional owner alternatives.""" source = Path(file_path).read_bytes() - tree = self._parser.parse(source) - expand = _expander(self._parser, tree, file_path) + original = self._parser.parse(source) + expand = _expander(self._parser, original, file_path) + + def parse_view(tree: Tree, view: bytes) -> tuple[CodeGraph, Tree]: + return self._parse_view( + file_path, view, tree, original=original, physical=source, expand=expand + ) + + return recover_conditional_profiles(self._parser, source, original, parse_view) + + @binding_scope + def _parse_view( + self, + file_path: str, + source: bytes, + tree: Tree, + *, + original: Tree, + physical: bytes, + expand: Callable[[str, int], str | None], + ) -> tuple[CodeGraph, Tree]: graph = CodeGraph(language="cpp", root_path=file_path) index_tree(tree.root_node, _INDEXED_SYNTAX, (REFERENCE_CANDIDATES,)) - graph._parse_state.c_declarations[file_path] = index_c_declarations( # noqa: SLF001 + graph._parse_state.c_declarations[file_path] = index_c_declarations( tree.root_node, self._parser.language, "cpp", source ) - graph._parse_state.c_headers[file_path] = header_facts( # noqa: SLF001 - "cpp", source, tree.root_node - ) + graph._parse_state.c_headers[file_path] = header_facts("cpp", physical, original.root_node) module_id = module_id_from_path(file_path) recovered, markers, declaration_markers, bodies = _recover_syntax( self._parser, source, tree @@ -175,8 +197,7 @@ def parse_file(self, file_path: str) -> CodeGraph: recovered, signatures = recover_signature_macros( self._parser, source, recovered, path=file_path, language="cpp", expand=expand ) - if markers or declaration_markers or bodies or signatures: - add_module_node(tree.root_node, file_path, module_id, graph) + add_module_node(original.root_node, file_path, module_id, graph) with signature_scope(signatures): with callable_scope(graph): _visit_module(recovered.root_node, file_path, module_id, graph) @@ -189,8 +210,12 @@ def parse_file(self, file_path: str) -> CodeGraph: bind_lexical_calls(graph) bind_cast_calls(graph) collect_function_references(recovered.root_node, module_id, graph) - collect_source_evidence(recovered.root_node, file_path, graph, source=source) - return graph + collect_source_evidence(recovered.root_node, file_path, graph, source=physical) + unit = graph.nodes[module_id] + graph.nodes[module_id] = replace( + unit, location=make_location(original.root_node, file_path) + ) + return graph, recovered def parse_directory(self, dir_path: str) -> CodeGraph: """Parse all C++ files under dir_path into a merged graph.""" @@ -210,6 +235,7 @@ def _link_cpp_calls(graph: CodeGraph) -> None: bind_lexical_calls(graph) bind_cast_calls(graph) link_cross_file_calls(graph) + mark_conditional_calls(graph) def _bind_out_of_line_methods(graph: CodeGraph) -> None: diff --git a/src/trailmark/parsers/objc/parser.py b/src/trailmark/parsers/objc/parser.py index 84536f9..ecfe859 100644 --- a/src/trailmark/parsers/objc/parser.py +++ b/src/trailmark/parsers/objc/parser.py @@ -19,11 +19,11 @@ from __future__ import annotations -from collections.abc import Iterator, Sequence +from collections.abc import Callable, Iterator, Sequence from dataclasses import replace from pathlib import Path -from tree_sitter import Node, Parser +from tree_sitter import Node, Parser, Tree from tree_sitter_language_pack import get_language from trailmark.models.edges import CodeEdge, EdgeConfidence, EdgeKind @@ -38,6 +38,10 @@ ) from trailmark.parsers._binding_index import binding_scope from trailmark.parsers._bindings import guard_call +from trailmark.parsers._c_conditional_recovery import ( + mark_conditional_calls, + recover_conditional_profiles, +) from trailmark.parsers._c_signature_macros import ( _expander, recover_signature_macros, @@ -102,11 +106,30 @@ def __init__(self) -> None: @binding_scope def parse_file(self, file_path: str) -> CodeGraph: - """Parse a single .m / .mm / .h file into a CodeGraph.""" + """Parse one file, retaining bounded conditional owner alternatives.""" source = Path(file_path).read_bytes() original = self._parser.parse(source) expand = _expander(self._parser, original, file_path) - tree, nullability_regions = parse_nullability_regions(self._parser, source, original) + + def parse_view(tree: Tree, view: bytes) -> tuple[CodeGraph, Tree]: + return self._parse_view( + file_path, view, tree, original=original, physical=source, expand=expand + ) + + return recover_conditional_profiles(self._parser, source, original, parse_view) + + @binding_scope + def _parse_view( + self, + file_path: str, + source: bytes, + tree: Tree, + *, + original: Tree, + physical: bytes, + expand: Callable[[str, int], str | None], + ) -> tuple[CodeGraph, Tree]: + tree, nullability_regions = parse_nullability_regions(self._parser, source, tree) tree, enum_macros = recover_enum_macros(self._parser, source, tree) tree, trailing_markers = recover_trailing_annotations(self._parser, source, tree) tree, signatures = recover_signature_macros( @@ -114,13 +137,16 @@ def parse_file(self, file_path: str) -> CodeGraph: ) graph = CodeGraph(language="objc", root_path=file_path) module_id = module_id_from_path(file_path) - if enum_macros or trailing_markers or signatures: + preserve_original = bool( + enum_macros or trailing_markers or signatures or source != physical + ) + if preserve_original: add_module_node(original.root_node, file_path, module_id, graph) with signature_scope(signatures): with callable_scope(graph): _visit_module(tree.root_node, file_path, module_id, graph) _add_enum_macros(graph, module_id, file_path, source, enum_macros) - if enum_macros or trailing_markers or signatures: + if preserve_original: unit = graph.nodes[module_id] graph.nodes[module_id] = replace( unit, location=make_location(original.root_node, file_path) @@ -138,8 +164,8 @@ def parse_file(self, file_path: str) -> CodeGraph: ) _bind_self_messages(graph) bind_ivar_messages(graph) - collect_source_evidence(tree.root_node, file_path, graph, source=source) - return graph + collect_source_evidence(tree.root_node, file_path, graph, source=physical) + return graph, tree def parse_directory(self, dir_path: str) -> CodeGraph: """Parse all Objective-C source files under dir_path.""" @@ -148,10 +174,16 @@ def parse_directory(self, dir_path: str) -> CodeGraph: "objc", dir_path, _EXTENSIONS, - link_calls=link_calls, + link_calls=_link_objc_calls, + parser_factory=ObjCParser, ) +def _link_objc_calls(graph: CodeGraph) -> None: + link_calls(graph) + mark_conditional_calls(graph) + + def _add_enum_macros( graph: CodeGraph, module_id: str, path: str, source: bytes, macros: Sequence[EnumMacro] ) -> None: diff --git a/tests/mutation_baseline.json b/tests/mutation_baseline.json index b193c94..bed9b99 100644 --- a/tests/mutation_baseline.json +++ b/tests/mutation_baseline.json @@ -3,16 +3,23 @@ "scope": { "src/trailmark/parsers/_c_trailing_annotations.py": "*", "src/trailmark/parsers/cpp/parser.py": [ - "_recover_syntax", + "CppParser._parse_view", "CppParser.parse_file", + "CppParser.parse_file.parse_view", "_extract_function", + "_function_body", "_function_unit", - "_function_body" + "_link_cpp_calls", + "_recover_syntax" ], "src/trailmark/parsers/objc/parser.py": [ + "ObjCParser._parse_view", + "ObjCParser.parse_directory", "ObjCParser.parse_file", + "ObjCParser.parse_file.parse_view", "_add_enum_macros", - "_extract_c_function" + "_extract_c_function", + "_link_objc_calls" ], "src/trailmark/parsers/rust/parser.py": "*", "src/trailmark/tree_sitter_custom/verus/__init__.py": "*", @@ -96,7 +103,10 @@ ], "src/trailmark/parsers/_bindings.py": [ "_guard_named_call" - ] + ], + "src/trailmark/parsers/_c_conditional_profiles.py": "*", + "src/trailmark/parsers/_c_conditional_recovery.py": "*", + "src/trailmark/parsers/c/_conditional.py": "*" }, "exceptions": [ { @@ -318,6 +328,17 @@ "original": "False", "mutated": "True", "reason": "Equivalent private default under both parser call paths: visit_c_declaration always passes resolve_casts explicitly. _recover_conditional_definitions omits it but always passes recovered=True, so the cast_shadows condition (resolve_casts and not recovered and not declaration.unresolved) is false with either default. No other production caller exists. Explicit cast-resolution policy, recovered-function metadata, and ordinary typedef-cast binding remain tested and are not exempted. Re-review if a caller begins omitting resolve_casts with recovered=False." + }, + { + "fingerprint": "121f63088d29390b7972cb93683409958298d68d1db6ac98b7a9bcea21366281", + "source_hash": "76b3a22390fe6a7ab6ad20a77b4f17cc2399bfa87b5e4c56fa242781089dbd9f", + "path": "src/trailmark/parsers/_c_conditional_profiles.py", + "function": "profile_views", + "line": 94, + "operator": "boolean", + "original": "True", + "mutated": "False", + "reason": "Equivalent in this private generator: names is the atom list, and _assignments constructs every tuple with exactly len(names) values, using product(repeat=len(names)) or comprehensions over those same names. islice and view deduplication never alter tuple length. Disabling zip strictness cannot change any assignment, byte mask, evidence string, or completeness result. Other boolean mutations and malformed conditional-source handling are not exempted." } ] } diff --git a/tests/test_c_conditional_profiles.py b/tests/test_c_conditional_profiles.py new file mode 100644 index 0000000..ea44dfc --- /dev/null +++ b/tests/test_c_conditional_profiles.py @@ -0,0 +1,95 @@ +"""Profile bounds, branch priority and byte mapping are shared frontend contracts.""" + +from dataclasses import FrozenInstanceError + +import pytest + +from trailmark.parsers._c_conditional_profiles import ( + CONDITIONAL, + SourceProfile, + condition, + profile_views, +) + +pytestmark = pytest.mark.mutation_fast + + +def _views(source: bytes) -> list[SourceProfile]: + directives = [] + offset = 0 + for line in source.splitlines(keepends=True): + match = CONDITIONAL.match(line) + if match is not None: + kind = match[1] + predicate = condition(line, kind) if kind not in {b"else", b"endif"} else ("", True) + directives.append((offset, offset + len(line.rstrip(b"\r\n")), kind, predicate)) + offset += len(line) + return list(profile_views(source, directives)) + + +@pytest.mark.parametrize(("atoms", "expected", "complete"), [(6, 64, True), (7, 16, False)]) +def test_enumeration_is_exhaustive_through_six_atoms_then_reports_its_limit( + atoms: int, expected: int, complete: bool +) -> None: + source = b"".join(f"#if F{i}\nyes{i}\n#else\nno{i}\n#endif\n".encode() for i in range(atoms)) + views = _views(source) + assert len(views) == expected + assert all(view.complete is complete for view in views) + assert all(len(view.source) == len(source) for view in views) + assert all(view.source.count(b"\n") == source.count(b"\n") for view in views) + combinations = { + tuple(f"yes{i}".encode() in view.source for i in range(atoms)) for view in views + } + assert len(combinations) == expected + assert (False,) * atoms in combinations and (True,) * atoms in combinations + if complete: + assert {sum(values) for values in combinations} == set(range(atoms + 1)) + with pytest.raises(FrozenInstanceError): + views[0].complete = not complete # ty: ignore[invalid-assignment] + + +@pytest.mark.parametrize("newline", [b"\n", b"\r\n"]) +def test_elif_selects_only_the_first_matching_arm(newline: bytes) -> None: + source = newline.join( + (b"#if A", b"first", b"#elif B", b"second", b"#else", b"third", b"#endif", b"") + ) + views = _views(source) + assert { + view.evidence: tuple( + word for word in (b"first", b"second", b"third") if word in view.source + ) + for view in views + } == { + "A=false; B=false": (b"third",), + "A=false; B=true": (b"second",), + "A=true; B=false": (b"first",), + } + assert all( + bytes(byte for byte in view.source if byte in (10, 13)) + == bytes(byte for byte in source if byte in (10, 13)) + for view in views + ) + + +@pytest.mark.parametrize(("literal", "expected"), [(b"0", b"off"), (b"1", b"on")]) +def test_literal_conditions_do_not_become_profile_variables( + literal: bytes, expected: bytes +) -> None: + (view,) = _views(b"#if " + literal + b"\non\n#else\noff\n#endif\n") + assert view.source.split() == [expected] + assert view.evidence == "" and view.complete is True + + +@pytest.mark.parametrize( + "source", [b"plain\n", b"#else\nbad\n", b"#if A\nnever closed\n", b"#endif\n"] +) +def test_absent_or_unmatched_directives_produce_no_profile(source: bytes) -> None: + assert _views(source) == [] + + +def test_defined_and_not_defined_stay_correlated_across_groups() -> None: + views = _views(b"#ifdef X\nyes\n#endif\n#if !defined(X)\nno\n#endif\n") + assert {view.evidence: view.source.split() for view in views} == { + "defined(X)=false": [b"no"], + "defined(X)=true": [b"yes"], + } diff --git a/tests/test_cpp_conditional_profiles.py b/tests/test_cpp_conditional_profiles.py new file mode 100644 index 0000000..d84864e --- /dev/null +++ b/tests/test_cpp_conditional_profiles.py @@ -0,0 +1,559 @@ +"""Brace-changing alternatives retain physical calls and syntactic ownership.""" + +import json +import pickle +from pathlib import Path + +import pytest +from tree_sitter import Parser, Tree +from tree_sitter_language_pack import get_language + +from trailmark.models import EdgeConfidence, EdgeKind, NodeKind +from trailmark.parse import parse_directory, parse_file +from trailmark.parsers import _c_conditional_recovery as recovery +from trailmark.parsers._c_conditional_profiles import SourceProfile, condition +from trailmark.parsers.c._conditional import conditional_views +from trailmark.query.api import QueryEngine + +pytestmark = pytest.mark.mutation_fast +_LANGUAGES = (("cpp", "cpp"), ("objc", "m")) +_REPRO = """void a() {} +void b() {} +void Setup(int x) { +#ifdef FLAG + if (x) { + a(); +#else + if (!x) { + b(); +#endif + a(); + } + b(); +} +void After() { a(); } +""" + + +def _write(tmp_path: Path, language: str, source: str) -> Path: + path = tmp_path / ("app." + dict(_LANGUAGES)[language]) + path.write_text(source) + return path + + +@pytest.mark.parametrize(("language", "extension"), _LANGUAGES) +def test_issue_224_keeps_both_arms_and_the_independent_after_function( + tmp_path: Path, language: str, extension: str +) -> None: + path = _write(tmp_path, language, _REPRO) + graph = parse_file(str(path), language) + setup = graph.nodes["app:Setup"] + assert (setup.location.start_line, setup.location.end_line) == (3, 14) + assert {key for key, value in setup.attributes if value is True} >= { + "conditional_source", + "parse_incomplete", + "syntax_recovered", + } + calls = [ + edge for edge in graph.edges if edge.kind == EdgeKind.CALLS and edge.source_id == setup.id + ] + assert { + (edge.target_id, edge.location.start_line if edge.location else None) for edge in calls + } == {("app:a", 6), ("app:b", 9), ("app:a", 11), ("app:b", 13)} + assert len(calls) == 4 + assert all(edge.confidence == EdgeConfidence.UNCERTAIN for edge in calls) + profiles = { + edge.location.start_line: json.loads(str(dict(edge.attributes)["conditional_profiles"])) + for edge in calls + if edge.location + } + assert profiles[6] == ["defined(FLAG)=true"] + assert profiles[9] == ["defined(FLAG)=false"] + assert profiles[11] == ["defined(FLAG)=false", "defined(FLAG)=true"] + after = [ + edge + for edge in graph.edges + if edge.source_id == "app:After" and edge.kind == EdgeKind.CALLS + ] + assert len(after) == 1 and after[0].confidence == EdgeConfidence.CERTAIN + assert {item.kind for item in graph.parse_diagnostics} >= {"syntax_error", "syntax_recovery"} + assert { + site.location.start_line for site in graph.call_sites.values() if site.caller_id == setup.id + } == {6, 9, 11, 13} + assert all( + "conditional_operands_unknown" not in site.gaps + for site in graph.call_sites.values() + if site.caller_id == setup.id + ) + assert all( + "conditional_source" in site.gaps + for site in graph.call_sites.values() + if site.caller_id == setup.id + ) + assert path.suffix == "." + extension + assert pickle.loads(pickle.dumps(graph)) == graph # noqa: S301 - Local graph only. + + +@pytest.mark.parametrize("owner", ["namespace", "class"]) +def test_owner_alternatives_at_the_same_physical_function_are_distinct( + tmp_path: Path, owner: str +) -> None: + ending = ";" if owner == "class" else "" + source = ( + "void a() {}\n#ifdef FLAG\n" + owner + " n {\n#else\n" + owner + " m {\n#endif\n" + "void run() { a(); }\n}" + ending + "\nvoid After() { a(); }\n" + ) + graph = parse_file(str(_write(tmp_path, "cpp", source)), "cpp") + assert { + key + for key, unit in graph.nodes.items() + if unit.kind in {NodeKind.FUNCTION, NodeKind.METHOD} + } == {"app:a", "app:n.run", "app:m.run", "app:After"} + assert graph.nodes["app:n.run"].location == graph.nodes["app:m.run"].location + for owner_name in ("n", "m"): + ident = "app:" + owner_name + ".run" + assert dict(graph.nodes[ident].attributes)["conditional_source"] is True + assert any( + edge.source_id == "app:" + owner_name + and edge.target_id == ident + and edge.kind == EdgeKind.CONTAINS + for edge in graph.edges + ) + assert any( + edge.source_id == ident + and edge.target_id == "app:a" + and edge.confidence == EdgeConfidence.UNCERTAIN + for edge in graph.edges + ) + + +@pytest.mark.parametrize(("language", "extension"), _LANGUAGES) +def test_declarations_inside_the_alternative_arm_are_retained( + tmp_path: Path, language: str, extension: str +) -> None: + source = """void a() {} +#ifdef FLAG +void first() { if (1) { +#else +void second() { if (0) { +#endif + a(); +} } +void After() { a(); } +""" + graph = parse_file(str(_write(tmp_path, language, source)), language) + assert {"app:first", "app:second", "app:After"} <= graph.nodes.keys() + assert all( + dict(graph.nodes[key].attributes)["conditional_source"] + for key in ("app:first", "app:second") + ) + + +def test_objc_method_keeps_its_class_and_message_ownership(tmp_path: Path) -> None: + source = """void a() {} +@implementation App +- (void)run:(int)x { +#ifdef FLAG + if (x) { +#else + if (!x) { +#endif + a(); + } + [self finish]; +} +- (void)finish {} +@end +""" + graph = parse_file(str(_write(tmp_path, "objc", source)), "objc") + unit = next(unit for unit in graph.nodes.values() if unit.name == "run:") + assert unit.kind == NodeKind.METHOD + assert dict(unit.attributes)["conditional_source"] is True + assert any( + edge.target_id == unit.id and edge.source_id == "app:App" and edge.kind == EdgeKind.CONTAINS + for edge in graph.edges + ) + assert any( + edge.source_id == unit.id + and graph.nodes[edge.target_id].name == "finish" + and edge.confidence == EdgeConfidence.UNCERTAIN + for edge in graph.edges + if edge.target_id in graph.nodes + ) + + +@pytest.mark.parametrize(("language", "extension"), _LANGUAGES) +@pytest.mark.parametrize( + "source", + [ + "#ifdef FLAG\nvoid a() {}\n#else\nvoid b() {}\n#endif\n", + 'const char *s = R"tag(\n#if FLAG\n{\n#else\n{\n#endif\n)tag";\nvoid a() {}\n', + "void a() noexcept {}\n", + "void broken( ;\n#if FLAG\nvoid a() {}\n#else\nvoid b() {}\n#endif\n", + ], +) +def test_balanced_and_opaque_source_matches_the_pipeline_without_profiles( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, language: str, extension: str, source: str +) -> None: + path = _write(tmp_path, language, source) + actual = QueryEngine.from_graph(parse_file(str(path), language)).to_snapshot() + module = __import__(f"trailmark.parsers.{language}.parser", fromlist=["parser"]) + monkeypatch.setattr( + module, + "recover_conditional_profiles", + lambda parser, source, original, parse_view: parse_view(original, source)[0], + ) + expected = QueryEngine.from_graph(parse_file(str(path), language)).to_snapshot() + assert actual == expected + + +def test_c_wrapper_retains_legacy_profile_bytes_and_offsets() -> None: + source = b"#if A\na\n#else\nb\n#endif\n" + expected = (b" \n \n \nb\n \n", b" \na\n \n \n \n") + parser = Parser(get_language("c")) + views = list(conditional_views(source, parser)) + assert len(views) == 2 + for (tree, _evidence, complete), masked in zip(views, expected, strict=True): + reference = parser.parse(masked) + assert tree.root_node.text == reference.root_node.text + assert tree.root_node.start_byte == reference.root_node.start_byte + assert tree.root_node.end_byte == reference.root_node.end_byte + assert complete is True + assert [evidence for _, evidence, _ in views] == ["A=false", "A=true"] + + +def test_profile_predicates_correlate_defined_and_its_negation() -> None: + assert condition(b"#if !defined(X)", b"if") == ("defined(X)", False) + assert condition(b"#elifdef X", b"elifdef") == ("defined(X)", True) + assert condition(b"#ifndef X", b"ifndef") == ("defined(X)", False) + assert condition(b"#if X && Y", b"if") == ("X && Y", True) + + +def test_recovery_parse_counter_never_exceeds_sixty_four_profiles( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + source = _REPRO + "".join(f"#if F{i}\nvoid f{i}() {{}}\n#endif\n" for i in range(40)) + original = recovery._profile_tree + counter = [] + + def count(parser: Parser, source: bytes, profile: SourceProfile) -> Tree: + counter.append(1) + return original(parser, source, profile) + + monkeypatch.setattr(recovery, "_profile_tree", count) + graph = parse_file(str(_write(tmp_path, "cpp", source)), "cpp") + assert len(counter) == 64 + assert any( + item.kind == "unsupported_syntax" and "64" in item.message + for item in graph.parse_diagnostics + ) + assert "app:Setup" in graph.nodes + + +@pytest.mark.parametrize(("language", "extension"), _LANGUAGES) +def test_profiles_keep_original_diagnostics_in_strict_mode( + tmp_path: Path, language: str, extension: str +) -> None: + _write(tmp_path, language, _REPRO) + with pytest.raises(ValueError, match="Incomplete source analysis"): + parse_directory(str(tmp_path), language, strict=True) + + +@pytest.mark.parametrize(("language", "extension"), _LANGUAGES) +def test_conditional_source_file_counts_and_real_workers_agree( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, language: str, extension: str +) -> None: + _write(tmp_path, language, _REPRO) + (tmp_path / ("other." + extension)).write_text("void other() {}\n") + monkeypatch.setenv("TRAILMARK_JOBS", "1") + serial = parse_directory(str(tmp_path), language) + monkeypatch.setenv("TRAILMARK_JOBS", "2") + parallel = parse_directory(str(tmp_path), language) + assert serial.source_file_counts == parallel.source_file_counts == {language: 2} + assert ( + QueryEngine.from_graph(serial).to_snapshot() + == QueryEngine.from_graph(parallel).to_snapshot() + ) + + +@pytest.mark.parametrize(("language", "extension"), _LANGUAGES) +def test_directory_linking_keeps_conditional_cross_file_calls_uncertain( + tmp_path: Path, language: str, extension: str +) -> None: + _write(tmp_path, language, _REPRO.replace("void a() {}", "void a();")) + (tmp_path / ("helper." + extension)).write_text("void a() {}\n") + graph = parse_directory(str(tmp_path), language) + calls = [ + edge + for edge in graph.edges + if edge.kind == EdgeKind.CALLS and edge.source_id.endswith(":Setup") + ] + assert len(calls) == 4 + assert all(edge.confidence == EdgeConfidence.UNCERTAIN for edge in calls) + assert any(edge.target_id == f"helper\\.{extension}:a" for edge in calls) + assert all("conditional_profiles" in dict(edge.attributes) for edge in calls) + + +@pytest.mark.parametrize(("language", "extension"), _LANGUAGES) +def test_zero_net_brace_arms_with_a_negative_prefix_still_need_profiles( + tmp_path: Path, language: str, extension: str +) -> None: + source = """void a() {} +void run(int x) { if (x) { a(); +#if FLAG +} else { +#else +} else { +#endif +a(); } } +""" + graph = parse_file(str(_write(tmp_path, language, source)), language) + assert dict(graph.nodes["app:run"].attributes)["conditional_source"] is True + assert len([edge for edge in graph.edges if edge.kind == EdgeKind.CALLS]) == 2 + + +@pytest.mark.parametrize(("language", "extension"), _LANGUAGES) +@pytest.mark.parametrize("alias", [False, True]) +def test_profile_selection_does_not_admit_conditional_signature_definitions( + tmp_path: Path, language: str, extension: str, alias: bool +) -> None: + source = """void a() {} +#ifdef FLAG +#define ENTRY int main(void) +ENTRY +{ + if(1) { +#else +void other(void) { + if(0) { +#endif +a(); } } +void After() {} +""" + if alias: + source = "#define ENTRY INNER\n" + source.replace("#define ENTRY int", "#define INNER int") + graph = parse_file(str(_write(tmp_path, language, source)), language) + assert "app:main" not in graph.nodes + assert dict(graph.nodes["app:other"].attributes)["conditional_source"] is True + assert "app:After" in graph.nodes + + +def test_profiles_compose_with_trailing_annotations_and_unconditional_signatures( + tmp_path: Path, +) -> None: + source = """#define ENTRY int main(void) +void a() {} +namespace n { +void run(int x) REQUIRES(mu) { +#if FLAG +if (x) { +#else +if (!x) { +#endif +a(); } } +} +ENTRY +{ a(); } +""" + graph = parse_file(str(_write(tmp_path, "cpp", source)), "cpp") + assert "app:n.run" in graph.nodes and "app:main" in graph.nodes + assert "app:n.After" not in graph.nodes + assert dict(graph.nodes["app:n.run"].attributes)["conditional_source"] is True + assert dict(graph.nodes["app:main"].attributes)["signature_macro"] == "ENTRY" + assert "trailing_annotation" in str( + dict(graph.nodes["app"].attributes)["cpp_declaration_markers"] + ) + assert {(site.caller_id, site.location.start_line) for site in graph.call_sites.values()} == { + ("app:n.run", 10), + ("app:main", 13), + } + + +def test_balanced_groups_do_not_consume_profile_parses_for_other_errors( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def unexpected(parser: Parser, source: bytes, profile: SourceProfile) -> Tree: + pytest.fail("Balanced arms must not trigger conditional profile parsing") + + monkeypatch.setattr(recovery, "_profile_tree", unexpected) + path = _write( + tmp_path, "cpp", "void broken( ;\n#if FLAG\nvoid a() {}\n#else\nvoid b() {}\n#endif\n" + ) + graph = parse_file(str(path), "cpp") + assert graph.parse_diagnostics + + +def test_alternative_profiles_do_not_import_unaffected_balanced_arm_declarations( + tmp_path: Path, +) -> None: + source = ( + _REPRO + + """namespace untouched { +#ifdef OTHER +void first() { a(); } +#else +void second() { b(); } +#endif +} +""" + ) + graph = parse_file(str(_write(tmp_path, "cpp", source)), "cpp") + assert "app:untouched.second" in graph.nodes + assert "app:untouched.first" not in graph.nodes + assert all( + edge.source_id in graph.nodes and edge.target_id in graph.nodes for edge in graph.edges + ) + assert "conditional_source" not in dict(graph.nodes["app:untouched.second"].attributes) + assert ( + len( + [ + edge + for edge in graph.edges + if edge.source_id == "app:untouched.second" and edge.kind == EdgeKind.CALLS + ] + ) + == 1 + ) + + +@pytest.mark.parametrize("trailing_newline", [False, True]) +def test_profile_ranges_keep_their_physical_byte_and_point_receipts(trailing_newline: bool) -> None: + parser = Parser(get_language("cpp")) + source = b"void a() {}\n#if A\nvoid b() {}\n#else\nvoid c() {}\n#endif\n" + directives = [ + (12, 17, b"if", ("A", True)), + (30, 35, b"else", ("", True)), + (48, 54, b"endif", ("", True)), + ] + if not trailing_newline: + source = source.rstrip(b"\n") + # Derive directive spans from physical lines, independently of the profile lexer. + directives = [] + offset = 0 + for line in source.splitlines(keepends=True): + if line.startswith(b"#"): + kind = line.split()[0][1:] + directives.append( + (offset, offset + len(line.rstrip(b"\n")), kind, condition(line, kind)) + ) + offset += len(line) + from trailmark.parsers._c_conditional_profiles import profile_views + + for profile in profile_views(source, directives): + tree = recovery._profile_tree(parser, source, profile) + for span in tree.included_ranges: + for byte, point in ( + (span.start_byte, span.start_point), + (span.end_byte, span.end_point), + ): + assert point.row == source[:byte].count(b"\n") + assert point.column == len(source[:byte].rsplit(b"\n", 1)[-1]) + assert all(span.start_byte < span.end_byte for span in tree.included_ranges) + + +def test_alternative_operand_interpretations_stay_unknown(tmp_path: Path) -> None: + source = "void target(const char *s) {}\n" + _REPRO.replace( + " b();\n}", ' target(\n#if OTHER\n"first"\n#else\n"second"\n#endif\n );\n}' + ) + graph = parse_file(str(_write(tmp_path, "cpp", source)), "cpp") + (site,) = [ + site + for site in graph.call_sites.values() + if site.caller_id == "app:Setup" and site.syntax.startswith("target(") + ] + assert site.arguments == () + assert {"conditional_source", "conditional_operands_unknown"} <= set(site.gaps) + assert site.execution == "unknown" + + +def test_diagnostic_points_to_the_whole_module(tmp_path: Path) -> None: + graph = parse_file(str(_write(tmp_path, "cpp", _REPRO)), "cpp") + (diagnostic,) = [item for item in graph.parse_diagnostics if item.kind == "syntax_recovery"] + assert diagnostic.location == graph.nodes["app"].location + + +def test_nested_callable_inherits_conditional_context_and_alternative_calls(tmp_path: Path) -> None: + source = _REPRO.replace( + " }\n b();", + """ } + auto thunk = []() { +#if OTHER + a(); +#else + b(); +#endif + }; + thunk(); + b();""", + ) + graph = parse_file(str(_write(tmp_path, "cpp", source)), "cpp") + (unit,) = [unit for unit in graph.nodes.values() if ".$lambda@" in unit.id] + assert dict(unit.attributes)["conditional_source"] is True + calls = [ + edge for edge in graph.edges if edge.source_id == unit.id and edge.kind == EdgeKind.CALLS + ] + assert {edge.target_id for edge in calls} == {"app:a", "app:b"} + assert all(edge.confidence == EdgeConfidence.UNCERTAIN for edge in calls) + assert all("conditional_profiles" in dict(edge.attributes) for edge in calls) + + +def test_no_improving_profile_keeps_the_original_graph( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + source = _REPRO + "UNKNOWN\n{}\n" + path = _write(tmp_path, "cpp", source) + original = recovery._profile_tree + parses = [] + + def count(parser: Parser, source: bytes, profile: SourceProfile) -> Tree: + parses.append(1) + return original(parser, source, profile) + + monkeypatch.setattr(recovery, "_profile_tree", count) + actual = QueryEngine.from_graph(parse_file(str(path), "cpp")).to_snapshot() + assert len(parses) == 2 + from trailmark.parsers.cpp import parser as cpp + + monkeypatch.setattr( + cpp, + "recover_conditional_profiles", + lambda parser, source, original, parse_view: parse_view(original, source)[0], + ) + assert actual == QueryEngine.from_graph(parse_file(str(path), "cpp")).to_snapshot() + + +def test_profile_collisions_keep_descendant_owners_and_nonzero_columns(tmp_path: Path) -> None: + source = ( + _REPRO + + """#ifdef OTHER + void duplicate() { if (1) { +#else + void duplicate() { if (0) { +#endif + auto thunk = []() { a(); }; + thunk(); } } +""" + ) + graph = parse_file(str(_write(tmp_path, "cpp", source)), "cpp") + functions = [unit for unit in graph.nodes.values() if unit.name == "duplicate"] + assert len(functions) == 2 + assert {unit.location.start_col for unit in functions} == {4} + assert {unit.id for unit in functions} == {"app:duplicate", "app:duplicate@17_4"} + lambdas = [unit for unit in graph.nodes.values() if ".$lambda@" in unit.id] + assert len(lambdas) == 2 + for unit in functions: + assert any(child.id.startswith(unit.id + ".") for child in lambdas) + assert all( + edge.source_id in graph.nodes and edge.target_id in graph.nodes for edge in graph.edges + ) + assert len([site for site in graph.call_sites.values() if ".$lambda@" in site.caller_id]) == 2 + + +def test_callable_overlap_uses_half_open_byte_intervals() -> None: + source = b"\n void action() {}\n" + root = Parser(get_language("cpp")).parse(source).root_node + (function,) = root.named_children + # Tree-sitter spans and recovery exclusions share half-open byte boundaries. + assert recovery._intersects(function, ((0, function.start_byte),)) is False + assert recovery._intersects(function, ((function.end_byte, len(source)),)) is False + assert recovery._intersects(function, ((function.start_byte, function.end_byte),)) is True diff --git a/tests/test_docs.py b/tests/test_docs.py index 8c93b34..2a20679 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -1351,7 +1351,10 @@ def test_cpp_identity_and_preprocessing_contracts() -> None: "graph locations refer to the generated view", "Analyze each relevant configuration in its own graph", "report the missing graph coverage explicitly", - "C++ and Objective-C do not currently share that recovery", + "first profile with fewer grammar errors", + "different owners for the same physical function", + "at most 64 recovery profile parses", + "calls stay uncertain after directory linking", "Java record declarations are currently skipped", "Swift class inheritance and protocol-conformance edges are not extracted", ): From f23afaeabb8d952204bbc71e20a9a02ffc167312 Mon Sep 17 00:00:00 2001 From: Scott Arciszewski <147527775+tob-scott-a@users.noreply.github.com> Date: Wed, 2 Dec 2026 06:02:13 -0500 Subject: [PATCH 2/2] Prepare concise v0.10.0 release notes and version metadata --- CHANGELOG.md | 60 +++++++++++++++++++++--------------- README.md | 4 +-- docs/constraints.md | 8 ++--- docs/graph-model.md | 2 +- docs/python-api.md | 7 +++-- docs/skills-compatibility.md | 4 +-- pyproject.toml | 2 +- src/trailmark/__init__.py | 2 +- tests/test_docs.py | 4 ++- uv.lock | 2 +- 10 files changed, 54 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e273dcb..248b40d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,33 +1,43 @@ # Changelog -## Unreleased - -- Show analysis progress on terminals and provide `--no-progress` to disable it (#233). -- Add opt-in parallel C++ parsing through `TRAILMARK_JOBS`, retaining serial graph output. - -- Resolve C++ same-class calls despite forward declarations and through anonymous - namespace owners in the same file. Prefer type definitions to later forward - declarations through shared insertion, including C and C++ enums. -- Extract C++ struct inheritance. Stabilize C-family directory module IDs by always - including escaped filename extensions, and use `.` in qualified declaration IDs. - Rebuild C-family graphs and refresh IDs in configs, queries, and annotations after upgrading. -- Document C-family preprocessing limitations and an agent workflow for trailing - annotation macros, macro-defined signatures, and conditional branches that split braces. -- Retain source-bound call-site operands across applicable frontends and add - typed constraint annotations, conditional parameter summaries, and an agent - workflow. Source gaps and unverified assumptions remain explicit. -- Advance full analysis snapshots to format 2 for constraint evidence and - parameter binding modes; rebuild format-1 snapshots. -- Keep Boolean-false incoming constraints unknown with an explicit gap, and - reject predicates whose literal sorts cannot describe a sequence slice. -- Give call sites portable identities based on named roots and relative files. - Reuse graph fingerprints for constraint operations while detecting context edits. +## 0.10.0 (2026-12-02) + +### Added + +- Manage portable claims with `trailmark constraints`. Inspect per-call gaps, + summarize wrappers, and check explicit preconditions. See [constraint annotations](docs/constraints.md). +- Save full snapshots with `analyze --snapshot`, then diff snapshots, source trees, + or revisions. Add `--preanalysis` to include derived evidence. +- Use conservative constraint binding for C, Go, Rust, Java, Solidity, + JavaScript, TypeScript, and supported PHP methods. +- See analysis progress in the terminal; use `--no-progress` to silence it. + +### Changed + +- Reuse claims after unrelated source edits; changed calls and signatures still + require review. + +### Fixed + +- Recover C-family functions hidden by annotation macros, object-like signatures, + and split conditional braces. Recovered calls retain uncertainty and diagnostics. +- Correct C++ call ownership through forward declarations and anonymous namespaces, + and retain struct inheritance. ### Performance -- Reuse C++ parse trees and syntax queries, streamline native scope and declaration - indexes, and reduce Python analysis overhead (#231, #232, #234, #235). - Graph output is unchanged. +- Reduce parsing work without changing graph output (#231, #232, #234, #235, #237). + Set `TRAILMARK_JOBS` to enable parallel C++ parsing. + +### Upgrade notes + +- Rebuild C-family graphs and refresh IDs in configs, queries, and annotations: + directory module IDs now include filename extensions. +- Rebuild older full snapshots with 0.10.0. Snapshot format 2 requires an exact + Trailmark version match. +- Update strict diff-JSON validators to accept the new evidence sections. +- Imported claim sidecars retain asserted evidence. Review their assumptions, + stale records, and orphan candidates before using summaries. ## 0.9.1 (2026-11-24) diff --git a/README.md b/README.md index 3a13c21..20b1b35 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ uses this foundation to triage mutation testing results and prioritize fuzzing. coarse taint) that store their results as annotations and named subgraphs. - **Visible gaps.** Calls that cannot be resolved become proxy nodes instead of disappearing, and `trailmark analyze --resolution` counts them. -- **Constraint annotations (unreleased).** Retain source-located call arguments, +- **Constraint annotations (v0.10.0).** Retain source-located call arguments, save typed input claims, and query conditional callee summaries with explicit assumptions. Preserve claims across unrelated file edits and inspect specific stale reasons for changed source, bindings or signatures. Summaries retain @@ -107,7 +107,7 @@ Most grammars are downloaded and cached on first use. Bundled grammars are compiled on first use, which needs a C compiler. See [Installation](https://github.com/trailofbits/trailmark/blob/main/docs/installation.md) for offline machines, TLS-inspecting proxies, and building from a checkout. -Skills integrators: see [v0.7 compatibility](https://github.com/trailofbits/trailmark/blob/main/docs/skills-compatibility.md) +Skills integrators: see [skills compatibility](https://github.com/trailofbits/trailmark/blob/main/docs/skills-compatibility.md) for schema, identity, state, and reachability checks. ## Quick start diff --git a/docs/constraints.md b/docs/constraints.md index 6bfada8..00dc37f 100644 --- a/docs/constraints.md +++ b/docs/constraints.md @@ -3,7 +3,7 @@ Constraint annotations let an agent save a claim about an argument at one source call site. They preserve the argument expression, source fingerprints, evidence, assumptions, and the producer's justification. They do not infer constraints or -prove that a claim follows from the source. This API is unreleased. +prove that a claim follows from the source. This API was added in v0.10.0. Use `call_sites(name)` to inspect operands and current target bindings, `annotate_constraint(...)` to save a claim, `constraints_of(name)` to check its @@ -400,13 +400,13 @@ digests for call syntax, receiver, operands, execution and gaps; target bindings confidence and deferred status; and caller plus target kinds, parameters and binding profiles. The digests use canonical JSON without absolute paths. Unrelated file edits and other graph metadata changes preserve claims whose local evidence is unchanged. -The unreleased signature receipt now includes the caller; regenerate receipts -produced by earlier development versions before reusing them. +Signature receipts include the caller; regenerate receipts produced by +earlier development versions before reusing them in v0.10.0. Freshness compares saved source receipts. Use `QueryEngine.from_snapshot(snapshot, verify_sources=True)` when claims must match current source files. Historical snapshots remain usable without those files. -Summaries use current local evidence without hashing the entire graph. The unreleased +Summaries use current local evidence without hashing the entire graph. The v0.10.0 summary format no longer includes `graph_fingerprint`; persisted claims carry their own dependency digests. After directly editing nodes or edges, call `GraphStore.rebuild_index()` to refresh topology and call-site binding indexes. diff --git a/docs/graph-model.md b/docs/graph-model.md index 9c39070..bca59b3 100644 --- a/docs/graph-model.md +++ b/docs/graph-model.md @@ -399,7 +399,7 @@ than rebinding raw type names globally. Syntax diagnostics coalesce nested error and report at most 256 individual errors per file plus a summary. Declaration nesting beyond 128 levels produces a coverage diagnostic. -## Constraint evidence (unreleased) +## Constraint evidence (v0.10.0) `CodeGraph.call_sites` holds immutable `CallSite` records with source spans, SHA-256 fingerprints, raw operands, receivers, and execution gaps. Their IDs diff --git a/docs/python-api.md b/docs/python-api.md index e9dec54..527f45a 100644 --- a/docs/python-api.md +++ b/docs/python-api.md @@ -275,7 +275,7 @@ Annotation kinds are `assumption`, `precondition`, `postcondition`, `finding`, `audit_note`, and the structured `constraint` kind. The import and preanalysis methods are described in [Findings and preanalysis](augmenting.md). -### Constraint evidence (unreleased) +### Constraint evidence (v0.10.0) `call_sites(name)` returns source occurrences, operand expressions and labels, current target bindings, and explicit gaps. `annotate_constraint(...)` saves a @@ -294,7 +294,7 @@ parameter. Each upstream wrapper requires `complete_callers:NODE_ID`; `sites[*].forwarded` contains flat `ForwardedSummary` receipts. The shared `max_depth` range is 0 through 32, with explicit depth, cycle and predicate-size gaps. Caller declaration changes invalidate dependent forwarding claims. -The unreleased summary shape omits the former `graph_fingerprint` field; claims +The v0.10.0 summary shape omits the former `graph_fingerprint` field; claims retain their own local dependency digests. The obsolete `GraphStore.graph_fingerprint()` helper is removed; use claim dependencies to assess freshness. @@ -465,7 +465,7 @@ graph. Native call edges retain call-site addresses in edge attributes. ## Reloadable analysis snapshots -The unreleased constraint API uses snapshot format 2. It adds source call sites, +The v0.10.0 constraint API uses snapshot format 2. It adds source call sites, parameter binding modes, and typed constraint payloads. Format-1 snapshots must be rebuilt; see [constraint persistence](constraints.md#identity-and-persistence). @@ -533,6 +533,7 @@ with older releases can check `trailmark.__version__` or probe with `hasattr()`. | 0.8.0 | `augment_binary_file`, `binary_artifacts`, `binary_ranges`, `source_at_address`, `disassemble_binary`; `BinaryImportOptions`, `BinaryLimits`, and `BinarySelection` | | 0.9.0 | `edge_kinds` on `reachable_from`, `ancestors_of`, and `paths_between` | | 0.9.1 | Reloadable `to_snapshot()` and `from_snapshot()` on `CodeGraph`, `GraphStore`, and `QueryEngine` | +| 0.10.0 | Source call sites, constraint annotations and summaries, entailment, preconditions, wrapper forwarding, caller inventories, and portable claim import/export; evidence-aware diffs and snapshot format 2 | ## Source analysis diagnostics diff --git a/docs/skills-compatibility.md b/docs/skills-compatibility.md index cde1f9d..63a13ee 100644 --- a/docs/skills-compatibility.md +++ b/docs/skills-compatibility.md @@ -1,4 +1,4 @@ -# v0.7 integration and skills compatibility +# Agent integration and skills compatibility Check the installed Trailmark version (`trailmark --version` or `trailmark.__version__`) separately from the skills/plugin package version. @@ -70,7 +70,7 @@ Selected dependency roots and effective exclusions are exposed by the owner as a caller and `summary()["call_edges"]` counts deferred edges. Consumers needing to exclude them must inspect raw graph edges before traversal. -## Constraint annotations (unreleased) +## Constraint annotations (v0.10.0) Feature-detect all five methods before enabling this workflow: `call_sites()`, `annotate_constraint()`, `constraints_of()`, `constraint_summary()`, and diff --git a/pyproject.toml b/pyproject.toml index 510a759..20cc7ab 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,7 +23,7 @@ reinstall-package = ["trailmark"] [project] name = "trailmark" -version = "0.9.1" +version = "0.10.0" description = "Parse source code into a queryable graph of functions, classes, calls, and semantic annotations" readme = "README.md" requires-python = ">=3.12" diff --git a/src/trailmark/__init__.py b/src/trailmark/__init__.py index c2ddebd..cc9152b 100644 --- a/src/trailmark/__init__.py +++ b/src/trailmark/__init__.py @@ -18,4 +18,4 @@ "SourceRoot", "supported_languages", ] -__version__ = "0.9.1" +__version__ = "0.10.0" diff --git a/tests/test_docs.py b/tests/test_docs.py index 2a20679..46890e2 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -416,7 +416,9 @@ def pyproject_data() -> dict[str, object]: ("CONTRIBUTING.md", "weekly on Monday at 06:00 UTC"), ("CONTRIBUTING.md", "Pull requests run one mutation campaign, using the fast pool"), # CLI output streams - ("README.md", "Constraint annotations (unreleased)"), + ("README.md", "Constraint annotations (v0.10.0)"), + ("docs/python-api.md", "| 0.10.0 | Source call sites"), + ("docs/skills-compatibility.md", "## Constraint annotations (v0.10.0)"), ("docs/constraints.md", "ConstraintClaim.grammar_version"), ("docs/constraints.md", "Candidates are never activated automatically"), ("docs/constraints.md", "Imported claims are always `asserted`"), diff --git a/uv.lock b/uv.lock index 0e3f513..def3553 100644 --- a/uv.lock +++ b/uv.lock @@ -467,7 +467,7 @@ wheels = [ [[package]] name = "trailmark" -version = "0.9.1" +version = "0.10.0" source = { editable = "." } dependencies = [ { name = "rustworkx" },