mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-10-27 06:12:20 +00:00
* fix(cpp): resolve qualified receiver types by namespace, not by tail
Cause: a C++ receiver declared with a qualified type (`rp::C x = ...`,
`void f(a::Config c)`, `rp::Box<int> b`) typed nothing. The capture keeps
the qualifier, but the shared receiver lookups read a qualifier only as a
`.` namespace-import handle, and C++ has neither: `#include` binds no
handle and the index keys `rp::C` under `C`. The two places that did type
qualified spellings — the `auto x = ns::T{}` brace-init rule and qualified
member fields — reduced them to their tail, which binds the NEAREST
same-named class: `auto x = rp::C{}` reached a global `C` through another
include, and `a::Config` inside a `namespace b` declaring its own Config
reached `b::Config` (both confident wrong CALLS edges).
Fix: a ScopeResolver opt-in, `resolveQualifiedTypeSpellings`, that C++
sets. When a qualified declared or return type binds nothing,
`resolveClassBindingForName` and the compound resolver's return-type lookup
fall back to `resolveQualifiedInheritanceBase` — the route qualified base
classes and qualified type references already take: the qualifier is
matched against the candidate's namespace and a tie resolves nothing. It
runs after every existing lookup and after the template-argument match, so
it adds edges and never retargets one. The brace-init rule now captures the
whole qualified_identifier, and non-generic qualified member fields keep
their qualifier, so both resolve through the same route; generic members
stay tail-reduced because specialization matching keys on the bare base
name.
Corpus A/B (lang-resolution, all languages): no edge outside the new
fixture moved; drops unchanged. bench/scope-capture cpp re-baselined (one
brace-init capture text, plus the new fixture).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cpp): bind qualified declarations that have no initializer
Cause: `rp::C x;` and `rp::C* x = nullptr;` emitted no type binding at
all. The plain-declaration annotation rules accept only a bare
`type_identifier` or `template_type`, and tree-sitter-cpp parses a
qualified type as a `qualified_identifier` wrapping one of those, so the
receiver of `x.m()` was untyped (no edge, and no drop either). The
initialized form `rp::C x = ...` was already captured by the `type: (_)`
assignment rule.
Fix: two @type-binding.annotation rules on the OUTER qualified_identifier
(plain declarator, and pointer inside an init_declarator) — the qualified
twins of the bare rules, one pattern per declarator shape like the
qualified member-field rules, with no node-type alternation. The spelling
is kept as written and resolved by the qualifier-aware route from the
previous commit.
Capture diff over the cpp corpus: 29 added @type-binding.annotation
matches on qualified locals, nothing removed or changed. Corpus A/B: no
edge or drop outside the new fixture moved. bench/scope-capture cpp
re-baselined.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cpp): record return types of header function prototypes
Cause: only function DEFINITIONS (and in-class method prototypes)
recorded a return type. A free-function prototype — `D makeD();`,
`namespace rp { C make(); }` — recorded none, and the usual layout is
"header declares, .cpp defines": the .cpp is never included, so an
includer saw no return fact at all and `auto x = makeD(); x.m()` /
`makeD().m()` typed nothing (the inline form recorded a drop, the bound
form not even that).
Fix: @type-binding.return rules for a prototype with a plain or pointer
return. In a function body the same syntax declares a block-scope
function (the most vexing parse, `D x();`), whose binding would be
hoisted to the module and type every undeclared `x` in the file, so
captures.ts keeps a prototype match only at namespace scope — the
translation unit or a namespace / extern "C" body, through preprocessor
conditionals (include guards), single-declaration extern "C" and
template prefixes. A prototype declared in a namespace keeps its binding
in that namespace instead of the module: the binding's scope is also
where its type is looked up, and from the module a global `Widget` in
the same header won over `rp::Widget`. Callers read namespace members by
definition identity, which joins in any scope, and namespace members are
never mirrored to includers by bare name anyway.
A reference return (`D& f();`) gets no rule: such a function is not
declared as a Function at all (no declaration pattern), so a return fact
would have nothing to attach to.
Capture diff over the cpp corpus: one added match outside the new
fixture (cpp-return-type's header prototype, same type as its
definition); the gate drops only the fixture's deliberate `E y();`.
Corpus A/B: no edge or drop outside the fixture moved.
bench/scope-capture cpp re-baselined.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(scope): type an inline call receiver from its callee's own return type
Cause: the compound resolver's free-call branch (`make().m()`) read the
callee's return type BY NAME from the caller's scope chain, while the
chain follow that types the bound form (`auto x = make(); x.m()`) reads
it BY DEFINITION IDENTITY (`producerTypeRef`). A callee that arrives by a
channel nothing mirrors a return binding through — a C++ using-directive
— therefore typed the bound form and dropped the inline one.
Fix: when the name read finds nothing, fall back to the return type the
callee's definition declares, via `producerTypeRef` (now exported from
imported-return-types.ts; the only change there). Only for a callee the
name actually BINDS at the call: `findExportedDefByName` falls back to the
first workspace callable of that name, and reading a return type off that
guess is not evidence. Measured: without the binding check the corpus
gained 15 non-C++ edges (Go range/chain factories, Swift call results),
all reached through that workspace-name guess and one of them provably
wrong (swift-return-type's `user.save()` bound to another fixture's
User); with it, no edge outside the new fixture moves.
Corpus A/B: edges and drops outside the fixture identical to main.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cpp): type receivers produced by a qualified factory callee
Cause: `auto x = rp::make(); x.m()` bound `x` to the literal type `auto`
— the bare `auto x = f()` constructor rule matches only an identifier
callee, so the generic assignment rule captured the placeholder — and
`rp::make().m()` reached the compound resolver as the free call
`rp::make`, whose name binds nothing. Neither had any route from the
qualified callee to its definition, so both typed nothing (`auto x =
rp::C()` likewise).
Fix:
- captures.ts promotes `auto x = ns::f()` / `auto x = ns::T()` (a
qualified_identifier whose innermost name is a plain identifier) to
@type-binding.constructor with the whole callee as the type, the
qualified twin of the bare rule; template factories keep their own
rule. interpret.ts drops any leftover `auto` / `decltype(auto)` binding,
which named no type.
- New ScopeResolver hook `splitQualifiedCallee` maps a callee spelling onto
the receiver/member pair the language's qualified CALL captures use (C++:
innermost scope segment, `a:🅱️:make` -> `b` / `make`), so shared code
never splits on `::`. The compound resolver's free-call branch, when the
callee's name binds nothing, resolves the definition through the existing
`resolveQualifiedReceiverMember` hook — the answer the call itself got —
and reads that definition's own return type by identity
(`producerTypeRef`). `auto x = rp::C()` resolves through the
qualified-type route instead.
Capture diff over the cpp corpus: one changed match outside the new
fixture (cpp-method-enrichment `auto category = Animal::classify(...)`
now binds the callee instead of `auto`; a class static method, which the
namespace lookup does not answer, so it stays untyped as before). Corpus
A/B: no edge or drop outside the fixture moved. bench/scope-capture cpp
re-baselined. The new cpp-captures rows also pin the namespace-scope gate
on prototype return types from the earlier commit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(cpp): bind qualified receiver owners
Preserve complete namespace qualifiers and declaration-owned return facts. Resolve inline namespace and chained alias types without borrowing unrelated functions or classes; cover review collision and header-order cases.
* fix(cpp): honor qualified type visibility
Carry header alias activation positions through include chains. Refuse unresolved type-owned qualifiers without rejecting value names, and align the lexical-ownership fixture with the scope-index contract.
* style(cpp): format inline namespace lookup
* fix(cpp): preserve factory lookup position
Keep later local type declarations from hiding an earlier namespace
factory. Name overload and class-factory recall limits explicitly.
Refs #3656
* fix(cpp): expand factory return aliases
Apply the provider qualified-type hook in producer-return lookup.
Keep authoritative refusals and the original declaration context.
Refs #3656
---------
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
668 lines
27 KiB
TypeScript
668 lines
27 KiB
TypeScript
/**
|
|
* Unit tests for C++ scope query + captures orchestrator.
|
|
*
|
|
* Pins the capture-tag vocabulary + range shape for every construct
|
|
* the scope-resolution pipeline reads. Runs against tree-sitter-cpp.
|
|
*/
|
|
|
|
import { describe, it, expect, beforeEach } from 'vitest';
|
|
import { emitCppScopeCaptures } from '../../../../src/core/ingestion/languages/cpp/captures.js';
|
|
import { cppProvider } from '../../../../src/core/ingestion/languages/c-cpp.js';
|
|
import { extractParsedFile } from '../../../../src/core/ingestion/scope-extractor-bridge.js';
|
|
import {
|
|
clearFileLocalNames,
|
|
isFileLocal,
|
|
} from '../../../../src/core/ingestion/languages/cpp/file-local-linkage.js';
|
|
|
|
function tagsFor(src: string, filePath = 'test.cpp'): string[][] {
|
|
const matches = emitCppScopeCaptures(src, filePath);
|
|
return matches.map((m) => Object.keys(m).sort());
|
|
}
|
|
|
|
function findMatch(src: string, predicate: (tags: string[]) => boolean, filePath = 'test.cpp') {
|
|
const matches = emitCppScopeCaptures(src, filePath);
|
|
return matches.find((m) => predicate(Object.keys(m)));
|
|
}
|
|
|
|
function allMatches(src: string, predicate: (tags: string[]) => boolean, filePath = 'test.cpp') {
|
|
const matches = emitCppScopeCaptures(src, filePath);
|
|
return matches.filter((m) => predicate(Object.keys(m)));
|
|
}
|
|
|
|
// ── Scopes ──────────────────────────────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — scopes', () => {
|
|
it('captures translation_unit as @scope.module', () => {
|
|
const all = tagsFor('int x = 1;');
|
|
expect(all.some((t) => t.includes('@scope.module'))).toBe(true);
|
|
});
|
|
|
|
it('captures class_specifier as @scope.class', () => {
|
|
const all = tagsFor('class Foo { int x; };');
|
|
expect(all.some((t) => t.includes('@scope.class'))).toBe(true);
|
|
});
|
|
|
|
it('captures struct_specifier as @scope.class', () => {
|
|
const all = tagsFor('struct Point { int x; int y; };');
|
|
expect(all.some((t) => t.includes('@scope.class'))).toBe(true);
|
|
});
|
|
|
|
it('captures namespace_definition as @scope.namespace', () => {
|
|
const all = tagsFor('namespace foo { int x; }');
|
|
expect(all.some((t) => t.includes('@scope.namespace'))).toBe(true);
|
|
});
|
|
|
|
it('captures function_definition as @scope.function', () => {
|
|
const all = tagsFor('void foo() { }');
|
|
expect(all.some((t) => t.includes('@scope.function'))).toBe(true);
|
|
});
|
|
|
|
it('captures lambda_expression as @scope.function', () => {
|
|
const all = tagsFor('auto f = [](int x) { return x; };');
|
|
expect(all.some((t) => t.includes('@scope.function'))).toBe(true);
|
|
});
|
|
|
|
it('captures block-level scopes (if, for, while, do, switch, case, try, catch)', () => {
|
|
const src = `
|
|
void f() {
|
|
if (true) { }
|
|
for (int i = 0; i < 10; i++) { }
|
|
while (true) { }
|
|
do { } while (false);
|
|
switch (0) { case 0: break; }
|
|
try { } catch (...) { }
|
|
}
|
|
`;
|
|
const all = tagsFor(src);
|
|
const blocks = all.filter((t) => t.includes('@scope.block'));
|
|
expect(blocks.length).toBeGreaterThanOrEqual(6);
|
|
});
|
|
|
|
it('captures for_range_loop as @scope.block', () => {
|
|
const src = `
|
|
#include <vector>
|
|
void f() {
|
|
std::vector<int> v;
|
|
for (auto& x : v) { }
|
|
}
|
|
`;
|
|
const all = tagsFor(src);
|
|
const blocks = all.filter((t) => t.includes('@scope.block'));
|
|
expect(blocks.length).toBeGreaterThanOrEqual(1);
|
|
});
|
|
});
|
|
|
|
// ── Declarations — classes / structs ────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — class declarations', () => {
|
|
it('captures named class with @declaration.class', () => {
|
|
const m = findMatch('class Foo { int x; };', (t) => t.includes('@declaration.class'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('Foo');
|
|
});
|
|
|
|
it('captures named struct with @declaration.struct', () => {
|
|
const m = findMatch('struct Point { int x; int y; };', (t) =>
|
|
t.includes('@declaration.struct'),
|
|
);
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('Point');
|
|
});
|
|
|
|
it('captures typedef anonymous struct with @declaration.struct (not typedef)', () => {
|
|
const src = 'typedef struct { int x; int y; } Point;';
|
|
const m = findMatch(src, (t) => t.includes('@declaration.struct'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('Point');
|
|
|
|
const typedefs = allMatches(src, (t) => t.includes('@declaration.typedef'));
|
|
expect(typedefs).toHaveLength(0);
|
|
});
|
|
|
|
it('captures template class with @declaration.class', () => {
|
|
const m = findMatch('template <typename T> class Container { T val; };', (t) =>
|
|
t.includes('@declaration.class'),
|
|
);
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('Container');
|
|
});
|
|
});
|
|
|
|
// ── Declarations — namespaces ───────────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — namespace declarations', () => {
|
|
it('captures named namespace with @declaration.namespace', () => {
|
|
const m = findMatch('namespace foo { int x; }', (t) => t.includes('@declaration.namespace'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('foo');
|
|
});
|
|
|
|
it('anonymous namespace has no @declaration.namespace (only @scope.namespace)', () => {
|
|
const matches = allMatches('namespace { int x; }', (t) => t.includes('@declaration.namespace'));
|
|
// Anonymous namespace should NOT produce a @declaration.namespace
|
|
expect(matches.length).toBe(0);
|
|
});
|
|
});
|
|
|
|
// ── Declarations — functions / methods ──────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — function declarations', () => {
|
|
it('captures function definition with @declaration.function', () => {
|
|
const m = findMatch('void foo() {}', (t) => t.includes('@declaration.function'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('foo');
|
|
});
|
|
|
|
it('captures function with pointer return as @declaration.function', () => {
|
|
const m = findMatch('int* create() {}', (t) => t.includes('@declaration.function'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('create');
|
|
});
|
|
|
|
it('captures out-of-class method (qualified_identifier) as @declaration.method', () => {
|
|
const m = findMatch('void Foo::bar() {}', (t) => t.includes('@declaration.method'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('bar');
|
|
});
|
|
|
|
it('captures destructor as @declaration.method', () => {
|
|
const m = findMatch('void Foo::~Foo() {}', (t) => t.includes('@declaration.method'));
|
|
expect(m).toBeDefined();
|
|
// destructor_name includes the ~
|
|
expect(m!['@declaration.name'].text).toContain('~');
|
|
});
|
|
|
|
it('captures inline method (field_identifier) as @declaration.method', () => {
|
|
const src = 'class Foo { void bar() {} };';
|
|
const m = findMatch(src, (t) => t.includes('@declaration.method'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('bar');
|
|
});
|
|
|
|
it('captures function prototype as @declaration.function', () => {
|
|
const m = findMatch('void foo();', (t) => t.includes('@declaration.function'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('foo');
|
|
});
|
|
|
|
it('captures template function as @declaration.function', () => {
|
|
const m = findMatch('template <typename T> void foo(T x) {}', (t) =>
|
|
t.includes('@declaration.function'),
|
|
);
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('foo');
|
|
});
|
|
});
|
|
|
|
// ── Declarations — fields ───────────────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — field declarations', () => {
|
|
it('captures plain field', () => {
|
|
const m = findMatch('class Foo { int val; };', (t) => t.includes('@declaration.field'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('val');
|
|
});
|
|
|
|
it('captures pointer field', () => {
|
|
const m = findMatch('class Foo { int* ptr; };', (t) => t.includes('@declaration.field'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('ptr');
|
|
});
|
|
|
|
it('captures reference field', () => {
|
|
const m = findMatch('class Foo { int& ref; };', (t) => t.includes('@declaration.field'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('ref');
|
|
});
|
|
});
|
|
|
|
// ── Declarations — variables ────────────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — variable declarations', () => {
|
|
it('captures variable with initializer', () => {
|
|
const m = findMatch('int x = 42;', (t) => t.includes('@declaration.variable'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('x');
|
|
});
|
|
|
|
it('captures all names in mixed initialized and uninitialized declarations', () => {
|
|
const matches = allMatches('void f() { int a = 1, b, *p, c = 3, d; }', (t) =>
|
|
t.includes('@declaration.variable'),
|
|
);
|
|
const names = matches.map((m) => m['@declaration.name'].text).sort();
|
|
expect(names).toEqual(['a', 'b', 'c', 'd', 'p']);
|
|
});
|
|
|
|
it('captures qualified-type multi-declarator variables', () => {
|
|
const src = 'namespace data { struct Pair {}; } void f() { data::Pair a, b; }';
|
|
const matches = allMatches(src, (t) => t.includes('@declaration.variable'));
|
|
const names = matches.map((m) => m['@declaration.name'].text).sort();
|
|
expect(names).toEqual(['a', 'b']);
|
|
});
|
|
});
|
|
|
|
// ── Declarations — enums ────────────────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — enum declarations', () => {
|
|
it('captures enum with @declaration.enum', () => {
|
|
const m = findMatch('enum Color { Red, Green, Blue };', (t) => t.includes('@declaration.enum'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('Color');
|
|
});
|
|
|
|
it('captures enum constants with @declaration.const', () => {
|
|
const matches = allMatches('enum Color { Red, Green, Blue };', (t) =>
|
|
t.includes('@declaration.const'),
|
|
);
|
|
expect(matches.length).toBe(3);
|
|
const names = matches.map((m) => m['@declaration.name'].text).sort();
|
|
expect(names).toEqual(['Blue', 'Green', 'Red']);
|
|
});
|
|
|
|
it('captures typedef anonymous enum with @declaration.enum (not typedef)', () => {
|
|
const src = 'typedef enum { Red, Green, Blue } Color;';
|
|
const m = findMatch(src, (t) => t.includes('@declaration.enum'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('Color');
|
|
|
|
const typedefs = allMatches(src, (t) => t.includes('@declaration.typedef'));
|
|
expect(typedefs).toHaveLength(0);
|
|
});
|
|
});
|
|
|
|
// ── Declarations — typedef / alias ──────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — typedef/alias declarations', () => {
|
|
it('captures typedef as @declaration.typedef', () => {
|
|
const m = findMatch('typedef int MyInt;', (t) => t.includes('@declaration.typedef'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('MyInt');
|
|
});
|
|
|
|
it('captures using alias as @declaration.typedef', () => {
|
|
const m = findMatch('using MyInt = int;', (t) => t.includes('@declaration.typedef'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('MyInt');
|
|
});
|
|
});
|
|
|
|
// ── Declarations — macros ───────────────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — macro declarations', () => {
|
|
it('captures #define as @declaration.macro', () => {
|
|
const m = findMatch('#define MAX 100', (t) => t.includes('@declaration.macro'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('MAX');
|
|
});
|
|
|
|
it('captures #define function as @declaration.macro', () => {
|
|
const m = findMatch('#define ADD(a,b) ((a)+(b))', (t) => t.includes('@declaration.macro'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.name'].text).toBe('ADD');
|
|
});
|
|
});
|
|
|
|
// ── Imports ─────────────────────────────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — imports', () => {
|
|
it('captures #include local as wildcard import', () => {
|
|
const m = findMatch('#include "foo.h"', (t) => t.includes('@import.source'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@import.source'].text).toBe('foo.h');
|
|
expect(m!['@import.kind'].text).toBe('wildcard');
|
|
expect(m!['@import.system']).toBeUndefined();
|
|
});
|
|
|
|
it('captures #include system with system marker', () => {
|
|
const m = findMatch('#include <iostream>', (t) => t.includes('@import.source'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@import.source'].text).toBe('iostream');
|
|
expect(m!['@import.system']).toBeDefined();
|
|
});
|
|
|
|
it('captures using namespace as wildcard import', () => {
|
|
const m = findMatch('using namespace std;', (t) => t.includes('@import.using-namespace'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@import.source'].text).toBe('std');
|
|
expect(m!['@import.kind'].text).toBe('wildcard');
|
|
});
|
|
|
|
it('captures using declaration as named import', () => {
|
|
const m = findMatch('using std::vector;', (t) => t.includes('@import.name'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@import.source'].text).toBe('std');
|
|
expect(m!['@import.name'].text).toBe('vector');
|
|
expect(m!['@import.kind'].text).toBe('named');
|
|
});
|
|
});
|
|
|
|
// ── References ──────────────────────────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — references', () => {
|
|
it('captures free call', () => {
|
|
const src = 'void f() { foo(); }';
|
|
const m = findMatch(src, (t) => t.includes('@reference.call.free'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@reference.name'].text).toBe('foo');
|
|
});
|
|
|
|
it('captures member call (obj.method())', () => {
|
|
const src = 'void f() { obj.method(); }';
|
|
const m = findMatch(src, (t) => t.includes('@reference.call.member'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@reference.name'].text).toBe('method');
|
|
});
|
|
|
|
it('captures member call (ptr->method())', () => {
|
|
const src = 'void f() { ptr->method(); }';
|
|
const m = findMatch(src, (t) => t.includes('@reference.call.member'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@reference.name'].text).toBe('method');
|
|
});
|
|
|
|
it('captures qualified call (Namespace::func())', () => {
|
|
const src = 'void f() { Foo::bar(); }';
|
|
const m = findMatch(src, (t) => t.includes('@reference.call.qualified'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@reference.name'].text).toBe('bar');
|
|
});
|
|
|
|
it('captures field read', () => {
|
|
const src = 'void f() { int x = obj.val; }';
|
|
const m = findMatch(src, (t) => t.includes('@reference.read'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@reference.name'].text).toBe('val');
|
|
});
|
|
|
|
it('captures field write', () => {
|
|
const src = 'void f() { obj.val = 42; }';
|
|
const m = findMatch(src, (t) => t.includes('@reference.write'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@reference.name'].text).toBe('val');
|
|
});
|
|
});
|
|
|
|
// ── Type bindings ───────────────────────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — type bindings', () => {
|
|
it('captures parameter type binding', () => {
|
|
const src = 'void foo(int x) {}';
|
|
const m = findMatch(src, (t) => t.includes('@type-binding.parameter'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@type-binding.name'].text).toBe('x');
|
|
});
|
|
|
|
it('captures variable type binding', () => {
|
|
const src = 'int x = 42;';
|
|
const m = findMatch(src, (t) => t.includes('@type-binding.assignment'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@type-binding.name'].text).toBe('x');
|
|
});
|
|
});
|
|
|
|
// ── Arity enrichment ────────────────────────────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — arity enrichment', () => {
|
|
it('enriches function declaration with parameter count', () => {
|
|
const m = findMatch('void foo(int x, int y) {}', (t) =>
|
|
t.includes('@declaration.parameter-count'),
|
|
);
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.parameter-count'].text).toBe('2');
|
|
});
|
|
|
|
it('enriches zero-parameter function', () => {
|
|
const m = findMatch('void foo() {}', (t) => t.includes('@declaration.parameter-count'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.parameter-count'].text).toBe('0');
|
|
});
|
|
|
|
it('detects default parameters (required < total)', () => {
|
|
const m = findMatch('void foo(int x, int y = 5) {}', (t) =>
|
|
t.includes('@declaration.required-parameter-count'),
|
|
);
|
|
expect(m).toBeDefined();
|
|
expect(m!['@declaration.required-parameter-count'].text).toBe('1');
|
|
expect(m!['@declaration.parameter-count'].text).toBe('2');
|
|
});
|
|
|
|
it('tags deleted declarations but not defaulted declarations', () => {
|
|
const deleted = findMatch('void foo(int) = delete;', (tags) =>
|
|
tags.includes('@declaration.is-deleted'),
|
|
);
|
|
const defaulted = emitCppScopeCaptures('struct S { S() = default; };', 'test.cpp').find(
|
|
(match) => Object.values(match).some((capture) => capture.text.includes('= default')),
|
|
);
|
|
|
|
expect(deleted?.['@declaration.is-deleted'].text).toBe('true');
|
|
expect(defaulted).toBeDefined();
|
|
expect(defaulted?.['@declaration.is-deleted']).toBeUndefined();
|
|
});
|
|
|
|
it('tags deleted free operators', () => {
|
|
const deleted = findMatch(
|
|
'struct S {}; bool operator==(const S&, const S&) = delete;',
|
|
(tags) => tags.includes('@declaration.is-deleted'),
|
|
);
|
|
|
|
expect(deleted?.['@declaration.name'].text).toBe('operator==');
|
|
expect(deleted?.['@declaration.is-deleted'].text).toBe('true');
|
|
});
|
|
|
|
it('tags deleted pointer-return free functions', () => {
|
|
const deleted = findMatch('int* lookup(int) = delete;', (tags) =>
|
|
tags.includes('@declaration.is-deleted'),
|
|
);
|
|
|
|
expect(deleted?.['@declaration.name'].text).toBe('lookup');
|
|
expect(deleted?.['@declaration.is-deleted'].text).toBe('true');
|
|
});
|
|
|
|
it('does not borrow a deleted initializer from another declarator', () => {
|
|
const declarations = allMatches('void f(int), g = delete(new int);', (tags) =>
|
|
tags.includes('@declaration.function'),
|
|
);
|
|
const f = declarations.find((match) => match['@declaration.name']?.text === 'f');
|
|
|
|
expect(f).toBeDefined();
|
|
expect(f?.['@declaration.is-deleted']).toBeUndefined();
|
|
});
|
|
|
|
it('preserves deleted-callable metadata in parsed local definitions', () => {
|
|
const parsed = extractParsedFile(
|
|
cppProvider,
|
|
`
|
|
void choose(int) = delete;
|
|
struct S {
|
|
S() = default;
|
|
void touch(double) = delete;
|
|
};
|
|
`,
|
|
'test.cpp',
|
|
);
|
|
|
|
const choose = parsed?.localDefs.find((def) => def.qualifiedName === 'choose');
|
|
const touch = parsed?.localDefs.find((def) => def.qualifiedName === 'touch');
|
|
const constructor = parsed?.localDefs.find(
|
|
(def) => def.type === 'Constructor' && def.qualifiedName === 'S',
|
|
);
|
|
|
|
expect(choose?.isDeleted).toBe(true);
|
|
expect(touch?.isDeleted).toBe(true);
|
|
expect(constructor?.isDeleted).not.toBe(true);
|
|
});
|
|
|
|
it('enriches call reference with arity', () => {
|
|
const src = 'void f() { foo(1, 2, 3); }';
|
|
const m = findMatch(src, (t) => t.includes('@reference.arity'));
|
|
expect(m).toBeDefined();
|
|
expect(m!['@reference.arity'].text).toBe('3');
|
|
});
|
|
});
|
|
|
|
// ── Static / anonymous namespace detection ──────────────────────────────────
|
|
|
|
describe('emitCppScopeCaptures — file-local linkage', () => {
|
|
beforeEach(() => {
|
|
clearFileLocalNames();
|
|
});
|
|
|
|
it('detects static function as file-local', () => {
|
|
emitCppScopeCaptures('static void helper() {}', 'test.cpp');
|
|
expect(isFileLocal('test.cpp', 'helper')).toBe(true);
|
|
});
|
|
|
|
it('does not mark non-static function as file-local', () => {
|
|
emitCppScopeCaptures('void helper() {}', 'test.cpp');
|
|
expect(isFileLocal('test.cpp', 'helper')).toBe(false);
|
|
});
|
|
|
|
it('detects function in anonymous namespace as file-local', () => {
|
|
emitCppScopeCaptures('namespace { void helper() {} }', 'test.cpp');
|
|
expect(isFileLocal('test.cpp', 'helper')).toBe(true);
|
|
});
|
|
|
|
it('does not mark function in named namespace as file-local', () => {
|
|
emitCppScopeCaptures('namespace foo { void helper() {} }', 'test.cpp');
|
|
expect(isFileLocal('test.cpp', 'helper')).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe('emitCppScopeCaptures — callable-flow passing modes (#2522 review, M5)', () => {
|
|
function modesFor(src: string): Record<string, string | undefined> {
|
|
const out: Record<string, string | undefined> = {};
|
|
for (const m of emitCppScopeCaptures(src, 'modes.cpp')) {
|
|
const binding = m['@callable-flow.binding']?.text;
|
|
if (m['@callable-flow.formal'] === undefined || binding === undefined) continue;
|
|
out[`${m['@callable-flow.owner']?.text}.${binding}`] = m['@callable-flow.passing-mode']?.text;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
it('classifies by the outermost declarator chain, never nested parameter lists', () => {
|
|
const modes = modesFor(
|
|
[
|
|
'void reg(void (*cb)(int& out)) {}',
|
|
'void take(int& v) {}',
|
|
'void raw(int* p) {}',
|
|
'void val(int v) {}',
|
|
'void refptr(void (*&cb)(int)) {}',
|
|
].join('\n'),
|
|
);
|
|
expect(modes).toMatchObject({
|
|
// by-value pointer copy — the nested `int&` must not make it an alias
|
|
'reg.cb': 'pointer',
|
|
'take.v': 'reference',
|
|
'raw.p': 'pointer',
|
|
'val.v': 'value',
|
|
// reference-to-pointer IS an alias
|
|
'refptr.cb': 'reference',
|
|
});
|
|
});
|
|
});
|
|
|
|
/**
|
|
* `TypeRef.declaredSpelling` for a C++ pointer parameter.
|
|
*
|
|
* tree-sitter-cpp hangs the `*` on the DECLARATOR, so `@type-binding.type` is a
|
|
* bare `User` and the binding records `User` — indistinguishable from a class
|
|
* the source subscripted through `operator[]`. The receiver-chain fold declines
|
|
* an index step without container evidence, so `repos[0].save()` depends
|
|
* entirely on the spelling being reconstructed here.
|
|
*/
|
|
describe('C++ pointer parameter — declared spelling', () => {
|
|
function bindingsFor(src: string): Record<string, { raw: string; spelling: string | undefined }> {
|
|
const parsed = extractParsedFile(cppProvider, src, 'test.cpp');
|
|
const out: Record<string, { raw: string; spelling: string | undefined }> = {};
|
|
for (const scope of parsed?.scopes ?? []) {
|
|
for (const [name, ref] of scope.typeBindings) {
|
|
out[name] = { raw: ref.rawName, spelling: ref.declaredSpelling };
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
it('reconstructs `User*` for a pointer parameter and leaves a value parameter alone', () => {
|
|
expect(bindingsFor('struct User {};\nvoid f(User* repos, User one) {}\n')).toMatchObject({
|
|
repos: { raw: 'User', spelling: 'User*' },
|
|
// Nothing was normalized away, so there is no spelling to keep — and an
|
|
// index step on it correctly finds no container evidence.
|
|
one: { raw: 'User', spelling: undefined },
|
|
});
|
|
});
|
|
|
|
it('reconstructs the same spelling regardless of where the star is written', () => {
|
|
expect(bindingsFor('struct User {};\nvoid f(User *repos) {}\n')).toMatchObject({
|
|
repos: { raw: 'User', spelling: 'User*' },
|
|
});
|
|
});
|
|
|
|
it('reconstructs NOTHING for shapes the exact match rejects', () => {
|
|
// Each of these is a real pointer-ish declaration whose element type is NOT
|
|
// the captured type: a reference is not a container at all, and `const T*`
|
|
// is not the shape being matched. A loose match would claim container
|
|
// evidence and re-mint the wrong edge.
|
|
const bindings = bindingsFor(
|
|
'struct User {};\nvoid f(User** grid, User& one, const User* ro, User (*fn)(int)) {}\n',
|
|
);
|
|
expect(bindings).toMatchObject({
|
|
one: { spelling: undefined },
|
|
ro: { spelling: undefined },
|
|
});
|
|
// `User**` matches no type-binding pattern at all, so there is no binding to
|
|
// carry evidence — the same safe outcome by a different route.
|
|
expect(bindings).not.toHaveProperty('grid');
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Which name a declaration binds, and to what type — for the shapes where the
|
|
* written declaration names no type directly (`auto`) or names it in a way only
|
|
* one syntactic position may claim (a function prototype).
|
|
*/
|
|
describe('C++ deduced and prototype type bindings', () => {
|
|
function rawTypeOf(src: string, name: string): string | undefined {
|
|
const parsed = extractParsedFile(cppProvider, src, 'test.cpp');
|
|
const refs = (parsed?.scopes ?? []).flatMap((scope) => {
|
|
const ref = scope.typeBindings.get(name);
|
|
return ref === undefined ? [] : [ref.rawName];
|
|
});
|
|
return refs[0];
|
|
}
|
|
|
|
it.each<[string, string, string | undefined]>([
|
|
// `auto` names no type; a leftover placeholder binds nothing.
|
|
['void f() { auto n = 5; }', 'n', undefined],
|
|
['auto g = [](auto v) { return v; };', 'v', undefined],
|
|
// A qualified callee is bound as written, like a bare one.
|
|
['void f() { auto x = make(); }', 'x', 'make'],
|
|
['void f() { auto x = rp::make(); }', 'x', 'rp::make'],
|
|
['void f() { auto x = a::b::make(); }', 'x', 'a::b::make'],
|
|
// A template factory keeps its dedicated rule (the template argument).
|
|
['void f() { auto x = std::make_shared<Dog>(); }', 'x', 'Dog'],
|
|
// A prototype records its return type at namespace scope, through an
|
|
// include guard, and never in a function body (the most vexing parse).
|
|
['D makeD();', 'makeD', 'D'],
|
|
['D* makeP();', 'makeP', 'D'],
|
|
['#ifndef G\n#define G\nnamespace rp { C make(); }\n#endif\n', 'make', 'C'],
|
|
['void f() { E y(); }', 'y', undefined],
|
|
])('%s binds %s to %s', (src, name, expected) => {
|
|
expect(rawTypeOf(src, name)).toBe(expected);
|
|
});
|
|
});
|
|
|
|
describe('written operator positions', () => {
|
|
it('keeps distinct synthetic operator references on their actual tokens', () => {
|
|
const source = 'int combine(A a, A b, A c) { return a + b + c; }';
|
|
const operators = emitCppScopeCaptures(source, 'operators.cpp')
|
|
.filter((match) => match['@reference.operator'])
|
|
.map((match) => match['@reference.name']);
|
|
const columns = [...new Set(operators.map((capture) => capture.range.startCol))].sort(
|
|
(a, b) => a - b,
|
|
);
|
|
expect(columns).toEqual([source.indexOf('+'), source.lastIndexOf('+')]);
|
|
for (const operator of operators) {
|
|
expect(operator.range.endCol - operator.range.startCol).toBe(1);
|
|
}
|
|
});
|
|
});
|