tdewolff / parse

Go parsers for web formats
MIT License
408 stars 64 forks source link

JS: Fix EmptyStmt Semicolon duplication when converts the AST to JS #100

Closed nidorx closed 2 years ago

nidorx commented 2 years ago

When converting AST to Javascript, when finding an EmptyStmt, a semicolon is being added.

The problem with this is that a new AST generated from this original conversion will result in different output than the previous one.

The test below, in the current version, results in an error.

  1. a; ; after 2 .JS() will be a; ;; ;; Screen Shot 2022-08-27 at 12 47 20

  2. function x() { let a = 33; ; } after 2 .JS() will be function x() { let a = 33; ;; ;; } Screen Shot 2022-08-27 at 12 47 35

The fix just ignores when an item from a BlockStmt is an EmptyStmt

Screen Shot 2022-08-27 at 12 52 10

func TestEmptyStmtToJs(t *testing.T) {
    var tests = []struct {
        input  string
        output string
    }{
        {"a; ;", "a; "},
        {"function x() { let a = 33; ; }", "function x () { let a = 33; }; "},
    }
    for _, tt := range tests {
        t.Run(tt.input, func(t *testing.T) {
            ast, err := Parse(parse.NewInputString(tt.input), Options{})
            if err != io.EOF {
                test.Error(t, err)
            }

            ast2, err := Parse(parse.NewInputString(ast.JS()), Options{})
            if err != io.EOF {
                test.Error(t, err)
            }
            test.String(t, ast2.JS(), tt.output)
        })
    }
}
tdewolff commented 2 years ago

Thanks!