fuzzy-lexical-reach.test.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. /**
  2. * A function nested inside another function is only callable from inside its
  3. * container. matchByExactName already filters candidates that way; matchFuzzy
  4. * must too, or a call to a builtin method (`res.text()`) whose only same-named
  5. * project symbol is some file's closure resolves onto that closure.
  6. */
  7. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  8. import * as fs from 'fs';
  9. import * as path from 'path';
  10. import * as os from 'os';
  11. import { CodeGraph } from '../src';
  12. import { matchFuzzy } from '../src/resolution/name-matcher';
  13. import type { Node } from '../src/types';
  14. import type { ResolutionContext, UnresolvedRef } from '../src/resolution/types';
  15. describe('fuzzy matching respects lexical reachability of nested functions', () => {
  16. let tempDir: string;
  17. let cg: CodeGraph | null = null;
  18. beforeEach(() => {
  19. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-fuzzy-reach-'));
  20. });
  21. afterEach(() => {
  22. cg?.destroy();
  23. cg = null;
  24. try {
  25. fs.rmSync(tempDir, { recursive: true, force: true });
  26. } catch {
  27. // Windows can still hold the SQLite handle for a moment; the OS temp dir is swept anyway.
  28. }
  29. });
  30. it('does not resolve a builtin method call onto another file\'s closure of the same name', async () => {
  31. fs.writeFileSync(
  32. path.join(tempDir, 'seed.ts'),
  33. [
  34. 'export function readSeedState(raw: string): string {',
  35. ' function text(): string {',
  36. ' return raw.trim();',
  37. ' }',
  38. ' return text();',
  39. '}',
  40. '',
  41. ].join('\n')
  42. );
  43. fs.writeFileSync(
  44. path.join(tempDir, 'fetch.ts'),
  45. [
  46. 'export async function readOkText(settled: { value: Response }): Promise<string> {',
  47. ' // A chained receiver reaches the resolver as the bare method name.',
  48. ' return settled.value.text();',
  49. '}',
  50. '',
  51. ].join('\n')
  52. );
  53. cg = await CodeGraph.init(tempDir, { index: true });
  54. cg.resolveReferences();
  55. const closure = cg
  56. .getNodesByKind('function')
  57. .find((n) => n.name === 'text' && n.filePath === 'seed.ts');
  58. const caller = cg.getNodesByKind('function').find((n) => n.name === 'readOkText');
  59. expect(closure).toBeDefined();
  60. expect(caller).toBeDefined();
  61. const fromCaller = cg.getOutgoingEdges(caller!.id).filter((e) => e.kind === 'calls');
  62. expect(fromCaller.map((e) => e.target)).not.toContain(closure!.id);
  63. // The in-container call still resolves.
  64. const container = cg.getNodesByKind('function').find((n) => n.name === 'readSeedState');
  65. const inside = cg.getOutgoingEdges(container!.id).filter((e) => e.kind === 'calls');
  66. expect(inside.map((e) => e.target)).toContain(closure!.id);
  67. });
  68. });
  69. /**
  70. * The reachability check must sit on the one candidate matchFuzzy would
  71. * commit to, never on the candidate set. Filtering a crowd of same-named
  72. * definitions down to the reachable ones leaves a single survivor, and the
  73. * strategy then hands it every call of that name: vite has a dozen `resolve`
  74. * definitions, most nested, and one reachable `resolve` method inherited 59
  75. * `import { resolve } from 'node:path'` calls that way (#1709). Driven
  76. * directly, so the shape is pinned regardless of what the earlier strategies
  77. * make of a given fixture.
  78. */
  79. describe('fuzzy reachability rejects a unique guess but never manufactures one', () => {
  80. const node = (partial: Partial<Node> & Pick<Node, 'id' | 'kind' | 'name' | 'filePath'>): Node => ({
  81. qualifiedName: partial.name,
  82. language: 'typescript',
  83. startLine: 1,
  84. endLine: 1,
  85. startColumn: 0,
  86. endColumn: 0,
  87. updatedAt: 0,
  88. ...partial,
  89. });
  90. // build.ts: function build() { const resolve = …; function resolve() {} }
  91. const container = node({ id: 'f:build', kind: 'function', name: 'build', filePath: 'build.ts', startLine: 1, endLine: 40 });
  92. const closure = node({ id: 'f:build.resolve', kind: 'function', name: 'resolve', qualifiedName: 'build::resolve', filePath: 'build.ts', startLine: 10, endLine: 12 });
  93. // pluginContainer.ts: class PluginContainer { resolve() {} }
  94. const method = node({ id: 'm:resolve', kind: 'method', name: 'resolve', qualifiedName: 'PluginContainer::resolve', filePath: 'pluginContainer.ts', startLine: 5, endLine: 9 });
  95. const contextWith = (nodes: Node[]): ResolutionContext =>
  96. ({
  97. getNodesInFile: () => [],
  98. getNodesByName: (name: string) => nodes.filter((n) => n.name === name),
  99. getNodesByLowerName: (name: string) => nodes.filter((n) => n.name.toLowerCase() === name),
  100. getNodesByQualifiedName: (qn: string) => [container].filter((n) => n.qualifiedName === qn),
  101. getNodesByKind: () => [],
  102. fileExists: () => false,
  103. readFile: () => null,
  104. getFileLines: () => [],
  105. getProjectRoot: () => '',
  106. getAllFiles: () => [],
  107. getImportMappings: () => [],
  108. }) as unknown as ResolutionContext;
  109. const callFrom = (filePath: string, line: number): UnresolvedRef => ({
  110. fromNodeId: 'f:caller',
  111. referenceName: 'resolve',
  112. referenceKind: 'calls',
  113. line,
  114. column: 2,
  115. filePath,
  116. language: 'typescript',
  117. });
  118. it('declines the sole candidate when it is a closure the call cannot reach', () => {
  119. expect(matchFuzzy(callFrom('vite.config.js', 3), contextWith([closure]))).toBeNull();
  120. });
  121. it('still resolves the sole candidate from inside its container', () => {
  122. expect(matchFuzzy(callFrom('build.ts', 20), contextWith([closure]))?.targetNodeId).toBe('f:build.resolve');
  123. });
  124. it('does not let the unreachable closure drop out and leave the method as a "unique" match', () => {
  125. // Two same-named callables: ambiguous, exactly as before the check existed.
  126. expect(matchFuzzy(callFrom('vite.config.js', 3), contextWith([closure, method]))).toBeNull();
  127. });
  128. it('trusts no nesting in C, where a nested function is an extraction artifact', () => {
  129. // betaflight: tree-sitter-c's recovery from `RESET_CONFIG(…, .pid = {…})`
  130. // runs resetPidProfile to the end of pid.c, so every function after it is
  131. // "nested" in the graph. C has no nested named functions; the call reaches it.
  132. const cClosure = node({ ...closure, id: 'f:c', language: 'c' as Node['language'], filePath: 'pid.c' });
  133. const cRef = { ...callFrom('core.c', 3), language: 'c' as UnresolvedRef['language'] };
  134. expect(matchFuzzy(cRef, contextWith([cClosure]))?.targetNodeId).toBe('f:c');
  135. });
  136. it('resolves a lone reachable method as before', () => {
  137. expect(matchFuzzy(callFrom('vite.config.js', 3), contextWith([method]))?.targetNodeId).toBe('m:resolve');
  138. });
  139. });