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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Fixes

- VBA calls and property reads/writes now link even when their case differs from the declaration, such as `a.idcalc` for `IDCalc`, or a call on a variable declared `As EXPEDIENTE` reaching the class `Expediente`; an ambiguous match is still left unlinked. (#346)
- After `codegraph-vba sync`, a VBA property access or saved-query name that had no target now links once a later edit adds the missing `Property Get`/`Let`/`Set` or query, in any case, without re-indexing the file that uses it. Fixes part of #336. (#346)


## [3.1.0] - 2026-11-29

Expand Down
358 changes: 358 additions & 0 deletions __tests__/vba-case-insensitive-retry.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,358 @@
/**
* Issue #346 (and the sync part of #336): VBA names are case-insensitive, so
* - the call-stub resolver links `a.idcalc` to `Anexo.IDCalc`;
* - a member access whose accessor is added to the class later re-links on
* `sync()` without re-extracting the caller's file;
* - the failed-reference retry on sync finds a VBA ref whose case differs
* from the procedure that a changed file now declares;
* - an ambiguous case-insensitive match still fails closed;
* - every other language keeps its case-sensitive behaviour.
*
* Every test indexes its own temp project through the real pipeline.
*/
import { describe, it, expect, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { CodeGraph, DatabaseConnection, getDatabasePath } from '../src';
import type { Edge, Node } from '../src/types';

const CLS_HEADER = ['VERSION 1.0 CLASS', 'BEGIN', " MultiUse = -1 'True", 'END'];

const openProjects: Array<{ cg: CodeGraph; dir: string }> = [];

afterEach(async () => {
while (openProjects.length > 0) {
const { cg, dir } = openProjects.pop()!;
try {
await cg.close();
} catch {
// ignore close errors
}
if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
}
});

function cls(name: string, body: string[]): string {
return [...CLS_HEADER, `Attribute VB_Name = "${name}"`, 'Option Explicit', ...body, ''].join('\n');
}

function bas(name: string, body: string[]): string {
return [`Attribute VB_Name = "${name}"`, 'Option Explicit', ...body, ''].join('\n');
}

interface Project {
cg: CodeGraph;
dir: string;
write(rel: string, src: string): void;
}

async function buildProject(files: Record<string, string>): Promise<Project> {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vba-ci-retry-'));
const write = (rel: string, src: string): void => {
const full = path.join(dir, rel);
fs.mkdirSync(path.dirname(full), { recursive: true });
fs.writeFileSync(full, src);
};
for (const [rel, src] of Object.entries(files)) write(rel, src);
const cg = await CodeGraph.init(dir, { index: false });
openProjects.push({ cg, dir });
await cg.indexAll();
return { cg, dir, write };
}

function meta(x: { metadata?: unknown }): Record<string, unknown> {
return (x.metadata ?? {}) as Record<string, unknown>;
}

/** The real (non-stub) node with `qualifiedName` of `kind`, optionally a given accessor. */
function real(cg: CodeGraph, qualifiedName: string, accessor?: string, kind: Node['kind'] = 'function'): Node {
const name = qualifiedName.split('.').pop()!;
const hits = cg
.searchNodes(name, { kinds: [kind], limit: 100 })
.map((r) => r.node)
.filter(
(n) =>
n.qualifiedName === qualifiedName &&
meta(n).stub !== true &&
(accessor === undefined || meta(n).accessor === accessor),
);
expect(hits, `node ${qualifiedName}${accessor ? ` (${accessor})` : ''}`).toHaveLength(1);
return hits[0]!;
}

function callsInto(cg: CodeGraph, target: Node): Edge[] {
return cg.getIncomingEdges(target.id).filter((e) => e.kind === 'calls');
}

function callerNames(cg: CodeGraph, target: Node): string[] {
return [...new Set(callsInto(cg, target).map((e) => cg.getNode(e.source)?.name ?? '?'))].sort();
}

/** The `updatedAt` stamp of every node of one file, to prove it was not re-extracted. */
function fileStamp(cg: CodeGraph, filePath: string): string {
return cg
.getNodesInFile(filePath)
.map((n) => `${n.id}@${n.updatedAt}`)
.sort()
.join('\n');
}

describe('VBA case-insensitive call-stub resolution (#346)', () => {
it('links a call and a member access whose case differs from the declaration', async () => {
const { cg } = await buildProject({
'src/Anexo.cls': cls('Anexo', [
'Private m_Nombre As String',
'Public Function IDCalc() As String',
' IDCalc = "1"',
'End Function',
'Public Property Let nombre(ByVal v As String)',
' m_Nombre = v',
'End Property',
'Public Function registrar() As Long',
'End Function',
]),
'src/Usa.cls': cls('Usa', [
'Public Sub Lee(ByVal a As Anexo)',
' Debug.Print a.idcalc',
'End Sub',
'Public Sub Escribe(ByVal a As Anexo)',
' a.Nombre = "x"',
'End Sub',
'Public Sub Llama()',
' Dim a As New Anexo',
' a.Registrar',
'End Sub',
]),
});

const idcalc = real(cg, 'Anexo.IDCalc');
expect(callerNames(cg, idcalc)).toEqual(['Lee']);
for (const e of callsInto(cg, idcalc)) {
expect(meta(e).repointDecision).toBe('reponted-to-real');
expect(meta(e).stub).toBe(false);
}

const nombre = real(cg, 'Anexo.nombre', 'let');
expect(callerNames(cg, nombre)).toEqual(['Escribe']);
expect(callsInto(cg, nombre).map((e) => meta(e).access)).toEqual(['let']);

expect(callerNames(cg, real(cg, 'Anexo.registrar'))).toEqual(['Llama']);

// No case-mismatched stub is left dangling.
const stubs = cg
.searchNodes('Anexo', { languages: ['vba'], kinds: ['function'], limit: 100 })
.map((r) => r.node)
.filter((n) => meta(n).stub === true);
expect(stubs.map((n) => n.qualifiedName)).toEqual([]);
});

it('an ambiguous case-insensitive match still fails closed', async () => {
const { cg } = await buildProject({
'src/a/Anexo.cls': cls('Anexo', ['Public Function IDCalc() As String', 'End Function']),
'src/b/Anexo.cls': cls('Anexo', ['Public Function IdCalc() As String', 'End Function']),
'src/Usa.cls': cls('Usa', [
'Public Sub Llama(ByVal a As Anexo)',
' a.idcalc',
'End Sub',
]),
});
for (const n of cg
.searchNodes('IDCalc', { languages: ['vba'], kinds: ['function'], limit: 100 })
.map((r) => r.node)
.filter((n) => meta(n).stub !== true)) {
expect(callsInto(cg, n), `no edge into ${n.filePath}`).toEqual([]);
}
});
});

describe('VBA failed-reference retry on sync (#346, #336)', () => {
const ANEXO = cls('Anexo', [
'Public Property Get Nombre() As String',
'End Property',
]);
const USA = cls('Usa', [
'Public Sub Lee(ByVal a As Anexo)',
' Debug.Print a.Nombre',
' Debug.Print a.codigo',
'End Sub',
'Public Sub Escribe(ByVal a As Anexo)',
' a.Codigo = 2',
'End Sub',
]);

it('an accessor added later re-links the existing caller in an unchanged file', async () => {
const p = await buildProject({ 'src/Anexo.cls': ANEXO, 'src/Usa.cls': USA });
const { cg } = p;
expect(callerNames(cg, real(cg, 'Anexo.Nombre', 'get'))).toEqual(['Lee']);
const before = fileStamp(cg, 'src/Usa.cls');

p.write(
'src/Anexo.cls',
cls('Anexo', [
'Public Property Get Nombre() As String',
'End Property',
'Public Property Get Codigo() As Long',
'End Property',
'Public Property Let Codigo(ByVal v As Long)',
'End Property',
]),
);
await cg.sync();

// The caller file was not re-extracted.
expect(fileStamp(cg, 'src/Usa.cls')).toBe(before);

const get = real(cg, 'Anexo.Codigo', 'get');
const let_ = real(cg, 'Anexo.Codigo', 'let');
expect(callerNames(cg, get)).toEqual(['Lee']);
expect(callerNames(cg, let_)).toEqual(['Escribe']);
const [read] = callsInto(cg, get);
expect(meta(read!)).toMatchObject({
synthesizedBy: 'vba-member-access',
access: 'get',
receiverType: 'Anexo',
stub: false,
repointDecision: 'reponted-to-real',
});
expect(callsInto(cg, let_).map((e) => meta(e).access)).toEqual(['let']);
expect(callerNames(cg, real(cg, 'Anexo.Nombre', 'get'))).toEqual(['Lee']);

// A second sync that touches the class again keeps exactly one edge each.
p.write(
'src/Anexo.cls',
cls('Anexo', [
"' moved down a line",
'Public Property Get Nombre() As String',
'End Property',
'Public Property Get Codigo() As Long',
'End Property',
'Public Property Let Codigo(ByVal v As Long)',
'End Property',
]),
);
await cg.sync();
expect(callsInto(cg, real(cg, 'Anexo.Codigo', 'get'))).toHaveLength(1);
expect(callsInto(cg, real(cg, 'Anexo.Codigo', 'let'))).toHaveLength(1);
});

it('parks only a missing member of a project class, once per caller and accessor', async () => {
const p = await buildProject({
'src/Anexo.cls': cls('Anexo', ['Public Campo As Long', 'Public Property Get Nombre() As String', 'End Property']),
'src/Usa.cls': cls('Usa', [
'Public Sub Lee(ByVal a As Anexo, ByVal rs As Recordset)',
' Debug.Print a.Codigo',
' Debug.Print a.codigo',
' Debug.Print a.Campo',
' Debug.Print rs.EOF',
'End Sub',
]),
});
const db = DatabaseConnection.open(getDatabasePath(p.dir));
const rows = db
.getDb()
.prepare(
`SELECT reference_name, reference_kind, status, name_tail, metadata FROM unresolved_refs
WHERE json_extract(metadata, '$.synthesizedBy') = 'vba-member-access'`,
)
.all() as Array<Record<string, string>>;
db.close();
expect(rows.map((r) => ({ ...r, metadata: JSON.parse(r.metadata!) }))).toEqual([
{
reference_name: 'Anexo.Codigo',
reference_kind: 'calls',
status: 'failed',
name_tail: 'Codigo',
metadata: { synthesizedBy: 'vba-member-access', receiverType: 'Anexo', member: 'Codigo', access: 'get' },
},
]);
});

it('a member access to a public field never becomes a dangling stub or a retried row', async () => {
const p = await buildProject({
'src/Campo.cls': cls('Campo', ['Public Valor As Long']),
'src/Usa.cls': cls('Usa', [
'Public Sub Lee(ByVal c As Campo)',
' c.Valor = c.Valor + 1',
'End Sub',
]),
});
const { cg } = p;
const stubs = cg
.searchNodes('Valor', { languages: ['vba'], kinds: ['function'], limit: 50 })
.map((r) => r.node)
.filter((n) => n.qualifiedName === 'Campo.Valor');
expect(stubs).toEqual([]);
p.write('src/Otro.bas', bas('Otro', ['Public Function Valor() As Long', 'End Function']));
await cg.sync();
expect(callsInto(cg, real(cg, 'Valor'))).toEqual([]);
});

it('a saved-query name whose case differs re-links when the query is added later', async () => {
const p = await buildProject({
'src/modules/modDatos.bas': bas('modDatos', [
'Public Sub CargarPendientes()',
' Set rs = getdb().OpenRecordset("qrypendientes")',
'End Sub',
]),
});
const { cg } = p;
const before = fileStamp(cg, 'src/modules/modDatos.bas');
p.write('src/queries/qryPendientes.sql', 'SELECT Id FROM TbExpedientes;\n');
p.write('src/queries/queries.json', JSON.stringify({ queries: [{ name: 'qryPendientes' }] }));
await cg.sync();
expect(fileStamp(cg, 'src/modules/modDatos.bas')).toBe(before);
const query = cg.getNodesByKind('query').find((n) => n.name === 'qryPendientes');
expect(query).toBeDefined();
const from = cg.getIncomingEdges(query!.id).map((e) => cg.getNode(e.source)?.name);
expect(from).toEqual(['CargarPendientes']);
});

it('a bare call keeps the answer a full index gives (the generic matcher is unchanged)', async () => {
const files = {
'src/Uno.bas': bas('Uno', ['Public Sub Principal()', ' Call hacerAlgo', 'End Sub']),
'src/Dos.bas': bas('Dos', ['Public Sub HacerAlgo()', 'End Sub']),
};
const p = await buildProject({ 'src/Uno.bas': files['src/Uno.bas'] });
p.write('src/Dos.bas', files['src/Dos.bas']);
await p.cg.sync();
const fresh = await buildProject(files);
expect(callerNames(p.cg, real(p.cg, 'HacerAlgo'))).toEqual(callerNames(fresh.cg, real(fresh.cg, 'HacerAlgo')));
});

it('the retry fails closed when two later files declare the name in different case', async () => {
const p = await buildProject({
'src/Uno.bas': bas('Uno', ['Public Sub Principal()', ' Call hacerAlgo', 'End Sub']),
});
const { cg } = p;
p.write('src/Dos.bas', bas('Dos', ['Public Sub HacerAlgo()', 'End Sub']));
p.write('src/Tres.bas', bas('Tres', ['Public Sub HACERALGO()', 'End Sub']));
await cg.sync();
const fresh = await buildProject({
'src/Uno.bas': bas('Uno', ['Public Sub Principal()', ' Call hacerAlgo', 'End Sub']),
'src/Dos.bas': bas('Dos', ['Public Sub HacerAlgo()', 'End Sub']),
'src/Tres.bas': bas('Tres', ['Public Sub HACERALGO()', 'End Sub']),
});
// The synced graph answers exactly what a full index answers.
const answer = (g: CodeGraph) => ['HacerAlgo', 'HACERALGO'].map((q) => callerNames(g, real(g, q)).join(','));
expect(answer(cg)).toEqual(answer(fresh.cg));
});
});

describe('non-VBA languages stay case-sensitive (#346)', () => {
it('a TypeScript call whose case differs stays unresolved after index and sync', async () => {
const p = await buildProject({
'src/b.ts': ['export function main() {', ' doThing();', '}', ''].join('\n'),
});
const { cg } = p;
p.write('src/a.ts', ['export function DoThing() {}', 'export function dothing2() {}', ''].join('\n'));
await cg.sync();
expect(callsInto(cg, real(cg, 'DoThing'))).toEqual([]);

const fresh = await buildProject({
'src/b.ts': ['export function main() {', ' doThing();', '}', ''].join('\n'),
'src/a.ts': ['export function DoThing() {}', ''].join('\n'),
});
expect(callsInto(fresh.cg, real(fresh.cg, 'DoThing'))).toEqual([]);
});
});
10 changes: 9 additions & 1 deletion docs/vba-stub-repoint-decision.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,15 @@ Consumer impact:
- **Accessor narrowing.** Step 1 (exact `qualifiedName`) keeps only the candidates that match the access: `get` accepts a `Property Get` or a plain `Sub`/`Function`, while `let` and `set` accept only their own accessor. A `Property Get` and `Property Let` with the same name are therefore no longer `declined-ambiguous`.
- **No dangling member stubs.** A member-access stub that ends `declined-not-found` (a public field, an unknown member) is deleted together with its edges, instead of staying `stub:true`. `declined-ambiguous` member stubs are kept and stamped as before.
- **Receiver typing.** Typed parameters (`ByRef a As Anexo`) now type their receiver, so `a.Member` and `With a` produce class-qualified stubs. A receiver whose type cannot be deduced never becomes a class-qualified stub; its `With` members stay `member-with` unresolved references.
- **Known limitation.** On an incremental `codegraph sync`, a member-access stub deleted as `declined-not-found` is not re-created when the accessor is added to the class later without re-extracting the caller file. In that case run `codegraph index` (or touch the caller file) to get the edge.
- **Known limitation (resolved in #346).** On an incremental `codegraph sync`, a member-access stub deleted as `declined-not-found` was not re-created when the accessor was added to the class later without re-extracting the caller file. See "What #346 changed": the access is now kept as a `failed` reference and the sync links it.

## What #346 changed

- **Case-insensitive lookup.** VBA ignores case, so both steps of the resolver (exact `qualifiedName`, then the `.bas`-qualified fallback) retry without case when the exact form finds nothing: `a.idcalc` links to `Anexo.IDCalc`, and a call on a variable declared `As EXPEDIENTE` reaches the members of the class `Expediente`. A target the exact lookup reached is reached the same way; two or more case-insensitive candidates still end `declined-ambiguous`.
- **Parked member accesses.** When a member-access stub ends `declined-not-found` and its receiver is a class the project declares, the stub and its edges are still deleted, but each caller's access is kept as an `unresolved_refs` row: `reference_kind = 'calls'`, `status = 'failed'`, `reference_name = '<Class>.<Member>'`, `name_tail = '<Member>'` and `metadata = { synthesizedBy: 'vba-member-access', receiverType, member, access }`. There is one row per caller, member and accessor. Not parked: library types the project does not declare (`Recordset`, `Control`, `Form`), and members the class declares as a field or constant.
- **Sync retry.** The incremental sync's failed-reference retry also looks VBA rows up by their tail without case, so it finds `codigo` when a changed file declares `Codigo`. A parked member access resolves only through the strategy above, including accessor narrowing, never through generic name matching. The edge it creates carries the same metadata as a repointed stub edge (`synthesizedBy: 'vba-member-access'`, `access`, `stub: false`, `repointDecision: 'reponted-to-real'`). The row is kept, so a later edit that moves the accessor re-links it.
- **Saved-query names** (`OpenRecordset("qrypendientes")`) re-link the same way when the query is added later in another case.
- **Generic name matching is unchanged.** A bare call `hacerAlgo` still links to `HacerAlgo` only where a full index would, and a sync gives the same answer as a full index.

## Migration from the round-5 prompt

Expand Down
Loading