Debian Codegraph @

gopls/internal/golang/highlight.go

raw symbols SCIP
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.
4
5 package golang
6
7 import (
8 "context"
9 "fmt"
10 "go/ast"
11 "go/token"
12 "go/types"
13 "strconv"
14 "strings"
15
16 "golang.org/x/tools/go/ast/edge"
17 "golang.org/x/tools/go/ast/inspector"
18 "golang.org/x/tools/gopls/internal/cache"
19 "golang.org/x/tools/gopls/internal/file"
20 "golang.org/x/tools/gopls/internal/protocol"
21 "golang.org/x/tools/gopls/internal/util/cursorutil"
22 "golang.org/x/tools/internal/astutil"
23 "golang.org/x/tools/internal/event"
24 "golang.org/x/tools/internal/fmtstr"
25 "golang.org/x/tools/internal/moreiters"
26 )
27
28 func Highlight(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) ([]protocol.DocumentHighlight, error) {
29 ctx, done := event.Start(ctx, "golang.Highlight")
30 defer done()
31
32 // We always want fully parsed files for highlight, regardless
33 // of whether the file belongs to a workspace package.
34 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
35 if err != nil {
36 return nil, fmt.Errorf("getting package for Highlight: %w", err)
37 }
38
39 start, end, err := pgf.RangePos(rng)
40 if err != nil {
41 return nil, err
42 }
43
44 cur, _, _, _ := astutil.Select(pgf.Cursor(), start, end) // can't fail: pgf contains pos
45
46 result, err := highlightPath(pkg.TypesInfo(), cur, start, end)
47 if err != nil {
48 return nil, err
49 }
50 var ranges []protocol.DocumentHighlight
51 for rng, kind := range result {
52 rng, err := pgf.NodeRange(rng)
53 if err != nil {
54 return nil, err
55 }
56 ranges = append(ranges, protocol.DocumentHighlight{
57 Range: rng,
58 Kind: kind,
59 })
60 }
61 return ranges, nil
62 }
63
64 // highlightPath returns ranges to highlight for the given the cursor.
65 func highlightPath(info *types.Info, cur inspector.Cursor, start, end token.Pos) (map[astutil.Range]protocol.DocumentHighlightKind, error) {
66 result := make(map[astutil.Range]protocol.DocumentHighlightKind)
67
68 // Inside a call to a printf-like function (as identified
69 // by a simple heuristic).
70 // Treat each corresponding ("%v", arg) pair as a highlight class.
71 for node := range cur.Enclosing((*ast.CallExpr)(nil)) {
72 call := node.Node().(*ast.CallExpr)
73 lit, idx := formatStringAndIndex(info, call)
74 if idx != -1 {
75 highlightPrintf(call, idx, start, end, lit, result)
76 }
77 }
78
79 switch node := cur.Node().(type) {
80 case *ast.BasicLit:
81 // Import path string literal?
82 if imp, ok := cur.Parent().Node().(*ast.ImportSpec); ok {
83 highlight := func(n ast.Node) {
84 highlightNode(result, n, protocol.Text)
85 }
86
87 // Highlight the import itself...
88 highlight(imp)
89
90 // ...and all references to it in the file.
91 if pkgname := info.PkgNameOf(imp); pkgname != nil {
92 _, curFile := cursorutil.FirstEnclosing[*ast.File](cur)
93 for c := range curFile.Preorder((*ast.Ident)(nil)) {
94 if id := c.Node().(*ast.Ident); info.Uses[id] == pkgname {
95 highlight(id)
96 }
97 }
98 }
99 return result, nil
100 }
101 highlightFuncControlFlow(cur, result)
102 case *ast.ReturnStmt, *ast.FuncDecl, *ast.FuncType:
103 highlightFuncControlFlow(cur, result)
104 case *ast.Ident:
105 // Check if ident is inside return or func decl.
106 highlightFuncControlFlow(cur, result)
107 highlightIdentifier(cur, info, result)
108 case *ast.ForStmt, *ast.RangeStmt:
109 var label *ast.Ident
110 if l, ok := cur.Parent().Node().(*ast.LabeledStmt); ok {
111 label = l.Label
112 }
113 highlightLoopControlFlow(node, label, info, result)
114 case *ast.SwitchStmt, *ast.TypeSwitchStmt:
115 var label *ast.Ident
116 if l, ok := cur.Parent().Node().(*ast.LabeledStmt); ok {
117 label = l.Label
118 }
119 highlightSwitchFlow(node, label, info, result)
120 case *ast.BranchStmt:
121 // BREAK can exit a loop, switch or select, while CONTINUE exit a loop so
122 // these need to be handled separately. They can also be embedded in any
123 // other loop/switch/select if they have a label. TODO: add support for
124 // GOTO and FALLTHROUGH as well.
125 switch node.Tok {
126 case token.BREAK:
127 if node.Label != nil {
128 highlightLabeledFlow(cur, info, result)
129 } else {
130 highlightUnlabeledBreakFlow(cur, info, result)
131 }
132 case token.CONTINUE:
133 if node.Label != nil {
134 highlightLabeledFlow(cur, info, result)
135 } else {
136 var (
137 stmt ast.Node
138 label *ast.Ident
139 )
140 if curLoop, ok := moreiters.First(cur.Enclosing((*ast.ForStmt)(nil), (*ast.RangeStmt)(nil))); ok {
141 stmt = curLoop.Node()
142 if l, ok := curLoop.Parent().Node().(*ast.LabeledStmt); ok {
143 label = l.Label
144 }
145 highlightLoopControlFlow(stmt, label, info, result)
146 }
147 }
148 }
149 }
150
151 return result, nil
152 }
153
154 // formatStringAndIndex returns the BasicLit and index of the BasicLit (the last
155 // non-variadic parameter) within the given printf-like call
156 // expression, returns -1 as index if unknown.
157 func formatStringAndIndex(info *types.Info, call *ast.CallExpr) (*ast.BasicLit, int) {
158 typ := info.Types[call.Fun].Type
159 if typ == nil {
160 return nil, -1 // missing type
161 }
162 sig, ok := typ.(*types.Signature)
163 if !ok {
164 return nil, -1 // ill-typed
165 }
166 if !sig.Variadic() {
167 // Skip checking non-variadic functions.
168 return nil, -1
169 }
170 idx := sig.Params().Len() - 2
171 if !(0 <= idx && idx < len(call.Args)) {
172 // Skip checking functions without a format string parameter, or
173 // missing the corresponding format argument.
174 return nil, -1
175 }
176 // We only care about literal format strings, so fmt.Sprint("a"+"b%s", "bar") won't be highlighted.
177 if lit, ok := call.Args[idx].(*ast.BasicLit); ok && lit.Kind == token.STRING {
178 return lit, idx
179 }
180 return nil, -1
181 }
182
183 // highlightPrintf highlights operations in a format string and their
184 // corresponding variadic arguments in a (possible) printf-style function call.
185 // For example:
186 //
187 // fmt.Printf("Hello %s, you scored %d", name, score)
188 //
189 // If the cursor is on %s or name, it will highlight %s as a write operation,
190 // and name as a read operation.
191 func highlightPrintf(call *ast.CallExpr, idx int, start, end token.Pos, lit *ast.BasicLit, result map[astutil.Range]protocol.DocumentHighlightKind) {
192 format, err := strconv.Unquote(lit.Value)
193 if err != nil {
194 return
195 }
196 if !strings.Contains(format, "%") {
197 return
198 }
199 operations, err := fmtstr.Parse(format, idx)
200 if err != nil {
201 return
202 }
203
204 // fmt.Printf("%[1]d %[1].2d", 3)
205 //
206 // When cursor is in `%[1]d`, we record `3` being successfully highlighted.
207 // And because we will also record `%[1].2d`'s corresponding arguments index is `3`
208 // in `visited`, even though it will not highlight any item in the first pass,
209 // in the second pass we can correctly highlight it. So the three are the same class.
210 succeededArg := 0
211 visited := make(map[astutil.Range]int, 0)
212
213 // highlightPair highlights the operation and its potential argument pair if the cursor is within either range.
214 highlightPair := func(rang fmtstr.Range, argIndex int) {
215 var (
216 rng astutil.Range
217 withinRng bool
218 )
219 rng, err = astutil.RangeInStringLiteral(lit, rang.Start, rang.End)
220 if err != nil {
221 return
222 }
223 visited[rng] = argIndex
224
225 if start == end {
226 // End pos can't equal to range's end, otherwise the two neighborhood
227 // such as (%[2]*d) are both highlighted if cursor in "d" (ending of [2]*).
228 withinRng = rng.Start <= start && end < rng.End()
229 } else {
230 // With a non-empty selection, there is no ambiguity.
231 withinRng = rng.Contains(astutil.RangeOf(start, end))
232 }
233
234 var (
235 arg ast.Expr
236 withinArg bool
237 )
238 if argIndex < len(call.Args) {
239 arg = call.Args[argIndex]
240 withinArg = astutil.NodeContains(arg, astutil.RangeOf(start, end))
241 }
242
243 if withinRng || withinArg {
244 highlightRange(result, rng, protocol.Write)
245 if arg != nil {
246 succeededArg = argIndex
247 highlightNode(result, arg, protocol.Read)
248 }
249 }
250 }
251
252 for _, op := range operations {
253 // If width or prec has any *, we can not highlight the full range from % to verb,
254 // because it will overlap with the sub-range of *, for example:
255 //
256 // fmt.Printf("%*[3]d", 4, 5, 6)
257 // ^ ^ we can only highlight this range when cursor in 6. '*' as a one-rune range will
258 // highlight for 4.
259 hasAsterisk := false
260
261 // Try highlight Width if there is a *.
262 if op.Width.Dynamic != -1 {
263 hasAsterisk = true
264 highlightPair(op.Width.Range, op.Width.Dynamic)
265 }
266
267 // Try highlight Precision if there is a *.
268 if op.Prec.Dynamic != -1 {
269 hasAsterisk = true
270 highlightPair(op.Prec.Range, op.Prec.Dynamic)
271 }
272
273 // Try highlight Verb.
274 if op.Verb.Verb != '%' {
275 // If any * is found inside operation, narrow the highlight range.
276 if hasAsterisk {
277 highlightPair(op.Verb.Range, op.Verb.ArgIndex)
278 } else {
279 highlightPair(op.Range, op.Verb.ArgIndex)
280 }
281 }
282 }
283
284 // Second pass, try to highlight those missed operations.
285 for rng, argIndex := range visited {
286 if succeededArg == argIndex {
287 highlightRange(result, rng, protocol.Write)
288 }
289 }
290 }
291
292 // highlightFuncControlFlow adds highlight ranges to the result map to
293 // associate results and result parameters.
294 //
295 // Specifically, if the cursor is in a result or result parameter, all
296 // results and result parameters with the same index are highlighted. If the
297 // cursor is in a 'func' or 'return' keyword, the func keyword as well as all
298 // returns from that func are highlighted.
299 //
300 // As a special case, if the cursor is within a complicated expression, control
301 // flow highlighting is disabled, as it would highlight too much.
302 func highlightFuncControlFlow(cur inspector.Cursor, result map[astutil.Range]protocol.DocumentHighlightKind) {
303
304 var (
305 funcType *ast.FuncType // type of enclosing func, or nil
306 funcBody *ast.BlockStmt // body of enclosing func, or nil
307 returnStmt *ast.ReturnStmt // enclosing ReturnStmt within the func, or nil
308 )
309
310 loop:
311 for cur := range cur.Enclosing() {
312 switch n := cur.Node().(type) {
313 // TODO(rfindley, low priority): these pre-existing cases for KeyValueExpr
314 // and CallExpr appear to avoid highlighting when the cursor is in a
315 // complicated expression. However, the basis for this heuristic is
316 // unclear. Can we formalize a rationale?
317 case *ast.KeyValueExpr:
318 // If cursor is in a key: value expr, we don't want control flow highlighting.
319 return
320
321 case *ast.FuncLit:
322 funcType = n.Type
323 funcBody = n.Body
324 break loop
325
326 case *ast.FuncDecl:
327 funcType = n.Type
328 funcBody = n.Body
329 break loop
330
331 case *ast.ReturnStmt:
332 returnStmt = n
333 }
334
335 // If cursor is an arg in a callExpr, we don't want control flow highlighting.
336 if cur.ParentEdgeKind() == edge.CallExpr_Args {
337 return
338 }
339 }
340
341 if funcType == nil {
342 return // cursor is not in a function
343 }
344
345 // Helper functions for inspecting the current location.
346 var (
347 pos = cur.Node().Pos()
348 inSpan = func(start, end token.Pos) bool { return start <= pos && pos < end }
349 inNode = func(n ast.Node) bool { return inSpan(n.Pos(), n.End()) }
350 )
351
352 inResults := funcType.Results != nil && inNode(funcType.Results)
353
354 // If the cursor is on a "return" or "func" keyword, but not highlighting any
355 // specific field or expression, we should highlight all of the exit points
356 // of the function, including the "return" and "func" keywords.
357 funcEnd := funcType.Func + token.Pos(len("func"))
358 highlightAll := cur.Node() == returnStmt || inSpan(funcType.Func, funcEnd)
359 var highlightIndexes map[int]bool
360
361 if highlightAll {
362 // Add the "func" part of the func declaration.
363 highlightRange(result, astutil.RangeOf(funcType.Func, funcEnd), protocol.Text)
364 } else if returnStmt == nil && !inResults {
365 return // nothing to highlight
366 } else {
367 // If we're not highlighting the entire return statement, we need to collect
368 // specific result indexes to highlight. This may be more than one index if
369 // the cursor is on a multi-name result field, but not in any specific name.
370 if !highlightAll {
371 highlightIndexes = make(map[int]bool)
372 if returnStmt != nil {
373 for i, n := range returnStmt.Results {
374 if inNode(n) {
375 highlightIndexes[i] = true
376 break
377 }
378 }
379 }
380
381 if funcType.Results != nil {
382 // Scan fields, either adding highlights according to the highlightIndexes
383 // computed above, or accounting for the cursor position within the result
384 // list.
385 // (We do both at once to avoid repeating the cumbersome field traversal.)
386 i := 0
387 findField:
388 for _, field := range funcType.Results.List {
389 for j, name := range field.Names {
390 if inNode(name) || highlightIndexes[i+j] {
391 highlightNode(result, name, protocol.Text)
392 highlightIndexes[i+j] = true
393 break findField // found/highlighted the specific name
394 }
395 }
396 // If the cursor is in a field but not in a name (e.g. in the space, or
397 // the type), highlight the whole field.
398 //
399 // Note that this may not be ideal if we're at e.g.
400 //
401 // (x,‸y int, z int8)
402 //
403 // ...where it would make more sense to highlight only y. But we don't
404 // reach this function if not in a func, return, ident, or basiclit.
405 if inNode(field) || highlightIndexes[i] {
406 highlightNode(result, field, protocol.Text)
407 highlightIndexes[i] = true
408 if inNode(field) {
409 for j := range field.Names {
410 highlightIndexes[i+j] = true
411 }
412 }
413 break findField // found/highlighted the field
414 }
415
416 n := len(field.Names)
417 if n == 0 {
418 n = 1
419 }
420 i += n
421 }
422 }
423 }
424 }
425
426 if funcBody != nil {
427 ast.Inspect(funcBody, func(n ast.Node) bool {
428 switch n := n.(type) {
429 case *ast.FuncDecl, *ast.FuncLit:
430 // Don't traverse into any functions other than enclosingFunc.
431 return false
432 case *ast.ReturnStmt:
433 if highlightAll {
434 // Add the entire return statement.
435 highlightNode(result, n, protocol.Text)
436 } else {
437 // Add the highlighted indexes.
438 for i, expr := range n.Results {
439 if highlightIndexes[i] {
440 highlightNode(result, expr, protocol.Text)
441 }
442 }
443 }
444 return false
445
446 }
447 return true
448 })
449 }
450 }
451
452 // highlightUnlabeledBreakFlow highlights the innermost enclosing
453 // for/range/switch or select
454 func highlightUnlabeledBreakFlow(cur inspector.Cursor, info *types.Info, result map[astutil.Range]protocol.DocumentHighlightKind) {
455 // Reverse walk the path until we find closest loop, select, or switch.
456 for cur := range cur.Enclosing() {
457 switch n := cur.Node().(type) {
458 case *ast.ForStmt, *ast.RangeStmt:
459 var label *ast.Ident
460 if l, ok := cur.Parent().Node().(*ast.LabeledStmt); ok {
461 label = l.Label
462 }
463 highlightLoopControlFlow(n, label, info, result)
464 return // only highlight the innermost statement
465 case *ast.SwitchStmt, *ast.TypeSwitchStmt:
466 var label *ast.Ident
467 if l, ok := cur.Parent().Node().(*ast.LabeledStmt); ok {
468 label = l.Label
469 }
470 highlightSwitchFlow(n, label, info, result)
471 return
472 case *ast.SelectStmt:
473 // TODO: add highlight when breaking a select.
474 return
475 }
476 }
477 }
478
479 // highlightLabeledFlow highlights the enclosing labeled for, range,
480 // or switch statement denoted by a labeled break or continue stmt.
481 //
482 // The input cursor must point to a [ast.BranchStmt]
483 func highlightLabeledFlow(curBranch inspector.Cursor, info *types.Info, result map[astutil.Range]protocol.DocumentHighlightKind) {
484 use := info.Uses[curBranch.Node().(*ast.BranchStmt).Label]
485 if use == nil {
486 return
487 }
488 for cur := range curBranch.Enclosing((*ast.LabeledStmt)(nil)) {
489 if label := cur.Node().(*ast.LabeledStmt); info.Defs[label.Label] == use {
490 switch label.Stmt.(type) {
491 case *ast.ForStmt, *ast.RangeStmt:
492 highlightLoopControlFlow(label.Stmt, label.Label, info, result)
493 case *ast.SwitchStmt, *ast.TypeSwitchStmt:
494 highlightSwitchFlow(label.Stmt, label.Label, info, result)
495 }
496 return
497 }
498 }
499 }
500
501 func highlightLoopControlFlow(loop ast.Node, label *ast.Ident, info *types.Info, result map[astutil.Range]protocol.DocumentHighlightKind) {
502 // Add the for statement.
503 rngStart := loop.Pos()
504 rngEnd := loop.Pos() + token.Pos(len("for"))
505 highlightRange(result, astutil.RangeOf(rngStart, rngEnd), protocol.Text)
506
507 // Traverse AST to find branch statements within the same for-loop.
508 ast.Inspect(loop, func(n ast.Node) bool {
509 switch n.(type) {
510 case *ast.ForStmt, *ast.RangeStmt:
511 return loop == n
512 case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
513 return false
514 }
515 b, ok := n.(*ast.BranchStmt)
516 if !ok {
517 return true
518 }
519 if b.Label == nil || info.Uses[b.Label] == info.Defs[label] {
520 highlightNode(result, b, protocol.Text)
521 }
522 return true
523 })
524
525 // Find continue statements in the same loop or switches/selects.
526 ast.Inspect(loop, func(n ast.Node) bool {
527 switch n.(type) {
528 case *ast.ForStmt, *ast.RangeStmt:
529 return loop == n
530 }
531
532 if n, ok := n.(*ast.BranchStmt); ok && n.Tok == token.CONTINUE {
533 highlightNode(result, n, protocol.Text)
534 }
535 return true
536 })
537
538 // We don't need to check other for loops if we aren't looking for labeled statements.
539 if label == nil {
540 return
541 }
542
543 // Find labeled branch statements in any loop.
544 ast.Inspect(loop, func(n ast.Node) bool {
545 b, ok := n.(*ast.BranchStmt)
546 if !ok {
547 return true
548 }
549 // statement with labels that matches the loop
550 if b.Label != nil && info.Uses[b.Label] == info.Defs[label] {
551 highlightNode(result, b, protocol.Text)
552 }
553 return true
554 })
555 }
556
557 func highlightSwitchFlow(node ast.Node, label *ast.Ident, info *types.Info, result map[astutil.Range]protocol.DocumentHighlightKind) {
558 // Add the switch statement.
559 rngStart := node.Pos()
560 rngEnd := node.Pos() + token.Pos(len("switch"))
561 highlightRange(result, astutil.RangeOf(rngStart, rngEnd), protocol.Text)
562
563 // Traverse AST to find break statements within the same switch.
564 ast.Inspect(node, func(n ast.Node) bool {
565 switch n.(type) {
566 case *ast.SwitchStmt, *ast.TypeSwitchStmt:
567 return node == n
568 case *ast.ForStmt, *ast.RangeStmt, *ast.SelectStmt:
569 return false
570 }
571
572 b, ok := n.(*ast.BranchStmt)
573 if !ok || b.Tok != token.BREAK {
574 return true
575 }
576
577 if b.Label == nil || info.Uses[b.Label] == info.Defs[label] {
578 highlightNode(result, b, protocol.Text)
579 }
580 return true
581 })
582
583 // We don't need to check other switches if we aren't looking for labeled statements.
584 if label == nil {
585 return
586 }
587
588 // Find labeled break statements in any switch
589 ast.Inspect(node, func(n ast.Node) bool {
590 b, ok := n.(*ast.BranchStmt)
591 if !ok || b.Tok != token.BREAK {
592 return true
593 }
594
595 if b.Label != nil && info.Uses[b.Label] == info.Defs[label] {
596 highlightNode(result, b, protocol.Text)
597 }
598
599 return true
600 })
601 }
602
603 func highlightNode(result map[astutil.Range]protocol.DocumentHighlightKind, n ast.Node, kind protocol.DocumentHighlightKind) {
604 highlightRange(result, astutil.NodeRange(n), kind)
605 }
606
607 func highlightRange(result map[astutil.Range]protocol.DocumentHighlightKind, rng astutil.Range, kind protocol.DocumentHighlightKind) {
608 // Order of traversal is important: some nodes (e.g. identifiers) are
609 // visited more than once, but the kind set during the first visitation "wins".
610 if _, exists := result[rng]; !exists {
611 result[rng] = kind
612 }
613 }
614
615 func highlightIdentifier(cur inspector.Cursor, info *types.Info, result map[astutil.Range]protocol.DocumentHighlightKind) {
616 ident := cur.Node().(*ast.Ident)
617
618 // obj may be nil if the Ident is undefined.
619 // In this case, the behavior expected by tests is
620 // to match other undefined Idents of the same name.
621 obj := info.ObjectOf(ident)
622
623 highlightIdent := func(n *ast.Ident, kind protocol.DocumentHighlightKind) {
624 if n.Name == ident.Name && info.ObjectOf(n) == obj {
625 highlightNode(result, n, kind)
626 }
627 }
628 // highlightWriteInExpr is called for expressions that are
629 // logically on the left side of an assignment.
630 // We follow the behavior of VSCode+Rust and GoLand, which differs
631 // slightly from types.TypeAndValue.Assignable:
632 // *ptr = 1 // ptr write
633 // *ptr.field = 1 // ptr read, field write
634 // s.field = 1 // s read, field write
635 // array[i] = 1 // array read
636 var highlightWriteInExpr func(expr ast.Expr)
637 highlightWriteInExpr = func(expr ast.Expr) {
638 switch expr := expr.(type) {
639 case *ast.Ident:
640 highlightIdent(expr, protocol.Write)
641 case *ast.SelectorExpr:
642 highlightIdent(expr.Sel, protocol.Write)
643 case *ast.StarExpr:
644 highlightWriteInExpr(expr.X)
645 case *ast.ParenExpr:
646 highlightWriteInExpr(expr.X)
647 }
648 }
649
650 _, curFile := cursorutil.FirstEnclosing[*ast.File](cur)
651 curFile.Inspect(nil, func(c inspector.Cursor) bool {
652 switch n := c.Node().(type) {
653 case *ast.AssignStmt:
654 for _, s := range n.Lhs {
655 highlightWriteInExpr(s)
656 }
657 case *ast.GenDecl:
658 if n.Tok == token.CONST || n.Tok == token.VAR {
659 for _, spec := range n.Specs {
660 if spec, ok := spec.(*ast.ValueSpec); ok {
661 for _, ele := range spec.Names {
662 highlightWriteInExpr(ele)
663 }
664 }
665 }
666 }
667 case *ast.IncDecStmt:
668 highlightWriteInExpr(n.X)
669 case *ast.SendStmt:
670 highlightWriteInExpr(n.Chan)
671 case *ast.CompositeLit:
672 t := info.TypeOf(n)
673 if t == nil {
674 t = types.Typ[types.Invalid]
675 }
676 if ptr, ok := t.Underlying().(*types.Pointer); ok {
677 t = ptr.Elem()
678 }
679 if _, ok := t.Underlying().(*types.Struct); ok {
680 for _, expr := range n.Elts {
681 if expr, ok := (expr).(*ast.KeyValueExpr); ok {
682 highlightWriteInExpr(expr.Key)
683 }
684 }
685 }
686 case *ast.RangeStmt:
687 highlightWriteInExpr(n.Key)
688 highlightWriteInExpr(n.Value)
689 case *ast.Field:
690 for _, name := range n.Names {
691 highlightIdent(name, protocol.Text)
692 }
693 case *ast.Ident:
694 // This case is reached for all Idents,
695 // including those also visited by highlightWriteInExpr.
696 if is[*types.Var](info.ObjectOf(n)) {
697 highlightIdent(n, protocol.Read)
698 } else {
699 // kind of idents in PkgName, etc. is Text
700 highlightIdent(n, protocol.Text)
701 }
702 case *ast.ImportSpec:
703 pkgname := info.PkgNameOf(n)
704 if obj != nil && pkgname == obj {
705 if n.Name != nil {
706 highlightNode(result, n.Name, protocol.Text)
707 } else {
708 highlightNode(result, n, protocol.Text)
709 }
710 }
711 }
712 return true
713 })
714 }