Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Short variable declaration in a 'for' loop should be outside the for_clause #164

Open
bhaible opened this issue Mar 4, 2025 · 0 comments

Comments

@bhaible
Copy link

bhaible commented Mar 4, 2025

A program that tracks the meaning of variables can usually work like this:

  • Recursive traversal through the TSNode tree.
  • When encountering a var_declaration, const_declaration, or short_var_declaration, take note of the variables in these declarations, which have a scope that lasts until the end of the current recursion level.

This simple algorithm works fine

But for the short_var_declaration in a for statement (cf. https://go.dev/ref/spec#For_statements), it does not work, because what tree-sitter returns has the structure

(for_statement (for_clause initializer: (short_var_declaration ...) ...) ...)

Here the program has to special-case for_statement and pull out the initializer field from the for_clause. This is cumbersome. It would be simpler if tree-sitter returned a structure like this:

(for_statement initializer: (short_var_declaration ...) (for_clause ...) ...)

How to reproduce:
Process this input file:

package main

import "fmt"

var z [5]string

func main() {
    for z := 1; z < 5; z++ {
        fmt.Printf("%v\n", z)
    }
}

The syntax tree that tree-sitter produces is:

(source_file (package_clause (package_identifier)) (import_declaration (import_spec path: (interpreted_string_literal (interpreted_string_literal_content)))) (var_declaration (var_spec name: (identifier) type: (array_type length: (int_literal) element: (type_identifier)))) (function_declaration name: (identifier) parameters: (parameter_list) body: (block (for_statement (for_clause initializer: (short_var_declaration left: (expression_list (identifier)) right: (expression_list (int_literal))) condition: (binary_expression left: (identifier) right: (int_literal)) update: (inc_statement (identifier))) body: (block (expression_statement (call_expression function: (selector_expression operand: (identifier) field: (field_identifier)) arguments: (argument_list (interpreted_string_literal (interpreted_string_literal_content) (escape_sequence)) (identifier)))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant