github.com/gostaticanalysis/astquery
go get github.com/gostaticanalysis/astquery

github.com/gostaticanalysis/astquery

astquery select a node set from AST by XPath

by gostaticanalysis

v0.0.0-20200823120951-321f091076cd (see all)License:MIT
go get github.com/gostaticanalysis/astquery
Readme

astquery PkgGoDev

astquery selects a node set from AST by XPath.

astquery uses antchfx/xpath. You can see a document of xpath expressions at antchfx/xpath's repository.

You can also use field of a node as an attributes such as @Name for *ast.Ident. In addtion you can use the follows as an attribute:

  • @type: type of a node
  • @pos: token.Position of a node in string value
  • @src: source code representation of a node with "go/format".Node

CLI Tool

Install

$ go get -u github.com/gostaticanalysis/astquery/cmd/astquery

How to use

Select a node set

$ astquery '//*[@type="CallExpr"]/Fun[@type="Ident" and @Name="panic"]' fmt

Select attributes

# Find calling panic in fmt package
$ astquery '//*[@type="CallExpr"]/Fun[@type="Ident" and @Name="panic"]/@pos' fmt
/usr/local/go/src/fmt/format.go:266:3
/usr/local/go/src/fmt/print.go:553:4
/usr/local/go/src/fmt/scan.go:240:2
/usr/local/go/src/fmt/scan.go:244:2
/usr/local/go/src/fmt/scan.go:253:5
/usr/local/go/src/fmt/scan.go:508:3
/usr/local/go/src/fmt/scan.go:1064:4
# Find with src code snipet
$ astquery '//*[starts-with(@src, "panic") and @type="CallExpr"]/@src' fmt
panic("fmt: unknown base; can't happen")
panic(err)
panic(scanError{err})
panic(scanError{errors.New(err)})
panic(e)
panic(io.EOF)
panic(e)

Analyzer

see: examples of analysis.Analyzer

func run(pass *analysis.Pass) (interface{}, error) {
    e := pass.ResultOf[astquery.Analyzer].(*astquery.Evaluator)
    ns, err := e.Select("//*[@type='CallExpr']/Fun[@type='Ident' and @Name='panic']")
    if err != nil {
        return nil, err
    }

    for _, n := range ns {
        pass.Reportf(n.Pos(), "don't panic")
    }

    return nil, nil
}

GitHub Stars

12

LAST COMMIT

2yrs ago

MAINTAINERS

0

CONTRIBUTORS

1

OPEN ISSUES

1

OPEN PRs

0
VersionTagPublished
v0.0.0-20200823120951-321f091076cd
2yrs ago
v0.0.0-20200823114411-a93266d2d37f
2yrs ago
v0.0.0-20200823060640-13abedadd9a4
2yrs ago
v0.0.0-20200823055309-e4691fbad96a
2yrs ago
No alternatives found
No tutorials found
Add a tutorial