Skip to content

Commit

Permalink
Fix simplifyCalls (#125)
Browse files Browse the repository at this point in the history
* Fix case where there are no arguments beyond the 'this' object

* For SAFE: simplifyCalls -
  Add test cases for calls without args.
  Add a TN test for calls without the ThisExpression
  • Loading branch information
BenBaryoPX authored Nov 3, 2024
1 parent 394c221 commit 7e0ce83
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
5 changes: 2 additions & 3 deletions src/modules/safe/simplifyCalls.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,13 @@ function simplifyCalls(arb, candidateFilter = () => true) {
for (let i = 0; i < arb.ast.length; i++) {
const n = arb.ast[i];
if (n.type === 'CallExpression' &&
n.arguments.length &&
n.arguments[0].type === 'ThisExpression' &&
n.arguments?.[0]?.type === 'ThisExpression' &&
n.callee.type === 'MemberExpression' &&
['apply', 'call'].includes(n.callee.property?.name || n.callee.property?.value) &&
(n.callee.object?.name || n.callee?.value) !== 'Function' &&
!/function/i.test(n.callee.object.type) &&
candidateFilter(n)) {
const args = (n.callee.property?.name || n.callee.property?.value) === 'apply' ? n.arguments[1].elements : n.arguments.slice(1);
const args = (n.callee.property?.name || n.callee.property?.value) === 'apply' ? n.arguments?.[1]?.elements : n.arguments?.slice(1);
arb.markNode(n, {
type: 'CallExpression',
callee: n.callee.object,
Expand Down
14 changes: 13 additions & 1 deletion tests/modules.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -682,12 +682,24 @@ describe('SAFE: separateChainedDeclarators', async () => {
});
describe('SAFE: simplifyCalls', async () => {
const targetModule = (await import('../src/modules/safe/simplifyCalls.js')).default;
it('TP-1', () => {
it('TP-1: With args', () => {
const code = `func1.apply(this, [arg1, arg2]); func2.call(this, arg1, arg2);`;
const expected = `func1(arg1, arg2);\nfunc2(arg1, arg2);`;
const result = applyModuleToCode(code, targetModule);
assert.strictEqual(result, expected);
});
it('TP-2: Without args', () => {
const code = `func1.apply(this); func2.call(this);`;
const expected = `func1();\nfunc2();`;
const result = applyModuleToCode(code, targetModule);
assert.strictEqual(result, expected);
});
it('TN-1: Ignore calls without ThisExpression', () => {
const code = `func1.apply({}); func2.call(null);`;
const expected = code;
const result = applyModuleToCode(code, targetModule);
assert.strictEqual(result, expected);
});
});
describe('SAFE: simplifyIfStatements', async () => {
const targetModule = (await import('../src/modules/safe/simplifyIfStatements.js')).default;
Expand Down

0 comments on commit 7e0ce83

Please sign in to comment.