1
0

branch-guards.test.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import { describe, it, expect, beforeAll, afterEach } from 'vitest';
  2. import * as fs from 'fs';
  3. import * as os from 'os';
  4. import * as path from 'path';
  5. import { CodeGraph } from '../src';
  6. import { initGrammars } from '../src/extraction/grammars';
  7. import { guardsInSource, guardLabel, supportsBranchGuards } from '../src/graph/branch-guards';
  8. import { buildNode } from '../src/ui-server/api/node';
  9. import { buildFlow } from '../src/ui-server/api/flow';
  10. beforeAll(async () => {
  11. await initGrammars();
  12. });
  13. /** Line (1-based) of the first line containing `needle`. */
  14. function lineOf(src: string, needle: string): number {
  15. const i = src.split('\n').findIndex((l) => l.includes(needle));
  16. if (i < 0) throw new Error(`no line contains ${needle}`);
  17. return i + 1;
  18. }
  19. async function labelAt(src: string, needle: string, language: 'tsx' | 'typescript' | 'swift' = 'tsx') {
  20. const line = lineOf(src, needle);
  21. const column = src.split('\n')[line - 1]!.indexOf(needle);
  22. return guardLabel(await guardsInSource(src, language, line, column));
  23. }
  24. describe('branch guards: JS/TS', () => {
  25. const handlePress = `
  26. export function ItemCard(props) {
  27. const handlePress = useCallback(() => {
  28. if (isUploading) return
  29. if (isCollected) {
  30. openObjectDetail(item, folderName)
  31. return
  32. }
  33. if (queueHasItems) {
  34. handleAddToQueue()
  35. return
  36. }
  37. handleStartCapture()
  38. }, [])
  39. return null
  40. }
  41. `;
  42. it('reads an if branch and the early-return guards before it', async () => {
  43. expect(await labelAt(handlePress, 'openObjectDetail(')).toBe('!isUploading && isCollected');
  44. });
  45. it('turns each earlier early-return into a negated guard, in source order', async () => {
  46. expect(await labelAt(handlePress, 'handleAddToQueue(')).toBe('!isUploading && !isCollected && queueHasItems');
  47. expect(await labelAt(handlePress, 'handleStartCapture(')).toBe('!isUploading && !isCollected && !queueHasItems');
  48. });
  49. it('does not climb past a function that is declared or assigned to a name', async () => {
  50. const src = `
  51. function outer() {
  52. if (outerCond) {
  53. const cb = () => {
  54. if (inner) run()
  55. }
  56. function named() { if (deep) walk() }
  57. }
  58. }`;
  59. expect(await labelAt(src, 'run()')).toBe('inner');
  60. expect(await labelAt(src, 'walk()')).toBe('deep');
  61. });
  62. it('an inline callback inherits the conditions its definition sits under', async () => {
  63. const src = `
  64. function verify(total) {
  65. if (selectedHasBarcode) {
  66. if (total > 1) {
  67. return { proceed: () => router.navigate('/barcode-matches') }
  68. }
  69. return { ok: true, proceed: () => captureObject(item) }
  70. }
  71. list.forEach((x) => { if (x.ok) keep(x) })
  72. }`;
  73. expect(await labelAt(src, 'captureObject(item)')).toBe('selectedHasBarcode && !(total > 1)');
  74. expect(await labelAt(src, "router.navigate(")).toBe('selectedHasBarcode && total > 1');
  75. expect(await labelAt(src, 'keep(x)')).toBe('!selectedHasBarcode && x.ok');
  76. });
  77. it('reads else, else-if, and the arms of a ternary', async () => {
  78. const src = `
  79. function f() {
  80. if (a) { one() } else if (b) { two() } else { three() }
  81. const x = ready ? go() : wait()
  82. }`;
  83. expect(await labelAt(src, 'one()')).toBe('a');
  84. expect(await labelAt(src, 'two()')).toBe('!a && b');
  85. expect(await labelAt(src, 'three()')).toBe('!a && !b');
  86. expect(await labelAt(src, 'go()')).toBe('ready');
  87. expect(await labelAt(src, 'wait()')).toBe('!ready');
  88. });
  89. it('reads switch cases, && / || short-circuits, and catch', async () => {
  90. const src = `
  91. function f() {
  92. switch (mode) {
  93. case 'verify': scan(); break
  94. default: capture()
  95. }
  96. ok && fire()
  97. ok || fallback()
  98. try { risky() } catch (e) { report(e) }
  99. }`;
  100. expect(await labelAt(src, 'scan()')).toBe("mode === 'verify'");
  101. expect(await labelAt(src, 'capture()')).toBe('mode: default');
  102. expect(await labelAt(src, 'fire()')).toBe('ok');
  103. expect(await labelAt(src, 'fallback()')).toBe('!ok');
  104. expect(await labelAt(src, 'report(e)')).toBe('on error');
  105. expect(await labelAt(src, 'risky()')).toBe('');
  106. });
  107. it('negates readably: a bare !x guard reads as x, a compound one is parenthesised', async () => {
  108. const src = `
  109. function f() {
  110. if (!ready) return
  111. if (a && b) { } else { alt() }
  112. if (count > 0) go()
  113. if (options?.verify !== false && (item.barcodes?.length ?? 0) > 0) verify()
  114. }`;
  115. expect(await labelAt(src, 'alt()')).toBe('ready && !(a && b)');
  116. expect(await labelAt(src, 'go()')).toBe('ready && count > 0');
  117. expect(await labelAt(src, 'verify()')).toBe('ready && options?.verify !== false && (item.barcodes?.length ?? 0) > 0');
  118. });
  119. it('a call inside a condition is not guarded by that condition', async () => {
  120. const src = `
  121. function f() {
  122. if (isReady()) run()
  123. }`;
  124. expect(await labelAt(src, 'isReady()')).toBe('');
  125. expect(await labelAt(src, 'run()')).toBe('isReady()');
  126. });
  127. it('an if whose body does not always exit is not a guard', async () => {
  128. const src = `
  129. function f() {
  130. if (x) { log() }
  131. go()
  132. }`;
  133. expect(await labelAt(src, 'go()')).toBe('');
  134. });
  135. it('caps a very long condition', async () => {
  136. const cond = 'a'.repeat(120);
  137. const src = `function f() {\n if (${cond}) go()\n}`;
  138. const label = await labelAt(src, 'go()');
  139. expect(label.length).toBeLessThan(90);
  140. expect(label.endsWith('…')).toBe(true);
  141. });
  142. });
  143. describe('branch guards: Swift', () => {
  144. it('reads guard, if/else, ternary and switch', async () => {
  145. const src = `
  146. func decide() {
  147. guard ready else { bail(); return }
  148. if isCollected { open() } else if other { two() } else { close() }
  149. let x = flag ? a() : b()
  150. switch mode { case .verify: scan() default: capture() }
  151. }`;
  152. expect(await labelAt(src, 'bail()', 'swift')).toBe('!ready');
  153. expect(await labelAt(src, 'open()', 'swift')).toBe('ready && isCollected');
  154. expect(await labelAt(src, 'two()', 'swift')).toBe('ready && !isCollected && other');
  155. expect(await labelAt(src, 'close()', 'swift')).toBe('ready && !isCollected && !other');
  156. expect(await labelAt(src, 'a()', 'swift')).toBe('ready && flag');
  157. expect(await labelAt(src, 'b()', 'swift')).toBe('ready && !flag');
  158. expect(await labelAt(src, 'scan()', 'swift')).toBe('ready && mode == .verify');
  159. expect(await labelAt(src, 'capture()', 'swift')).toBe('ready && mode: default');
  160. });
  161. it('joins multi-clause conditions and treats an early return as a guard', async () => {
  162. const src = `
  163. func f() {
  164. if let item = current, item.count > 0 { use(item) }
  165. if busy { return }
  166. go()
  167. }`;
  168. expect(await labelAt(src, 'use(item)', 'swift')).toBe('let item = current, item.count > 0');
  169. expect(await labelAt(src, 'go()', 'swift')).toBe('!busy');
  170. });
  171. });
  172. describe('branch guards: unsupported', () => {
  173. it('reports no guards for a language without rules', async () => {
  174. expect(supportsBranchGuards('python')).toBe(false);
  175. expect(await guardsInSource('def f():\n if x:\n go()\n', 'python', 3, 4)).toEqual([]);
  176. });
  177. });
  178. describe('branch guards: on the wire', () => {
  179. let dir: string | undefined;
  180. afterEach(() => {
  181. if (dir) fs.rmSync(dir, { recursive: true, force: true });
  182. dir = undefined;
  183. });
  184. it('labels symbol-view rails and flow connectors with the call site\'s conditions', async () => {
  185. dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-when-'));
  186. fs.mkdirSync(path.join(dir, 'src'));
  187. fs.writeFileSync(
  188. path.join(dir, 'src', 'app.ts'),
  189. 'export function helper() { return 1 }\n' +
  190. 'export function other() { return 2 }\n' +
  191. 'export function run(ready: boolean, busy: boolean) {\n' +
  192. ' if (busy) return\n' +
  193. ' if (ready) {\n' +
  194. ' helper()\n' +
  195. ' } else {\n' +
  196. ' other()\n' +
  197. ' }\n' +
  198. '}\n'
  199. );
  200. const cg = CodeGraph.initSync(dir);
  201. await cg.indexAll();
  202. const run = cg.getNodesByName('run')[0]!;
  203. const helper = cg.getNodesByName('helper')[0]!;
  204. type Rel = { node: { name: string }; edges: Array<{ when?: string }> };
  205. const view = (await buildNode(cg, dir, run.id)) as { outgoing: { items: Rel[] } };
  206. const byName = new Map(view.outgoing.items.map((r) => [r.node.name, r]));
  207. expect(byName.get('helper')?.edges[0]?.when).toBe('!busy && ready');
  208. expect(byName.get('other')?.edges[0]?.when).toBe('!busy && !ready');
  209. const callee = (await buildNode(cg, dir, helper.id)) as { incoming: { items: Rel[] } };
  210. expect(callee.incoming.items.find((r) => r.node.name === 'run')?.edges[0]?.when).toBe('!busy && ready');
  211. const flow = await buildFlow(cg, dir, new URLSearchParams('from=run&to=helper'));
  212. const hop = flow.flows[0]!.hops[1]!;
  213. expect(hop.edge?.when).toBe('!busy && ready');
  214. expect(hop.edge?.label).toBe('calls · when !busy && ready');
  215. cg.close();
  216. });
  217. });