branch-guards.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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: the arms of one decision', () => {
  187. /** The guards at the site, unjoined. */
  188. async function guardsAt(src: string, needle: string, language: 'tsx' | 'typescript' | 'swift' = 'tsx') {
  189. const line = lineOf(src, needle);
  190. const column = src.split('\n')[line - 1]!.indexOf(needle);
  191. return guardsInSource(src, language, line, column);
  192. }
  193. const ifElse = `
  194. export async function authUser(req, res) {
  195. const user = await User.findOne({ email })
  196. if (user && (await user.matchPassword(password))) {
  197. res.json({ token: generateToken(user._id) })
  198. } else {
  199. res.status(401)
  200. throw new Error('Invalid email or password')
  201. }
  202. }`;
  203. it('gives an if and its else the same branch, with negated flipped', async () => {
  204. const yes = await guardsAt(ifElse, 'res.json');
  205. const no = await guardsAt(ifElse, 'res.status');
  206. expect(yes).toHaveLength(1);
  207. expect(no).toHaveLength(1);
  208. expect(yes[0]!.text).toBe(no[0]!.text);
  209. expect(yes[0]!.negated).toBe(false);
  210. expect(no[0]!.negated).toBe(true);
  211. // The identity of the FORK, not of the arm: both arms of one `if`.
  212. expect(yes[0]!.branch).toBe(no[0]!.branch);
  213. expect(yes[0]!.branch).toMatch(/^\d+:\d+$/);
  214. // The else arm ends by throwing; the then arm runs on.
  215. expect(no[0]!.armExit).toBe('throw');
  216. expect(yes[0]!.armExit).toBeUndefined();
  217. });
  218. const earlyExit = `
  219. export async function createReview(req, res) {
  220. const product = await Product.findById(req.params.id)
  221. if (!product) {
  222. res.status(404)
  223. throw new Error('Product not found')
  224. }
  225. await product.save()
  226. }`;
  227. it('gives an early exit and the code it guards the same branch', async () => {
  228. const inside = await guardsAt(earlyExit, 'res.status');
  229. const after = await guardsAt(earlyExit, 'product.save');
  230. expect(inside).toHaveLength(1);
  231. expect(after).toHaveLength(1);
  232. expect(inside[0]!.branch).toBe(after[0]!.branch);
  233. expect(inside[0]!.negated).toBe(false);
  234. expect(after[0]!.negated).toBe(true);
  235. // The arm NOT taken throws — what the rail draws as the fork's terminal.
  236. expect(after[0]!.form).toBe('guard');
  237. expect(after[0]!.exit).toBe('throw');
  238. expect(inside[0]!.armExit).toBe('throw');
  239. });
  240. const switched = `
  241. export function route(kind) {
  242. switch (kind) {
  243. case 'a':
  244. first()
  245. break
  246. case 'b':
  247. second()
  248. break
  249. default:
  250. other()
  251. }
  252. }`;
  253. it('gives every case of one switch the same branch', async () => {
  254. const a = await guardsAt(switched, 'first()');
  255. const b = await guardsAt(switched, 'second()');
  256. const d = await guardsAt(switched, 'other()');
  257. expect(a[0]!.branch).toBe(b[0]!.branch);
  258. expect(a[0]!.branch).toBe(d[0]!.branch);
  259. expect([a[0]!.text, b[0]!.text, d[0]!.text]).toEqual(['kind === \'a\'', 'kind === \'b\'', 'kind: default']);
  260. });
  261. it('gives two try/catch blocks branches of their own', async () => {
  262. const src = `
  263. export async function save() {
  264. try { await a() } catch (e) { first(e) }
  265. try { await b() } catch (e) { second(e) }
  266. }`;
  267. const one = await guardsAt(src, 'first(e)');
  268. const two = await guardsAt(src, 'second(e)');
  269. expect(one[0]!.text).toBe('on error');
  270. expect(two[0]!.text).toBe('on error');
  271. expect(one[0]!.branch).not.toBe(two[0]!.branch);
  272. });
  273. it('does not call an arm an exit because a later elif raises', async () => {
  274. const src = `
  275. def handler(user):
  276. if not user:
  277. raise HTTPException(400)
  278. elif not user.is_active:
  279. raise HTTPException(400)
  280. go(user)
  281. `;
  282. // The `elif` arm raises; the arm it is written in runs on to `go(user)`.
  283. const after = await guardsInSource(src, 'python', lineOf(src, 'go(user)'), 4);
  284. expect(after.map((g) => g.armExit ?? null)).toEqual(after.map(() => null));
  285. });
  286. it('reads a Swift guard as an exit', async () => {
  287. const src = `
  288. func load() {
  289. guard let user = current else { return }
  290. fetch(user)
  291. }`;
  292. const after = await guardsAt(src, 'fetch(user)', 'swift');
  293. expect(after[0]!.form).toBe('guard');
  294. expect(after[0]!.exit).toBe('return');
  295. expect(after[0]!.branch).toMatch(/^\d+:\d+$/);
  296. });
  297. });
  298. describe('branch guards: unsupported', () => {
  299. it('reports no guards for a language without rules', async () => {
  300. expect(supportsBranchGuards('ruby')).toBe(false);
  301. expect(await guardsInSource('def f\n if x\n go()\n end\nend\n', 'ruby', 3, 4)).toEqual([]);
  302. });
  303. });
  304. describe('branch guards: on the wire', () => {
  305. let dir: string | undefined;
  306. afterEach(() => {
  307. if (dir) fs.rmSync(dir, { recursive: true, force: true });
  308. dir = undefined;
  309. });
  310. it('labels symbol-view rails and flow connectors with the call site\'s conditions', async () => {
  311. dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-when-'));
  312. fs.mkdirSync(path.join(dir, 'src'));
  313. fs.writeFileSync(
  314. path.join(dir, 'src', 'app.ts'),
  315. 'export function helper() { return 1 }\n' +
  316. 'export function other() { return 2 }\n' +
  317. 'export function run(ready: boolean, busy: boolean) {\n' +
  318. ' if (busy) return\n' +
  319. ' if (ready) {\n' +
  320. ' helper()\n' +
  321. ' } else {\n' +
  322. ' other()\n' +
  323. ' }\n' +
  324. '}\n'
  325. );
  326. const cg = CodeGraph.initSync(dir);
  327. await cg.indexAll();
  328. const run = cg.getNodesByName('run')[0]!;
  329. const helper = cg.getNodesByName('helper')[0]!;
  330. type Rel = { node: { name: string }; edges: Array<{ when?: string }> };
  331. const view = (await buildNode(cg, dir, run.id)) as { outgoing: { items: Rel[] } };
  332. const byName = new Map(view.outgoing.items.map((r) => [r.node.name, r]));
  333. expect(byName.get('helper')?.edges[0]?.when).toBe('!busy && ready');
  334. expect(byName.get('other')?.edges[0]?.when).toBe('!busy && !ready');
  335. const callee = (await buildNode(cg, dir, helper.id)) as { incoming: { items: Rel[] } };
  336. expect(callee.incoming.items.find((r) => r.node.name === 'run')?.edges[0]?.when).toBe('!busy && ready');
  337. const flow = await buildFlow(cg, dir, new URLSearchParams('from=run&to=helper'));
  338. const hop = flow.flows[0]!.hops[1]!;
  339. expect(hop.edge?.when).toBe('!busy && ready');
  340. expect(hop.edge?.label).toBe('calls · when !busy && ready');
  341. cg.close();
  342. });
  343. });
  344. // =============================================================================
  345. // Call arguments — what a site passes
  346. // =============================================================================
  347. async function argsAt(src: string, needle: string, language: 'tsx' | 'typescript' | 'swift' = 'tsx') {
  348. const line = lineOf(src, needle);
  349. const column = src.split('\n')[line - 1]!.indexOf(needle);
  350. return callArgumentsInSource(src, language, line, column);
  351. }
  352. describe('call arguments', () => {
  353. const login = `
  354. async function handleLogin(values) {
  355. await SecureStore.setItemAsync('userEmail', values.email)
  356. const res = await client.post('/auth/login', { email: values.email, password, ...rest })
  357. Alert.alert(i18n.t('error_login_failed'), err.message, [{ text: 'OK' }])
  358. router.push({ pathname: '/item/[id]', params: { id } })
  359. captureView.finalizeCaptureSession()
  360. run(() => go(), async (x) => x, new Thing(1))
  361. const big = fetch(\`/api/\${id}\`, { method: 'POST', headers, body, mode, cache, credentials })
  362. }
  363. `;
  364. it('keeps literals and names whole, folds objects to their keys, arrays and functions to a shape', async () => {
  365. expect(await argsAt(login, 'SecureStore.setItemAsync(')).toBe("'userEmail', values.email");
  366. expect(await argsAt(login, 'client.post(')).toBe("'/auth/login', { email, password, ...rest }");
  367. expect(await argsAt(login, 'Alert.alert(')).toBe('i18n.t(…), err.message, […]');
  368. expect(await argsAt(login, 'router.push(')).toBe('{ pathname, params }');
  369. expect(await argsAt(login, 'run(')).toBe('() => …, () => …, new Thing(…)');
  370. expect(await argsAt(login, 'fetch(')).toBe('`/api/${id}`, { method, headers, body, mode, … }');
  371. });
  372. it('an empty argument list is an empty string; a position outside a call is null', async () => {
  373. expect(await argsAt(login, 'captureView.finalizeCaptureSession(')).toBe('');
  374. expect(await argsAt(login, 'async function handleLogin')).toBeNull();
  375. });
  376. it('Swift: labels stay with their values, a trailing closure is a shape', async () => {
  377. const src = `
  378. class CaptureEvents {
  379. func emitZipComplete(result: ZipResult) {
  380. sendEvent(withName: "onZipComplete", body: ["zipURL": result.url])
  381. tracker.setup(side: side, angle: 45)
  382. DispatchQueue.main.async { finish() }
  383. }
  384. }
  385. `;
  386. expect(await argsAt(src, 'sendEvent(', 'swift')).toBe('withName: "onZipComplete", body: […]');
  387. expect(await argsAt(src, 'tracker.setup(', 'swift')).toBe('side: side, angle: 45');
  388. expect(await argsAt(src, 'DispatchQueue.main.async', 'swift')).toBe('{ … }');
  389. });
  390. });
  391. // =============================================================================
  392. // Triggers — what fires a site
  393. // =============================================================================
  394. async function triggerAt(src: string, needle: string, language: 'tsx' | 'typescript' | 'swift' = 'tsx') {
  395. const line = lineOf(src, needle);
  396. const column = src.split('\n')[line - 1]!.indexOf(needle);
  397. return triggerInSource(src, language, line, column);
  398. }
  399. describe('triggers', () => {
  400. const login = `
  401. function LoginButton({ values }) {
  402. const formik = useFormik({
  403. initialValues: values,
  404. onSubmit: (v) => {
  405. handleLogin(v.email, v.password)
  406. },
  407. })
  408. useEffect(() => {
  409. warmUp()
  410. }, [])
  411. useEffect(() => {
  412. const sub = nativeEmitter.addListener('onZipComplete', (data) => { finish(data) })
  413. return () => sub.remove()
  414. }, [])
  415. const handleRemove = useCallback(() => {
  416. removeCredential(values.email)
  417. }, [values])
  418. fetchThing().then(() => done())
  419. return (
  420. <View>
  421. <Button onPress={formik.submitForm} />
  422. <TouchableOpacity onPress={() => handleSelectAccount(account)} />
  423. <Pressable onPress={handleRemove} />
  424. <Row.Item onLongPress={() => { if (ok) confirm() }} />
  425. <KeyboardAvoidingView behavior={isAndroid() ? 'height' : 'padding'} />
  426. <FlatList renderItem={({ item }) => renderRow(item)} keyExtractor={keyOf} />
  427. </View>
  428. )
  429. }
  430. function warn() {
  431. Alert.alert('Remove?', 'Sure?', [{ text: 'OK', onPress: () => removeAll() }], { cancelable: true })
  432. }
  433. `;
  434. it('a call under a JSX prop: the prop and the element', async () => {
  435. expect(await triggerAt(login, 'handleSelectAccount(')).toEqual({ kind: 'prop', name: 'onPress', of: 'TouchableOpacity' });
  436. expect(await triggerAt(login, 'confirm()')).toEqual({ kind: 'prop', name: 'onLongPress', of: 'Row.Item' });
  437. // A handler passed as a value: the site IS the attribute.
  438. expect(await triggerAt(login, 'handleRemove} />')).toEqual({ kind: 'prop', name: 'onPress', of: 'Pressable' });
  439. // A function under any prop fires later; a value computed in a prop runs at render.
  440. expect(await triggerAt(login, 'renderRow(item)')).toEqual({ kind: 'prop', name: 'renderItem', of: 'FlatList' });
  441. expect(await triggerAt(login, 'isAndroid()')).toBeNull();
  442. expect(await triggerAt(login, 'keyOf}')).toBeNull();
  443. });
  444. it('a call under an on* option: the key and the call it configures', async () => {
  445. expect(await triggerAt(login, 'handleLogin(')).toEqual({ kind: 'option', name: 'onSubmit', of: 'useFormik' });
  446. // The option's object inside an array argument: still the call it configures.
  447. expect(await triggerAt(login, 'removeAll()')).toEqual({ kind: 'option', name: 'onPress', of: 'Alert.alert' });
  448. });
  449. it('a call inside a runs-later callback: the callee and its first literal', async () => {
  450. expect(await triggerAt(login, 'warmUp()')).toEqual({ kind: 'callback', name: 'useEffect', of: null });
  451. expect(await triggerAt(login, 'finish(data)')).toEqual({ kind: 'callback', name: 'addListener', of: "'onZipComplete'" });
  452. expect(await triggerAt(login, 'done()')).toEqual({ kind: 'callback', name: 'then', of: null });
  453. });
  454. it('a named handler is its own story: nothing fires the call inside it, from here', async () => {
  455. expect(await triggerAt(login, 'removeCredential(')).toBeNull();
  456. // A plain call in a component body is fired by nothing in particular.
  457. expect(await triggerAt(login, 'fetchThing()')).toBeNull();
  458. expect(await triggerAt(login, 'handleLogin(', 'swift')).toBeNull();
  459. });
  460. });