From 5c365b6764a6c18d8d5b92f55d019c9d4e3ee576 Mon Sep 17 00:00:00 2001 From: echo094 <20028238+echo094@users.noreply.github.com> Date: Sun, 25 Feb 2024 23:03:45 +0800 Subject: [PATCH] sojsonv7: fix bug in purifyFunction #75 Signed-off-by: echo094 <20028238+echo094@users.noreply.github.com> --- src/plugin/sojsonv7.js | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/src/plugin/sojsonv7.js b/src/plugin/sojsonv7.js index 0a7e9de..e0e89f3 100644 --- a/src/plugin/sojsonv7.js +++ b/src/plugin/sojsonv7.js @@ -784,22 +784,42 @@ function unlockEnv(ast) { traverse(ast, { StringLiteral: unlockLint }) } +/** + * If a function acts as follows: + * A = function (p1, p2) { return p1 + p2 } + * + * Convert its call to a binary expression: + * A(a, b) => a + b + */ function purifyFunction(path) { - const node = path.node - if (!t.isIdentifier(node.left) || !t.isFunctionExpression(node.right)) { + const left = path.get('left') + const right = path.get('right') + if (!left.isIdentifier() || !right.isFunctionExpression()) { + return + } + const name = left.node.name + const params = right.node.params + if (params.length !== 2) { return } - const name = node.left.name - if (node.right.body.body.length !== 1) { + const name1 = params[0].name + const name2 = params[1].name + if (right.node.body.body.length !== 1) { return } - let retStmt = node.right.body.body[0] + let retStmt = right.node.body.body[0] if (!t.isReturnStatement(retStmt)) { return } if (!t.isBinaryExpression(retStmt.argument, { operator: '+' })) { return } + if ( + retStmt.argument.left?.name !== name1 || + retStmt.argument.right?.name !== name2 + ) { + return + } const fnPath = path.getFunctionParent() || path.scope.path fnPath.traverse({ CallExpression: function (_path) {