Skip to content

Commit

Permalink
Add identifier range info
Browse files Browse the repository at this point in the history
In order to support microsoft/vscode-go#962 this exposes the start/end range of
the identifiers for each declaration. In some case (particularly imports) the
`ast.Ident` is `nil`, so the identifier range is possibly `nil` too.
  • Loading branch information
Matt Good committed May 4, 2017
1 parent 3bda790 commit bcbc73d
Showing 1 changed file with 36 additions and 16 deletions.
52 changes: 36 additions & 16 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,18 @@ import (
"golang.org/x/tools/go/buildutil"
)

type Range struct {
Start token.Pos `json:"start"`
End token.Pos `json:"end"`
}

type Declaration struct {
Label string `json:"label"`
Type string `json:"type"`
ReceiverType string `json:"receiverType,omitempty"`
Start token.Pos `json:"start"`
End token.Pos `json:"end"`
Children []Declaration `json:"children,omitempty"`
Label string `json:"label"`
Type string `json:"type"`
ReceiverType string `json:"receiverType,omitempty"`
Range
Identifier *Range `json:"identifier,omitempty"`
Children []Declaration `json:"children,omitempty"`
}

var (
Expand All @@ -29,6 +34,21 @@ var (
modified = flag.Bool("modified", false, "read an archive of the modified file from standard input")
)

func nodeRange(n ast.Node) Range {
return Range{
Start: n.Pos(),
End: n.End(),
}
}

func identRange(i *ast.Ident) *Range {
if i == nil {
return nil
}
r := nodeRange(i)
return &r
}

func main() {
flag.Parse()
fset := token.NewFileSet()
Expand Down Expand Up @@ -71,8 +91,8 @@ func main() {
decl.Name.String(),
"function",
receiverType,
decl.Pos(),
decl.End(),
nodeRange(decl),
identRange(decl.Name),
[]Declaration{},
})
case *ast.GenDecl:
Expand All @@ -83,8 +103,8 @@ func main() {
spec.Path.Value,
"import",
"",
spec.Pos(),
spec.End(),
nodeRange(spec),
identRange(spec.Name),
[]Declaration{},
})
case *ast.TypeSpec:
Expand All @@ -93,8 +113,8 @@ func main() {
spec.Name.String(),
"type",
"",
spec.Pos(),
spec.End(),
nodeRange(spec),
identRange(spec.Name),
[]Declaration{},
})
case *ast.ValueSpec:
Expand All @@ -103,8 +123,8 @@ func main() {
id.Name,
"variable",
"",
id.Pos(),
id.End(),
nodeRange(id),
identRange(id),
[]Declaration{},
})
}
Expand All @@ -121,8 +141,8 @@ func main() {
fileAst.Name.String(),
"package",
"",
fileAst.Pos(),
fileAst.End(),
nodeRange(fileAst),
identRange(fileAst.Name),
declarations,
}}

Expand Down

0 comments on commit bcbc73d

Please sign in to comment.