Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 35 additions & 25 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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)

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions docs/constraints.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/graph-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 26 additions & 8 deletions docs/parser-coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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:

Expand Down
7 changes: 4 additions & 3 deletions docs/python-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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).

Expand Down Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions docs/skills-compatibility.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion src/trailmark/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@
"SourceRoot",
"supported_languages",
]
__version__ = "0.9.1"
__version__ = "0.10.0"
108 changes: 108 additions & 0 deletions src/trailmark/parsers/_c_conditional_profiles.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading