Runtime-diagnosed (LSPDIAG2 at the pass_calls join) LSP-strategy reds.
NESTED-CLASS ENCLOSING QN (cbm_enclosing_func_qn, helpers.c): a method in a
nested class was qualified with only the INNERMOST class (Inner), not the full
chain (Outer.Inner) that the def walk's compute_class_qn produces. So a call
inside a nested-class method sourced to the file node (callable=0) AND its
enclosing_func_qn failed to equal the LSP-resolved caller QN (strategy ABSENT,
e.g. lsp_outer_dispatch). Build the full outer->inner dotted class chain so the
enclosing QN matches the class/method node QN. Single-class and top-level cases
are unchanged (the chain collapses to the prior value).
CONSTRUCTOR RESOLUTION (cs_lsp.c cs_resolve_object_creation, java_lsp.c): `new
Foo()` synthesized a callee `Foo..ctor` / `Foo.Foo` whose ".ctor"/doubled short
name joined nothing (call callee_name is "Foo") and pointed at a non-existent
node -> no edge (cs_ctor, cs_ctor_synthetic, lsp_constructor, lsp_constructor_synth
all dead). A C#/Java constructor registers as <type_qn>.<ClassShortName>, so look
it up by the class short name; when no explicit ctor exists, resolve the call to
the existing Foo CLASS node (short name "Foo" == callee_name -> join matches, node
exists -> edge forms carrying the strategy).
Reproduced by repro_lsp_java_cs (nested-dispatch + constructor strategies RED).
NOTE: the *_unindexed / lsp_unresolved strategies are intentionally below the
confidence floor and target missing symbols (no edge can exist) -- flagged
separately as likely test-scope issues, not fixed here.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Three flagged decisions, resolved with the maintainer (accuracy-first):
- Markdown heading label: production correctly mints "Section" (a valid, accurate
label); a heading is not a Class. Correct the repro ASSERTION "Class"->"Section"
rather than degrade the graph to match the test.
- AWK: a bare `rule` (`{...}`/`/re/{...}`/BEGIN/END) is ANONYMOUS top-level code,
not a named callable -> a call inside a rule is legitimately Module-sourced.
Remove "rule" from awk_func_types (it is not a function boundary) and rewrite
the fixture so the call-under-test (`inner`) lives inside a named `function`
(`process`), validly exercising callable-sourcing. The graph stays accurate.
- issue471: convert the flaky wall-clock perf reproduction into a DETERMINISTIC
termination guard. At N=5000 the O(n^2) parse sits at ~15 s (the alarm) and
flipped red/green on CI load; N=2000 finishes <1 s under any load, so the
"deeply-nested ambiguous parse terminates (no hang/crash)" assertion is now
stable on all platforms. The O(n^2) perf bug #471 remains OPEN, tracked
separately (wall-clock perf cannot be reliably CI-gated).
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Per-case-verified (AST-confirmed) production fixes for def-extraction reds.
DEF-LABEL:
- Zig: struct name is on the parent variable_declaration's identifier (value is a
struct_declaration) -> resolve it -> "Class".
- Dockerfile/GoMod/PROPERTIES: get_module_parents() returned NULL for these, so
extract_variables bailed at the module gate and never reached var extraction.
Wire their module parents (properties roots at `file`); add PROPERTIES
(property->key) + GoMod (require_spec->module_path) var-name cases -> Variable.
- K8s/Kustomize: K8s emitted "Resource", which is NOT in the valid-label set (so
the def was dropped by label validation) -> use the valid "Class"; Kustomize
emitted no def -> mint a "Class" from `kind:`.
- BitBake: bitbake_func_types referenced a nonexistent node; use the real
function_definition/anonymous_python_function + a name resolver -> Function.
- PKL: classMethod name nested in methodHeader>identifier -> Function (+ a
module-level function added to the fixture source).
MALFORMED QN:
- Makefile: skip dot-prefixed targets (.PHONY/.DEFAULT are directives, not defs).
- INI: section name is the inner `text` child (was "[database]\n").
- Markdown: collapse whitespace in heading QN segments (def.name stays readable).
ACCURACY NOTE: kept the Markdown heading label as "Section" (a valid, accurate
label) rather than degrade it to "Class" to satisfy the repro assertion -- a
heading is not a class. The assertion is the inaccurate side; Markdown
"no def labelled Class" intentionally stays RED pending review of that assertion.
Reproduced by repro_grammar_{core,build,config,markup,systems} (RED).
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Per-case-verified callable-sourcing fixes (AST-confirmed via a standalone dumper).
PRODUCTION BUGS (a def-extractor minted a "Function" for a node kind absent from
function_node_types, desyncing def-extraction from call-scope attribution):
- CFML: cf_function_tag is minted as a Function by extract_cfml_function_tag but
was not in cfml_func_types, so no SCOPE_FUNC was pushed -> in-body calls sourced
to Module. Add "cf_function_tag" to cfml_func_types + compute_cfml_func_qn
(reads the name from cf_attribute, gated in compute_func_qn which has source);
the cf_function_tag walk_defs case now pushes children + continues so the
generic extract_func_def does not double-mint.
- GoTemplate: define_action minted by extract_gotemplate_define but
function_node_types was empty. Add gotemplate_func_types={"define_action"} +
compute_gotemplate_func_qn (strips the quoted template name); the define_action
walk_defs case pushes children + continues (its `name` field is a quoted string,
which the generic path would double-mint with quotes).
BROKEN FIXTURES (production correct):
- SCSS: `@include` sat in a CSS rule_set (not a callable) -> legitimately
Module-sourced. Moved it inside a `@mixin card { }` body.
- Move: named-address `module calc::math` + expression bodies made the grammar
emit ERROR nodes (failed even extract-clean). Switched to `module 0x1::math`
with statement-terminated bodies; the in-body `add(x,1);` now callable-sources.
- QML/Pine: the only in-body calls targeted EXTERNAL symbols (Math.max/ta.ema ->
no edge) and the same-file calls were top-level. Added a same-file callee called
in-body; removed the top-level calls. Dim-6 callee assertions preserved.
Reproduced by repro_grammar_{web,systems,markup,misc} callable-sourcing (RED).
AWK + Dart still deferred to focused tasks.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Per-case-verified callable-sourcing fixes (AST-confirmed via a standalone dumper).
PRODUCTION BUGS:
- Clojure/Scheme/Racket: [CBM_LANG_*] had empty function_node_types, so no
SCOPE_FUNC was pushed and every in-body call sourced to Module. Wire
clojure_func_types={"list_lit"}, scheme/racket={"list"}. Since these kinds also
match plain call forms, gate def-vs-call in compute_func_qn (extract_unified.c,
which has ctx->source; the shared resolver does not): compute_lisp_func_qn
returns the def name only when the list head is a def-form (defn/define/...),
NULL otherwise, so non-def lists like (add x 1) push no scope.
- Elixir: def/defp/defmacro are `call` nodes (so are in-body calls); the shared
resolver returned NULL for them. compute_elixir_func_qn names a def call (gated
strictly on the def-macro target) and returns NULL for non-def calls.
BROKEN FIXTURE (production correct) -- Starlark: extraction works; the in-body
go_binary(...) callee is an EXTERNAL undefined rule, so it correctly yields no
CALLS edge (unresolved callee -> no edge, universal behavior). Added a same-file
_base_deps() def called inside make_binary's body for a resolvable in-body call
-> Function-sourced edge. go_binary(...) kept (dim-6 callee assertion preserved).
Reproduced by repro_grammar_{functional,scripting,config} (Clojure/Scheme/Racket/
Elixir/Starlark callable-sourcing were RED). AWK (rule-naming) + Dart (structural)
deferred to focused tasks.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Per-case verification (AST-confirmed) of three RED expression-config-language
reproductions, distinguishing genuine production bugs from broken fixtures.
PRODUCTION BUG — Nickel (def + call were not extracted):
- nickel_func_types "fun" -> "fun_expr": the bare `fun` matched only the keyword
token, never a node; the lambda node is `fun_expr` (anonymous), whose name is on
the enclosing let_binding's `pat` field, so cbm_resolve_func_name climbs to the
let_binding to name it (anonymous lambdas self-filter).
- nickel_call_types "infix_expr" -> "applicative": infix_expr is binary-operator
application (`a + b`); the real call `f x y` is a curried `applicative`. New
extract_nickel_callee emits one edge per curried call (requires a `t2` arg,
outermost applicative only), guarded against the pass-through applicative
wrapper that surrounds every Nickel value.
BROKEN FIXTURES (production correct) — the callable-sourcing invariant requires
module_sourced==0, but these fixtures called functions at the TOP LEVEL (the
output expression), which is legitimately Module-sourced. Each fixture corrected
so its only call sites are INSIDE a function body and the output merely REFERENCES
the function; all def/call assertions preserved (makeServer/addPort/go_binary defs
+ their calls remain):
- jsonnet: output `server: build`, `local build(host)=makeServer(host,8080)`.
- nickel: output `make = mkServer`; `addPort port 0` stays in mkServer's body.
- starlark: `default_rule = make_binary`; go_binary stays in make_binary's body.
Reproduced by repro_grammar_config (jsonnet/nickel/starlark callable-sourcing +
nickel def/call were RED).
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
- Jsonnet: a function binding is a `bind` node with the name on the `function`
field and a `params` field (value binds have no params -> skipped); add "bind"
to jsonnet_func_types and resolve its name. Call: `functioncall` callee = first
`id` child.
- Typst: `#let f(x) = ...` is a `let` whose `pattern` is a `call`; the name is
that call's `item` field (value `#let x = 1` has a non-call pattern -> skipped).
Add "let" to typst_func_types. Call: `call` callee = `item` field.
- Meson: meson_call_types listed phantom node kinds ("function_expression",
"command") that do not exist in the grammar; the real builtin invocation is a
`normal_command` whose `command` field is the callee. Replace with the real
node + resolve the callee.
Reproduced by the repro_grammar_{config,markup,build} suites (jsonnet/typst defs
+ jsonnet/typst/meson calls were RED).
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Pony `fun`/`be`/`new` (method/constructor/ffi_method) live in pony_func_types,
so the main def-walk extracts them via extract_func_def and labelled every one
"Function" — even those declared inside a class/actor/struct/trait/interface/
primitive, which are methods. Detect the enclosing class-like ancestor (via the
spec's class_node_types) and promote such defs to "Method" with a parent_class
link, mirroring the Go-receiver and C++ out-of-line Method paths. Free functions
(no class-like ancestor) stay "Function".
Reproduced by repro_grammar_systems_pony ("no def labelled Method", was RED).
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
- GraphQL/Prisma/Smali: extract schema fields as "Field" defs (field_definition /
column_declaration), gated per-language; recognise their class-body nodes
(fields_definition / statement_block) via per-language cases so the common
"statement_block" kind never hijacks another language's class body.
- Pony: class members (method/constructor/ffi_method) have no name field; the
name is the first identifier child -> "Method" defs.
- PKL: clazz name is an identifier child -> "Class" def.
- Dockerfile: ENV/ARG names from env_pair name field / arg_instruction -> Variable.
- CSS: call_expression callee is a function_name child (e.g. url()).
- TLA+: add bound_op to tlaplus_call_types so operator applications resolve.
Reproduced by the repro_grammar_* suites (were RED for missing defs/calls).
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Several grammars produced no Function def and/or no CALLS edge because the
name/callee is not in the standard `name`/`function` field. Add precise
per-grammar extraction (verified against the actual tree-sitter parse trees):
- SCSS: function_statement/mixin_statement name is a `name` CHILD (not a field);
the call node is `include_statement` (callee = its identifier child). Also fix
scss_call_types, which listed "call_expression" instead of include_statement.
- SQL: create_function / invocation carry the name on a nested
object_reference > `name` field.
- COBOL: call_statement's callee is its `x` string-literal (program name),
dequoted.
- Elm: value_declaration name is functionDeclarationLeft > lower_case_identifier;
function_call_expr callee is target > value_expr > name (value_qid).
- Teal: the `local function foo()` form carries the name on a `function_name`
child rather than the `name` field.
Reproduced by the repro_grammar_* and repro_invariant_enclosing_parity suites
(SCSS/SQL/COBOL/Elm/Teal), which were RED for missing defs/calls.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
The unified/calls extractor used a private 4-case name resolver
(resolve_func_name_node) that returned NULL for the ~130 grammars whose
function node has no `name` field — Fortran subroutine, SCSS mixin, SQL
create_function, Julia short-form, the Lisp/FP family, and more. On NULL,
push_boundary_scopes never pushed a SCOPE_FUNC, so every call inside such
a function was attributed to the enclosing Module instead of the callable
(QUALITY_ANALYSIS gap #3).
Export the rich resolver from extract_defs (cbm_resolve_func_name) — a
strict superset that already drives definition extraction (generic name
field, arrow/declarator, C/C++ declarator chain, plus the per-language
quirks) — and route the calls scope path (compute_func_qn) through it,
preserving the enclosing-class QN join. Definition extraction is
unchanged (it already called this resolver); the two paths now share one
source of truth, the same de-drift pattern used for
cbm_resolve_c_declarator_name_node (#438).
Reproduced by repro_invariant_enclosing_parity (Fortran, SCSS, SQL,
Verilog, Julia, Nix, CommonLisp, EmacsLisp, Dart, COBOL): each asserts no
CALLS edge is Module-sourced and was RED; the fix makes them
callable-sourced.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Root cause of the systemic callable-sourcing gap (QUALITY_ANALYSIS gap #3; only
3.69% of real-repo CALLS were Function/Method-sourced): func_kinds_for_lang fell
back to func_kinds_generic for the ~130 languages without a curated entry, missing
their real function node types, so cbm_find_enclosing_func never found the parent
function and attributed in-body calls to the Module node.
Fix: in the default case, use the language spec's function_node_types (the single
source of truth extraction already uses) when present. Curated languages (Go/
Python/C/C++/Rust/Java/...) are unchanged — no regression to the green gate.
Flips the callable-sourcing + enclosing-parity reproductions for the drifted
languages (dart/perl/scss/nix/fortran/cobol/verilog/vhdl/...) toward green.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
Addresses #463 review: the declarator-chain name resolver was copied into
helpers.c, extract_unified.c, and extract_defs.c, and CBM_DECLARATOR_DEPTH_LIMIT
was #defined twice -- the same triplication drift that caused #438.
- Add cbm_resolve_c_declarator_name_node() to helpers.{c,h} as the single
source of truth, carrying is_c_terminal_name/resolve_qualified_name with it.
- Route the defs, calls, and unified extractors through it.
- Hoist CBM_DECLARATOR_DEPTH_LIMIT into helpers.h; extract_defs.c's
DECLARATOR_DEPTH_LIMIT now derives from it.
Canonicalizes on the original extract_defs.c logic (operator/destructor aware)
so defs behavior is unchanged and calls/unified now agree with it.
Test: full suite green except an unrelated ASan RSS-budget check; clang-format clean.
Signed-off-by: Kris Kersey <kris@kerseyfabrications.com>
A CALLS edge whose caller is a C/C++/CUDA/GLSL function was sourced to the
file's Module node instead of the calling Function. "Find callers of X"
returned a file path, outbound trace_path returned empty, and
(:Function)-[:CALLS]->(:Function) queries missed for these languages.
Root cause: the enclosing-function resolvers read only tree-sitter's `name`
field, but a `function_definition` node has none — the name lives in the
declarator chain (pointer/function/parenthesized/array declarators). So
func_node_name() (internal/cbm/helpers.c) and resolve_func_name_node()
(internal/cbm/extract_unified.c) returned NULL, the enclosing scope fell
back to the module QN, and the edge was attributed to the Module node. This
is the C counterpart to #220, which fixed the definition-naming path but not
the enclosing-call path.
Fix: descend the declarator chain to the innermost name node (mirroring
resolve_c_declarator_name in extract_defs.c, including qualified and operator
names) when a function_definition lacks a `name` field. Adds the regression
test c_caller_attribution asserting a C call's enclosing_func_qn is the
function, not the module.
Fixes#438
Signed-off-by: Kris Kersey <kris@kerseyfabrications.com>
extract_class_def() sets start_line and end_line from the tree-sitter
node span, but left def.lines = 0 (zeroed by memset at function entry).
The equivalent function push_method_def() correctly computes
def.lines = end_line - start_line + 1
The same one-liner was simply missing from the class extraction path.
This affects all languages — Python, TypeScript, Go, and any other
language where Class nodes are extracted via extract_class_def().
Regression test: after indexing a project, at least one Class node must
have c.lines > 0.
Signed-off-by: Thomas Dyar <tdyar@intersystems.com>
Vendors the two MIT-licensed grammars from intersystems/tree-sitter-objectscript
@a7ffcdf (the language vendor's official grammars, ABI 15) that PR #467 needs:
internal/cbm/vendored/grammars/objectscript_udl/ (.cls)
internal/cbm/vendored/grammars/objectscript_routine/ (.mac/.inc/.rtn/.int)
Each directory carries the verbatim generated parser.c + scanner.c + tree_sitter/
headers + LICENSE. The one adjustment: each scanner.c's upstream
`#include "../../common/scanner.h"` is repointed to a per-directory
`objectscript_common.h` (a verbatim copy of the upstream common/scanner.h), because
this repo's shared vendored/common/scanner.h belongs to the cfml/fsharp grammars and
differs. Updates MANIFEST.md + THIRD_PARTY.md.
These files are dormant until #467 (the grammar shims + extraction) is rebased on
top; main's build is unaffected.
Refs #462, #467.
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
try_route_from_annotation read the annotation name via the "name" field
(ts_node_child_by_field_name). tree-sitter-kotlin annotation nodes have no
"name" field: the name lives in a nested type_identifier under (user_type)
or (constructor_invocation (user_type ...)). The lookup returned null, so
every Kotlin @RestController route was dropped (0 decorator-source routes)
while Java worked. Args are likewise under constructor_invocation as
value_arguments (each wrapped in value_argument), not Java argument_list.
Add annotation_name_node()/annotation_args_node() that fall back to the
Kotlin AST shape (Java path unchanged) and unwrap value_argument when
scanning for the route path. Kotlin @GetMapping/@PostMapping/etc. now yield
Route nodes and HANDLES edges. Adds handles_spring_kotlin regression test.
Signed-off-by: jsw6701 <86887824+jsw6701@users.noreply.github.com>
Python calls of the form iris_obj.classMethodValue('Pkg.Class', 'Method')
emitted no CALLS edge. The detection existed in walk_calls, which is dead
code — the pipeline uses cbm_extract_unified → handle_calls, not walk_calls.
Move the IRIS Native API string-dispatch detection to handle_calls. When a
Python call's callee ends in .classMethodValue, .classMethodVoid,
.classMethodBoolean, or .classMethodObject, and both string-literal arguments
can be extracted, emit a synthetic CALLS edge to Arg1.Arg2.
The pattern generalizes beyond this specific API: any library that takes
class/method names as string literals follows the same shape.
Regression test: python_iris_classMethodValue in test_extraction.c.
Signed-off-by: Thomas Dyar <tdyar@intersystems.com>
* fix(perl): stop extracting config strings as call targets
The Perl branch of extract_scripting_callee blindly returned the text of
child(0) of every call node. In config-heavy Perl (.cgi/.pl with embedded
log4perl-style config), tree-sitter-perl misparses dotted config tokens
(e.g. "log4perl.appender.File.utf8") into call-shaped nodes, and that
dotted string was emitted as a callee_name, later matched by the generic
short-name resolver to unrelated project subs.
Now the Perl branch pulls the real name token (method/function field, else
child(0)) and validates it as a bare Perl sub/method identifier via
perl_is_identifier_callee: must start with a letter or '_' and contain only
[A-Za-z0-9_:] (allowing the '::' package separator). Any '.', whitespace,
quote, or '/' disqualifies it and NULL is returned so no CALLS edge forms.
Gated to CBM_LANG_PERL; other languages are untouched.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Shane McCarron <shane.mccarron@corvexconnect.com>
* fix(resolver): don't match Perl builtins to project subs
Perl builtins (push/shift/keys/sprintf/...) carry no language or call-kind
awareness through the generic name-matcher in cbm_registry_resolve. When a
project defines a sub whose name collides with a builtin, an invocation of
the builtin was wired to that sub by same-module / suffix matching - a
false-positive CALLS edge.
Adds cbm_perl_is_builtin (curated, sorted bsearch set of 94 perlfunc core
builtins) and applies it in both call-resolution passes (sequential
resolve_single_call and parallel resolve_file_calls), gated on the file
language == CBM_LANG_PERL and only AFTER LSP resolution has declined, so a
genuine LSP-resolved call is never suppressed. The file language is threaded
into both resolvers via a new trailing CBMLanguage parameter; every other
language reaches cbm_registry_resolve unchanged (byte-identical behavior).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Shane McCarron <shane.mccarron@corvexconnect.com>
* fix(resolver): suppress generic short-name matching for Perl method calls
A Perl method call ($obj->m / Class->m) carries no receiver type at the
structural tier, so the generic short-name matcher in cbm_registry_resolve
would wire $dbh->commit / $cgi->param / $logger->log to any project sub
sharing the bare method name - the dominant source of false-positive CALLS
edges in CPAN/framework-heavy Perl. Resolving such a call correctly is the
LSP's job, not the bare-name matcher's.
Adds a CBMCall.is_method flag (zero-init false, so all other languages and
existing call sites are unaffected). method_call_expression is added to the
Perl call node set and handle_calls sets is_method=true only for that node
type when the file language is Perl. Both call-resolution passes then skip
generic resolution for Perl method calls (combined with the builtin guard
from the prior commit). Genuine intra-project function calls (non-method,
non-builtin) still resolve as before. LSP-resolved method calls are
unaffected because the guard runs only after LSP resolution declines.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Shane McCarron <shane.mccarron@corvexconnect.com>
* test(perl): cover call-graph noise fixes (builtins, methods, config strings)
Hermetic tests for the three Perl call-graph noise fixes:
test_extraction.c (extraction tier):
- config string is never emitted as a callee; genuine call still extracted
- builtin calls (push/keys) extracted but never flagged is_method
- arrow/method calls ($self->commit / $dbh->commit) set is_method=true,
while the genuine function call (helper) does not
- a JS method call never sets is_method (flag is Perl-only — other
languages unaffected)
test_registry.c (resolver tier):
- cbm_perl_is_builtin recognizes core builtins (incl. first/last of the
sorted set) and rejects project subs, case variants, empty, and NULL
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Shane McCarron <shane.mccarron@corvexconnect.com>
* fix(perl): address QA round 1
Round 1 (Claude panel + DO DeepSeek) findings:
- Rework the Perl noise guard so it suppresses only WEAK generic matches
(suffix_match/unique_name) and KEEPS high-confidence same_module/import_map.
The prior guard ran before cbm_registry_resolve and dropped genuine same-file
calls to builtin-named subs (e.g. a project sub log/index/open called as a
bare function) that pre-PR resolved via same_module. Extracted the decision
into pure, unit-tested cbm_perl_suppress_generic_match() shared by the
sequential (pass_calls.c) and parallel (pass_parallel.c) resolvers; corrected
the inaccurate comments (Perl has no LSP/textual stage before the guard).
- Tighten perl_is_identifier_callee to require '::' pairs (reject a lone ':',
':::', or trailing '::').
- Add resolver-contract tests covering weak-match suppression, same_module/
import_map retention, genuine-call survival, non-Perl no-op, and NULL strategy.
Verified on a real Perl monorepo: .cgi builtin/CPAN/config-string noise stays
eliminated while same_module edges to builtin-named subs are recovered.
Signed-off-by: Shane McCarron <shane.mccarron@corvexconnect.com>
* fix(perl): address QA round 2
Round 2 (Claude panel) caught a regression introduced by the round-1 refactor:
cbm_perl_suppress_generic_match whitelisted only the exact strategies
"same_module" and "import_map", but resolve_import_map can also return
"import_map_suffix" (confidence 0.85 — a genuine import-based resolution, not a
weak short-name guess). A '::'-qualified Perl builtin/method call resolved via
the import-suffix fallback was therefore dropped, contradicting the helper's
documented contract and partially missing acceptance criterion (d).
Add import_map_suffix to the kept (high-confidence) set so only the weak
short-name strategies (suffix_match / unique_name) are suppressed; update the
doc comment and add a unit-test case asserting import_map_suffix is retained.
Deferred as advisory (non-blocking, noted on the PR): a hypothetical leading-'::'
(main:: shorthand) under-extraction in perl_is_identifier_callee, and a
colon-edge-case coverage gap (logic correct by inspection).
Signed-off-by: Shane McCarron <shane.mccarron@corvexconnect.com>
---------
Signed-off-by: Shane McCarron <shane.mccarron@corvexconnect.com>
Co-authored-by: Shane McCarron <shane.mccarron@corvexconnect.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
A byte-identity audit of all vendored license files against their
upstream repositories found 113 copies differing only by a missing
trailing newline (vendoring artifact) — replaced with the exact
upstream bytes. Five needed real corrections: fennel carried an
unfilled MIT template although its upstream is CC0-1.0 at the pinned
commit; ron now carries the repo's LICENSE-MIT (dual MIT/Apache
upstream); python, wit, and verilog were refreshed to current upstream
bytes. The manifest's first-party table was also corrected: six of the
twelve grammars are self-maintained forks whose retained upstream
licenses are now byte-verified (assembly's upstream has been deleted
from GitHub; the retained MIT copy is the surviving grant). The audit
tool is kept as scripts/audit-license-provenance.py for future sweeps.
Removes the heaviest vendored grammar (66 MB) along with its language
wiring and test fixtures; the supported-language count moves to 158
across README, site, and manifest. The grammar manifest additionally
records the canonical-source decisions for the five
registry-disagreement grammars and the per-directory license files
restored earlier this week.
The alloc.h/array.h/parser.h headers in
internal/cbm/vendored/common/tree_sitter/ are part of the tree-sitter C
runtime (MIT, (c) 2018 Max Brunsfeld) but had no LICENSE file alongside
them. Copy the upstream MIT license into that directory and clarify in
THIRD_PARTY.md the split between the tree-sitter-html scanner helpers
(common/, (c) 2014) and the core runtime headers (common/tree_sitter/,
(c) 2018).
Restore upstream LICENSE files for every vendored grammar and C library
across both vendored trees (19 grammar dirs, lz4, zstd, simplecpp,
verstable, wyhash, ts_runtime, common, mongoose, xxhash, yyjson; SQLite
public-domain notice). Add the nomic-embed-code Apache-2.0 license plus a
NOTICE describing the embedding derivation. First-party grammars carry
the project MIT license.
THIRD_PARTY.md now defers grammar provenance to the verified
MANIFEST.md instead of a stale hand-written table (which misattributed
clojure as EPL-1.0 — it is CC0-1.0), covers all vendored libraries, and
documents the Hybrid LSP reference servers and stdlib type-data
provenance (typeshed, Go stdlib introspection, hand-curated specs).
Profiling symfony (416 s wall, one core pinned) convicted cbm_registry_lookup_type -> strcmp at 95% of samples: the PHP and Python def-registration loops probe the registry per Method (receiver-stub check) BEFORE the hash indexes exist, i.e. a linear scan over the growing type table - O(methods x types) per file, and the cross resolvers run per file. Java and Kotlin never called cbm_registry_finalize at all, leaving every lookup during their file walks linear over the whole cross registry. Fixes: (1) two-phase registration in php/py (types, finalize, then funcs/methods); (2) finalize added to the java/kotlin cross entry points; (3) lookups now tail-scan entries added after finalize - previously such entries were silently INVISIBLE to the hashed path (reproduce-first: tslsp_hash_registry_post_finalize_adds was red); (4) cbm_registry_finalize_into allocates the index from a per-call scratch arena - putting buckets into the pipeline-lifetime result arena per file accumulated +1.1 GB RSS on the FastAPI incremental test (incr_full_index caught it), and the py tier-2 builder (one def per call) skips mid-build finalize entirely. symfony: 416 s -> 12 s, identical node count; suite 5577/0.
The hand-rolled dump writer stored index cells fully inline regardless of payload size. SQLite's format spills index payloads above the max-local threshold (16,422 bytes at the 64 KB page size) to overflow pages, so a long key written inline makes the reader interpret key bytes as an overflow page number: PRAGMA integrity_check reported 'invalid page number 0x43654C6C' (ASCII from the key text) in idx_nodes_name on elasticsearch (very long Section names), and name lookups on that index silently returned nothing. write_index_btree now rewrites oversized cells (varint + local prefix + overflow chain via write_overflow_pages) before page building; promoted separators carry their chains with them. Reproduce-first: sw_long_index_keys_overflow (20 KB name; integrity_check failed pre-fix, ok post-fix). Also escapes the remaining raw text interpolations in DATA_FLOWS route props and HANDLES handler QNs (the ~51-edge malformed tail after 6c04ab7).
c_process_function's template-param attach wrote rf->type_param_names on the registry — in the Tier-2 cross-LSP phase that registry is shared READ-ONLY across all resolve workers, so the write raced concurrent readers AND stored a pointer into the writing worker's per-file arena; once that arena was recycled the shared registry held dangling memory, crashing other workers intermittently (bitcoin: SIGSEGV in c_process_function strcmp via cbm_run_c_lsp_cross_with_registry, ~1-in-2 runs). A registry_shared flag now marks the cross context and the attach is skipped there (cross-phase template deduction falls back to positional names — graceful degradation); the single-file extract phase keeps full fidelity. Real-repo-tier reproduction: 10x bitcoin index loop, 0 failures post-fix (pre-fix ~50% crash rate); suite 5575/0.
bind_lambda_args and the method-reference arity path indexed the resolved method signature's NULL-terminated param_types array by the CALL-SITE argument index. A call with more arguments than the resolved overload declares (overload mismatch, varargs) read past the terminator and dereferenced whatever followed in the arena as a CBMType* - SIGSEGV while indexing elasticsearch (same out-of-bounds family as #427 and the bitcoin targs fix). Both sites now bound the index by the walked param count. Reproduce-first: 6-line fixture - run(Runnable) invoked with six lambdas - crashed rc=134 pre-fix; fork+exit-signal regression test lsp_java_lambda_args_exceed_params_no_crash added; suite 5574/0.
The C/C++ LSP's explicit-template-argument call path (template_function, e.g. Using<Fmt>(v)) filled a stack array const CBMType *targs[16] without NULL-terminating it before cbm_type_substitute. With more declared type params than explicit args (bitcoin src/serialize.h: Using's Wrapper<Formatter, T&> with 2 params, 1 arg), the bounded args walk read uninitialized stack; any non-NULL garbage got bound to the type param and woven into the REGISTERED return-type graph, then dereferenced at a later call site - SIGSEGV (crash shape: string bytes misread as a CBMType*). All c_lsp targs arrays are now zero-filled, and cbm_type_substitute's args walk treats implausible values (misaligned / below the first page) as the terminator so contract violations can never leak garbage into a type graph. Reproduce-first: deterministic poison-args unit test (typerep_substitute_rejects_garbage_args_entries) + real-repo verification (bitcoin indexes clean under ASan; was a deterministic SIGSEGV).
Indexing large OSS during the perf sweep crashed three LSP resolvers, all by stack overflow in their recursive resolve walks (macOS crash reports): elasticsearch — SIGSEGV in bind_lambda_args under deep recursive java_resolve_calls_in_node frames; bitcoin — SIGSEGV in cbm_type_substitute via c_adl_resolve under deep c_resolve_calls_in_node frames; microsoft/TypeScript — SIGBUS under an unbounded lookup_member_type cycle (cyclic type graph in reallyLargeFile.ts). The expression-eval guards (eval_depth) did not cover these walks. Each resolver now has a depth-guarded entry (walk_depth cap 512 for the Java/C AST walks, member_depth cap 64 for TS member lookup); past the cap the subtree resolves as unknown — graceful degradation instead of a crash. Reproduce-first: prod CLI probes crashed pre-fix (nested-call Java rc=139, nested-call C++ rc=139); fork+exit-signal regression tests added (TS cyclic shape needs a real cross-file registry, so it is verified at the real-repo tier — microsoft/TypeScript now indexes clean). Side-finding documented in the sweep report: Java BLOCK nesting >=3000 is minutes-slow (separate pathology, not this fix).
C++/CUDA out-of-line method definitions (Foo::bar in a .cpp; the class body lives declaration-only in a header) were recorded as free Functions with no link to their class. A new helper cpp_out_of_line_parent_class() detects a qualified_identifier declarator on a function_definition and resolves the immediate enclosing class (descending nested scopes ns::Foo::bar to the direct parent); extract_func_def then promotes the def to label Method with parent_class set to the class QN so DEFINES_METHOD edges resolve. Distilled (reimplemented) from PR #428. Reproduce-first: cpp_out_of_line_method_issue428 (single-level out-of-line defs; the nested-namespace path isn't isolation-testable because tree-sitter-cpp parses a synthetic doubly-qualified def as an ERROR node, so it is exercised by real codebases).
The C++ LSP passes a class's declared template-param names (e.g. template<class T, class Alloc = ...>) alongside an instance's fewer template args (vector<int>). The substitution loop is bounded by type_params, so a param matching beyond the supplied args indexed type_args[i] past the array — reading adjacent arena memory (a type-name string byte) as a CBMType* that c_eval_expr_type later dereferenced -> SEGV (ASan: stack-buffer-overflow in cbm_type_substitute via c_eval_expr_type). Deterministic, all platforms; distinct from the #424 allocator crash. Fix at the single chokepoint: bound the args length by the (NULL-terminated) param count and gate every type_args[i] access by it, so no caller can over-read regardless of language. Reproduce-first: typerep_substitute_short_args_no_oob_issue427.
Defense-in-depth follow-up to the tree-sitter bind: route sqlite3 and libgit2
allocations through mimalloc explicitly so a correct binary never depends on the
fragile MI_OVERRIDE symbol override (where the Windows static-MinGW link can
resolve a library's malloc to mimalloc but its free to the CRT, corrupting the
heap). Prod-only, guarded by the existing CBM_BIND_TS_ALLOCATOR; the CRT+ASan
test build compiles these as no-ops and stays unchanged.
New cbm_alloc_init() consolidates all three binds behind a static idempotency
guard. main() calls it as its very first statement — before cbm_mcp_server_new
opens the in-memory store — because SQLITE_CONFIG_MALLOC must run before the
first sqlite3_open*/sqlite3_initialize, else sqlite3_config returns SQLITE_MISUSE
silently and the bind is ignored (the return code is asserted). cbm_init() also
calls cbm_alloc_init() so pipeline-pass entry points get the binds too; the
ts_set_allocator bind moved out of cbm_init into cbm_alloc_init.
sqlite3: a static sqlite3_mem_methods backed by mi_malloc/mi_free/mi_realloc,
xSize via mi_usable_size, xRoundup to an 8-byte boundary, xInit returning
SQLITE_OK, xShutdown a no-op (int-sized sqlite signatures wrapped with size_t
casts). libgit2: a static git_allocator (gmalloc/grealloc/gfree → mi_*) installed
via git_libgit2_opts(GIT_OPT_SET_ALLOCATOR). The allocator is set BEFORE any
git_libgit2_init: git_allocator_global_init keeps a custom allocator if one is
already set (git__allocator.gmalloc != git_failalloc_malloc), the pre-init global
is the fail-allocator, and there is no allocator reset on git_libgit2_shutdown —
so binding once at startup survives pass_githistory's per-call init/shutdown
pairs. libgit2 code is additionally guarded by HAVE_LIBGIT2.
Test build 5564/0 ASan-clean; prod build clean with CBM_BIND_TS_ALLOCATOR=1; the
HAVE_LIBGIT2 branch type-checked against the libgit2 sys/alloc.h struct shape;
lint-ci clean.
Root cause (corrected from the report): not a tree-sitter null-subtree sentinel — 0xffffffffffffffff is a freed/heap-corrupted pointer. The vendored ts runtime allocates via its overridable ts_current_malloc/free; under the prod build's MI_OVERRIDE=1, the Windows static-MinGW link (--allow-multiple-definition) resolves ts_malloc to mimalloc but ts_free can resolve to the CRT free (or vice-versa), corrupting the heap freelist and crashing mid-parse on large templated C++ headers (scales with parse churn, not syntax). cbm_init now calls ts_set_allocator(mi_malloc, mi_calloc, mi_realloc, mi_free) so ts allocate+free go through one allocator on every platform. Guarded to CFLAGS_PROD (MI_OVERRIDE=1); the test build stays CRT+ASan to avoid an alloc/free mismatch there. Tests in test_stack_overflow.c: allocator-binding mechanism + large-templated-C++ extraction guard (the C++ gap noted in #424).
Remove leftover getenv(CBM_DBG_*) debug fprintf blocks in extract_calls.c/pass_calls.c (cppcheck always-true). Convert parse_lisp_imports to a stack-based walk (no recursion → no NOLINT, avoids deep-nesting overflow). Apply Homebrew clang-format to all touched sources. Local suite 5562/0, lint-ci clean.
fwcd/tree-sitter-kotlin wraps a whole class in an ERROR node when a member uses companion object / inner class combined with a delegation specifier. recover_kotlin_error_classes scans an ERROR node's flat tokens for class/object keyword + identifier, emits the Class def (respecting enclosing class QN) and collects bases from delegation_specifier siblings. Strictly additive (only fires on ERROR regions). Fixes inherit_kotlin (MyClass companion + Node inner).
pass_semantic + pass_parallel: when a decorator name resolves to no local def, upsert a synthetic '<decorator:NAME>' node (label Decorator) and emit DECORATES+USAGE — fixes rust #[derive]/#[allow], swift @discardableResult, scala @deprecated (deduped per project; pipeline-level so extraction histograms unaffected). py_lsp: inject a synthetic CBMCall for resolved subscript/operator dunders on typed receivers so they reach the CALLS pipeline — fixes python s[0]->Seq.__getitem__.
Imports: per-grammar parsers for hare/pascal/powershell/scheme/racket/starlark/tcl/teal/zsh + css/html/cmake/bitbake/kconfig/gn/just/nix/jsonnet/pkl/nickel/thrift/capnp/d/tablegen/crystal/fsharp/ada; node-extraction for D/PowerShell/Pascal/Julia/F#; INHERITS for those. Pipeline edges: register Variable/Field defs for WRITES/READS resolution; CONFIGURES pass consuming env_accesses; DEPENDS_ON from go.mod/requirements.txt; SQS dot-form QN. Golden updates: julia +Class, just +Function (correct new extraction).