benjamn / recast

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

If statements on same line aren't always separated with semicolon #222

Open Flaise opened 9 years ago

Flaise commented 9 years ago

I'm using Recast for macro evaluation by replacing nodes of the AST with other sub-ASTs. I've found a situation where it doesn't generate valid Javascript:

var recast = require('recast')
var builders = recast.types.builders
var parse = recast.parse
var print = recast.print

var branchA = parse('if(a) b()').program.body[0]
var branchB = parse('if(b) a()').program.body[0]
var main = parse('r\ns')
main.program.body[0] = branchA
main.program.body[1] = branchB

console.log(print(main).code)

Output:

if(a) b()if(b) a()

It appears that Recast doesn't know what to do when the loc objects refer to different sources of input. I can make it work by doing this:

delete branchA.loc
console.log(print(main).code)

Output:

if(a) b()
if(b) a()

But it would be nice if Recast knew what to do for this edge case.

Using: Node 4.1.1 recast 0.10.34

benjamn commented 9 years ago

How would you feel about the printer inserting a semicolon in cases like these?

Flaise commented 9 years ago

It would be surprising behavior because r and s are separated by a newline but as long as it's valid Javascript it's good for my use case.