Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions src/dataflow/cfg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,12 +471,31 @@ export function containsKind(root: Node, kind: SyntaxKind): boolean {
return found;
}

const THROWING_KINDS = new Set([
SyntaxKind.CallExpression,
SyntaxKind.NewExpression,
SyntaxKind.AwaitExpression,
SyntaxKind.TaggedTemplateExpression,
]);

/** May evaluating this subtree throw? Over-approximate: any call-like or await counts. */
export function mayThrow(root: Node): boolean {
return (
containsKind(root, SyntaxKind.CallExpression) ||
containsKind(root, SyntaxKind.NewExpression) ||
containsKind(root, SyntaxKind.AwaitExpression) ||
containsKind(root, SyntaxKind.TaggedTemplateExpression)
);
if (THROWING_KINDS.has(root.getKind())) return true;
let found = false;
root.forEachDescendant((node, traversal) => {
if (found) {
traversal.stop();
return;
}
// Match containsKind's callable boundary: nested bodies execute separately from this subtree.
if (isFunctionBoundary(node)) {
traversal.skip();
return;
}
if (THROWING_KINDS.has(node.getKind())) {
found = true;
traversal.stop();
}
});
return found;
}
20 changes: 20 additions & 0 deletions test/dataflow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import { describe, expect, test } from "bun:test";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { Project } from "ts-morph";
import { analyze } from "../src/core";
import { backwardSlice } from "../src/dataflow";
import { mayThrow } from "../src/dataflow/cfg";
import type { AnalysisOptions } from "../src/options";
import type { CfgEdge, FunctionCfg, ProgramGraphs, SdgEdge } from "../src/schema";

Expand Down Expand Up @@ -166,6 +168,24 @@ describe("CFG gate", () => {
});
});

test("throwability scans all throw kinds without entering nested callables", () => {
const project = new Project({ useInMemoryFileSystem: true });
const source = project.createSourceFile(
"throwability.ts",
[
"async function outer() {",
" call();",
" new Thing();",
" await task;",
" tag`value`;",
" const nested = () => call();",
"}",
].join("\n"),
);
const statements = source.getFunctionOrThrow("outer").getStatements();
expect(statements.map((statement) => mayThrow(statement))).toEqual([true, true, true, true, false]);
});

// ------------------------------------------------------------------------------------------------
// Dominance gate (control dependence, hand-computed)
// ------------------------------------------------------------------------------------------------
Expand Down