Skip to content

fix(safe eval): apply compound assignment operators and support ++/-- - #298

Open
bardrop wants to merge 1 commit into
JSONPath-Plus:mainfrom
bardrop-oss:fix-safe-eval-compound-assignment
Open

bardrop wants to merge 1 commit into
JSONPath-Plus:mainfrom
bardrop-oss:fix-safe-eval-compound-assignment

Conversation

@bardrop

@bardrop bardrop commented Nov 16, 2026

Copy link
Copy Markdown

PR description

Fixes #297.

The jsep assignment plugin parses all compound assignment operators and ++ / --, but the safe evaluator always did a plain = (it never read ast.operator), and had no case for UpdateExpression. So with the default eval: "safe", x = 30, x -= @.v set x to @.v, silently, and x++ threw Unexpected expression.

What changed in src/Safe-Script.js:

  • x op= y now runs BINOPS[op](x, () => y), so it reuses the existing operator table. ||=, &&= and ??= keep short-circuiting the right side.
  • New evalUpdateExpression for prefix and postfix ++ / --. It lets JS do the update on a local copy, so number conversion matches JS ("4"++ gives 5).
  • Like in JS, a compound assignment or update on an undefined variable now throws a ReferenceError (q is not defined). Before, q += 1 quietly set q to 1.
  • Property operands (@.v += 1, @.v++) are still refused, same as @.v = 1 today.

I checked every compound operator and both update forms against plain JS with 7 start values (number, numeric string, 0, null, undefined, negative). All match on this branch; main differed on 117 of 137 cases. (2n BigInt literals are not parsed by jsep, so they are out of scope.)

Checklist

  • - Added tests
  • - Ran npm test, ensuring linting passes
  • - Adjust README documentation if relevant (not needed: README does not list the supported syntax)

The jsep assignment plugin parses `+=`, `-=`, `*=`, `??=` and the other
compound operators, but the safe evaluator ignored `ast.operator` and
always did a plain `=`. So `x = 30, x -= @.price` set x to the price
instead of subtracting it, with no error, and only gave the right answer
for `+=` when x started at 0. `x++` / `--x` (UpdateExpression) failed
with "Unexpected expression".

Compound operators now reuse the binary operator table (`||=`, `&&=` and
`??=` still short-circuit their right side), and `++` / `--` follow JS
for prefix and postfix forms. Like in JS, using an undefined variable on
the left now throws a ReferenceError instead of silently treating it as
a fresh variable. Property operands are still refused.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Safe eval treats -=, *= and other compound assignments as =

1 participant