benjamn/recast — pull request #26 by benjamn (2013-06-03 06:02:35+00:00)
Title: Insert parentheses where necessary

Closes #21.

Improper parentheses handling was an issue I avoided for a long time because it's possible to get away with naive parenthesization as long as you don't trigger generic reprinting of an expression that requires parentheses. I was also able to postpone fixing the problem by conservatively parenthesizing certain expressions (such as `SequenceExpression`s) that were likely to need parentheses anyway. Nevertheless, as you can tell from running `whiskey lib/parens.js` without any of the subsequent commits, this branch vastly improves the correctness of the pretty-printer with regard to parentheses.

Determining whether parentheses are necessary is a task that requires examining the ancestry of the node in question, so this branch introduces the notion of a `Path` from the root of the AST to the node currently being printed. Once the `Path` abstraction was introduced, the remaining work was mostly a matter of implementing rules for various situations.

I owe a significant debt of gratitude to https://github.com/mishoo/UglifyJS2/blob/9fc6796d2a/lib/output.js#L425 for inspiring many of these rules, although I had to rewrite each of them in terms of Esprima AST node types.