Language and rule architecture
The architecture uses a common tree-sitter context, independently registered languages and rules, typed grammar capabilities, and application-owned required coverage. This document records the current architecture and its compatibility behavior.
Ownership and interfaces
Section titled “Ownership and interfaces”| Boundary | Owner and contract |
|---|---|
| Language identity | LanguageDefinition declares an open identity and suffixes; required rules belong to an application profile |
| Parsing | ContextParser produces TreeContext backed by a concrete tree-sitter Tree; .root exposes its root Node |
| Grammar interpretation | Language adapters implement the consuming domain’s narrow syntax protocols |
| Rule behavior | RuleBundle consumes TreeContext and declares identity, API version, diagnostic IDs and RuleRequirements |
| Checker configuration | Owner-local typed fragments declare schemas and identities; policy.models.Checkers explicitly composes them |
| Application policy | AnalysisProfile specifies required diagnostic coverage and explicitly unavailable optional analysis |
| Composition | plugins/builtins.py connects language adapters, shared rules and language-specific checks |
| Execution | TypedAnalyzer validates its composition, uses the session’s parse and runs enabled bundles |
| Session lifetime | AnalysisSession owns exact snapshot parsing, reusable semantic evidence and session-scoped adapter instances created by for_session() within one execution |
| Registration | Language discovery and rule ownership are registered separately; AnalyzerRegistry validates composed analyzers |
Checker configuration and its compatibility contract are described in Checker-owned registration.
Required capabilities are explicit. A rule that consumes semantic evidence
requires it through RuleRequirements; metrics and architecture rules receive
their grammar contracts through typed construction. Registration and execution
validate availability without inspecting rule identities or concrete rule classes.
Validation runs before enable flags can skip analysis, and rules added after
analyzer construction cannot bypass capability checks.
All language-specific node interpretation stays with language adapters or specific language rules. Shared algorithms retain concrete domain contracts and tree nodes; there are no generic payload dictionaries, casts or secondary Python ASTs. Python annotations and forward annotation expressions are handled with its registered tree-sitter grammar. Parser warnings disclose recovery limitations; infrastructure and required capability failures remain analysis errors.
Package placement follows behavior ownership. Shared rules sit with the policy
that executes them: metrics in metrics/, dependency checks in architecture/,
and usage and boundary checks in semantics/. Language-specific rules live beside
the grammar they interpret, and there is no root-level catch-all rule package.
Language plugins do not assemble analyzers or select shared rule sets, and shared
analysis and rules do not import concrete language plugins. Application
composition imports concrete languages and rules, binds them through typed
construction and dispatches on no language identity; the CLI and snapshot
infrastructure stay outside domain analysis. Snapshot identity includes content
and grammar, so staged and working-tree sources never share stale evidence.
Conflicting contents for one semantic module within one execution are rejected
explicitly, sessions reject a different policy, and a selected source snapshot
takes precedence over a reference with the same language and path.
Java is registered through the same composition. Its grammar interpretation
and type policy live in languages/java/; shared engines never import that
package. BindingSyntax.inherited_types returns tuple[Node, ...] so a language
can expose multiple independent inheritance clauses. Custom semantic adapters
must return an empty tuple when there are no bases. Java’s checked scope and
resolution limits follow the shared per-checker coverage in
checker configuration.
Rust follows the same composition under languages/rust/. Its semantic adapter
analyzes each .rs file independently (package() returns the file path,
module_names uses the extension-stripped file path, import_target() links
only keyword-rooted imports to file-level declarations in the same file rather
than linking non-keyword external crate imports to a sibling local .rs file,
and interop_group() returns "rust", isolating Rust from other languages’
unresolved member reads, module names, same-package lookups and
parameter-property auxiliary indexing). Within a single file, it attaches only
directly declared inherent methods to an impl type, resolves self receivers
and associated functions (including Self::new()) against that impl type, and
replaces Self only when an annotation spells bare Self or a reference form
such as &Self, &mut Self or &'a Self (wrapped forms such as Wrap<Self>
and Option<&Self> keep their outer type as written). It
binds pattern introducers (let, for, while, loop, if let, match
arms, closures) as lexical declarations through the shared sequential_scope,
scope_exterior and hoisted hooks: same-scope let, if let, while let,
let-else, let chains with binding leaves, and match arms whose guard
contains a let condition open sequential scope regions visible only to
subsequent siblings and guarded branches (with captured_pattern bindings such
as let y @ Some(x) = d else { return; }; entering the same region and plain
let initializers staying in the enclosing scope); scope_exterior places
for iterables, the first let value of an if let/while let chain, if
else branches and item name nodes (fn, struct, enum, trait, union,
mod) in the enclosing scope before the node’s own bindings so crate::h and
aliases resolve to the function symbol rather than a same-named parameter; and
hoisted keeps inner items visible across the block (see
unused.parameter).
It treats const_item/static_item in any scope as non-fields, and counts
fields of #[derive] items (including single-level
#[cfg_attr(..., derive(...))]), fields whose declared type’s final path segment
is PhantomData, and non-wildcard struct pattern bindings as read.
Single-file name resolution resolves only keyword-rooted paths (crate::,
self::, super::) whose intermediate segments descend through inline mod
declarations in the same file, plus use aliases rooted at those paths.
Unconfirmed keyword-rooted paths fall back to ModuleUses.unresolved (keeping
same-named declarations reachable), and unconfirmed type annotations withhold
type evidence (None) so member reads stay unresolved rather than mis-binding
to a same-named local type. In lexical lookup (_visible_binding), value
bindings and use aliases compete innermost scope first up to the innermost
mod boundary, with visible let bindings outranking hoisted items and use
aliases, while type-only items (struct with braces, type, enum, trait,
union, mod), extern crate, type-only use aliases and impl/trait
associated fn declarations stay out of value resolution (binds_value=False).
Conditional compilation (#[cfg]) is not evaluated and macro bodies remain
untyped token trees; exact resolution boundaries and conservative fallbacks are
recorded in
Rust name-resolution known limits.
Session-scoped adapter instances are created through for_session().
AnalysisSession caches one session-scoped instance per composed adapter
instance by object identity (holding the composed instance so dataclass-derived
adapters work without custom equality handling), calling for_session() once
per composed adapter per session. RustSemanticSyntax.for_session() returns a
fresh instance per AnalysisSession whose ModuleUses, ImportEvidence,
renamed/aliased type-name (_renamed) and expanded use/declaration
(_expanded) caches are plain dictionaries keyed by snapshot root
(context.root.id) and released with the session, while the composition-time
instance holds no per-snapshot evidence. Semantic alias target lookup reuses
ImportEvidence.aliases, and lexical binding competition
(bindings._visible_binding) receives the session’s ImportEvidence.values
instead of re-expanding use declarations directly. _expand_use is held only
by languages/rust/imports.py (snapshot-cached declaration expansion),
languages/rust/consumed_fields.py (RustConsumedFields) and
languages/rust/syntax.py (RustImports), expanded once per snapshot per
holder; languages/rust/modules.py and languages/rust/semantic_syntax.py do
not hold or call _expand_use. exported keeps pub/pub(crate)/pub(super)
items, attributed items, trait and trait-impl methods, root fn main outside
lib.rs, and ModuleUses reachability, while implicit_use() exempts
_-prefixed names, matching rustc’s dead-code conventions. Rust registers no
failure-flow rule because it has no exception handlers.
Shared semantic analysis exposes eight narrow adapter hooks with safe defaults
on SemanticNodes so existing languages retain unchanged behavior:
BindingSyntax.sequential_scope(node) defaults to False (when True, a
declaration, let condition/chain with binding leaves, or match_pattern
whose guard contains a let condition opens a new scope region so its targets
become visible only to subsequent siblings and guarded branches);
BindingSyntax.scope_exterior(node) defaults to () (subtrees inside a
scope-owning node placed in the enclosing scope before the node’s own bindings,
including in Rust for iterables, the first let value of an
if let/while let chain, if else branches and item name nodes);
BindingSyntax.hoisted(node) defaults to False (items declared in the
enclosing block scope across sequential regions);
BindingSyntax.binds_value(node) defaults to True (a declared name is
visible to bare value references; Rust returns False for associated functions
inside impl/trait bodies, for extern crate declarations—with or without
an alias—and for use imports whose in-file target is type-only, so
SemanticIndex.lookup(name, scope, value=True) skips them for value references
while type references and path roots via in_annotation still resolve, with
tests/test_value_binding_names.py guarding unchanged behavior across the six
other built-in analyzers);
SemanticSyntax.configured_import(entry, context) defaults to exact module
matching (entry.module in context.policy.third_party_modules), letting Rust
keep keyword roots (crate, self, super, including whole-root aliases)
internal while extending a configured external crate root to its imported
sub-items;
SemanticSyntax.for_session() defaults to returning self for stateless
adapters while letting stateful adapters keep per-snapshot caches inside the
active AnalysisSession, cached by composed adapter instance identity;
SemanticSyntax.interop_group() defaults to "" (sharing the legacy
cross-snapshot namespace so Python, Go, Java, JavaScript, TypeScript and TSX
retain unchanged behavior, keeping JS, TS and TSX interoperable across relative
imports and member reads in one group), while Rust returns "rust" so
ProjectUsage.modules (keyed by (group, name)), same-package peer lookups,
UsageEvidence.unresolved (evidence.uncertain(group)) and parameter-property
auxiliary indexing (constructed per interop_group() only for groups that
have a parameter_property_syntax() provider, namely the default "" group
when a TypeScript/TSX snapshot is present, while skipping "rust") never cross between
Rust and any other language (tests/test_interop_groups.py guards this
isolation); and BindingSyntax.result_type(node, declared) separates a
function’s declared result from its type evidence.
BindingSyntax.result_type(node, declared) defaults to returning declared
itself. A function’s Symbol.annotation/annotation_text keep the result it
declares, which the result contracts (has_result, call_result,
concrete_result, the typed-converter reading in boundary evidence, and
unused.return) read as proof that a call yields a value;
Symbol.result_type is the evidence the index derives the function’s
type_name and class_scope from, and Symbol.type_evidence() returns it for
a function and annotation for every other declaration. The index calls the
hook only when a result is declared, so an undeclared result never has type
evidence. Rust does not follow type alias chains: it returns None when the
declared result’s outer type (looking through &/&mut and generic wrappers)
is a qualified path that cannot be confirmed to a directly declared type
(struct, enum, union or trait) through this file’s inline mod
declarations (a terminal supplied only through a pub use / glob re-export, or
matched only by a same-named fn, const, static or mod, gives no type
evidence and stays unconfirmed), confirms to a type alias, or uses a bare
name declared as a type alias or use … as rename in the same file (Self
is substituted only for bare Self and reference forms such as &Self,
&mut Self and &'a Self, leaving wrapped forms such as Wrap<Self> and
Option<&Self> as written).
Member reads on such a result stay unresolved instead of binding to a same-named
in-file type, while discarded-result warnings and typed-converter classification
remain unchanged; tests/test_result_type_evidence.py guards unchanged behavior
across the six other built-in analyzers.
Rust name-resolution known limits
Section titled “Rust name-resolution known limits”Twelve known Rust name-resolution, macro and changed-scope limits apply (user-visible entries are also summarized in the skill checker index and on affected checker pages):
- Single-file analysis and keyword-rooted paths. Each
.rsfile is analyzed independently: out-of-line modules (mod child;,#[path = "..."] mod name;), cross-filecrate::…paths,pub usere-exports, glob imports (use m::*;),extern crate self as name;and leading::absolute paths are not followed across files, and non-keyword external crate imports never link to sibling local.rsfiles. Only keyword-rooted paths (crate::,self::,super::) descending through inlinemoddeclarations in the same file resolve to their target declaration; unconfirmed keyword-rooted paths place their final segment inModuleUses.unresolved(keeping same-named declarations reachable). Leading::-prefixed paths do not receive that exemption (false-positive limit for::api::work()underextern crate self as api;). Bare calls imported via a glob resolve lexically innermost-scope-first rather than enteringModuleUses.unresolved: if an enclosing module declares a same-named private function nearer than the glob’s source, the call binds to the nearer item (false positive on the glob source, false negative on the nearer item; an explicituseresolves accurately, and unused siblings across multiple modules declaringpub fn hiddenare not reported). - Files declaring an out-of-line module. Whenever a file contains
mod child;, private functions and methods declared at file root or inside inlinemod/impl/traitbodies, as well as allstructandunionfields (includingpub), are not reported. Nested functions and named closures inside function bodies remain candidates. - Conditional compilation is not evaluated. Every
#[cfg(…)]and#[cfg_attr(…)]item (including#[cfg(any())],#[cfg(test)]and feature predicates) is treated as enabled, and nested#[cfg_attr(..., cfg_attr(...))]attributes are not expanded recursively. Whencfg-gated same-named items coexist in one container, keyword-rooted paths bind to the first declaration in source order (which can shiftunused.functionorunused.returnfindings). - Type aliases and unconfirmed type paths are not followed. Parameter or
return annotations written with a local
typealias, ause … asrename, or a qualified path not confirmed to a directly declared type (struct,enum,union,trait) through this file’s inlinemoddeclarations (including re-exported terminals or terminals matched only by a same-namedfn/const/static/mod) provide no type evidence (None): member reads stay unresolved by member name rather than mis-binding (and qualified or renamedserde_json::Valuecallback parameters do not reporttype.boundary, whiletype.broadstill reports them).Selfresolves to theimpltype only for bareSelfand reference forms (&Self,&mut Self,&'a Self,&&Self), leaving wrapped forms such asOption<&Self>as written. - Member reads with unknown receiver type. When a receiver’s type cannot be
determined (generics, trait objects, pattern bindings, or
.name/::nametokens inside macro arguments), the member name is treated as read across Rust files only and never affects files in other languages. - Same-scope value and type collisions. Within one scope, a function shares
a single symbol slot with a same-named
mod, type,extern crateor type-onlyuse(later overwrites earlier); raw identifiersr#pandpare distinct names; and block-local type items (struct,enum,trait,union,mod) plus associatedconstitems still participate in bare-name lookup. - Macros. Macro bodies are not expanded.
macro_rules!definition bodies are skipped completely by read collection (so fields or functions referenced only inside a definition body can still be reported), whereas.nameand::nametokens inside macro invocation arguments contribute unresolved member reads under limit 5. For any macro invocation, inline{name}captures and named format width/precision parameters ({v:width$},{v:.decimals$}, skipping}fill before alignment) count as reads of the visible value binding without subtracting explicitname = …arguments (under-reporting an unusedpinprintln!("{p}", p = 7)); on the serialization side, named width/precision parameters are not captures and}-fill skipping is not enabled. Format and print macros (println!,print!,eprintln!,eprint!,format!,format_args!) are matched solely by final path segment without modelingmacro_rules!shadowing (theirname = …labels are not counted as reads). Macro names—bare or qualified at any depth—stay in the macro namespace at every path segment and never count as value reads, unresolved member reads, call targets orModuleUses.unresolved, while reads inside macro arguments stay unaffected. - Assertion macro recognition.
assert!,assert_eq!,assert_ne!,debug_assert!,debug_assert_eq!anddebug_assert_ne!are recognized by final path segment (std::andcore::prefixes match as well); locally redefined macros with those names are not distinguished. unused.returnscope. Discarded-result warnings inspect only the written return annotation (or proven value body) without modelingasync,#[must_use]or type-alias targets: discarding an unannotatedasync fnFutureor unannotated#[must_use]result is not reported, whereas a unit return written through a type alias (type U = (); fn f() -> U) still warns.- Callable spellings and alias depth. Parenthesized
transmutecalls ((std::mem::transmute)(x)) are not matched bytype.assertion(which requires a direct identifier or path callee), whereas path spelling unwraps parentheses for serialization checks. Separately, value alias chains exceeding the 64-step path-spelling budget (counting each syntax unwrap and alias hop) yield no resolved path spelling, so path-basedtype.broadandtype.assertionfindings stop reporting once the budget is exhausted. - Extreme syntax nesting. Deeply nested expressions or blocks (roughly 300+ levels) exceed the interpreter recursion limit and fail the run with exit code 2. This limit is shared across all seven built-in analyzers.
- Changed-mode diagnostic scope (
--base/--staged). Every direct item declared inside animpl,traitor inlinemodbody (excluding comments and outer attributes—including methods, functions, associatedconst/type,static, multi-lineuseandstructdeclarations) is an independent incremental unit; editing a block header (through its opening{line and trailing comment) selects the whole block; editing only an outer attribute line (such as#[test]or#[repr(C)]) or standalone doc-comment line above an item does not select the item (use--allor edit the item itself); top-level items outside those blocks follow the shared root-statement and header rules.
Offline verification and corpus boundaries: Pluvy runs offline on tree-sitter
grammars without invoking rustc, cargo or external crate registries; real
third-party crate corpora are analyzed offline against static source snapshots,
and fixtures referencing external crates or unstable syntax cannot be compiled
standalone.
Shared alias and output analysis
Section titled “Shared alias and output analysis”semantics/aliases.py owns stable callable/module alias resolution and constructor
provenance. NameSyntax supplies transparent grammar expressions, imported-name
identity and recognized built-ins. Resolution uses the canonical semantic index;
cycles, shadowing and multiple assignments do not become guessed destinations.
semantics/flow.py owns single-assignment carrier and container forwarding. Its
Destinations protocol classifies a use as permitted, rejected or requiring further
traversal. Both third-party boundary evidence and serialization checks use this
same algorithm. An internal use cannot be hidden by another permitted output use.
semantics/failure.py owns the separate builtin.failure policy bundle, which
reports swallowed wide captures and coalescing chains that hide failures behind
literal defaults. It shares no traversal or evidence with semantics/flow.py,
whose carrier forwarding serves encoding output proof.
EncodingRule consumes EncodingSyntax, which defines member_encoder for
receiver-agnostic member recognition and also identifies qualified encoders,
decoders, argument consumers and actual output APIs. GrammarEncoding provides
the default member_encoder implementation backed by its member_encoders set.
A structural EncodingSyntax implementation that does not inherit
GrammarEncoding must define member_encoder itself; registration does not
validate protocol members, and a missing definition fails closed during analysis
with an AnalysisError such as
Rule bundle … failed: '…' object has no attribute 'member_encoder'. The
argument capability on EncodingSyntax returns the canonical ParameterSlot
for a payload;
this lets shared semantics enforce configured positional/keyword output
selectors without reading grammar fields.
BroadTypeOptions.encoding owns validated additive encoder, decoder and output
API declarations, including the restricted *.member encoder form. Explicit
decoder evidence wins over configured output matches. A decoder rejection takes precedence
over a configured library-input exemption. Grammar/API interpretation lives in
languages/; shared semantic code imports no concrete language or grammar and
contains no language-name dispatch.
Application composition supplies Python, Go, Java, Rust and JavaScript adapters. Their
type-rule objects receive an EncodingRule through their constructor
and retain ownership of their combined type.broad diagnostics; JavaScript
registers that rule directly. This keeps diagnostic ownership unique. Custom
construction of PythonTypeRule, GoTypeRule, JavaTypeRule, RustTypeRule or
TypeScriptTypeRule must supply the encoding rule explicitly. They reuse the
session’s existing context and boundary index.
Current serializer adapters cover Python json.dumps plus pydantic
dump_json/model_dump_json member names, JavaScript/TypeScript/TSX
JSON.stringify, imported Go JSON Marshal/MarshalIndent, selected imported
Gson/Jackson Java serializers and Rust serde_json to_string/to_string_pretty/
to_vec/to_value paths (spelled through use aliases or directly). Exact scoped
instance outputs are available in Python, Go, Java, JavaScript, TypeScript and TSX;
Rust does not recognize instance outputs. Java interprets invocation nodes and functional-interface fields; Go supplies
the proven first payload binding of a byte/error result; Rust spells qualified
paths through RustPathNames and recognizes println!/print!/eprintln!/
eprint! arguments, receiver-proven std::io::stdout()/stderr() and
Result-unwrapped std::fs::File::create(...) write_all/write calls, and
std::fs::write payloads as terminal outputs without treating arbitrary Write
calls, memory buffers, containers or derived values as outputs. Shared flow
checks that binding’s every read and leaves sibling error results independent.
Exact supported signatures and conservative limits are documented in
Serialization boundaries.
Shared guarded projection analysis
Section titled “Shared guarded projection analysis”GuardedProjectionRule consumes the language-owned ProjectionSyntax capability
and existing session semantic index. semantics/projection/ owns checker options,
binding identity, candidate evidence and consecutive-region clustering.
languages/projection_syntax.py shares the grammar operations, and each language
supplies its predicate and construction interpretation through ProjectionSyntax.
Language code cannot import the projection rule implementation; shared matching
imports no language implementation and selects no language identity. Built-in
composition requires this diagnostic for Python, Go, Java, JS, TS, TSX and Rust, and a
new language must supply equivalent adapters and behavioral tests before claiming
coverage. Exact syntax coverage and conservative limits are documented in
the guarded projection checker reference.
Changed-scope capability
Section titled “Changed-scope capability”Source.changed_lines is None for a full audit and a concrete frozen set for
changed snapshots, including deletion anchors. Built-in analyzers receive a ScopeSyntax adapter through TypedAnalyzer.scopes
(Rust registers RustScopes in languages/rust/change_scopes.py, overriding
definition and header_end for direct items inside impl/trait/inline mod
bodies; see
Rust name-resolution known limits
limit 12). The shared AffectedScopes
consumer expands edits using grammar-owned definition extents and class headers,
then filters emitted diagnostics. It never truncates the parsed snapshot or
semantic evidence. Rules declare file-level obligations with Finding.scope="file";
the default is "line". Ownership and placement use file scope, without rule-ID
dispatch in the shared filter.
Custom TypedAnalyzer compositions must supply this capability for changed-scope
runs; missing capability fails visibly instead of silently claiming scoped checks.
Full-source library calls remain compatible with the default Source constructor.
Run-level deletion gate
Section titled “Run-level deletion gate”TestDeletionGate in semantics/testing/gate.py is a run-level execution shape,
not a RuleBundle. It consumes the baseline evidence ports supplied by the CLI
and the narrow BaselineParsing protocol, whose TestBinding pairs a
ContextParser with the same TestSyntax used by TestIntegrityRule. The gate
itself imports no snapshot, language or plugin module: reading baseline blobs
belongs to snapshots.py, and parser/syntax assembly belongs to application
composition.
plugins/builtins.py exposes builtin_deletion_gate(), symmetric with
builtin_registry(). It iterates builtin_languages(), attaches each plugin’s
parser, and selects the matching TestSyntax; TypeScript and TSX reuse
JavaScriptTestSyntax, and Rust binds RustTestSyntax, whose candidates are
#[test] (and *::test) functions whose file matches the shared test paths (the
default globs cover tests/* and */tests/*, so inline #[cfg(test)] mod tests
modules under src/ are not checked by test.integrity or test.deletion unless
those source paths are added to paths). The private bindings container implements
BaselineParsing. Gate bindings are fixed to the built-in language set: a custom
AnalyzerRegistry passed to main(..., analyzers=...) does not participate in
gate composition, so a deleted file in a language outside that set is selected
from the diff but has no binding and is skipped silently. The gate is not
registered by any analyzer, so
AnalysisProfile.required_rules does not apply to it; this is a deliberate,
documented exception for run-level checks. Its single diagnostic remains part of
the policy switch, and enabled: false skips the gate.
cli.py invokes the gate only for --base and --staged. It reads changed
paths, asks the gate for current changed test candidates, reads their baseline
blobs, collects deleted-file baselines, then merges the returned findings with
analyzer findings under the same sort key. --all never activates the gate.
Deleted files are not analyzed inputs, so report files counts current selected
sources only; deletion findings are file-scoped and anchored at line 1, column 1.
Infrastructure failures such as an unmerged staged index or a non-UTF-8 baseline
blob fail closed through the existing CLI error path.
Extending the application
Section titled “Extending the application”A shared rule consumes the same concrete context regardless of source language:
@dataclass(frozen=True)class ModuleSizeRule: name: str = "project.module_size" api_version: int = 2 requirements: RuleRequirements = RuleRequirements() rule_ids: tuple[str, ...] = ("project.module_size",)
def check(self, context: TreeContext) -> tuple[Finding, ...]: if context.root.named_child_count <= 100: return () return (Finding(path=context.source.path, line=1, column=1, rule="project.module_size", message="Split module responsibilities"),)This example bounds top-level named syntax nodes; their meaning is grammar-defined. A rule requiring a normalized concept such as executable statements must consume the appropriate typed syntax capability instead of assuming identical node shapes.
builtin_analyzers() returns concrete TypedAnalyzer objects. Extend their
bundles before registering them in an AnalyzerRegistry. Use builtin_registry()
for the standard application composition. Pass the same registry to discovery and
execution; cli.main(arguments, analyzers=registry) provides that integration.
Rules do not declare a list of language identities. Applicability and grammar
capability bindings belong to application composition.
For a new language, declare its identity, suffixes, grammar and adapters; build an
application profile and compatible rule bundle registry; then compose and register
its analyzer. The count-dialect
fixture in tests/test_extensions.py uses a registered tree-sitter grammar and
verifies discovery, CLI findings, source selection and session lifetime through
the same public extension path.
Compatibility and failure behavior
Section titled “Compatibility and failure behavior”Extension contracts are defined over the common tree context rather than a language-specific one:
- Extensions consume the shared
TreeContext. ContextParser,RuleBundle,BundleRegistryandTypedAnalyzertake no arbitrary context type parameters.- Rules declare capabilities through explicit requirements; applicability and grammar capability bindings belong to application composition.
- Language plugins do not assemble analyzers; built-in assembly is application-owned.
AnalysisProfile.required_rulesdeclares required diagnostic coverage.- Custom analyzers provide
validate(),needs_semantics(policy)and accept an optional execution session; they expose a typed optionalsemantic_binding, which registration attaches automatically, and remain responsible for their declared contract and failures.
The configuration schema and the extension API are separate compatibility boundaries. Registration rejects legacy-shaped extension objects, ambiguous suffixes, invalid identities, missing required coverage and conflicting rule ownership. Undeclared findings and executing plugin failures still fail closed. Disabled bundles do not execute; disabling all rules avoids parsing after composition validation. Required coverage remains independent of checker enable flags.
Analysis runs on tree-sitter recovery and checks over the available syntax. A
custom parser that raises SyntaxFailure supplies tuple[ParseWarning, ...] and
must explain in its warnings which dependent checks are unavailable. Recovery
differences must remain tested and documented. Source selection stays
snapshot-based and gate execution stays read-only.
Checker-owned registration
Section titled “Checker-owned registration”Checkers explicitly composes typed configuration fragments. It declares no
checker fields or checker-name list itself. Owners declare their concrete options,
configuration key and diagnostic mapping beside the associated checker contracts:
| Owner | Configuration |
|---|---|
| Function measurements | metrics/options.py |
| Architecture checks | architecture/options.py |
| Serialization checks | semantics/encoding_options.py |
| Boundary and usage checks | semantics/options.py |
| Shared type and syntax switches | policy/type_options.py |
policy/contracts.py owns strict, frozen base contracts and CheckerDefinition.
Each fragment declares concrete Pydantic fields, derives JSON aliases from its
checker definitions, and contributes CheckerState values through cooperative
checker_states() composition. A state contains only identity, diagnostic mapping
and an enable flag. Option payloads remain in their original concrete fields;
there is no heterogeneous option store, cast, dynamic model or serialization step.
disabled_checkers() and disabled_rules() consume those states uniformly.
function_size declares its five diagnostic IDs at its owner; it needs no special
branch in shared policy code. Rule implementations and built-in requirement
profiles reference the same definitions. Validation rejects duplicate names,
empty/duplicate diagnostic IDs, overlapping diagnostic ownership and differences
between registered checker names and the composed schema’s field aliases.
A new checker contributes a typed fragment and adds that fragment to the explicit
application composition. Its schema, defaults and disabled-diagnostic expansion
then participate automatically. Runtime discovery of arbitrary checker schemas is
outside this API. Each overriding checker_states() must include
super().checker_states(); the field-registration invariant rejects omissions.
Policy JSON, the Python option constructors (for example
BroadTypeOptions(encoding=EncodingOptions(...)) inside Checkers(type_broad=...)
and CheckerOptions for checkers without extra settings) and imports from
policy.models are supported. That module owns composition and re-exports
canonical option classes rather than defining them. Package-level MetricRule
and ArchitectureRule exports load their concrete implementations lazily, so
importing checker contracts does not create an execution-to-policy import cycle.
policy/contracts.py holds the leaf contracts and imports no application modules.
The composition module imports owner contracts, and runtime checkers consume their
owner’s definitions and concrete policy fields.