benjamn / recast

JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
MIT License
4.91k stars 347 forks source link

Pretty-print output for increment/decrement operator expression followed by method call causes error when evaluated #1384

Open cgdangelo opened 6 months ago

cgdangelo commented 6 months ago

Given an expression of the form (a++).toString(), pretty-printing removes the parentheses around the operator expression, transforming it to a++.toString().

When that output is evaluated, a SyntaxError or ReferenceError is thrown for postfix and prefix operators respectively.

> recast.print(recast.parse("a=0;(a++).toString()")).code
'a=0;(a++).toString()'
> eval(_)
'0'
> recast.prettyPrint(recast.parse("a=0;(a++).toString()")).code
'a = 0;\na++.toString();'
> eval(_)
Uncaught SyntaxError: Unexpected token '.'
> recast.print(recast.parse("a=0;(--a).toString()")).code
'a=0;(--a).toString()'
> eval(_)
'-1'
> recast.prettyPrint(recast.parse("a=0;(--a).toString()")).code
'a = 0;\n--a.toString();'
> eval(_)
Uncaught ReferenceError: Invalid left-hand side expression in prefix operation
    at eval (eval at <anonymous> (REPL484:1:1), <anonymous>:2:5)