diff --git a/gazelle/BUILD.bazel b/gazelle/BUILD.bazel index 7467648c6b..30758181ed 100644 --- a/gazelle/BUILD.bazel +++ b/gazelle/BUILD.bazel @@ -6,9 +6,7 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") # gazelle:prefix github.com/bazel-contrib/rules_python/gazelle # gazelle:exclude bazel-out # gazelle:exclude deps.bzl -# gazelle:exclude internal # gazelle:exclude internal_dev_deps.bzl -# gazelle:resolve go github.com/tree-sitter/tree-sitter-python/bindings/go @com_github_tree_sitter_tree_sitter_python//:go_default_library gazelle( name = "gazelle", ) @@ -38,7 +36,7 @@ filegroup( "//modules_mapping:distribution", "//python:distribution", "//pythonconfig:distribution", - ] + glob(["internal/**"]), + ], visibility = ["@rules_python//:__pkg__"], ) diff --git a/gazelle/MODULE.bazel b/gazelle/MODULE.bazel index 407be5338f..466389ec55 100644 --- a/gazelle/MODULE.bazel +++ b/gazelle/MODULE.bazel @@ -8,7 +8,6 @@ bazel_dep(name = "bazel_skylib", version = "1.8.2") bazel_dep(name = "rules_python", version = "1.5.0") bazel_dep(name = "rules_go", version = "0.59.0", repo_name = "io_bazel_rules_go") bazel_dep(name = "gazelle", version = "0.47.0", repo_name = "bazel_gazelle") -bazel_dep(name = "rules_cc", version = "0.0.16") local_path_override( module_name = "rules_python", @@ -23,29 +22,12 @@ use_repo( "com_github_bmatcuk_doublestar_v4", "com_github_emirpasic_gods", "com_github_ghodss_yaml", - "com_github_mattn_go_pointer", + "com_github_odvcencio_gotreesitter", "com_github_stretchr_testify", "in_gopkg_yaml_v2", "org_golang_x_sync", ) -http_archive = use_repo_rule("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -http_archive( - name = "com_github_tree_sitter_go_tree_sitter", - build_file = "//:internal/go_tree_sitter_BUILD.bazel", - integrity = "sha256-rAsyh/Kydqt24TBaA6H14obQlkaQWwj1QNec3xza6NM=", - strip_prefix = "go-tree-sitter-c9492002f76ed75037e3fe6d3bbabb54ed3e1ff5", - url = "https://github.com/tree-sitter/go-tree-sitter/archive/c9492002f76ed75037e3fe6d3bbabb54ed3e1ff5.zip", -) - -http_archive( - name = "com_github_tree_sitter_tree_sitter_python", - build_file = "//:internal/tree_sitter_python_BUILD.bazel", - integrity = "sha256-e86IfrLzPpS/dKaWRc9RONQJZyDlT9MmmmEkwGuTxYQ=", - url = "https://github.com/tree-sitter/tree-sitter-python/releases/download/v0.25.0/tree-sitter-python.tar.gz", -) - python_stdlib_list = use_extension("//python:extensions.bzl", "python_stdlib_list") use_repo( python_stdlib_list, diff --git a/gazelle/deps.bzl b/gazelle/deps.bzl index a7868c666a..4df20c658d 100644 --- a/gazelle/deps.bzl +++ b/gazelle/deps.bzl @@ -31,49 +31,11 @@ def python_stdlib_list_deps(): url = "https://files.pythonhosted.org/packages/8c/25/f1540879c8815387980e56f973e54605bd924612399ace31487f7444171c/stdlib_list-0.12.0.tar.gz", ) -def tree_sitter_deps(): - "Fetch tree-sitter dependencies with custom BUILD files" - if "com_github_tree_sitter_go_tree_sitter" not in native.existing_rules(): - http_archive( - name = "com_github_tree_sitter_go_tree_sitter", - build_file = Label("//:internal/go_tree_sitter_BUILD.bazel"), - integrity = "sha256-rAsyh/Kydqt24TBaA6H14obQlkaQWwj1QNec3xza6NM=", - strip_prefix = "go-tree-sitter-c9492002f76ed75037e3fe6d3bbabb54ed3e1ff5", - url = "https://github.com/tree-sitter/go-tree-sitter/archive/c9492002f76ed75037e3fe6d3bbabb54ed3e1ff5.zip", - ) - if "com_github_tree_sitter_tree_sitter_python" not in native.existing_rules(): - http_archive( - name = "com_github_tree_sitter_tree_sitter_python", - build_file = Label("//:internal/tree_sitter_python_BUILD.bazel"), - integrity = "sha256-e86IfrLzPpS/dKaWRc9RONQJZyDlT9MmmmEkwGuTxYQ=", - url = "https://github.com/tree-sitter/tree-sitter-python/releases/download/v0.25.0/tree-sitter-python.tar.gz", - ) - def gazelle_deps(): - tree_sitter_deps() go_deps() python_stdlib_list_deps() def go_deps(): - # Prevent `bazel run //:gazelle_update_repos` from generating `go_repository` - # entries for the repos managed by `tree_sitter_deps()` or for the 11 other - # language grammars required by upstream `go-tree-sitter/go.mod` for its own - # internal unit tests. Without these directives, `gazelle update-repos` sees - # those modules in `go list -m all` and re-adds them here; declaring - # `# gazelle:repository` directives tells `update-repos` to skip them. - # gazelle:repository http_archive name=com_github_tree_sitter_go_tree_sitter - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_c - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_cpp - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_embedded_template - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_go - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_html - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_java - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_javascript - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_json - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_php - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_python - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_ruby - # gazelle:repository http_archive name=com_github_tree_sitter_tree_sitter_rust "Fetch go dependencies" go_repository( name = "com_github_bazelbuild_bazel_gazelle", @@ -149,10 +111,10 @@ def go_deps(): version = "v0.6.0", ) go_repository( - name = "com_github_mattn_go_pointer", - importpath = "github.com/mattn/go-pointer", - sum = "h1:n+XhsuGeVO6MEAp7xyEukFINEa+Quek5psIR/ylA6o0=", - version = "v0.0.1", + name = "com_github_odvcencio_gotreesitter", + importpath = "github.com/odvcencio/gotreesitter", + sum = "h1:FjtamNv5ke7SJlQxJnL75FEp3hZWVHDKBY3jXEcQw8Q=", + version = "v1.0.0-rc.1", ) go_repository( name = "com_github_pmezard_go_difflib", diff --git a/gazelle/go.mod b/gazelle/go.mod index cdf28f264f..444de1259e 100644 --- a/gazelle/go.mod +++ b/gazelle/go.mod @@ -11,9 +11,8 @@ require ( github.com/bmatcuk/doublestar/v4 v4.9.1 github.com/emirpasic/gods v1.18.1 github.com/ghodss/yaml v1.0.0 + github.com/odvcencio/gotreesitter v1.0.0-rc.1 github.com/stretchr/testify v1.9.0 - github.com/tree-sitter/go-tree-sitter v0.24.1-0.20251112183152-c9492002f76e - github.com/tree-sitter/tree-sitter-python v0.25.0 golang.org/x/sync v0.11.0 gopkg.in/yaml.v2 v2.4.0 ) @@ -21,7 +20,7 @@ require ( require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/google/go-cmp v0.6.0 // indirect - github.com/mattn/go-pointer v0.0.1 // indirect + github.com/kr/text v0.1.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect golang.org/x/mod v0.23.0 // indirect golang.org/x/sys v0.30.0 // indirect diff --git a/gazelle/go.sum b/gazelle/go.sum index 1b141b6642..1c40ba468b 100644 --- a/gazelle/go.sum +++ b/gazelle/go.sum @@ -14,16 +14,17 @@ github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/mattn/go-pointer v0.0.1 h1:n+XhsuGeVO6MEAp7xyEukFINEa+Quek5psIR/ylA6o0= -github.com/mattn/go-pointer v0.0.1/go.mod h1:2zXcozF6qYGgmsG+SeTZz3oAbFLdD3OWqnUbNvJZAlc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/odvcencio/gotreesitter v1.0.0-rc.1 h1:FjtamNv5ke7SJlQxJnL75FEp3hZWVHDKBY3jXEcQw8Q= +github.com/odvcencio/gotreesitter v1.0.0-rc.1/go.mod h1:hBVkghd0paaYAVwd2087vfwdeU984bQbMo9LvpE0moo= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/tree-sitter/go-tree-sitter v0.24.1-0.20251112183152-c9492002f76e h1:B9WMBx89/TkqtmwfP+7OhREoGB6RdgmGk9ErlbiTOFI= -github.com/tree-sitter/go-tree-sitter v0.24.1-0.20251112183152-c9492002f76e/go.mod h1:r77ig7BikoZhHrrsjAnv8RqGti5rtSyvDHPzgTPsUuU= -github.com/tree-sitter/tree-sitter-python v0.25.0 h1:O6XD9v8U1LOcRc3cNj9nM7XufrtEBezE6VrpRrHZDf0= -github.com/tree-sitter/tree-sitter-python v0.25.0/go.mod h1:cpdthSy/Yoa28aJFBscFHlGiU+cnSiSh1kuDVtI8YeM= golang.org/x/mod v0.23.0 h1:Zb7khfcRGKk+kqfxFaP5tZqCnDZMjC5VtUBs87Hr6QM= golang.org/x/mod v0.23.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= @@ -32,8 +33,9 @@ golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/tools/go/vcs v0.1.0-deprecated h1:cOIJqWBl99H1dH5LWizPa+0ImeeJq3t3cJjaeOWUAL4= golang.org/x/tools/go/vcs v0.1.0-deprecated/go.mod h1:zUrvATBAvEI9535oC0yWYsLsHIV4Z7g63sNPVMtuBy8= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/gazelle/internal/go_tree_sitter_BUILD.bazel b/gazelle/internal/go_tree_sitter_BUILD.bazel deleted file mode 100644 index 901e614cf0..0000000000 --- a/gazelle/internal/go_tree_sitter_BUILD.bazel +++ /dev/null @@ -1,47 +0,0 @@ -"""Build file for github.com/tree-sitter/go-tree-sitter.""" - -load("@io_bazel_rules_go//go:def.bzl", "go_library") -load("@rules_cc//cc:defs.bzl", "cc_library") - -cc_library( - name = "tree_sitter_sources", - hdrs = glob([ - "include/**/*.h", - "src/**/*.h", - "src/**/*.c", - ]), - defines = [ - "_DEFAULT_SOURCE", - "_POSIX_C_SOURCE=200112L", - ], - includes = [ - "include", - "src", - ], - visibility = ["//visibility:private"], -) - -go_library( - name = "go-tree-sitter", - srcs = glob( - ["*.go"], - exclude = ["*_test.go"], - ) + [ - "allocator.c", - "allocator.h", - ], - cdeps = [":tree_sitter_sources"], - cgo = True, - copts = [ - "-std=c11", - ], - importpath = "github.com/tree-sitter/go-tree-sitter", - visibility = ["//visibility:public"], - deps = ["@com_github_mattn_go_pointer//:go_default_library"], -) - -alias( - name = "go_default_library", - actual = ":go-tree-sitter", - visibility = ["//visibility:public"], -) diff --git a/gazelle/internal/tree_sitter_python_BUILD.bazel b/gazelle/internal/tree_sitter_python_BUILD.bazel deleted file mode 100644 index 1f6fe1fa81..0000000000 --- a/gazelle/internal/tree_sitter_python_BUILD.bazel +++ /dev/null @@ -1,36 +0,0 @@ -"""Build file for github.com/tree-sitter/tree-sitter-python.""" - -load("@io_bazel_rules_go//go:def.bzl", "go_library") -load("@rules_cc//cc:defs.bzl", "cc_library") - -cc_library( - name = "tree_sitter_python_sources", - hdrs = [ - "src/parser.c", - "src/scanner.c", - "src/tree_sitter/alloc.h", - "src/tree_sitter/array.h", - "src/tree_sitter/parser.h", - ], - includes = ["bindings/go"], - visibility = ["//visibility:private"], -) - -go_library( - name = "go", - srcs = ["bindings/go/binding.go"], - cdeps = [":tree_sitter_python_sources"], - cgo = True, - copts = [ - "-std=c11", - "-fPIC", - ], - importpath = "github.com/tree-sitter/tree-sitter-python/bindings/go", - visibility = ["//visibility:public"], -) - -alias( - name = "go_default_library", - actual = ":go", - visibility = ["//visibility:public"], -) diff --git a/gazelle/python/BUILD.bazel b/gazelle/python/BUILD.bazel index 5579dd7713..3de24bab3f 100644 --- a/gazelle/python/BUILD.bazel +++ b/gazelle/python/BUILD.bazel @@ -38,8 +38,8 @@ go_library( "@com_github_emirpasic_gods//lists/singlylinkedlist", "@com_github_emirpasic_gods//sets/treeset", "@com_github_emirpasic_gods//utils", - "@com_github_tree_sitter_go_tree_sitter//:go-tree-sitter", - "@com_github_tree_sitter_tree_sitter_python//:go_default_library", + "@com_github_odvcencio_gotreesitter//:gotreesitter", + "@com_github_odvcencio_gotreesitter//grammars/python", "@org_golang_x_sync//errgroup", ], ) diff --git a/gazelle/python/file_parser.go b/gazelle/python/file_parser.go index 04ba14a6c8..62de642eea 100644 --- a/gazelle/python/file_parser.go +++ b/gazelle/python/file_parser.go @@ -24,8 +24,13 @@ import ( "strings" bzl "github.com/bazelbuild/buildtools/build" - sitter "github.com/tree-sitter/go-tree-sitter" - tree_sitter_python "github.com/tree-sitter/tree-sitter-python/bindings/go" + sitter "github.com/odvcencio/gotreesitter" + pythonGrammar "github.com/odvcencio/gotreesitter/grammars/python" +) + +var ( + pythonLanguage = pythonGrammar.Language() + pythonParsers = sitter.NewParserPool(pythonLanguage) ) const ( @@ -60,20 +65,15 @@ func NewFileParser() *FileParser { return &FileParser{} } -// parseCodeToTree instantiates a new tree-sitter Parser and parses the Python code, -// returning the parsed tree-sitter Tree. Callers are responsible for calling Close() -// on the returned Tree to release its underlying C resources when finished. +// ParseCode parses Python source. Callers must release the tree after using its nodes. // It logs a warning if the syntax tree contains parse errors. -func parseCodeToTree(code []byte, path string) (*sitter.Tree, error) { - parser := sitter.NewParser() - defer parser.Close() - if err := parser.SetLanguage(sitter.NewLanguage(tree_sitter_python.Language())); err != nil { - return nil, err - } - - tree := parser.ParseCtx(context.Background(), code, nil) - if tree == nil { - return nil, fmt.Errorf("failed to parse %q", path) +func ParseCode(code []byte, path string) (*sitter.Tree, error) { + tree, err := pythonParsers.ParseStrict(code) + if err != nil { + if tree != nil { + tree.Release() + } + return nil, fmt.Errorf("failed to parse %q: %w", path, err) } root := tree.RootNode() @@ -90,51 +90,40 @@ func parseCodeToTree(code []byte, path string) (*sitter.Tree, error) { return tree, nil } - for i := uint(0); i < root.ChildCount(); i++ { + for i := 0; i < root.ChildCount(); i++ { child := root.Child(i) if child.IsError() { // Example logs: // gazelle: Parse error at {Row:1 Column:0}: // def search_one_more_level[T](): - log.Printf("Parse error at %+v:\n%+v", child.StartPosition(), child.Utf8Text(code)) + log.Printf("Parse error at %+v:\n%+v", child.StartPoint(), child.Text(code)) // Log the internal tree-sitter representation of what was parsed. Eg: // gazelle: The above was parsed as: (ERROR (identifier) (call function: (list (identifier)) arguments: (argument_list))) - log.Printf("The above was parsed as: %v", child.ToSexp()) + log.Printf("The above was parsed as: %v", child.SExpr(pythonLanguage)) } } return tree, nil } -// ParseCode instantiates a new tree-sitter Parser and parses the python code, returning -// the tree-sitter RootNode. -// It prints a warning if parsing fails. -func ParseCode(code []byte, path string) (*sitter.Node, error) { - tree, err := parseCodeToTree(code, path) - if err != nil { - return nil, err - } - return tree.RootNode(), nil -} - // parseMain returns true if the python file has an `if __name__ == "__main__":` block, // which is a common idiom for python scripts/binaries. func (p *FileParser) parseMain(ctx context.Context, node *sitter.Node) bool { - for i := uint(0); i < node.ChildCount(); i++ { + for i := 0; i < node.ChildCount(); i++ { if err := ctx.Err(); err != nil { return false } child := node.Child(i) - if child.Kind() == sitterNodeTypeIfStatement && - child.Child(1).Kind() == sitterNodeTypeComparisonOperator && child.Child(1).Child(1).Kind() == "==" { + if child.Type(pythonLanguage) == sitterNodeTypeIfStatement && + child.Child(1).Type(pythonLanguage) == sitterNodeTypeComparisonOperator && child.Child(1).Child(1).Type(pythonLanguage) == "==" { statement := child.Child(1) a, b := statement.Child(0), statement.Child(2) // convert "'__main__' == __name__" to "__name__ == '__main__'" - if b.Kind() == sitterNodeTypeIdentifier { + if b.Type(pythonLanguage) == sitterNodeTypeIdentifier { a, b = b, a } - if a.Kind() == sitterNodeTypeIdentifier && a.Utf8Text(p.code) == "__name__" && - b.Kind() == sitterNodeTypeString && string(p.code[b.StartByte()+1:b.EndByte()-1]) == "__main__" { + if a.Type(pythonLanguage) == sitterNodeTypeIdentifier && a.Text(p.code) == "__name__" && + b.Type(pythonLanguage) == sitterNodeTypeString && string(p.code[b.StartByte()+1:b.EndByte()-1]) == "__main__" { return true } } @@ -145,18 +134,18 @@ func (p *FileParser) parseMain(ctx context.Context, node *sitter.Node) bool { // parseImportStatement parses a node for an import statement, returning a `Module` and a boolean // representing if the parse was OK or not. func parseImportStatement(node *sitter.Node, code []byte) (Module, bool) { - switch node.Kind() { + switch node.Type(pythonLanguage) { case sitterNodeTypeDottedName: return Module{ - Name: node.Utf8Text(code), - LineNumber: uint32(node.StartPosition().Row) + 1, + Name: node.Text(code), + LineNumber: node.StartPoint().Row + 1, }, true case sitterNodeTypeAliasedImport: return parseImportStatement(node.Child(0), code) case sitterNodeTypeWildcardImport: return Module{ Name: "*", - LineNumber: uint32(node.StartPosition().Row) + 1, + LineNumber: node.StartPoint().Row + 1, }, true } return Module{}, false @@ -176,8 +165,8 @@ func cleanImportString(s string) string { // an import statement. It updates FileParser.output.Modules with the `module` that the // import represents. func (p *FileParser) parseImportStatements(node *sitter.Node) bool { - if node.Kind() == sitterNodeTypeImportStatement { - for j := uint(1); j < node.ChildCount(); j++ { + if node.Type(pythonLanguage) == sitterNodeTypeImportStatement { + for j := 1; j < node.ChildCount(); j++ { m, ok := parseImportStatement(node.Child(j), p.code) if !ok { continue @@ -191,15 +180,15 @@ func (p *FileParser) parseImportStatements(node *sitter.Node) bool { } p.output.Modules = append(p.output.Modules, m) } - } else if node.Kind() == sitterNodeTypeImportFromStatement { - from := node.Child(1).Utf8Text(p.code) + } else if node.Type(pythonLanguage) == sitterNodeTypeImportFromStatement { + from := node.Child(1).Text(p.code) from = cleanImportString(from) // If the import is from the current package, we don't need to add it to the modules i.e. from . import Class1. // If the import is from a different relative package i.e. from .package1 import foo, we need to add it to the modules. if from == "." { return true } - for j := uint(3); j < node.ChildCount(); j++ { + for j := 3; j < node.ChildCount(); j++ { m, ok := parseImportStatement(node.Child(j), p.code) if !ok { continue @@ -220,8 +209,8 @@ func (p *FileParser) parseImportStatements(node *sitter.Node) bool { // parseComments parses a node for comments, returning true if the node is a comment. // It updates FileParser.output.Comments with the parsed comment. func (p *FileParser) parseComments(node *sitter.Node) bool { - if node.Kind() == sitterNodeTypeComment { - p.output.Comments = append(p.output.Comments, Comment(node.Utf8Text(p.code))) + if node.Type(pythonLanguage) == sitterNodeTypeComment { + p.output.Comments = append(p.output.Comments, Comment(node.Text(p.code))) return true } return false @@ -235,23 +224,23 @@ func (p *FileParser) SetCodeAndFile(code []byte, relPackagePath, filename string // isTypeCheckingBlock returns true if the given node is an `if TYPE_CHECKING:` block. func (p *FileParser) isTypeCheckingBlock(node *sitter.Node) bool { - if node.Kind() != sitterNodeTypeIfStatement || node.ChildCount() < 2 { + if node.Type(pythonLanguage) != sitterNodeTypeIfStatement || node.ChildCount() < 2 { return false } condition := node.Child(1) // Handle `if TYPE_CHECKING:` - if condition.Kind() == sitterNodeTypeIdentifier && condition.Utf8Text(p.code) == "TYPE_CHECKING" { + if condition.Type(pythonLanguage) == sitterNodeTypeIdentifier && condition.Text(p.code) == "TYPE_CHECKING" { return true } // Handle `if typing.TYPE_CHECKING:` - if condition.Kind() == "attribute" && condition.ChildCount() >= 3 { + if condition.Type(pythonLanguage) == "attribute" && condition.ChildCount() >= 3 { object := condition.Child(0) attr := condition.Child(2) - if object.Kind() == sitterNodeTypeIdentifier && object.Utf8Text(p.code) == "typing" && - attr.Kind() == sitterNodeTypeIdentifier && attr.Utf8Text(p.code) == "TYPE_CHECKING" { + if object.Type(pythonLanguage) == sitterNodeTypeIdentifier && object.Text(p.code) == "typing" && + attr.Type(pythonLanguage) == sitterNodeTypeIdentifier && attr.Text(p.code) == "TYPE_CHECKING" { return true } } @@ -261,11 +250,11 @@ func (p *FileParser) isTypeCheckingBlock(node *sitter.Node) bool { // pytestPluginExpression unwraps parentheses, ignoring comments before the value. func pytestPluginExpression(node *sitter.Node) *sitter.Node { - for node != nil && node.Kind() == "parenthesized_expression" { + for node != nil && node.Type(pythonLanguage) == "parenthesized_expression" { var expression *sitter.Node - for i := uint(0); i < node.NamedChildCount(); i++ { + for i := 0; i < node.NamedChildCount(); i++ { child := node.NamedChild(i) - if child.Kind() != sitterNodeTypeComment { + if child.Type(pythonLanguage) != sitterNodeTypeComment { expression = child break } @@ -282,11 +271,11 @@ func pytestPluginString(node *sitter.Node, code []byte) (string, bool) { if node == nil { return "", false } - if node.Kind() == "concatenated_string" { + if node.Type(pythonLanguage) == "concatenated_string" { var value strings.Builder - for i := uint(0); i < node.NamedChildCount(); i++ { + for i := 0; i < node.NamedChildCount(); i++ { child := node.NamedChild(i) - if child.Kind() == sitterNodeTypeComment { + if child.Type(pythonLanguage) == sitterNodeTypeComment { continue } part, ok := pytestPluginString(child, code) @@ -297,10 +286,10 @@ func pytestPluginString(node *sitter.Node, code []byte) (string, bool) { } return value.String(), true } - if node.Kind() != sitterNodeTypeString || node.HasError() { + if node.Type(pythonLanguage) != sitterNodeTypeString || node.HasError() { return "", false } - literal := node.Utf8Text(code) + literal := node.Text(code) quote := strings.IndexAny(literal, "\"'") if quote < 0 { return "", false @@ -369,16 +358,16 @@ func pytestPluginString(node *sitter.Node, code []byte) (string, bool) { // imports. As with conditional imports, all statically declared alternatives are // included; Python code is never executed to determine the active branch. func (p *FileParser) parsePytestPlugins(node *sitter.Node) { - if p.inLocalScope || node.Kind() != "assignment" { + if p.inLocalScope || node.Type(pythonLanguage) != "assignment" { return } - left := node.ChildByFieldName("left") - if left == nil || left.Kind() != sitterNodeTypeIdentifier || left.Utf8Text(p.code) != "pytest_plugins" { + left := node.ChildByFieldName("left", pythonLanguage) + if left == nil || left.Type(pythonLanguage) != sitterNodeTypeIdentifier || left.Text(p.code) != "pytest_plugins" { return } - right := node.ChildByFieldName("right") - for right != nil && right.Kind() == "assignment" { - right = right.ChildByFieldName("right") + right := node.ChildByFieldName("right", pythonLanguage) + for right != nil && right.Type(pythonLanguage) == "assignment" { + right = right.ChildByFieldName("right", pythonLanguage) } right = pytestPluginExpression(right) if right == nil || right.HasError() { @@ -388,17 +377,17 @@ func (p *FileParser) parsePytestPlugins(node *sitter.Node) { if value != "" { p.output.Modules = append(p.output.Modules, Module{ Name: value, - LineNumber: uint32(node.StartPosition().Row) + 1, + LineNumber: node.StartPoint().Row + 1, Filepath: p.relFilepath, TypeCheckingOnly: p.inTypeCheckingBlock, PytestPlugin: true, }) } } - if right.Kind() == "list" || right.Kind() == "tuple" || right.Kind() == "expression_list" { - for i := uint(0); i < right.NamedChildCount(); i++ { + if right.Type(pythonLanguage) == "list" || right.Type(pythonLanguage) == "tuple" || right.Type(pythonLanguage) == "expression_list" { + for i := 0; i < right.NamedChildCount(); i++ { child := right.NamedChild(i) - if child.Kind() == sitterNodeTypeComment { + if child.Type(pythonLanguage) == sitterNodeTypeComment { continue } value, ok := pytestPluginString(child, p.code) @@ -431,14 +420,14 @@ func (p *FileParser) parse(ctx context.Context, node *sitter.Node) { p.inTypeCheckingBlock = wasInTypeCheckingBlock p.inLocalScope = wasInLocalScope }() - if node.Kind() == "function_definition" || node.Kind() == "class_definition" || node.Kind() == "lambda" { + if node.Type(pythonLanguage) == "function_definition" || node.Type(pythonLanguage) == "class_definition" || node.Type(pythonLanguage) == "lambda" { p.inLocalScope = true } if p.isTypeCheckingBlock(node) { p.inTypeCheckingBlock = true } - for i := uint(0); i < node.ChildCount(); i++ { + for i := 0; i < node.ChildCount(); i++ { if err := ctx.Err(); err != nil { return } @@ -456,11 +445,11 @@ func (p *FileParser) parse(ctx context.Context, node *sitter.Node) { } func (p *FileParser) Parse(ctx context.Context) (*ParserOutput, error) { - tree, err := parseCodeToTree(p.code, p.relFilepath) + tree, err := ParseCode(p.code, p.relFilepath) if err != nil { return nil, err } - defer tree.Close() + defer tree.Release() rootNode := tree.RootNode() p.output.HasMain = p.parseMain(ctx, rootNode) diff --git a/gazelle/python/file_parser_test.go b/gazelle/python/file_parser_test.go index c3711a6ff0..dd766be7b1 100644 --- a/gazelle/python/file_parser_test.go +++ b/gazelle/python/file_parser_test.go @@ -261,8 +261,12 @@ func TestParseRestoresStateOnCancellation(t *testing.T) { "if TYPE_CHECKING:\n import foo.bar", } { t.Run(code, func(t *testing.T) { - root, err := ParseCode([]byte(code), "example.py") - assert.NoError(t, err) + tree, err := ParseCode([]byte(code), "example.py") + if err != nil { + t.Fatal(err) + } + defer tree.Release() + root := tree.RootNode() if root == nil { t.Fatal("missing syntax tree") } @@ -562,9 +566,12 @@ except ValueError, OSError, OverflowError: if __name__ == "__main__": pass `) - rootNode, err := ParseCode(code, "pep758.py") - assert.NoError(t, err) - assert.False(t, rootNode.HasError(), "expected PEP 758 except clause to parse without error") + tree, err := ParseCode(code, "pep758.py") + if err != nil { + t.Fatal(err) + } + defer tree.Release() + assert.False(t, tree.RootNode().HasError(), "expected PEP 758 except clause to parse without error") p := NewFileParser() p.SetCodeAndFile(code, "", "pep758.py") diff --git a/news/1913.fixed.md b/news/1913.fixed.md new file mode 100644 index 0000000000..bca1ea8a24 --- /dev/null +++ b/news/1913.fixed.md @@ -0,0 +1,4 @@ +(gazelle) The Python extension can now cross-compile without a C toolchain and +no longer needs the Tree-sitter scanner headers +([#1913](https://github.com/bazel-contrib/rules_python/issues/1913), +[#2573](https://github.com/bazel-contrib/rules_python/issues/2573)).