1
0

ts-field-classification.test.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. /**
  2. * TS/JS class-field kind classification (#808).
  3. *
  4. * `public_field_definition` (TS) / `field_definition` (JS) previously
  5. * extracted as method-kind nodes unconditionally, so a plain annotated field
  6. * (`public fonts: Fonts;`) was reported as a method — misrepresenting class
  7. * shape and defeating kind-based filtering (#756 had to work around it).
  8. *
  9. * Now classification follows the VALUE: arrow-function / function-expression
  10. * fields (and HOF-wrapped ones, mirroring resolveBody) stay methods; every
  11. * other field is a property. Parity requirements: the property keeps its
  12. * type-annotation `references` edge, visibility, and static-ness; method
  13. * fields keep walking their bodies (calls still attributed).
  14. */
  15. import { describe, it, expect, beforeAll, afterEach } from 'vitest';
  16. import * as fs from 'fs';
  17. import * as path from 'path';
  18. import * as os from 'os';
  19. import { CodeGraph } from '../src';
  20. import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  21. beforeAll(async () => {
  22. await initGrammars();
  23. await loadAllGrammars();
  24. });
  25. describe('TS/JS class field classification (#808)', () => {
  26. let tmpDir: string | undefined;
  27. afterEach(() => {
  28. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  29. tmpDir = undefined;
  30. });
  31. it('TS: plain fields are properties; function-valued fields are methods', async () => {
  32. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-808-ts-'));
  33. fs.writeFileSync(
  34. path.join(tmpDir, 'app.ts'),
  35. [
  36. 'declare function throttle(f: unknown, ms: number): unknown;',
  37. 'class Fonts {}',
  38. 'class History {}',
  39. 'class App {',
  40. ' public fonts: Fonts;', // plain annotated → property
  41. ' private history: History = new History();', // annotated + initializer → property
  42. ' interactiveCanvas: HTMLCanvasElement | null = null;', // union type → property
  43. ' count = 0;', // plain value → property
  44. ' static defaults = { a: 1 };', // object value → property
  45. ' onClick = () => { this.run(); };', // arrow field → method
  46. ' onScroll = throttle((e: Event) => { this.run(); }, 100);', // HOF-wrapped → method
  47. ' handler = function namedFn() {};', // function expression → method
  48. ' handleClick(): void {}', // real method
  49. ' get value(): number { return 1; }', // getter stays method
  50. ' run(): void {}',
  51. '}',
  52. ].join('\n')
  53. );
  54. const cg = CodeGraph.initSync(tmpDir);
  55. try {
  56. await cg.indexAll();
  57. const kindOf = (name: string) =>
  58. cg.getNodesByName(name).map((n) => n.kind).sort().join(',');
  59. expect(kindOf('fonts')).toBe('property');
  60. expect(kindOf('history')).toBe('property');
  61. expect(kindOf('interactiveCanvas')).toBe('property');
  62. expect(kindOf('count')).toBe('property');
  63. expect(kindOf('defaults')).toBe('property');
  64. expect(kindOf('onClick')).toBe('method');
  65. expect(kindOf('onScroll')).toBe('method');
  66. expect(kindOf('handler')).toBe('method');
  67. expect(kindOf('handleClick')).toBe('method');
  68. expect(kindOf('value')).toBe('method');
  69. // Parity: the property keeps its type-annotation reference edge.
  70. const fontsProp = cg.getNodesByName('fonts').find((n) => n.kind === 'property')!;
  71. const fontsRefs = cg
  72. .getOutgoingEdges(fontsProp.id)
  73. .filter((e) => e.kind === 'references')
  74. .map((e) => cg.getNode(e.target)?.name);
  75. expect(fontsRefs).toContain('Fonts');
  76. // Parity: visibility survives the property path.
  77. expect(fontsProp.visibility).toBe('public');
  78. const historyProp = cg.getNodesByName('history').find((n) => n.kind === 'property')!;
  79. expect(historyProp.visibility).toBe('private');
  80. // Parity: arrow-field bodies still walk — onClick calls run.
  81. const onClick = cg.getNodesByName('onClick')[0]!;
  82. const calls = cg
  83. .getOutgoingEdges(onClick.id)
  84. .filter((e) => e.kind === 'calls')
  85. .map((e) => cg.getNode(e.target)?.name);
  86. expect(calls).toContain('run');
  87. // Signature carries the declared type, C#-style "Type name".
  88. expect(fontsProp.signature).toBe('Fonts fonts');
  89. } finally {
  90. cg.destroy();
  91. tmpDir = undefined;
  92. }
  93. });
  94. it('JS: field_definition classifies the same way', async () => {
  95. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-808-js-'));
  96. fs.writeFileSync(
  97. path.join(tmpDir, 'app.js'),
  98. [
  99. 'class App {',
  100. ' count = 0;',
  101. ' config = { retries: 3 };',
  102. ' onClick = () => { this.run(); };',
  103. ' run() {}',
  104. '}',
  105. 'module.exports = App;',
  106. ].join('\n')
  107. );
  108. const cg = CodeGraph.initSync(tmpDir);
  109. try {
  110. await cg.indexAll();
  111. expect(cg.getNodesByName('count')[0]?.kind).toBe('property');
  112. expect(cg.getNodesByName('config')[0]?.kind).toBe('property');
  113. expect(cg.getNodesByName('onClick')[0]?.kind).toBe('method');
  114. } finally {
  115. cg.destroy();
  116. tmpDir = undefined;
  117. }
  118. });
  119. it('field initializers still register callbacks (fn-ref scan)', async () => {
  120. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-808-fnref-'));
  121. fs.writeFileSync(
  122. path.join(tmpDir, 'main.ts'),
  123. [
  124. 'function onSave(): void {}',
  125. 'function onLoad(): void {}',
  126. 'export class Registry {',
  127. ' static handlers = { save: onSave, load: onLoad };',
  128. '}',
  129. ].join('\n')
  130. );
  131. const cg = CodeGraph.initSync(tmpDir);
  132. try {
  133. await cg.indexAll();
  134. const onSave = cg.getNodesByName('onSave')[0]!;
  135. const fnRefs = cg
  136. .getIncomingEdges(onSave.id)
  137. .filter((e) => e.metadata?.fnRef === true);
  138. expect(fnRefs.length).toBeGreaterThan(0);
  139. } finally {
  140. cg.destroy();
  141. tmpDir = undefined;
  142. }
  143. });
  144. });