1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
15 "golang.org/x/tools/go/ast/astutil"
16 "golang.org/x/tools/internal/event"
17 "golang.org/x/tools/internal/lsp/protocol"
18 errors "golang.org/x/xerrors"
21 func Highlight(ctx context.Context, snapshot Snapshot, fh FileHandle, pos protocol.Position) ([]protocol.Range, error) {
22 ctx, done := event.Start(ctx, "source.Highlight")
25 pkg, pgf, err := GetParsedFile(ctx, snapshot, fh, WidestPackage)
27 return nil, errors.Errorf("getting file for Highlight: %w", err)
29 spn, err := pgf.Mapper.PointSpan(pos)
33 rng, err := spn.Range(pgf.Mapper.Converter)
37 path, _ := astutil.PathEnclosingInterval(pgf.File, rng.Start, rng.Start)
39 return nil, fmt.Errorf("no enclosing position found for %v:%v", int(pos.Line), int(pos.Character))
41 // If start == end for astutil.PathEnclosingInterval, the 1-char interval
42 // following start is used instead. As a result, we might not get an exact
43 // match so we should check the 1-char interval to the left of the passed
44 // in position to see if that is an exact match.
45 if _, ok := path[0].(*ast.Ident); !ok {
46 if p, _ := astutil.PathEnclosingInterval(pgf.File, rng.Start-1, rng.Start-1); p != nil {
48 case *ast.Ident, *ast.SelectorExpr:
49 path = p // use preceding ident/selector
53 result, err := highlightPath(pkg, path)
57 var ranges []protocol.Range
58 for rng := range result {
59 mRng, err := posToMappedRange(snapshot, pkg, rng.start, rng.end)
63 pRng, err := mRng.Range()
67 ranges = append(ranges, pRng)
72 func highlightPath(pkg Package, path []ast.Node) (map[posRange]struct{}, error) {
73 result := make(map[posRange]struct{})
74 switch node := path[0].(type) {
77 if _, ok := path[1].(*ast.ImportSpec); ok {
78 err := highlightImportUses(pkg, path, result)
82 highlightFuncControlFlow(path, result)
83 case *ast.ReturnStmt, *ast.FuncDecl, *ast.FuncType:
84 highlightFuncControlFlow(path, result)
86 highlightIdentifiers(pkg, path, result)
87 case *ast.ForStmt, *ast.RangeStmt:
88 highlightLoopControlFlow(path, result)
90 highlightSwitchFlow(path, result)
92 // BREAK can exit a loop, switch or select, while CONTINUE exit a loop so
93 // these need to be handled separately. They can also be embedded in any
94 // other loop/switch/select if they have a label. TODO: add support for
95 // GOTO and FALLTHROUGH as well.
96 if node.Label != nil {
97 highlightLabeledFlow(node, result)
101 highlightUnlabeledBreakFlow(path, result)
103 highlightLoopControlFlow(path, result)
107 // If the cursor is in an unidentified area, return empty results.
113 type posRange struct {
117 func highlightFuncControlFlow(path []ast.Node, result map[posRange]struct{}) {
118 var enclosingFunc ast.Node
119 var returnStmt *ast.ReturnStmt
120 var resultsList *ast.FieldList
121 inReturnList := false
124 // Reverse walk the path till we get to the func block.
125 for i, n := range path {
126 switch node := n.(type) {
127 case *ast.KeyValueExpr:
128 // If cursor is in a key: value expr, we don't want control flow highlighting
131 // If cusor is an arg in a callExpr, we don't want control flow highlighting.
133 for _, arg := range node.Args {
134 if arg == path[i-1] {
143 resultsList = node.Type.Results
147 resultsList = node.Type.Results
149 case *ast.ReturnStmt:
151 // If the cursor is not directly in a *ast.ReturnStmt, then
152 // we need to know if it is within one of the values that is being returned.
153 inReturnList = inReturnList || path[0] != returnStmt
156 // Cursor is not in a function.
157 if enclosingFunc == nil {
160 // If the cursor is on a "return" or "func" keyword, we should highlight all of the exit
161 // points of the function, including the "return" and "func" keywords.
162 highlightAllReturnsAndFunc := path[0] == returnStmt || path[0] == enclosingFunc
163 switch path[0].(type) {
164 case *ast.Ident, *ast.BasicLit:
165 // Cursor is in an identifier and not in a return statement or in the results list.
166 if returnStmt == nil && !inReturnList {
170 highlightAllReturnsAndFunc = true
172 // The user's cursor may be within the return statement of a function,
173 // or within the result section of a function's signature.
176 if returnStmt != nil {
177 for _, n := range returnStmt.Results {
178 nodes = append(nodes, n)
180 } else if resultsList != nil {
181 for _, n := range resultsList.List {
182 nodes = append(nodes, n)
185 _, index := nodeAtPos(nodes, path[0].Pos())
187 // Highlight the correct argument in the function declaration return types.
188 if resultsList != nil && -1 < index && index < len(resultsList.List) {
190 start: resultsList.List[index].Pos(),
191 end: resultsList.List[index].End(),
193 result[rng] = struct{}{}
195 // Add the "func" part of the func declaration.
196 if highlightAllReturnsAndFunc {
198 start: enclosingFunc.Pos(),
199 end: enclosingFunc.Pos() + token.Pos(len("func")),
201 result[r] = struct{}{}
203 ast.Inspect(enclosingFunc, func(n ast.Node) bool {
204 // Don't traverse any other functions.
206 case *ast.FuncDecl, *ast.FuncLit:
207 return enclosingFunc == n
209 ret, ok := n.(*ast.ReturnStmt)
214 // Add the entire return statement, applies when highlight the word "return" or "func".
215 if highlightAllReturnsAndFunc {
218 // Add the relevant field within the entire return statement.
219 if -1 < index && index < len(ret.Results) {
220 toAdd = ret.Results[index]
223 result[posRange{start: toAdd.Pos(), end: toAdd.End()}] = struct{}{}
229 func highlightUnlabeledBreakFlow(path []ast.Node, result map[posRange]struct{}) {
230 // Reverse walk the path until we find closest loop, select, or switch.
231 for _, n := range path {
233 case *ast.ForStmt, *ast.RangeStmt:
234 highlightLoopControlFlow(path, result)
235 return // only highlight the innermost statement
236 case *ast.SwitchStmt:
237 highlightSwitchFlow(path, result)
239 case *ast.SelectStmt:
240 // TODO: add highlight when breaking a select.
246 func highlightLabeledFlow(node *ast.BranchStmt, result map[posRange]struct{}) {
247 obj := node.Label.Obj
248 if obj == nil || obj.Decl == nil {
251 label, ok := obj.Decl.(*ast.LabeledStmt)
255 switch label.Stmt.(type) {
256 case *ast.ForStmt, *ast.RangeStmt:
257 highlightLoopControlFlow([]ast.Node{label.Stmt, label}, result)
258 case *ast.SwitchStmt:
259 highlightSwitchFlow([]ast.Node{label.Stmt, label}, result)
263 func labelFor(path []ast.Node) *ast.Ident {
265 if n, ok := path[1].(*ast.LabeledStmt); ok {
272 func highlightLoopControlFlow(path []ast.Node, result map[posRange]struct{}) {
274 var loopLabel *ast.Ident
275 stmtLabel := labelFor(path)
277 // Reverse walk the path till we get to the for loop.
278 for i := range path {
279 switch n := path[i].(type) {
280 case *ast.ForStmt, *ast.RangeStmt:
281 loopLabel = labelFor(path[i:])
283 if stmtLabel == nil || loopLabel == stmtLabel {
293 // Add the for statement.
296 end: loop.Pos() + token.Pos(len("for")),
298 result[rng] = struct{}{}
300 // Traverse AST to find branch statements within the same for-loop.
301 ast.Inspect(loop, func(n ast.Node) bool {
303 case *ast.ForStmt, *ast.RangeStmt:
305 case *ast.SwitchStmt, *ast.SelectStmt:
308 b, ok := n.(*ast.BranchStmt)
312 if b.Label == nil || labelDecl(b.Label) == loopLabel {
313 result[posRange{start: b.Pos(), end: b.End()}] = struct{}{}
318 // Find continue statements in the same loop or switches/selects.
319 ast.Inspect(loop, func(n ast.Node) bool {
321 case *ast.ForStmt, *ast.RangeStmt:
325 if n, ok := n.(*ast.BranchStmt); ok && n.Tok == token.CONTINUE {
326 result[posRange{start: n.Pos(), end: n.End()}] = struct{}{}
331 // We don't need to check other for loops if we aren't looking for labeled statements.
332 if loopLabel == nil {
336 // Find labeled branch statements in any loop
337 ast.Inspect(loop, func(n ast.Node) bool {
338 b, ok := n.(*ast.BranchStmt)
342 // Statment with labels that matches the loop.
343 if b.Label != nil && labelDecl(b.Label) == loopLabel {
344 result[posRange{start: b.Pos(), end: b.End()}] = struct{}{}
350 func highlightSwitchFlow(path []ast.Node, result map[posRange]struct{}) {
351 var switchNode ast.Node
352 var switchNodeLabel *ast.Ident
353 stmtLabel := labelFor(path)
355 // Reverse walk the path till we get to the switch statement.
356 for i := range path {
357 switch n := path[i].(type) {
358 case *ast.SwitchStmt:
359 switchNodeLabel = labelFor(path[i:])
360 if stmtLabel == nil || switchNodeLabel == stmtLabel {
366 // Cursor is not in a switch statement
367 if switchNode == nil {
371 // Add the switch statement.
373 start: switchNode.Pos(),
374 end: switchNode.Pos() + token.Pos(len("switch")),
376 result[rng] = struct{}{}
378 // Traverse AST to find break statements within the same switch.
379 ast.Inspect(switchNode, func(n ast.Node) bool {
381 case *ast.SwitchStmt:
382 return switchNode == n
383 case *ast.ForStmt, *ast.RangeStmt, *ast.SelectStmt:
387 b, ok := n.(*ast.BranchStmt)
388 if !ok || b.Tok != token.BREAK {
392 if b.Label == nil || labelDecl(b.Label) == switchNodeLabel {
393 result[posRange{start: b.Pos(), end: b.End()}] = struct{}{}
398 // We don't need to check other switches if we aren't looking for labeled statements.
399 if switchNodeLabel == nil {
403 // Find labeled break statements in any switch
404 ast.Inspect(switchNode, func(n ast.Node) bool {
405 b, ok := n.(*ast.BranchStmt)
406 if !ok || b.Tok != token.BREAK {
410 if b.Label != nil && labelDecl(b.Label) == switchNodeLabel {
411 result[posRange{start: b.Pos(), end: b.End()}] = struct{}{}
418 func labelDecl(n *ast.Ident) *ast.Ident {
425 if n.Obj.Decl == nil {
428 stmt, ok := n.Obj.Decl.(*ast.LabeledStmt)
435 func highlightImportUses(pkg Package, path []ast.Node, result map[posRange]struct{}) error {
436 basicLit, ok := path[0].(*ast.BasicLit)
438 return errors.Errorf("highlightImportUses called with an ast.Node of type %T", basicLit)
440 ast.Inspect(path[len(path)-1], func(node ast.Node) bool {
441 if imp, ok := node.(*ast.ImportSpec); ok && imp.Path == basicLit {
442 result[posRange{start: node.Pos(), end: node.End()}] = struct{}{}
445 n, ok := node.(*ast.Ident)
449 obj, ok := pkg.GetTypesInfo().ObjectOf(n).(*types.PkgName)
453 if !strings.Contains(basicLit.Value, obj.Name()) {
456 result[posRange{start: n.Pos(), end: n.End()}] = struct{}{}
462 func highlightIdentifiers(pkg Package, path []ast.Node, result map[posRange]struct{}) error {
463 id, ok := path[0].(*ast.Ident)
465 return errors.Errorf("highlightIdentifiers called with an ast.Node of type %T", id)
467 // Check if ident is inside return or func decl.
468 highlightFuncControlFlow(path, result)
470 // TODO: maybe check if ident is a reserved word, if true then don't continue and return results.
472 idObj := pkg.GetTypesInfo().ObjectOf(id)
473 pkgObj, isImported := idObj.(*types.PkgName)
474 ast.Inspect(path[len(path)-1], func(node ast.Node) bool {
475 if imp, ok := node.(*ast.ImportSpec); ok && isImported {
476 highlightImport(pkgObj, imp, result)
478 n, ok := node.(*ast.Ident)
482 if n.Name != id.Name {
485 if nObj := pkg.GetTypesInfo().ObjectOf(n); nObj == idObj {
486 result[posRange{start: n.Pos(), end: n.End()}] = struct{}{}
493 func highlightImport(obj *types.PkgName, imp *ast.ImportSpec, result map[posRange]struct{}) {
494 if imp.Name != nil || imp.Path == nil {
497 if !strings.Contains(imp.Path.Value, obj.Name()) {
500 result[posRange{start: imp.Path.Pos(), end: imp.Path.End()}] = struct{}{}