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
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,15 @@ export function replaceIdentifierWithFixedValueNotAssignedAtDeclarationMatch(arb

// Check for exactly one assignment to a literal value
const assignmentRef = getSingleAssignmentReference(n);
if (assignmentRef && assignmentRef.parentNode.right.type === 'Literal') {
if (assignmentRef && (assignmentRef.parentNode.right.type === 'Literal' || assignmentRef.parentNode.right.type === 'Identifier')) {

// Ensure no unsafe usage patterns exist
// Only check conditional context for write (assignment) references -
// a read reference inside a conditional is safe to inline
const isWriteReference = (r) =>
r.parentNode?.type === 'AssignmentExpression' && r.parentKey === 'left';
const hasUnsafeReferences = n.references.some(r =>
isForLoopIterator(r) || isInConditionalContext(r)
isForLoopIterator(r) || (isWriteReference(r) && isInConditionalContext(r))
);

if (!hasUnsafeReferences) {
Expand Down Expand Up @@ -130,12 +134,23 @@ export function replaceIdentifierWithFixedValueNotAssignedAtDeclarationTransform

// Additional safety check: ensure references aren't modified in complex ways
if (!areReferencesModified(arb.ast, referencesToReplace)) {
// For Identifier values (e.g., te = O), verify the target is safe to inline
if (valueNode.type === 'Identifier') {
if (!valueNode.declNode) {
return arb; // Can't verify target safety without declaration node
}
const targetRefs = valueNode.declNode.references || [];
if (areReferencesModified(arb.ast, targetRefs)) {
return arb;
}
}
for (let i = 0; i < referencesToReplace.length; i++) {
const ref = referencesToReplace[i];

// Skip function calls where identifier is the callee
// Example: let func; func = someFunction; func(); // Don't replace func()
if (ref.parentNode.type === 'CallExpression' && ref.parentKey === 'callee') {

// Skip function calls where identifier is the callee and value is a Literal
// Example: let x; x = 3; x(); // Don't replace with 3()
// But allow: let te; te = O; te(123); // Replace with O(123)
if (ref.parentNode.type === 'CallExpression' && ref.parentKey === 'callee' && valueNode.type === 'Literal') {
continue;
}

Expand Down
15 changes: 14 additions & 1 deletion src/modules/safe/replaceNewFuncCallsWithLiteralContent.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,20 @@ function parseCodeStringToAST(codeStr) {
};
}

const body = generateFlatAST(codeStr, {detailed: false, includeSrc: false})[0].body;
let body;
const flatAST = generateFlatAST(codeStr, {detailed: false, includeSrc: false});
if (flatAST.length && flatAST[0].body) {
body = flatAST[0].body;
} else {
// Code string comes from new Function("code") where "code" is a function body.
// Statements like "return this" are only valid inside a function, so wrap and re-parse.
const wrappedAST = generateFlatAST(`(function(){${codeStr}})`, {detailed: false, includeSrc: false});
const funcBody = wrappedAST.length && wrappedAST[0].body[0]?.expression?.body?.body;
if (!funcBody) {
throw new Error(`Failed to parse code string: "${codeStr.substring(0, 80)}..."`);
}
body = funcBody;
}

if (body.length > 1) {
return {
Expand Down
43 changes: 41 additions & 2 deletions src/modules/safe/resolveProxyReferences.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,30 @@ import {areReferencesModified} from '../utils/areReferencesModified.js';
import {doesDescendantMatchCondition} from '../utils/doesDescendantMatchCondition.js';
import {getMainDeclaredObjectOfMemberExpression} from '../utils/getMainDeclaredObjectOfMemberExpression.js';

/**
* Checks if the target identifier name is shadowed by a different declaration
* at the reference's scope, which would make replacement incorrect.
*/
function isTargetShadowedAtReference(ref, targetName, targetDeclNode) {
let scope = ref.scope;
while (scope) {
const vars = scope.variables || [];
for (let j = 0; j < vars.length; j++) {
if (vars[j].name === targetName) {
const ids = vars[j].identifiers || [];
for (let k = 0; k < ids.length; k++) {
if (ids[k] === targetDeclNode) {
return false; // Same declaration = not shadowed
}
}
return true; // Different declaration = shadowed
}
}
scope = scope.upper;
}
return false;
}

// Static array for supported node types to avoid recreation overhead
const SUPPORTED_REFERENCE_TYPES = ['Identifier', 'MemberExpression'];

Expand Down Expand Up @@ -126,7 +150,8 @@ export function resolveProxyReferencesMatch(arb, candidateFilter = () => true) {
}

// Both the proxy and target must not be modified
if (areReferencesModified(arb.ast, refs) || areReferencesModified(arb.ast, [n.init])) {
const initRefs = n.init.declNode?.references || [n.init];
if (areReferencesModified(arb.ast, refs) || areReferencesModified(arb.ast, initRefs)) {
continue;
}

Expand Down Expand Up @@ -157,7 +182,21 @@ export function resolveProxyReferencesTransform(arb, match) {

// Replace each reference to the proxy with the target
for (let i = 0; i < references.length; i++) {
arb.markNode(references[i], targetNode);
const ref = references[i];
// Determine which name to check for shadowing
let checkName, checkDeclNode;
if (targetNode.type === 'Identifier') {
checkName = targetNode.name;
checkDeclNode = targetNode.declNode;
} else if (targetNode.type === 'MemberExpression') {
const rootObj = getMainDeclaredObjectOfMemberExpression(targetNode);
checkName = rootObj?.name;
checkDeclNode = rootObj?.declNode;
}
if (checkName && isTargetShadowedAtReference(ref, checkName, checkDeclNode)) {
continue;
}
arb.markNode(ref, targetNode);
}

return arb;
Expand Down
83 changes: 80 additions & 3 deletions src/modules/safe/resolveProxyVariables.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
import {areReferencesModified} from '../utils/areReferencesModified.js';

/**
* Checks if the target identifier name is shadowed by a different declaration
* at the reference's scope, which would make replacement incorrect.
*/
function isTargetShadowedAtReference(ref, targetName, targetDeclNode) {
let scope = ref.scope;
while (scope) {
const vars = scope.variables || [];
for (let j = 0; j < vars.length; j++) {
if (vars[j].name === targetName) {
const ids = vars[j].identifiers || [];
for (let k = 0; k < ids.length; k++) {
if (ids[k] === targetDeclNode) {
return false; // Same declaration = not shadowed
}
}
return true; // Different declaration = shadowed
}
}
scope = scope.upper;
}
return false;
}

/**
* Validates that a VariableDeclarator represents a proxy variable assignment.
*
Expand Down Expand Up @@ -87,14 +111,23 @@ export function resolveProxyVariablesTransform(arb, match) {
if (areReferencesModified(arb.ast, references)) {
return arb;
}

// Also check if the TARGET variable's references are modified
const targetRefs = targetIdentifier.declNode?.references || [];
if (areReferencesModified(arb.ast, targetRefs)) {
return arb;
}

// Replace all references with the target identifier
for (let i = 0; i < references.length; i++) {
const ref = references[i];
// Skip if target name is shadowed by a different declaration at this reference
if (isTargetShadowedAtReference(ref, targetIdentifier.name, targetIdentifier.declNode)) {
continue;
}
arb.markNode(ref, targetIdentifier);
}
}

return arb;
}

Expand Down Expand Up @@ -122,8 +155,52 @@ export function resolveProxyVariablesTransform(arb, match) {
export default function resolveProxyVariables(arb, candidateFilter = () => true) {
const matches = resolveProxyVariablesMatch(arb, candidateFilter);

// Separate matches into safe and unsafe batches
const safeMatches = [];
const unsafeMatches = [];

// Pre-validate all matches before applying any changes
for (let i = 0; i < matches.length; i++) {
arb = resolveProxyVariablesTransform(arb, matches[i]);
const match = matches[i];
const {declaratorNode, targetIdentifier, references, shouldRemove} = match;
const proxyName = declaratorNode.id?.name || '?';
const targetName = targetIdentifier?.name || '?';

// Skip self-replacements (proxy name === target name)
// These are no-ops and waste processing time
if (proxyName === targetName) {
continue;
}

if (shouldRemove) {
// Unused proxies are always safe to remove
safeMatches.push(match);
} else {
// Check safety conditions using original AST state
if (!areReferencesModified(arb.ast, references)) {
const targetRefs = targetIdentifier.declNode?.references || [];
if (!areReferencesModified(arb.ast, targetRefs)) {
// Check shadowing for each reference
let allRefsSafe = true;
for (let j = 0; j < references.length; j++) {
if (isTargetShadowedAtReference(references[j], targetIdentifier.name, targetIdentifier.declNode)) {
allRefsSafe = false;
break;
}
}
if (allRefsSafe) {
safeMatches.push(match);
continue;
}
}
}
unsafeMatches.push(match);
}
}

// Apply all safe replacements in one batch
for (let i = 0; i < safeMatches.length; i++) {
arb = resolveProxyVariablesTransform(arb, safeMatches[i]);
}

return arb;
Expand Down
Loading