diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts index 1992ab52038..5a54edd3cc6 100644 --- a/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.test.ts @@ -1528,3 +1528,95 @@ it("projects and adopts more than the default per-file capacity when explicitly "exceed the offered tree capacity", ); }); + +it("resolves pure sequence call targets without spurious unknown frontiers", () => { + for (const callSource of [ + "(0, localFn)(1);", + "const aliasFn = localFn; (0, aliasFn)(1);", + "(0, 0, localFn)(1);", + ]) { + const graph = graphFor(` + function localFn(x) { return x; } + ${callSource} + `); + expect( + graph.unknowns.filter( + ({ reason, detail }) => + reason === "dynamic-call" || + detail.includes("operator operand") || + detail.includes("operator result"), + ), + ).toEqual([]); + const localNode = graph.nodes.find( + ({ kind, label }) => kind === "function" && label === "localFn", + ); + const callNode = graph.nodes.find(({ kind }) => kind === "call-site"); + expect(localNode).toBeDefined(); + expect(callNode).toBeDefined(); + expect(graph.relations).toContainEqual( + expect.objectContaining({ + source_node_id: callNode?.node_id, + target_node_id: localNode?.node_id, + relation: "calls", + resolution: "resolved", + }), + ); + } +}); + +it("projects conditional, side-effectful, and member sequence call targets accurately", () => { + const conditional = graphFor(` + function a() { return 1; } + function b() { return 2; } + (0, cond ? a : b)(); + `); + const callNode = conditional.nodes.find(({ kind }) => kind === "call-site"); + const candidateTargets = conditional.relations + .filter( + ({ source_node_id, relation }) => + source_node_id === callNode?.node_id && relation === "calls", + ) + .map(({ target_node_id, resolution }) => ({ + label: conditional.nodes.find(({ node_id }) => node_id === target_node_id) + ?.label, + resolution, + })) + .sort((left, right) => + String(left.label).localeCompare(String(right.label)), + ); + expect(candidateTargets).toEqual([ + { label: "a", resolution: "candidate" }, + { label: "b", resolution: "candidate" }, + ]); + expect( + conditional.unknowns.filter(({ reason }) => reason === "dynamic-call"), + ).toHaveLength(1); + + const sideEffectful = graphFor(` + function sideEffect() {} + function localFn() {} + (sideEffect(), localFn)(); + `); + expect( + sideEffectful.unknowns.filter(({ reason }) => reason === "dynamic-call"), + ).toEqual([ + expect.objectContaining({ + detail: "Unsupported SequenceExpression call target.", + }), + ]); + + const member = graphFor(` + const obj = { method() { return 1; } }; + (0, obj.method)(); + `); + expect( + member.unknowns.filter(({ reason }) => reason === "dynamic-call"), + ).toEqual([ + expect.objectContaining({ + detail: "Unsupported MemberExpression call target.", + }), + ]); + expect( + member.unknowns.filter(({ detail }) => detail.includes("operator operand")), + ).toEqual([]); +}); diff --git a/src/application/javascript/JavaScriptSemanticGraphBuilder.ts b/src/application/javascript/JavaScriptSemanticGraphBuilder.ts index 9451c5fc2a2..ea1309953a3 100644 --- a/src/application/javascript/JavaScriptSemanticGraphBuilder.ts +++ b/src/application/javascript/JavaScriptSemanticGraphBuilder.ts @@ -1022,6 +1022,8 @@ const projectCalls = (context: FileContext): void => { candidate_node_ids: [], evidence: unknownSemanticEvidence(context.file, argument.location), }); + const valueLocation = + argument.valueExpressionLocation ?? argument.location; const references = argument.valueExpressionLocation !== null && expressions.has( @@ -1029,7 +1031,7 @@ const projectCalls = (context: FileContext): void => { ) ? [] : context - .referenceNodesWithin(argument.location) + .referenceNodesWithin(valueLocation) .filter( (reference) => reference.function_node_id === callNode.function_node_id, @@ -1041,7 +1043,7 @@ const projectCalls = (context: FileContext): void => { relation: "aliases", resolution: references.length === 1 && - rangesEqual(reference.identity.source_range, argument.location) + rangesEqual(reference.identity.source_range, valueLocation) ? "resolved" : "candidate", }); diff --git a/src/application/javascript/JavaScriptSemanticGraphExpressionInfluence.test.ts b/src/application/javascript/JavaScriptSemanticGraphExpressionInfluence.test.ts index 5bcdf851ba3..051c647f87a 100644 --- a/src/application/javascript/JavaScriptSemanticGraphExpressionInfluence.test.ts +++ b/src/application/javascript/JavaScriptSemanticGraphExpressionInfluence.test.ts @@ -201,6 +201,238 @@ it("keeps sequence side effects unknown instead of attributing earlier values di ).toBe(true); }); +it.each([ + ["initializer", 'const url = (0, base + "/x"); fetch(url);'], + ["argument", 'fetch((0, base + "/x"));'], +])( + "unwraps pure sequence wrappers in %s influence without false unknowns", + (_label, body) => { + const result = trace(body); + expect(result.nodes.map((node) => node.label)).toContain("argument 0"); + expect( + result.relations.some((edge) => edge.relation === "influences"), + ).toBe(true); + expect( + result.unknowns.some( + (unknown) => + unknown.detail.includes("operator operand") || + unknown.detail.includes("operator result"), + ), + ).toBe(false); + }, +); + +it.each([ + ["numeric prefix", "fetch((0, base));"], + ["undefined prefix", "fetch((undefined, base));"], +])( + "resolves identifier alias and reaches default forward influence across %s sequence argument", + (_label, body) => { + const graph = graphForJavaScript( + `const base = "https://example.test"; ${body}`, + ); + const argumentNode = graph.nodes.find( + (node) => node.label === "argument 0", + ); + if (argumentNode === undefined) throw new Error("Expected argument 0 node"); + const aliasEdges = graph.relations.filter( + (edge) => + edge.relation === "aliases" && + edge.target_node_id === argumentNode.node_id, + ); + expect(aliasEdges).toHaveLength(1); + const sourceNode = graph.nodes.find( + (node) => node.node_id === aliasEdges[0]?.source_node_id, + ); + expect(sourceNode?.label).toBe("base"); + expect(aliasEdges[0]?.resolution).toBe("resolved"); + const forward = trace(body); + expect(forward.nodes.map((node) => node.label)).toContain("argument 0"); + expect(forward.unknowns).toEqual([]); + }, +); + +it("keeps impure sequence call arguments conservative without resolved alias shortcuts", () => { + const graph = graphForJavaScript( + 'const base = "https://example.test"; fetch((sideEffect(), base));', + ); + const argumentNode = graph.nodes.find((node) => node.label === "argument 0"); + if (argumentNode === undefined) throw new Error("Expected argument 0 node"); + expect( + graph.relations.some( + (edge) => + edge.relation === "aliases" && + edge.target_node_id === argumentNode.node_id && + edge.resolution === "resolved", + ), + ).toBe(false); + const forward = trace("fetch((sideEffect(), base));"); + expect(forward.status).toBe("partial"); + expect( + forward.unknowns.some( + (unknown) => + unknown.family === "data-flow" && unknown.reason === "unknown-value", + ), + ).toBe(true); +}); + +it("scopes return aliases to the unwrapped pure sequence value without spurious undefined edges", () => { + const graph = graphForJavaScript( + "function f(x) { return (undefined, x); } function g(y) { return (sideEffect(), y); }", + ); + const returnNodes = graph.nodes.filter((node) => node.kind === "return-site"); + expect(returnNodes).toHaveLength(2); + const fNode = graph.nodes.find( + (node) => node.kind === "function" && node.label === "f", + ); + const gNode = graph.nodes.find( + (node) => node.kind === "function" && node.label === "g", + ); + const pureReturn = returnNodes.find( + (node) => node.function_node_id === fNode?.node_id, + ); + const impureReturn = returnNodes.find( + (node) => node.function_node_id === gNode?.node_id, + ); + if (pureReturn === undefined || impureReturn === undefined) + throw new Error("Expected two return nodes"); + const pureAliases = graph.relations.filter( + (edge) => + edge.relation === "aliases" && edge.target_node_id === pureReturn.node_id, + ); + expect(pureAliases).toHaveLength(1); + expect(pureAliases[0]?.resolution).toBe("resolved"); + expect( + graph.nodes.find((node) => node.node_id === pureAliases[0]?.source_node_id) + ?.label, + ).toBe("x"); + expect( + graph.relations.some( + (edge) => + edge.relation === "aliases" && + edge.target_node_id === impureReturn.node_id && + edge.resolution === "resolved", + ), + ).toBe(false); +}); + +it.each([ + ["numeric prefix", "(0, base)"], + ["undefined prefix", "(undefined, base)"], +])( + "traces forward influence through unwrapped pure sequence initializer aliases (%s)", + (_label, initializer) => { + const graph = graphForJavaScript( + `const base = "unique"; const alias = ${initializer}; fetch(alias);`, + ); + const baseNode = graph.nodes.find( + (node) => node.kind === "binding" && node.label === "base", + ); + const aliasNode = graph.nodes.find( + (node) => node.kind === "binding" && node.label === "alias", + ); + if (baseNode === undefined || aliasNode === undefined) + throw new Error("Expected base and alias binding nodes"); + const aliasInputs = graph.relations.filter( + (edge) => + edge.relation === "aliases" && + edge.target_node_id === aliasNode.node_id, + ); + expect(aliasInputs).toHaveLength(1); + expect(aliasInputs[0]?.resolution).toBe("resolved"); + expect( + graph.nodes.find( + (node) => node.node_id === aliasInputs[0]?.source_node_id, + )?.label, + ).toBe("base"); + const fromBase = queryJavaScriptSemanticGraph( + graph, + javaScriptSemanticQueryInputSchema.parse({ + seed: { kind: "semantic-node", node_id: baseNode.node_id }, + direction: "forward-influence", + }), + ); + expect(fromBase.status).toBe("found"); + expect(fromBase.unknowns).toEqual([]); + expect(fromBase.nodes.map((node) => node.label)).toEqual( + expect.arrayContaining(["base", "alias", "argument 0"]), + ); + expect(fromBase.nodes.some((node) => node.label === "undefined")).toBe( + false, + ); + const fromLiteral = queryJavaScriptSemanticGraph( + graph, + javaScriptSemanticQueryInputSchema.parse({ + seed: { kind: "literal", value: "unique" }, + direction: "forward-influence", + }), + ); + expect(fromLiteral.unknowns).toEqual([]); + expect(fromLiteral.nodes.map((node) => node.label)).toEqual( + expect.arrayContaining(["alias", "argument 0"]), + ); + const dynamicGraph = graphForJavaScript( + `function wrap(base) { const alias = ${initializer}; fetch(alias); }`, + ); + const paramNode = dynamicGraph.nodes.find( + (node) => node.kind === "parameter" && node.label === "base", + ); + if (paramNode === undefined) throw new Error("Expected base parameter"); + const fromParam = queryJavaScriptSemanticGraph( + dynamicGraph, + javaScriptSemanticQueryInputSchema.parse({ + seed: { kind: "semantic-node", node_id: paramNode.node_id }, + direction: "forward-influence", + }), + ); + expect(fromParam.nodes.map((node) => node.label)).toEqual( + expect.arrayContaining(["alias", "argument 0"]), + ); + }, +); + +it.each([ + [ + "side-effecting prefix", + 'const base = "unique"; const alias = (sideEffect(), base); fetch(alias);', + ], + [ + "shadowed undefined prefix", + 'let undefined = "shadow"; const base = "unique"; const alias = (undefined, base); fetch(alias);', + ], +])( + "keeps %s sequence initializer aliases conservative without direct alias shortcuts", + (_label, source) => { + const graph = graphForJavaScript(source); + const baseNode = graph.nodes.find( + (node) => node.kind === "binding" && node.label === "base", + ); + const aliasNode = graph.nodes.find( + (node) => node.kind === "binding" && node.label === "alias", + ); + if (baseNode === undefined || aliasNode === undefined) + throw new Error("Expected base and alias binding nodes"); + expect( + graph.relations.some( + (edge) => + edge.relation === "aliases" && + edge.target_node_id === aliasNode.node_id, + ), + ).toBe(false); + const fromBase = queryJavaScriptSemanticGraph( + graph, + javaScriptSemanticQueryInputSchema.parse({ + seed: { kind: "semantic-node", node_id: baseNode.node_id }, + direction: "forward-influence", + }), + ); + expect(fromBase.status).toBe("partial"); + expect( + fromBase.unknowns.some((unknown) => unknown.reason === "unknown-value"), + ).toBe(true); + }, +); + it("keeps older call-site literal evidence searchable when argument literals are absent", () => { const graph = graphForJavaScript('consume("only-direct");'); const legacy = { diff --git a/src/application/javascript/JavaScriptSemanticGraphExpressionProjection.ts b/src/application/javascript/JavaScriptSemanticGraphExpressionProjection.ts index fd5fb243215..c2d13355e6c 100644 --- a/src/application/javascript/JavaScriptSemanticGraphExpressionProjection.ts +++ b/src/application/javascript/JavaScriptSemanticGraphExpressionProjection.ts @@ -326,8 +326,22 @@ export function* projectSemanticExpressionInfluence( properties: { conditional }, }); }; - for (const flow of context.ir.initializerFlows) - connect(expressions.get(key(flow.source)), bindings.get(key(flow.target))); + for (const flow of context.ir.initializerFlows) { + const target = bindings.get(key(flow.target)); + const expression = expressions.get(key(flow.source)); + if (expression !== undefined) { + connect(expression, target); + continue; + } + const read = reads.get(key(flow.source)); + if (read !== undefined) + addSemanticGraphRelation(context.state, { + source: read, + target, + relation: "aliases", + resolution: "resolved", + }); + } for (const flow of context.ir.assignmentFlows) { const source = expressions.get(key(flow.source)); const target = writes.get(key(flow.target)); diff --git a/src/application/javascript/JavaScriptSemanticGraphFlowProjection.ts b/src/application/javascript/JavaScriptSemanticGraphFlowProjection.ts index c77502ff5ff..f6f0c481081 100644 --- a/src/application/javascript/JavaScriptSemanticGraphFlowProjection.ts +++ b/src/application/javascript/JavaScriptSemanticGraphFlowProjection.ts @@ -284,12 +284,13 @@ export const projectSemanticReturnValues = ( for (const callable of context.ir.callables) for (const site of callable.returnSites) { const returnNode = context.returnSiteNodes.get(site.returnSiteId); + const valueLocation = site.valueExpressionLocation ?? site.location; const references = site.valueExpressionLocation !== null && expressions.has(javascriptSourceRangeKey(site.valueExpressionLocation)) ? [] : context - .referenceNodesWithin(site.location) + .referenceNodesWithin(valueLocation) .filter( (reference) => reference.function_node_id === returnNode?.function_node_id, diff --git a/src/domain/javascript/javascriptAstValues.test.ts b/src/domain/javascript/javascriptAstValues.test.ts index a5db84acc38..43e7400f8af 100644 --- a/src/domain/javascript/javascriptAstValues.test.ts +++ b/src/domain/javascript/javascriptAstValues.test.ts @@ -2,6 +2,7 @@ import * as t from "@babel/types"; import { expect, it } from "vitest"; import { + isPureJavaScriptLiteralExpression, semanticMemberChain, semanticStaticPropertyKey, staticObjectOwnMethodReader, @@ -9,6 +10,7 @@ import { staticObjectPropertyReader, staticObjectCopyPropertyReader, staticObjectPropertyNames, + unwrapPureJavaScriptSequenceExpression, } from "./javascriptAstValues.js"; it("keeps string spread indices separate from named descriptor fields", () => { @@ -656,6 +658,52 @@ it("ignores null and propertyless copy sources without erasing indexed strings", expect(read("minVersion").status).toBe("missing"); }); +it("classifies pure literal leading expressions and unwraps pure sequences conservatively", () => { + const target = t.identifier("localFn"); + const unshadowed = (id: t.Identifier) => id.name === "undefined"; + for (const pure of [ + t.numericLiteral(0), + t.stringLiteral("ok"), + t.booleanLiteral(true), + t.nullLiteral(), + t.bigIntLiteral(1n), + t.templateLiteral( + [t.templateElement({ raw: "raw", cooked: "raw" }, true)], + [], + ), + t.unaryExpression("void", t.numericLiteral(0)), + t.unaryExpression("!", t.numericLiteral(0)), + t.unaryExpression("-", t.numericLiteral(1)), + t.unaryExpression("-", t.bigIntLiteral(1n)), + t.tsAsExpression(t.numericLiteral(0), t.tsAnyKeyword()), + t.sequenceExpression([t.numericLiteral(0), t.nullLiteral()]), + t.identifier("undefined"), + ]) { + expect(isPureJavaScriptLiteralExpression(pure, unshadowed)).toBe(true); + const wrapped = t.sequenceExpression([pure, target]); + expect(unwrapPureJavaScriptSequenceExpression(wrapped, unshadowed)).toBe( + target, + ); + } + const impureCases: t.Expression[] = [ + t.callExpression(t.identifier("sideEffect"), []), + t.unaryExpression("void", t.callExpression(t.identifier("sideEffect"), [])), + t.unaryExpression("+", t.identifier("obj")), + t.identifier("other"), + t.identifier("undefined"), + ]; + for (const [index, impure] of impureCases.entries()) { + const checker = index === impureCases.length - 1 ? () => false : unshadowed; + expect(isPureJavaScriptLiteralExpression(impure, checker)).toBe(false); + const seq = t.sequenceExpression([impure, target]); + expect(unwrapPureJavaScriptSequenceExpression(seq, checker)).toBe(seq); + } + const singleElement = t.sequenceExpression([target]); + expect(unwrapPureJavaScriptSequenceExpression(singleElement)).toBe( + singleElement, + ); +}); + it("bounds conditional copy sources by the keys their branches may copy", () => { const flag = t.identifier("flag"); const comparison = t.binaryExpression("===", flag, t.stringLiteral("darwin")); diff --git a/src/domain/javascript/javascriptAstValues.ts b/src/domain/javascript/javascriptAstValues.ts index 53383442b30..bec8d6e28bb 100644 --- a/src/domain/javascript/javascriptAstValues.ts +++ b/src/domain/javascript/javascriptAstValues.ts @@ -78,6 +78,79 @@ export const unwrapJavaScriptExpression = ( return { node: current, depth }; }; +/** + * Whether evaluating `node` is provably free of runtime side effects and + * abrupt errors, admitting only literal expressions, safe unary forms, + * nested pure sequences, and caller-verified unshadowed `undefined`. + */ +export const isPureJavaScriptLiteralExpression = ( + node: t.Node, + isUnshadowedUndefined?: (node: t.Identifier) => boolean, +): boolean => { + const pending: t.Node[] = [node]; + while (pending.length > 0) { + const current = unwrapJavaScriptExpression(pending.pop()!).node; + if ( + t.isNumericLiteral(current) || + t.isStringLiteral(current) || + t.isBooleanLiteral(current) || + t.isNullLiteral(current) || + t.isBigIntLiteral(current) || + (t.isTemplateLiteral(current) && + current.expressions.length === 0 && + current.quasis.every((quasi) => quasi.value.cooked !== null)) + ) + continue; + if ( + t.isIdentifier(current, { name: "undefined" }) && + isUnshadowedUndefined?.(current) === true + ) + continue; + if (t.isUnaryExpression(current)) { + if (current.operator === "void" || current.operator === "!") { + pending.push(current.argument); + continue; + } + const argument = unwrapJavaScriptExpression(current.argument).node; + if ( + (current.operator === "+" || current.operator === "-") && + (t.isNumericLiteral(argument) || + (current.operator === "-" && t.isBigIntLiteral(argument))) + ) + continue; + } + if (t.isSequenceExpression(current) && current.expressions.length > 0) { + for (const expression of current.expressions) pending.push(expression); + continue; + } + return false; + } + return true; +}; + +/** + * Unwrap transparent expression wrappers and comma expressions with at least + * two operands whose leading expressions (`0 .. n-2`) are provably pure. + */ +export const unwrapPureJavaScriptSequenceExpression = ( + node: t.Node, + isUnshadowedUndefined?: (node: t.Identifier) => boolean, +): t.Node => { + let current = unwrapJavaScriptExpression(node).node; + while ( + t.isSequenceExpression(current) && + current.expressions.length >= 2 && + current.expressions + .slice(0, -1) + .every((expression) => + isPureJavaScriptLiteralExpression(expression, isUnshadowedUndefined), + ) + ) { + current = unwrapJavaScriptExpression(current.expressions.at(-1)!).node; + } + return current; +}; + /** Read one syntax-level primitive only when its value is exact. */ export const readExactJavaScriptLiteral = ( node: t.Node, diff --git a/src/domain/javascript/javascriptSemanticAnalysis.execution_points.test.ts b/src/domain/javascript/javascriptSemanticAnalysis.execution_points.test.ts index 9acb9a8e820..ace891ad43d 100644 --- a/src/domain/javascript/javascriptSemanticAnalysis.execution_points.test.ts +++ b/src/domain/javascript/javascriptSemanticAnalysis.execution_points.test.ts @@ -97,3 +97,20 @@ it.each([ ])("keeps the literal across %s", (_, source) => { expect(returned(source)).toEqual({ status: "literal", value: 1 }); }); + +it.each([ + [ + "a leading getter inside a sequence call target", + `export function observe() { const state = { v: 1, get trigger() { this.v = 2; return 0; } }; const fn = () => {}; (state.trigger, fn)(); return state.v; }`, + ], + [ + "a trailing member getter inside a pure sequence call target", + `export function observe() { const state = { v: 1, get method() { this.v = 2; return () => {}; } }; (0, state.method)(); return state.v; }`, + ], + [ + "a leading call inside a sequence call target", + `export function observe() { const state = { v: 1 }; const touch = (o) => { o.v = 2; }; const fn = () => {}; (touch(state), fn)(); return state.v; }`, + ], +])("does not hide side effects across %s", (_, source) => { + expect(returned(source)?.status).toBe("unknown"); +}); diff --git a/src/domain/javascript/javascriptSemanticCallResolution.test.ts b/src/domain/javascript/javascriptSemanticCallResolution.test.ts index 31977aa646b..c30ff06993a 100644 --- a/src/domain/javascript/javascriptSemanticCallResolution.test.ts +++ b/src/domain/javascript/javascriptSemanticCallResolution.test.ts @@ -692,3 +692,155 @@ it("indexes one statement body for distinct captured functions", () => { lookup.mockRestore(); } }); + +it.each([ + [ + "single numeric literal", + "function localFn(x) { return x; } (0, localFn)(1);", + ], + [ + "const alias", + "function localFn(x) { return x; } const aliasFn = localFn; (0, aliasFn)(1);", + ], + [ + "multi-literal sequence", + "function localFn(x) { return x; } (0, 0, localFn)(1);", + ], + [ + "nested pure sequence", + "function localFn(x) { return x; } (0, (0, localFn))(1);", + ], + [ + "mixed pure primitives", + 'function localFn(x) { return x; } ("ok", null, undefined, true, false, void 0, !0, -1, 0n, `x`, localFn)(1);', + ], + [ + "stored sequence alias", + "function localFn(x) { return x; } const wrapped = (0, localFn); wrapped(1);", + ], +])("resolves pure sequence call target (%s)", (_label, source) => { + const ir = analyzeJavaScriptSemantics(source); + const localFn = ir.callables.find(({ name }) => name === "localFn"); + if (localFn === undefined) throw new Error("Missing localFn callable"); + expect(ir.callSites).toHaveLength(1); + expect(ir.callSites[0]).toMatchObject({ + resolution: "exact", + calleeCallableIds: [localFn.callableId], + }); + expect(ir.argumentFlows).toEqual([ + expect.objectContaining({ + callSiteId: ir.callSites[0]?.callSiteId, + argumentIndex: 0, + callableId: localFn.callableId, + }), + ]); + expect(ir.callReturnFlows).toEqual([ + expect.objectContaining({ + callSiteId: ir.callSites[0]?.callSiteId, + callableId: localFn.callableId, + }), + ]); + expect(ir.frontiers).toEqual([]); + expect(ir.expressionFlows).toEqual([]); +}); + +it("resolves conditional candidates inside a pure sequence call target", () => { + const ir = analyzeJavaScriptSemantics(` + function a(x) { return x; } + function b(x) { return x; } + (0, cond ? a : b)(1); + `); + const a = ir.callables.find(({ name }) => name === "a"); + const b = ir.callables.find(({ name }) => name === "b"); + if (a === undefined || b === undefined) + throw new Error("Missing conditional callables"); + expect(ir.callSites).toHaveLength(1); + expect(ir.callSites[0]).toMatchObject({ + resolution: "ambiguous", + calleeCallableIds: [a.callableId, b.callableId].sort(), + }); + expect(ir.argumentFlows.map(({ callableId }) => callableId).sort()).toEqual( + [a.callableId, b.callableId].sort(), + ); + expect(ir.frontiers).toEqual([ + expect.objectContaining({ + kind: "dynamic-call", + reason: "Conditional or logical call target has multiple candidates.", + }), + ]); + expect(ir.expressionFlows.map(({ operator }) => operator)).toEqual(["?:"]); +}); + +it.each([ + [ + "side-effecting call", + "function sideEffect() {} function localFn() {} (sideEffect(), localFn)();", + ], + [ + "side-effecting void", + "function sideEffect() {} function localFn() {} (void sideEffect(), localFn)();", + ], + [ + "non-literal binding read", + "function localFn() {} const extra = 0; (extra, localFn)();", + ], + [ + "shadowed undefined", + "function localFn() {} function run(undefined) { (undefined, localFn)(); }", + ], + [ + "with dynamic scope", + "function localFn() {} with ({}) { (undefined, localFn)(); }", + ], + [ + "inner impure sequence", + "function sideEffect() {} function localFn() {} (0, (sideEffect(), localFn))();", + ], +])( + "preserves conservative unresolved reporting for impure sequence (%s)", + (_label, source) => { + const ir = analyzeJavaScriptSemantics(source); + const localFn = ir.callables.find(({ name }) => name === "localFn"); + if (localFn === undefined) throw new Error("Missing localFn"); + const outerCall = ir.callSites.find( + ({ calleeCallableIds }) => calleeCallableIds.length === 0, + ); + expect(outerCall).toMatchObject({ + resolution: "unresolved", + calleeCallableIds: [], + }); + expect(ir.frontiers).toContainEqual( + expect.objectContaining({ + kind: "dynamic-call", + location: outerCall?.calleeLocation, + reason: "Unsupported SequenceExpression call target.", + }), + ); + }, +); + +it("unwraps pure sequence around member calls to preserve MemberExpression behavior", () => { + const ir = analyzeJavaScriptSemantics(` + const obj = { method(x) { return x; } }; + (0, obj.method)(1); + `); + expect(ir.callSites).toHaveLength(1); + expect(ir.callSites[0]).toMatchObject({ + resolution: "unresolved", + calleeCallableIds: [], + }); + expect(ir.frontiers).toEqual([ + expect.objectContaining({ + kind: "dynamic-call", + location: ir.callSites[0]?.calleeLocation, + reason: "Unsupported MemberExpression call target.", + }), + ]); + expect(ir.expressionFlows).toEqual([]); + expect(ir.objectOperations).toEqual([ + expect.objectContaining({ + kind: "read", + propertyPath: ["method"], + }), + ]); +}); diff --git a/src/domain/javascript/javascriptSemanticCallResolution.ts b/src/domain/javascript/javascriptSemanticCallResolution.ts index 2885083e363..47d39119293 100644 --- a/src/domain/javascript/javascriptSemanticCallResolution.ts +++ b/src/domain/javascript/javascriptSemanticCallResolution.ts @@ -9,10 +9,8 @@ import type { import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import { semanticCallableIdForNode } from "./javascriptSemanticProjection.js"; import { semanticBindingAtRead } from "./javascriptSemanticMutationInitializers.js"; -import { - unwrapJavaScriptExpression, - runtimeFunctionParameters, -} from "./javascriptAstValues.js"; +import { runtimeFunctionParameters } from "./javascriptAstValues.js"; +import { unwrapPureSemanticSequenceExpression } from "./javascriptSemanticGlobalReference.js"; import { resolveSemanticBindingState, type JavaScriptSemanticAnalysisState, @@ -60,13 +58,15 @@ export const resolveLocalCallables = ( bindingCache: input.bindingCache, }); +export { unwrapPureSemanticSequenceExpression }; + const resolveCallables = ( node: t.Node, context: CallResolutionContext, ): LocalCallableResolution => { - // `unwrapJavaScriptExpression` strips all transparent layers iteratively, - // so a single recursion step suffices (no per-layer stack growth). - const unwrapped = unwrapJavaScriptExpression(node).node; + // `unwrapPureSemanticSequenceExpression` strips all transparent layers and + // pure-leading sequences iteratively, so a single recursion step suffices. + const unwrapped = unwrapPureSemanticSequenceExpression(node, context.state); if (unwrapped !== node) return resolveCallables(unwrapped, context); const direct = semanticCallableIdForNode(node); if (direct !== null && context.callableById.has(direct)) diff --git a/src/domain/javascript/javascriptSemanticCalls.ts b/src/domain/javascript/javascriptSemanticCalls.ts index a417b45c9b7..4063ef1c101 100644 --- a/src/domain/javascript/javascriptSemanticCalls.ts +++ b/src/domain/javascript/javascriptSemanticCalls.ts @@ -15,7 +15,6 @@ import { javaScriptExpressionWrapperTarget, readExactJavaScriptLiteral, semanticStaticPropertyKey, - unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; import { resolveSemanticBindingState, @@ -26,6 +25,7 @@ import { type LocalCallableResolution, parameterBindings, resolveLocalCallables, + unwrapPureSemanticSequenceExpression, } from "./javascriptSemanticCallResolution.js"; import { traverseJavaScriptValueAst } from "./javascriptSemanticTraversal.js"; import { range } from "./javascriptStaticAnalysisHelpers.js"; @@ -247,7 +247,7 @@ const retainedArguments = ( if (node === null) continue; const valueNode = t.isExpression(node) && !t.isSpreadElement(node) - ? unwrapJavaScriptExpression(node).node + ? unwrapPureSemanticSequenceExpression(node, state) : null; retained.push({ index, diff --git a/src/domain/javascript/javascriptSemanticDerivedAnalysis.ts b/src/domain/javascript/javascriptSemanticDerivedAnalysis.ts index dfb837312a2..29996c986dc 100644 --- a/src/domain/javascript/javascriptSemanticDerivedAnalysis.ts +++ b/src/domain/javascript/javascriptSemanticDerivedAnalysis.ts @@ -21,6 +21,10 @@ import { readExactJavaScriptLiteral, unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; +import { + isIntrinsicGlobalReference, + unwrapPureSemanticSequenceExpression, +} from "./javascriptSemanticGlobalReference.js"; import { semanticPrimitiveSet } from "./javascriptSemanticPrimitives.js"; import { JAVASCRIPT_ANALYSIS_RESOURCE_DEFAULTS } from "./javascriptAnalysisResourceControls.js"; @@ -163,11 +167,13 @@ function* collectExpressionFlowsSteps( const initializers: JavaScriptSemanticIr["initializerFlows"][number][] = []; const literalReturns: JavaScriptSemanticIr["literalReturns"][number][] = []; const candidates: { node: t.Node; ownerCallableId: string | null }[] = []; + const discardedPureExpressions = new WeakSet(); let truncated = false; const stack = createSemanticCallableIdStack( new Set(callables.map((item) => item.callableId)), ); yield* traverseJavaScriptValueAstSteps(program, state.erasedSyntaxNodes, { + skip: (node) => discardedPureExpressions.has(node), enter: (node, parent) => { stack.enter(node, parent); const returnValue = t.isReturnStatement(node) @@ -176,7 +182,10 @@ function* collectExpressionFlowsSteps( ? node.body : null; if (returnValue != null) { - const expression = unwrapJavaScriptExpression(returnValue).node; + const expression = unwrapPureSemanticSequenceExpression( + returnValue, + state, + ); const exact = readExactJavaScriptLiteral(expression); if (exact.found) { const value = semanticPrimitiveSet([exact.value], state.precision); @@ -198,13 +207,25 @@ function* collectExpressionFlowsSteps( t.isIdentifier(node.id) && node.init != null ) { - const init = unwrapJavaScriptExpression(node.init).node; - if (isInfluenceExpression(init)) { + const init = unwrapPureSemanticSequenceExpression(node.init, state); + if ( + isInfluenceExpression(init) || + (t.isIdentifier(init) && + !isIntrinsicGlobalReference(init, state, "undefined")) + ) { if (initializers.length < budget) initializers.push({ target: range(node.id), source: range(init) }); else truncated = true; } } + if ( + t.isSequenceExpression(node) && + unwrapPureSemanticSequenceExpression(node, state) !== node + ) { + for (const leading of node.expressions.slice(0, -1)) + discardedPureExpressions.add(leading); + return; + } if ( isInfluenceExpression(node) && !(t.isTemplateLiteral(node) && t.isTaggedTemplateExpression(parent)) @@ -259,7 +280,7 @@ function* collectExpressionFlowsSteps( (t.isUnaryExpression(node) && (node.operator === "void" || node.operator === "delete")) || (t.isSequenceExpression(node) && index !== values.length - 1); - const operand = unwrapJavaScriptExpression(value).node; + const operand = unwrapPureSemanticSequenceExpression(value, state); const exact = readExactJavaScriptLiteral(operand); const literal = exact.found ? semanticPrimitiveSet([exact.value], state.precision) @@ -313,7 +334,7 @@ function* collectAssignmentFlowsSteps( const target = unwrapJavaScriptExpression(node.left).node; // Destructuring has its own property-selection owner. if (!t.isIdentifier(target) && !t.isMemberExpression(target)) return; - const source = unwrapJavaScriptExpression(node.right).node; + const source = unwrapPureSemanticSequenceExpression(node.right, state); flows.push({ target: range(target), source: range(source), diff --git a/src/domain/javascript/javascriptSemanticExecutionPoints.test.ts b/src/domain/javascript/javascriptSemanticExecutionPoints.test.ts index 11230a4780d..7afc80a0088 100644 --- a/src/domain/javascript/javascriptSemanticExecutionPoints.test.ts +++ b/src/domain/javascript/javascriptSemanticExecutionPoints.test.ts @@ -101,3 +101,47 @@ it.each(["!trigger", "typeof trigger", "void trigger", "trigger === 1"])( ); }, ); + +it("detaches member receiver on sequence member calls while preserving property-read and leading calls", () => { + const direct = parsed("obj.method(arg);"); + const directStmt = direct.body[0]; + if ( + !t.isExpressionStatement(directStmt) || + !t.isCallExpression(directStmt.expression) + ) + throw new Error("Expected direct call"); + expect(javaScriptExecutions(directStmt.expression, directStmt)).toEqual([ + { + kind: "call", + node: directStmt.expression, + operands: [ + (directStmt.expression.callee as t.MemberExpression).object, + directStmt.expression.arguments[0], + ], + }, + ]); + + const sequence = parsed("(0, obj.method)(arg);"); + const seqStmt = sequence.body[0]; + if ( + !t.isExpressionStatement(seqStmt) || + !t.isCallExpression(seqStmt.expression) + ) + throw new Error("Expected sequence call"); + expect(javaScriptExecutions(seqStmt.expression, seqStmt)).toEqual([ + { + kind: "call", + node: seqStmt.expression, + operands: [seqStmt.expression.arguments[0]], + }, + ]); + expect(Object.fromEntries(kindsByType("(0, obj.method)(arg);"))).toEqual({ + CallExpression: ["call"], + MemberExpression: ["property-read"], + }); + expect( + Object.fromEntries(kindsByType("(sideEffect(), localFn)(arg);")), + ).toEqual({ + CallExpression: ["call", "call"], + }); +}); diff --git a/src/domain/javascript/javascriptSemanticGlobalReference.ts b/src/domain/javascript/javascriptSemanticGlobalReference.ts index 7a8b36f3598..22b193d7e6a 100644 --- a/src/domain/javascript/javascriptSemanticGlobalReference.ts +++ b/src/domain/javascript/javascriptSemanticGlobalReference.ts @@ -1,4 +1,5 @@ import * as t from "@babel/types"; +import { unwrapPureJavaScriptSequenceExpression } from "./javascriptAstValues.js"; import { electronMemberPath } from "./javascriptElectronMemberWrites.js"; import { isUnshadowedGlobal } from "./javascriptSemanticMutationInitializers.js"; import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js"; @@ -78,3 +79,12 @@ export const isUnmodifiedImportMetaUrl = ( ): boolean => isImportMetaUrl(node) && !ambientPathMayHaveChanged(state, ["import-meta", "url"]); + +/** Strip transparent syntax wrappers and pure-leading comma sequences. */ +export const unwrapPureSemanticSequenceExpression = ( + node: t.Node, + state: JavaScriptSemanticAnalysisState, +): t.Node => + unwrapPureJavaScriptSequenceExpression(node, (identifier) => + isIntrinsicGlobalReference(identifier, state, "undefined"), + ); diff --git a/src/domain/javascript/javascriptSemanticReturns.ts b/src/domain/javascript/javascriptSemanticReturns.ts index 31e23057013..886a637d6dc 100644 --- a/src/domain/javascript/javascriptSemanticReturns.ts +++ b/src/domain/javascript/javascriptSemanticReturns.ts @@ -18,7 +18,7 @@ import type { } from "./javascriptExportShapeComparisonSchemas.js"; import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; import { semanticCallableIdForNode } from "./javascriptSemanticProjection.js"; -import { unwrapJavaScriptExpression } from "./javascriptAstValues.js"; +import { unwrapPureSemanticSequenceExpression } from "./javascriptSemanticCallResolution.js"; import { resolveSemanticBindingState, type JavaScriptSemanticAnalysisState, @@ -57,7 +57,7 @@ export const collectSemanticReturns = ( const returned = expression.node === null ? null - : unwrapJavaScriptExpression(expression.node).node; + : unwrapPureSemanticSequenceExpression(expression.node, state); sites.push({ returnSiteId: semanticReturnSiteId( callable.callableId, @@ -191,7 +191,7 @@ const callableIdsForNode = ( seen: ReadonlySet, snapshot = false, ): string[] => { - const unwrapped = unwrapJavaScriptExpression(node).node; + const unwrapped = unwrapPureSemanticSequenceExpression(node, state); if (unwrapped !== node) return callableIdsForNode(unwrapped, state, admitted, seen, snapshot); const direct = semanticCallableIdForNode(node); diff --git a/src/domain/javascript/javascriptSemanticValues.ts b/src/domain/javascript/javascriptSemanticValues.ts index 7e67920ce67..8d7718c61e1 100644 --- a/src/domain/javascript/javascriptSemanticValues.ts +++ b/src/domain/javascript/javascriptSemanticValues.ts @@ -44,6 +44,7 @@ import { semanticStaticPropertyKey, unwrapJavaScriptExpression, } from "./javascriptAstValues.js"; +import { unwrapPureSemanticSequenceExpression } from "./javascriptSemanticGlobalReference.js"; import { semanticAmbiguousProvenance, semanticLocalProvenance, @@ -650,6 +651,26 @@ const evaluateExpressionValue = ( expressionDepth: context.expressionDepth + unwrapped.depth, }); } + const unwrappedSequence = unwrapPureSemanticSequenceExpression( + node, + context.state, + ); + if (unwrappedSequence !== node) { + if ( + context.expressionDepth + 1 > + context.state.precision.expression_depth + ) { + context.dependence.lowest = EVERY_CALLER; + return semanticResourceLimitUnknown( + "expression-depth", + context.state.precision, + ); + } + return evaluateExpression(unwrappedSequence, { + ...context, + expressionDepth: context.expressionDepth + 1, + }); + } const literal = readExactJavaScriptLiteral(node); if (literal.found) return primitiveSet([literal.value], context.state.precision);