closure-collection-synthesizer.test.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  2. import * as fs from 'node:fs';
  3. import * as path from 'node:path';
  4. import * as os from 'node:os';
  5. import { CodeGraph } from '../src';
  6. /**
  7. * End-to-end synthesizer test for closure-collection dynamic dispatch.
  8. *
  9. * A method appends a closure to a collection property; another method iterates
  10. * that property *invoking each element* (`coll.forEach { $0() }`) — a dynamic
  11. * dispatch tree-sitter can't resolve, so a flow into the dispatcher dead-ends
  12. * before the registered closures. This is Alamofire's request-validation shape:
  13. * `DataRequest.validate` does `validators.write { $0.append(validator) }`, the
  14. * base `Request.didCompleteTask` runs `validators.forEach { $0() }`.
  15. *
  16. * Verify the synthesizer (1) links the dispatcher → each same-named registrar
  17. * across files/classes, (2) handles both the Swift `prop.write { $0.append }`
  18. * and the direct `prop.append(...)` registrar forms, (3) surfaces the wiring
  19. * site, and (4) does NOT fire on a `.forEach` that doesn't invoke its element
  20. * (the closure-invoke is the precision gate — a plain collection is skipped).
  21. */
  22. describe('closure-collection synthesizer', () => {
  23. let dir: string;
  24. beforeEach(() => {
  25. dir = fs.mkdtempSync(path.join(os.tmpdir(), 'closure-coll-fixture-'));
  26. });
  27. afterEach(() => {
  28. fs.rmSync(dir, { recursive: true, force: true });
  29. });
  30. it('links dispatcher → registrars across files, both append forms, and skips non-invoked collections', async () => {
  31. // Base class: the dispatchers (iterate-and-invoke) + a non-closure control.
  32. fs.writeFileSync(
  33. path.join(dir, 'Request.swift'),
  34. `class Request {
  35. var validators: [() -> Void] = []
  36. var handlers: [() -> Void] = []
  37. var names: [String] = []
  38. func didCompleteTask() {
  39. let validators = validators
  40. validators.forEach { $0() }
  41. }
  42. func runHandlers() {
  43. handlers.forEach { $0() }
  44. }
  45. func printNames() {
  46. names.forEach { print($0) }
  47. }
  48. }
  49. `
  50. );
  51. // Subclass: the registrars (append a closure) in a DIFFERENT file/class.
  52. fs.writeFileSync(
  53. path.join(dir, 'DataRequest.swift'),
  54. `class DataRequest: Request {
  55. func validate(_ validation: @escaping () -> Void) -> Self {
  56. let validator: () -> Void = { validation() }
  57. validators.write { $0.append(validator) }
  58. return self
  59. }
  60. func onEvent(_ handler: @escaping () -> Void) {
  61. handlers.append(handler)
  62. }
  63. func addName(_ n: String) {
  64. names.append(n)
  65. }
  66. }
  67. `
  68. );
  69. const cg = await CodeGraph.init(dir, { silent: true });
  70. await cg.indexAll();
  71. const db = (cg as any).db.db;
  72. const rows = db
  73. .prepare(
  74. `SELECT s.name source_name, s.kind source_kind, t.name target_name,
  75. json_extract(e.metadata,'$.field') field,
  76. json_extract(e.metadata,'$.registeredAt') registeredAt
  77. FROM edges e
  78. JOIN nodes s ON s.id = e.source
  79. JOIN nodes t ON t.id = e.target
  80. WHERE json_extract(e.metadata,'$.synthesizedBy') = 'closure-collection'`
  81. )
  82. .all();
  83. cg.close?.();
  84. expect(rows.length).toBeGreaterThan(0);
  85. // Every edge originates from a dispatcher method and is a real `calls` hop.
  86. expect(rows.every((r: any) => r.source_kind === 'method')).toBe(true);
  87. // The validators flow: didCompleteTask → validate, captured via the Swift
  88. // Protected `prop.write { $0.append }` form, wiring site surfaced.
  89. const validatorsEdge = rows.find(
  90. (r: any) => r.field === 'validators' && r.target_name === 'validate'
  91. );
  92. expect(validatorsEdge).toBeTruthy();
  93. expect(validatorsEdge.source_name).toBe('didCompleteTask');
  94. // Exact wiring-site line, not just shape: pins the binary-search line
  95. // resolver (#1235) to the same answer as the old per-match slice+split.
  96. expect(validatorsEdge.registeredAt).toBe('DataRequest.swift:4');
  97. // The handlers flow: runHandlers → onEvent, via the direct `prop.append`
  98. // form — proves both registrar shapes are covered.
  99. const handlersEdge = rows.find(
  100. (r: any) => r.field === 'handlers' && r.target_name === 'onEvent'
  101. );
  102. expect(handlersEdge).toBeTruthy();
  103. expect(handlersEdge.source_name).toBe('runHandlers');
  104. // Precision gate: `names.forEach { print($0) }` does NOT invoke its element,
  105. // so `names` is not a closure collection — no edge, and addName is never a target.
  106. expect(rows.some((r: any) => r.field === 'names')).toBe(false);
  107. expect(rows.some((r: any) => r.target_name === 'addName')).toBe(false);
  108. });
  109. it('is a no-op on non-Swift/Kotlin code even when the text patterns occur (#1235)', async () => {
  110. // JS that contains every textual trigger the scanner looks for —
  111. // `.forEach`, `.push(`, even a `{ $0(` lookalike inside a string — but
  112. // `{ $0( ` / `{ it( ` element-invocation is Swift/Kotlin trailing-closure
  113. // syntax, so the pass must skip the language entirely (this scan running
  114. // ungated over `.push(`-heavy JS/PHP was the #1235 25-minute index).
  115. fs.writeFileSync(
  116. path.join(dir, 'queue.js'),
  117. `class Queue {
  118. constructor() { this.tasks = []; }
  119. register(fn) { this.tasks.push(fn); }
  120. drain() { this.tasks.forEach(function (t) { t(); }); }
  121. weird() { const s = "tasks.forEach { $0( } tasks.push("; return s; }
  122. }
  123. module.exports = Queue;
  124. `
  125. );
  126. const cg = await CodeGraph.init(dir, { silent: true });
  127. await cg.indexAll();
  128. const db = (cg as any).db.db;
  129. const count = db
  130. .prepare(
  131. `SELECT count(*) c FROM edges
  132. WHERE json_extract(metadata,'$.synthesizedBy') = 'closure-collection'`
  133. )
  134. .get();
  135. cg.close?.();
  136. expect(count.c).toBe(0);
  137. });
  138. });