tree-sitter / tree-sitter-go

Go grammar for tree-sitter
MIT License
317 stars 63 forks source link

`import` syntax bug #121

Closed mjambon closed 1 year ago

mjambon commented 1 year ago

Here's a valid Go program (with nonstandard formatting):

$ cat bug.go 
package main
import ("fmt")
func main() {
    fmt.Println("yo")
}

$ go run bug.go
yo

The tree-sitter-go parser doesn't like it:

~/tree-sitter-go $ npx tree-sitter parse bug.go
(source_file [0, 0] - [5, 0]
  (package_clause [0, 0] - [0, 12]
    (package_identifier [0, 8] - [0, 12]))
  (import_declaration [1, 0] - [1, 14]
    (import_spec_list [1, 7] - [1, 14]
      (ERROR [1, 8] - [1, 13]
        (import_spec [1, 8] - [1, 13]
          path: (interpreted_string_literal [1, 8] - [1, 13])))))
  (function_declaration [2, 0] - [4, 1]
    name: (identifier [2, 5] - [2, 9])
    parameters: (parameter_list [2, 9] - [2, 11])
    body: (block [2, 12] - [4, 1]
      (call_expression [3, 1] - [3, 18]
        function: (selector_expression [3, 1] - [3, 12]
          operand: (identifier [3, 1] - [3, 4])
          field: (field_identifier [3, 5] - [3, 12]))
        arguments: (argument_list [3, 12] - [3, 18]
          (interpreted_string_literal [3, 13] - [3, 17]))))))
bug.go  0 ms    (ERROR [1, 8] - [1, 13])

Here's a simpler example. Note that we get different kinds of errors (ERROR vs. MISSING) depending on the string length:

~/tree-sitter-go $ npx tree-sitter parse <(echo 'import ("foooooo")')
(source_file [0, 0] - [1, 0]
  (import_declaration [0, 0] - [0, 18]
    (import_spec_list [0, 7] - [0, 18]
      (ERROR [0, 8] - [0, 17]
        (import_spec [0, 8] - [0, 17]
          path: (interpreted_string_literal [0, 8] - [0, 17]))))))
/dev/fd/63  0 ms    (ERROR [0, 8] - [0, 17])

~/tree-sitter-go $ npx tree-sitter parse <(echo 'import ("fooooooo")')
(source_file [0, 0] - [1, 0]
  (import_declaration [0, 0] - [0, 19]
    (import_spec_list [0, 7] - [0, 19]
      (import_spec [0, 8] - [0, 18]
        path: (interpreted_string_literal [0, 8] - [0, 18])))))
/dev/fd/63  0 ms    (MISSING "\n" [0, 18] - [0, 18])

~/tree-sitter-go $ npx tree-sitter --version
tree-sitter 0.20.8 (d4c1bf7ce78051b7f4a381d1508d68928512ed5f)

This is a minor bug since the Go reformatter will normally reformat this, resulting in parsing success (try go fmt bug.go).

The different behavior ERROR vs. MISSING is intriguing, though.