Copy
package main
import "github.com/t14raptor/go-fast/ast"
// BlockStatementInsertVisitor inserts block statements where possible.
// Input:
// ```js
// if (x) y;
// while(x) y;
// for(;;) y;
// ```
// Output:
// ```js
// if (x) {
// y;
// }
// while (x) {
// y;
// }
// for (; ;) {
// y;
// }
type BlockStatementInsertVisitor struct {
ast.NoopVisitor
}
func (v *BlockStatementInsertVisitor) tryBlockStatementInsert(n *ast.Statement) {
switch n.Stmt.(type) {
case *ast.EmptyStatement, *ast.BlockStatement:
// If the statement is empty or already a block then don't do anything.
return
}
n.Stmt = &ast.BlockStatement{List: []ast.Statement{{n.Stmt}}}
}
func (v *BlockStatementInsertVisitor) VisitIfStatement(n *ast.IfStatement) {
n.VisitChildrenWith(v)
v.tryBlockStatementInsert(n.Consequent)
if n.Alternate != nil {
v.tryBlockStatementInsert(n.Alternate)
}
}
func (v *BlockStatementInsertVisitor) VisitForStatement(n *ast.ForStatement) {
n.VisitChildrenWith(v)
v.tryBlockStatementInsert(n.Body)
}
func (v *BlockStatementInsertVisitor) VisitForInStatement(n *ast.ForInStatement) {
n.VisitChildrenWith(v)
v.tryBlockStatementInsert(n.Body)
}
func (v *BlockStatementInsertVisitor) VisitForOfStatement(n *ast.ForOfStatement) {
n.VisitChildrenWith(v)
v.tryBlockStatementInsert(n.Body)
}
func (v *BlockStatementInsertVisitor) VisitWhileStatement(n *ast.WhileStatement) {
n.VisitChildrenWith(v)
v.tryBlockStatementInsert(n.Body)
}