branch-guards.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 { callArgumentsInSource, guardsInSource, guardLabel, supportsBranchGuards, triggerInSource } 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('keeps a disjunctive guard in parentheses, so the join stays unambiguous', async () => {
  46. const src = `
  47. function go(object) {
  48. if (isUploading) return
  49. if (!object?.id || !object?.name) {
  50. bail()
  51. return
  52. }
  53. proceed()
  54. }
  55. `;
  56. expect(await labelAt(src, 'bail(')).toBe('!isUploading && (!object?.id || !object?.name)');
  57. expect(await labelAt(src, 'proceed(')).toBe('!isUploading && !(!object?.id || !object?.name)');
  58. });
  59. it('turns each earlier early-return into a negated guard, in source order', async () => {
  60. expect(await labelAt(handlePress, 'handleAddToQueue(')).toBe('!isUploading && !isCollected && queueHasItems');
  61. expect(await labelAt(handlePress, 'handleStartCapture(')).toBe('!isUploading && !isCollected && !queueHasItems');
  62. });
  63. it('does not climb past a function that is declared or assigned to a name', async () => {
  64. const src = `
  65. function outer() {
  66. if (outerCond) {
  67. const cb = () => {
  68. if (inner) run()
  69. }
  70. function named() { if (deep) walk() }
  71. }
  72. }`;
  73. expect(await labelAt(src, 'run()')).toBe('inner');
  74. expect(await labelAt(src, 'walk()')).toBe('deep');
  75. });
  76. it('an inline callback inherits the conditions its definition sits under', async () => {
  77. const src = `
  78. function verify(total) {
  79. if (selectedHasBarcode) {
  80. if (total > 1) {
  81. return { proceed: () => router.navigate('/barcode-matches') }
  82. }
  83. return { ok: true, proceed: () => captureObject(item) }
  84. }
  85. list.forEach((x) => { if (x.ok) keep(x) })
  86. }`;
  87. expect(await labelAt(src, 'captureObject(item)')).toBe('selectedHasBarcode && !(total > 1)');
  88. expect(await labelAt(src, "router.navigate(")).toBe('selectedHasBarcode && total > 1');
  89. expect(await labelAt(src, 'keep(x)')).toBe('!selectedHasBarcode && x.ok');
  90. });
  91. it('reads else, else-if, and the arms of a ternary', async () => {
  92. const src = `
  93. function f() {
  94. if (a) { one() } else if (b) { two() } else { three() }
  95. const x = ready ? go() : wait()
  96. }`;
  97. expect(await labelAt(src, 'one()')).toBe('a');
  98. expect(await labelAt(src, 'two()')).toBe('!a && b');
  99. expect(await labelAt(src, 'three()')).toBe('!a && !b');
  100. expect(await labelAt(src, 'go()')).toBe('ready');
  101. expect(await labelAt(src, 'wait()')).toBe('!ready');
  102. });
  103. it('reads switch cases, && / || short-circuits, and catch', async () => {
  104. const src = `
  105. function f() {
  106. switch (mode) {
  107. case 'verify': scan(); break
  108. default: capture()
  109. }
  110. ok && fire()
  111. ok || fallback()
  112. try { risky() } catch (e) { report(e) }
  113. }`;
  114. expect(await labelAt(src, 'scan()')).toBe("mode === 'verify'");
  115. expect(await labelAt(src, 'capture()')).toBe('mode: default');
  116. expect(await labelAt(src, 'fire()')).toBe('ok');
  117. expect(await labelAt(src, 'fallback()')).toBe('!ok');
  118. expect(await labelAt(src, 'report(e)')).toBe('on error');
  119. expect(await labelAt(src, 'risky()')).toBe('');
  120. });
  121. it('negates readably: a bare !x guard reads as x, a compound one is parenthesised', async () => {
  122. const src = `
  123. function f() {
  124. if (!ready) return
  125. if (a && b) { } else { alt() }
  126. if (count > 0) go()
  127. if (options?.verify !== false && (item.barcodes?.length ?? 0) > 0) verify()
  128. }`;
  129. expect(await labelAt(src, 'alt()')).toBe('ready && !(a && b)');
  130. expect(await labelAt(src, 'go()')).toBe('ready && count > 0');
  131. expect(await labelAt(src, 'verify()')).toBe('ready && options?.verify !== false && (item.barcodes?.length ?? 0) > 0');
  132. });
  133. it('a call inside a condition is not guarded by that condition', async () => {
  134. const src = `
  135. function f() {
  136. if (isReady()) run()
  137. }`;
  138. expect(await labelAt(src, 'isReady()')).toBe('');
  139. expect(await labelAt(src, 'run()')).toBe('isReady()');
  140. });
  141. it('an if whose body does not always exit is not a guard', async () => {
  142. const src = `
  143. function f() {
  144. if (x) { log() }
  145. go()
  146. }`;
  147. expect(await labelAt(src, 'go()')).toBe('');
  148. });
  149. it('caps a very long condition', async () => {
  150. const cond = 'a'.repeat(120);
  151. const src = `function f() {\n if (${cond}) go()\n}`;
  152. const label = await labelAt(src, 'go()');
  153. expect(label.length).toBeLessThan(90);
  154. expect(label.endsWith('…')).toBe(true);
  155. });
  156. });
  157. describe('branch guards: Swift', () => {
  158. it('reads guard, if/else, ternary and switch', async () => {
  159. const src = `
  160. func decide() {
  161. guard ready else { bail(); return }
  162. if isCollected { open() } else if other { two() } else { close() }
  163. let x = flag ? a() : b()
  164. switch mode { case .verify: scan() default: capture() }
  165. }`;
  166. expect(await labelAt(src, 'bail()', 'swift')).toBe('!ready');
  167. expect(await labelAt(src, 'open()', 'swift')).toBe('ready && isCollected');
  168. expect(await labelAt(src, 'two()', 'swift')).toBe('ready && !isCollected && other');
  169. expect(await labelAt(src, 'close()', 'swift')).toBe('ready && !isCollected && !other');
  170. expect(await labelAt(src, 'a()', 'swift')).toBe('ready && flag');
  171. expect(await labelAt(src, 'b()', 'swift')).toBe('ready && !flag');
  172. expect(await labelAt(src, 'scan()', 'swift')).toBe('ready && mode == .verify');
  173. expect(await labelAt(src, 'capture()', 'swift')).toBe('ready && mode: default');
  174. });
  175. it('joins multi-clause conditions and treats an early return as a guard', async () => {
  176. const src = `
  177. func f() {
  178. if let item = current, item.count > 0 { use(item) }
  179. if busy { return }
  180. go()
  181. }`;
  182. expect(await labelAt(src, 'use(item)', 'swift')).toBe('let item = current, item.count > 0');
  183. expect(await labelAt(src, 'go()', 'swift')).toBe('!busy');
  184. });
  185. });
  186. describe('branch guards: unsupported', () => {
  187. it('reports no guards for a language without rules', async () => {
  188. expect(supportsBranchGuards('ruby')).toBe(false);
  189. expect(await guardsInSource('def f\n if x\n go()\n end\nend\n', 'ruby', 3, 4)).toEqual([]);
  190. });
  191. });
  192. describe('branch guards: on the wire', () => {
  193. let dir: string | undefined;
  194. afterEach(() => {
  195. if (dir) fs.rmSync(dir, { recursive: true, force: true });
  196. dir = undefined;
  197. });
  198. it('labels symbol-view rails and flow connectors with the call site\'s conditions', async () => {
  199. dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-when-'));
  200. fs.mkdirSync(path.join(dir, 'src'));
  201. fs.writeFileSync(
  202. path.join(dir, 'src', 'app.ts'),
  203. 'export function helper() { return 1 }\n' +
  204. 'export function other() { return 2 }\n' +
  205. 'export function run(ready: boolean, busy: boolean) {\n' +
  206. ' if (busy) return\n' +
  207. ' if (ready) {\n' +
  208. ' helper()\n' +
  209. ' } else {\n' +
  210. ' other()\n' +
  211. ' }\n' +
  212. '}\n'
  213. );
  214. const cg = CodeGraph.initSync(dir);
  215. await cg.indexAll();
  216. const run = cg.getNodesByName('run')[0]!;
  217. const helper = cg.getNodesByName('helper')[0]!;
  218. type Rel = { node: { name: string }; edges: Array<{ when?: string }> };
  219. const view = (await buildNode(cg, dir, run.id)) as { outgoing: { items: Rel[] } };
  220. const byName = new Map(view.outgoing.items.map((r) => [r.node.name, r]));
  221. expect(byName.get('helper')?.edges[0]?.when).toBe('!busy && ready');
  222. expect(byName.get('other')?.edges[0]?.when).toBe('!busy && !ready');
  223. const callee = (await buildNode(cg, dir, helper.id)) as { incoming: { items: Rel[] } };
  224. expect(callee.incoming.items.find((r) => r.node.name === 'run')?.edges[0]?.when).toBe('!busy && ready');
  225. const flow = await buildFlow(cg, dir, new URLSearchParams('from=run&to=helper'));
  226. const hop = flow.flows[0]!.hops[1]!;
  227. expect(hop.edge?.when).toBe('!busy && ready');
  228. expect(hop.edge?.label).toBe('calls · when !busy && ready');
  229. cg.close();
  230. });
  231. });
  232. // =============================================================================
  233. // Call arguments — what a site passes
  234. // =============================================================================
  235. async function argsAt(src: string, needle: string, language: 'tsx' | 'typescript' | 'swift' = 'tsx') {
  236. const line = lineOf(src, needle);
  237. const column = src.split('\n')[line - 1]!.indexOf(needle);
  238. return callArgumentsInSource(src, language, line, column);
  239. }
  240. describe('call arguments', () => {
  241. const login = `
  242. async function handleLogin(values) {
  243. await SecureStore.setItemAsync('userEmail', values.email)
  244. const res = await client.post('/auth/login', { email: values.email, password, ...rest })
  245. Alert.alert(i18n.t('error_login_failed'), err.message, [{ text: 'OK' }])
  246. router.push({ pathname: '/item/[id]', params: { id } })
  247. captureView.finalizeCaptureSession()
  248. run(() => go(), async (x) => x, new Thing(1))
  249. const big = fetch(\`/api/\${id}\`, { method: 'POST', headers, body, mode, cache, credentials })
  250. }
  251. `;
  252. it('keeps literals and names whole, folds objects to their keys, arrays and functions to a shape', async () => {
  253. expect(await argsAt(login, 'SecureStore.setItemAsync(')).toBe("'userEmail', values.email");
  254. expect(await argsAt(login, 'client.post(')).toBe("'/auth/login', { email, password, ...rest }");
  255. expect(await argsAt(login, 'Alert.alert(')).toBe('i18n.t(…), err.message, […]');
  256. expect(await argsAt(login, 'router.push(')).toBe('{ pathname, params }');
  257. expect(await argsAt(login, 'run(')).toBe('() => …, () => …, new Thing(…)');
  258. expect(await argsAt(login, 'fetch(')).toBe('`/api/${id}`, { method, headers, body, mode, … }');
  259. });
  260. it('an empty argument list is an empty string; a position outside a call is null', async () => {
  261. expect(await argsAt(login, 'captureView.finalizeCaptureSession(')).toBe('');
  262. expect(await argsAt(login, 'async function handleLogin')).toBeNull();
  263. });
  264. it('Swift: labels stay with their values, a trailing closure is a shape', async () => {
  265. const src = `
  266. class CaptureEvents {
  267. func emitZipComplete(result: ZipResult) {
  268. sendEvent(withName: "onZipComplete", body: ["zipURL": result.url])
  269. tracker.setup(side: side, angle: 45)
  270. DispatchQueue.main.async { finish() }
  271. }
  272. }
  273. `;
  274. expect(await argsAt(src, 'sendEvent(', 'swift')).toBe('withName: "onZipComplete", body: […]');
  275. expect(await argsAt(src, 'tracker.setup(', 'swift')).toBe('side: side, angle: 45');
  276. expect(await argsAt(src, 'DispatchQueue.main.async', 'swift')).toBe('{ … }');
  277. });
  278. });
  279. // =============================================================================
  280. // Triggers — what fires a site
  281. // =============================================================================
  282. async function triggerAt(src: string, needle: string, language: 'tsx' | 'typescript' | 'swift' = 'tsx') {
  283. const line = lineOf(src, needle);
  284. const column = src.split('\n')[line - 1]!.indexOf(needle);
  285. return triggerInSource(src, language, line, column);
  286. }
  287. describe('triggers', () => {
  288. const login = `
  289. function LoginButton({ values }) {
  290. const formik = useFormik({
  291. initialValues: values,
  292. onSubmit: (v) => {
  293. handleLogin(v.email, v.password)
  294. },
  295. })
  296. useEffect(() => {
  297. warmUp()
  298. }, [])
  299. useEffect(() => {
  300. const sub = nativeEmitter.addListener('onZipComplete', (data) => { finish(data) })
  301. return () => sub.remove()
  302. }, [])
  303. const handleRemove = useCallback(() => {
  304. removeCredential(values.email)
  305. }, [values])
  306. fetchThing().then(() => done())
  307. return (
  308. <View>
  309. <Button onPress={formik.submitForm} />
  310. <TouchableOpacity onPress={() => handleSelectAccount(account)} />
  311. <Pressable onPress={handleRemove} />
  312. <Row.Item onLongPress={() => { if (ok) confirm() }} />
  313. <KeyboardAvoidingView behavior={isAndroid() ? 'height' : 'padding'} />
  314. <FlatList renderItem={({ item }) => renderRow(item)} keyExtractor={keyOf} />
  315. </View>
  316. )
  317. }
  318. function warn() {
  319. Alert.alert('Remove?', 'Sure?', [{ text: 'OK', onPress: () => removeAll() }], { cancelable: true })
  320. }
  321. `;
  322. it('a call under a JSX prop: the prop and the element', async () => {
  323. expect(await triggerAt(login, 'handleSelectAccount(')).toEqual({ kind: 'prop', name: 'onPress', of: 'TouchableOpacity' });
  324. expect(await triggerAt(login, 'confirm()')).toEqual({ kind: 'prop', name: 'onLongPress', of: 'Row.Item' });
  325. // A handler passed as a value: the site IS the attribute.
  326. expect(await triggerAt(login, 'handleRemove} />')).toEqual({ kind: 'prop', name: 'onPress', of: 'Pressable' });
  327. // A function under any prop fires later; a value computed in a prop runs at render.
  328. expect(await triggerAt(login, 'renderRow(item)')).toEqual({ kind: 'prop', name: 'renderItem', of: 'FlatList' });
  329. expect(await triggerAt(login, 'isAndroid()')).toBeNull();
  330. expect(await triggerAt(login, 'keyOf}')).toBeNull();
  331. });
  332. it('a call under an on* option: the key and the call it configures', async () => {
  333. expect(await triggerAt(login, 'handleLogin(')).toEqual({ kind: 'option', name: 'onSubmit', of: 'useFormik' });
  334. // The option's object inside an array argument: still the call it configures.
  335. expect(await triggerAt(login, 'removeAll()')).toEqual({ kind: 'option', name: 'onPress', of: 'Alert.alert' });
  336. });
  337. it('a call inside a runs-later callback: the callee and its first literal', async () => {
  338. expect(await triggerAt(login, 'warmUp()')).toEqual({ kind: 'callback', name: 'useEffect', of: null });
  339. expect(await triggerAt(login, 'finish(data)')).toEqual({ kind: 'callback', name: 'addListener', of: "'onZipComplete'" });
  340. expect(await triggerAt(login, 'done()')).toEqual({ kind: 'callback', name: 'then', of: null });
  341. });
  342. it('a named handler is its own story: nothing fires the call inside it, from here', async () => {
  343. expect(await triggerAt(login, 'removeCredential(')).toBeNull();
  344. // A plain call in a component body is fired by nothing in particular.
  345. expect(await triggerAt(login, 'fetchThing()')).toBeNull();
  346. expect(await triggerAt(login, 'handleLogin(', 'swift')).toBeNull();
  347. });
  348. });