Debian Codegraph @

gopls/internal/golang/semtok.go

raw symbols SCIP
1 // Copyright 2024 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 // This file defines the Semantic Tokens operation for Go source.
8
9 import (
10 "bytes"
11 "context"
12 "errors"
13 "fmt"
14 "go/ast"
15 "go/token"
16 "go/types"
17 "log"
18 "maps"
19 "path/filepath"
20 "regexp"
21 "slices"
22 "strconv"
23 "strings"
24 "time"
25
26 "golang.org/x/tools/gopls/internal/cache"
27 "golang.org/x/tools/gopls/internal/cache/metadata"
28 "golang.org/x/tools/gopls/internal/cache/parsego"
29 "golang.org/x/tools/gopls/internal/file"
30 "golang.org/x/tools/gopls/internal/protocol"
31 "golang.org/x/tools/gopls/internal/protocol/semtok"
32 "golang.org/x/tools/gopls/internal/util/bug"
33 "golang.org/x/tools/gopls/internal/util/safetoken"
34 "golang.org/x/tools/internal/astutil"
35 "golang.org/x/tools/internal/event"
36 "golang.org/x/tools/internal/fmtstr"
37 )
38
39 // semDebug enables comprehensive logging of decisions
40 // (gopls semtok foo.go > /dev/null shows log output).
41 // It should never be true in checked-in code.
42 const semDebug = false
43
44 func SemanticTokens(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng *protocol.Range) (*protocol.SemanticTokens, error) {
45 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
46 if err != nil {
47 return nil, err
48 }
49
50 // Select range.
51 var start, end token.Pos
52 if rng != nil {
53 var err error
54 start, end, err = pgf.RangePos(*rng)
55 if err != nil {
56 return nil, err // e.g. invalid range
57 }
58 } else {
59 tok := pgf.Tok
60 start, end = tok.Pos(0), tok.Pos(tok.Size()) // entire file
61 }
62
63 // Reject full semantic token requests for large files.
64 //
65 // The LSP says that errors for the semantic token requests
66 // should only be returned for exceptions (a word not
67 // otherwise defined). This code treats a too-large file as an
68 // exception. On parse errors, the code does what it can.
69 const maxFullFileSize = 100000
70 if int(end-start) > maxFullFileSize {
71 return nil, fmt.Errorf("semantic tokens: range %s too large (%d > %d)",
72 fh.URI().Path(), end-start, maxFullFileSize)
73 }
74
75 tv := tokenVisitor{
76 ctx: ctx,
77 metadataSource: snapshot,
78 metadata: pkg.Metadata(),
79 info: pkg.TypesInfo(),
80 fset: pkg.FileSet(),
81 pkg: pkg,
82 pgf: pgf,
83 start: start,
84 end: end,
85 }
86
87 tv.visit()
88
89 semanticTokenModifiers := snapshot.Options().EnabledSemanticTokenModifiers()
90 if snapshot.IsBuiltin(fh.URI()) {
91 // The shadowing modifier is not appropriate for the fake builtin.go file.
92 semanticTokenModifiers = maps.Clone(semanticTokenModifiers)
93 semanticTokenModifiers[semtok.ModShadowing] = false
94 }
95
96 return &protocol.SemanticTokens{
97 Data: semtok.Encode(
98 tv.tokens,
99 snapshot.Options().EnabledSemanticTokenTypes(),
100 semanticTokenModifiers),
101 ResultID: time.Now().String(), // for delta requests, but we've never seen any
102 }, nil
103 }
104
105 type tokenVisitor struct {
106 // inputs
107 ctx context.Context // for event logging
108 metadataSource metadata.Source // used to resolve imports
109 metadata *metadata.Package
110 info *types.Info
111 fset *token.FileSet
112 pkg *cache.Package
113 pgf *parsego.File
114 start, end token.Pos // range of interest
115
116 // working state
117 stack []ast.Node // path from root of the syntax tree
118 tokens []semtok.Token // computed sequence of semantic tokens
119 }
120
121 func (tv *tokenVisitor) visit() {
122 f := tv.pgf.File
123 // may not be in range, but harmless
124 tv.token(f.Package, len("package"), semtok.TokKeyword)
125 if f.Name != nil {
126 tv.token(f.Name.NamePos, len(f.Name.Name), semtok.TokNamespace)
127 }
128 for _, decl := range f.Decls {
129 // Only look at the decls that overlap the range.
130 if decl.End() <= tv.start || decl.Pos() >= tv.end {
131 continue
132 }
133 ast.Inspect(decl, tv.inspect)
134 }
135
136 // Scan all files for imported pkgs, ignore the ambiguous pkg.
137 // This is to be consistent with the behavior in [go/doc]: https://pkg.go.dev/pkg/go/doc.
138 importByName := make(map[string]*types.PkgName)
139 for _, pgf := range tv.pkg.CompiledGoFiles() {
140 for _, imp := range pgf.File.Imports {
141 if obj := tv.pkg.TypesInfo().PkgNameOf(imp); obj != nil {
142 if old, ok := importByName[obj.Name()]; ok {
143 if old != nil && old.Imported() != obj.Imported() {
144 importByName[obj.Name()] = nil // nil => ambiguous across files
145 }
146 continue
147 }
148 importByName[obj.Name()] = obj
149 }
150 }
151 }
152
153 for _, cg := range f.Comments {
154 for _, c := range cg.List {
155 // Only look at the comment that overlap the range.
156 if c.End() <= tv.start || c.Pos() >= tv.end {
157 continue
158 }
159 tv.comment(c, importByName)
160 }
161 }
162 }
163
164 // Matches (for example) "[F]", "[*p.T]", "[p.T.M]"
165 // The first group is reference name. e.g. The first group of "[*p.T.M]" is "p.T.M".
166 var docLinkRegex = regexp.MustCompile(`\[\*?([\pL_][\pL_0-9]*(\.[\pL_][\pL_0-9]*){0,2})]`)
167
168 // findDocLinkIndices finds the indices of the doc links in the line.
169 // It will ignore the url link, e.g. "[go]: https://go.dev".
170 // For a invalid url link, it would be considered as a doc link, e.g. "[go]: h://go.dev".
171 func findDocLinkIndices(line string) [][]int {
172 indices := docLinkRegex.FindAllStringSubmatchIndex(line, -1)
173
174 ret := slices.DeleteFunc(
175 indices,
176 func(index []int) bool {
177 // end is the end index of the first submatch, which is the next pos of ']'
178 end := index[1]
179
180 if end < len(line) && line[end] == ':' {
181 url := strings.TrimSpace(line[end+1:])
182 before, _, found := strings.Cut(url, "://")
183 if found && isScheme(before) {
184 // Valid URL, skip this match
185 return true
186 }
187 }
188
189 return false
190 },
191 )
192
193 return ret
194 }
195
196 // isScheme reports whether s is a recognized URL scheme.
197 // Note that if strings of new length (beyond 3-7)
198 // are added here, the fast path at the top of autoURL will need updating.
199 func isScheme(s string) bool {
200 switch s {
201 case "file",
202 "ftp",
203 "gopher",
204 "http",
205 "https",
206 "mailto",
207 "nntp":
208 return true
209 }
210 return false
211 }
212
213 // comment emits semantic tokens for a comment.
214 // If the comment contains doc links or "go:" directives,
215 // it emits a separate token for each link or directive and
216 // each comment portion between them.
217 func (tv *tokenVisitor) comment(c *ast.Comment, importByName map[string]*types.PkgName) {
218 if strings.HasPrefix(c.Text, "//go:") {
219 tv.godirective(c)
220 return
221 }
222
223 pkgScope := tv.pkg.Types().Scope()
224 // lookupObjects interprets the name in various forms
225 // (X, p.T, p.T.M, etc) and return the list of symbols
226 // denoted by each identifier in the dotted list.
227 lookupObjects := func(name string) (objs []types.Object) {
228 scope := pkgScope
229 if pkg, suffix, ok := strings.Cut(name, "."); ok {
230 if obj, _ := importByName[pkg]; obj != nil {
231 objs = append(objs, obj)
232 scope = obj.Imported().Scope()
233 name = suffix
234 }
235 }
236
237 if recv, method, ok := strings.Cut(name, "."); ok {
238 obj, ok := scope.Lookup(recv).(*types.TypeName)
239 if !ok {
240 return nil
241 }
242 objs = append(objs, obj)
243 t, ok := obj.Type().(*types.Named)
244 if !ok {
245 return nil
246 }
247 m, _, _ := types.LookupFieldOrMethod(t, true, tv.pkg.Types(), method)
248 if m == nil {
249 return nil
250 }
251 objs = append(objs, m)
252 return objs
253 } else {
254 obj := scope.Lookup(name)
255 if obj == nil {
256 return nil
257 }
258 if _, ok := obj.(*types.PkgName); !ok && !obj.Exported() {
259 return nil
260 }
261 objs = append(objs, obj)
262 return objs
263
264 }
265 }
266
267 pos := c.Pos()
268 for line := range strings.SplitSeq(c.Text, "\n") {
269 last := 0
270
271 for _, idx := range findDocLinkIndices(line) {
272 // The first group is the reference name. e.g. "X", "p.T", "p.T.M".
273 name := line[idx[2]:idx[3]]
274 if objs := lookupObjects(name); len(objs) > 0 {
275 if last < idx[2] {
276 tv.token(pos+token.Pos(last), idx[2]-last, semtok.TokComment)
277 }
278 offset := pos + token.Pos(idx[2])
279 for i, obj := range objs {
280 if i > 0 {
281 tv.token(offset, len("."), semtok.TokComment)
282 offset += token.Pos(len("."))
283 }
284 id, rest, _ := strings.Cut(name, ".")
285 name = rest
286 tok, mods := tv.appendObjectModifiers(nil, obj)
287 tv.token(offset, len(id), tok, mods...)
288 offset += token.Pos(len(id))
289 }
290 last = idx[3]
291 }
292 }
293 if last != len(c.Text) {
294 tv.token(pos+token.Pos(last), len(line)-last, semtok.TokComment)
295 }
296 pos += token.Pos(len(line) + 1)
297 }
298 }
299
300 // token emits a token of the specified extent and semantics.
301 func (tv *tokenVisitor) token(start token.Pos, length int, typ semtok.Type, modifiers ...semtok.Modifier) {
302 if !start.IsValid() {
303 return
304 }
305 if length <= 0 {
306 return // vscode doesn't like 0-length Tokens
307 }
308 end := start + token.Pos(length)
309 if start >= tv.end || end <= tv.start {
310 return
311 }
312 // want a line and column from start (in LSP coordinates). Ignore line directives.
313 rng, err := tv.pgf.PosRange(start, end)
314 if err != nil {
315 event.Error(tv.ctx, "failed to convert to range", err)
316 return
317 }
318 if rng.End.Line != rng.Start.Line {
319 // this happens if users are typing at the end of the file, but report nothing
320 return
321 }
322 tv.tokens = append(tv.tokens, semtok.Token{
323 Line: rng.Start.Line,
324 Start: rng.Start.Character,
325 Len: rng.End.Character - rng.Start.Character, // (on same line)
326 Type: typ,
327 Modifiers: modifiers,
328 })
329 }
330
331 // strStack converts the stack to a string, for debugging and error messages.
332 func (tv *tokenVisitor) strStack() string {
333 msg := []string{"["}
334 for _, n := range slices.Backward(tv.stack) {
335 msg = append(msg, strings.TrimPrefix(fmt.Sprintf("%T", n), "*ast."))
336 }
337 if len(tv.stack) > 0 {
338 pos := tv.stack[len(tv.stack)-1].Pos()
339 if _, err := safetoken.Offset(tv.pgf.Tok, pos); err != nil {
340 msg = append(msg, fmt.Sprintf("invalid position %v for %s", pos, tv.pgf.URI))
341 } else {
342 posn := safetoken.Position(tv.pgf.Tok, pos)
343 msg = append(msg, fmt.Sprintf("(%s:%d,col:%d)",
344 filepath.Base(posn.Filename), posn.Line, posn.Column))
345 }
346 }
347 msg = append(msg, "]")
348 return strings.Join(msg, " ")
349 }
350
351 // srcLine returns the source text for n (truncated at first newline).
352 func (tv *tokenVisitor) srcLine(n ast.Node) string {
353 file := tv.pgf.Tok
354 line := safetoken.Line(file, n.Pos())
355 start, err := safetoken.Offset(file, file.LineStart(line))
356 if err != nil {
357 return ""
358 }
359 end := start
360 for ; end < len(tv.pgf.Src) && tv.pgf.Src[end] != '\n'; end++ {
361
362 }
363 return string(tv.pgf.Src[start:end])
364 }
365
366 func (tv *tokenVisitor) inspect(n ast.Node) (descend bool) {
367 if n == nil {
368 tv.stack = tv.stack[:len(tv.stack)-1] // pop
369 return true
370 }
371 tv.stack = append(tv.stack, n) // push
372 defer func() {
373 if !descend {
374 tv.stack = tv.stack[:len(tv.stack)-1] // pop
375 }
376 }()
377
378 switch n := n.(type) {
379 case *ast.ArrayType:
380 case *ast.AssignStmt:
381 tv.token(n.TokPos, len(n.Tok.String()), semtok.TokOperator)
382 case *ast.BasicLit:
383 if n.Kind == token.STRING {
384 if strings.Contains(n.Value, "\n") {
385 // has to be a string.
386 tv.multiline(n.Pos(), n.End(), semtok.TokString)
387 } else if !tv.formatString(n) {
388 // not a format string, color the whole as a TokString.
389 tv.token(n.Pos(), len(n.Value), semtok.TokString)
390 }
391 } else {
392 tv.token(n.Pos(), len(n.Value), semtok.TokNumber)
393 }
394 case *ast.BinaryExpr:
395 tv.token(n.OpPos, len(n.Op.String()), semtok.TokOperator)
396 case *ast.BlockStmt:
397 case *ast.BranchStmt:
398 tv.token(n.TokPos, len(n.Tok.String()), semtok.TokKeyword)
399 case *ast.CallExpr:
400 if n.Ellipsis.IsValid() {
401 tv.token(n.Ellipsis, len("..."), semtok.TokOperator)
402 }
403 case *ast.CaseClause:
404 iam := "case"
405 if n.List == nil {
406 iam = "default"
407 }
408 tv.token(n.Case, len(iam), semtok.TokKeyword)
409 case *ast.ChanType:
410 // chan | chan <- | <- chan
411 switch {
412 case n.Arrow == token.NoPos:
413 tv.token(n.Begin, len("chan"), semtok.TokKeyword)
414 case n.Arrow == n.Begin:
415 tv.token(n.Arrow, 2, semtok.TokOperator)
416 pos := tv.findKeyword("chan", n.Begin+2, n.Value.Pos())
417 tv.token(pos, len("chan"), semtok.TokKeyword)
418 case n.Arrow != n.Begin:
419 tv.token(n.Begin, len("chan"), semtok.TokKeyword)
420 tv.token(n.Arrow, 2, semtok.TokOperator)
421 }
422 case *ast.CommClause:
423 length := len("case")
424 if n.Comm == nil {
425 length = len("default")
426 }
427 tv.token(n.Case, length, semtok.TokKeyword)
428 case *ast.CompositeLit:
429 case *ast.DeclStmt:
430 case *ast.DeferStmt:
431 tv.token(n.Defer, len("defer"), semtok.TokKeyword)
432 case *ast.Ellipsis:
433 tv.token(n.Ellipsis, len("..."), semtok.TokOperator)
434 case *ast.EmptyStmt:
435 case *ast.ExprStmt:
436 case *ast.Field:
437 case *ast.FieldList:
438 case *ast.ForStmt:
439 tv.token(n.For, len("for"), semtok.TokKeyword)
440 case *ast.FuncDecl:
441 case *ast.FuncLit:
442 case *ast.FuncType:
443 if n.Func != token.NoPos {
444 tv.token(n.Func, len("func"), semtok.TokKeyword)
445 }
446 case *ast.GenDecl:
447 tv.token(n.TokPos, len(n.Tok.String()), semtok.TokKeyword)
448 case *ast.GoStmt:
449 tv.token(n.Go, len("go"), semtok.TokKeyword)
450 case *ast.Ident:
451 tv.ident(n)
452 case *ast.IfStmt:
453 tv.token(n.If, len("if"), semtok.TokKeyword)
454 if n.Else != nil {
455 // x.Body.End() or x.Body.End()+1, not that it matters
456 pos := tv.findKeyword("else", n.Body.End(), n.Else.Pos())
457 tv.token(pos, len("else"), semtok.TokKeyword)
458 }
459 case *ast.ImportSpec:
460 tv.importSpec(n)
461 return false
462 case *ast.IncDecStmt:
463 tv.token(n.TokPos, len(n.Tok.String()), semtok.TokOperator)
464 case *ast.IndexExpr:
465 case *ast.IndexListExpr:
466 case *ast.InterfaceType:
467 tv.token(n.Interface, len("interface"), semtok.TokKeyword)
468 case *ast.KeyValueExpr:
469 case *ast.LabeledStmt:
470 case *ast.MapType:
471 tv.token(n.Map, len("map"), semtok.TokKeyword)
472 case *ast.ParenExpr:
473 case *ast.RangeStmt:
474 tv.token(n.For, len("for"), semtok.TokKeyword)
475 // x.TokPos == token.NoPos is legal (for range foo {})
476 offset := n.TokPos
477 if offset == token.NoPos {
478 offset = n.For
479 }
480 pos := tv.findKeyword("range", offset, n.X.Pos())
481 tv.token(pos, len("range"), semtok.TokKeyword)
482 case *ast.ReturnStmt:
483 tv.token(n.Return, len("return"), semtok.TokKeyword)
484 case *ast.SelectStmt:
485 tv.token(n.Select, len("select"), semtok.TokKeyword)
486 case *ast.SelectorExpr:
487 case *ast.SendStmt:
488 tv.token(n.Arrow, len("<-"), semtok.TokOperator)
489 case *ast.SliceExpr:
490 case *ast.StarExpr:
491 tv.token(n.Star, len("*"), semtok.TokOperator)
492 case *ast.StructType:
493 tv.token(n.Struct, len("struct"), semtok.TokKeyword)
494 case *ast.SwitchStmt:
495 tv.token(n.Switch, len("switch"), semtok.TokKeyword)
496 case *ast.TypeAssertExpr:
497 if n.Type == nil {
498 pos := tv.findKeyword("type", n.Lparen, n.Rparen)
499 tv.token(pos, len("type"), semtok.TokKeyword)
500 }
501 case *ast.TypeSpec:
502 case *ast.TypeSwitchStmt:
503 tv.token(n.Switch, len("switch"), semtok.TokKeyword)
504 case *ast.UnaryExpr:
505 tv.token(n.OpPos, len(n.Op.String()), semtok.TokOperator)
506 case *ast.ValueSpec:
507 // things only seen with parsing or type errors, so ignore them
508 case *ast.BadDecl, *ast.BadExpr, *ast.BadStmt:
509 return false
510 // not going to see these
511 case *ast.File, *ast.Package:
512 tv.errorf("implement %T %s", n, safetoken.Position(tv.pgf.Tok, n.Pos()))
513 // other things we knowingly ignore
514 case *ast.Comment, *ast.CommentGroup:
515 return false
516 default:
517 tv.errorf("failed to implement %T", n)
518 }
519 return true
520 }
521
522 // formatString tries to report directives and string literals
523 // inside a (possible) printf-like call, it returns false and does nothing
524 // if the string is not a format string.
525 func (tv *tokenVisitor) formatString(lit *ast.BasicLit) bool {
526 if len(tv.stack) <= 1 {
527 return false
528 }
529 call, ok := tv.stack[len(tv.stack)-2].(*ast.CallExpr)
530 if !ok {
531 return false
532 }
533 lastNonVariadic, idx := formatStringAndIndex(tv.info, call)
534 if idx == -1 || lit != lastNonVariadic {
535 return false
536 }
537 format, err := strconv.Unquote(lit.Value)
538 if err != nil {
539 return false
540 }
541 if !strings.Contains(format, "%") {
542 return false
543 }
544 operations, err := fmtstr.Parse(format, idx)
545 if err != nil {
546 return false
547 }
548
549 // It's a format string, compute interleaved sub range of directives and literals.
550 // pos tracks literal substring position within the overall BasicLit.
551 pos := lit.ValuePos
552 for _, op := range operations {
553 // Skip "%%".
554 if op.Verb.Verb == '%' {
555 continue
556 }
557 rng, err := astutil.RangeInStringLiteral(lit, op.Range.Start, op.Range.End)
558 if err != nil {
559 return false
560 }
561 // Report literal substring.
562 tv.token(pos, int(rng.Start-pos), semtok.TokString)
563 // Report formatting directive.
564 tv.token(rng.Start, int(rng.EndPos-rng.Start), semtok.TokString, semtok.ModFormat)
565 pos = rng.EndPos
566 }
567 // Report remaining literal substring.
568 tv.token(pos, int(lit.End()-pos), semtok.TokString)
569 return true
570 }
571
572 func (tv *tokenVisitor) appendObjectModifiers(mods []semtok.Modifier, obj types.Object) (semtok.Type, []semtok.Modifier) {
573 if obj.Pkg() == nil {
574 mods = append(mods, semtok.ModDefaultLibrary)
575 }
576
577 // Note: PkgName, Builtin, Label have type Invalid, which adds no modifiers.
578 mods = appendTypeModifiers(mods, obj.Type())
579
580 switch obj := obj.(type) {
581 case *types.PkgName:
582 return semtok.TokNamespace, mods
583
584 case *types.Builtin:
585 return semtok.TokFunction, mods
586
587 case *types.Func:
588 if obj.Signature().Recv() != nil {
589 return semtok.TokMethod, mods
590 } else {
591 return semtok.TokFunction, mods
592 }
593
594 case *types.TypeName:
595 if is[*types.TypeParam](types.Unalias(obj.Type())) {
596 return semtok.TokTypeParam, mods
597 }
598 return semtok.TokType, mods
599
600 case *types.Const:
601 mods = append(mods, semtok.ModReadonly)
602 return semtok.TokVariable, mods
603
604 case *types.Var:
605 switch obj.Kind() {
606 case types.PackageVar:
607 mods = append(mods, semtok.ModStatic)
608 case types.RecvVar, types.ParamVar:
609 return semtok.TokParameter, mods
610 case types.FieldVar:
611 return semtok.TokProperty, mods
612 }
613 return semtok.TokVariable, mods
614
615 case *types.Label:
616 return semtok.TokLabel, mods
617
618 case *types.Nil:
619 mods = append(mods, semtok.ModReadonly)
620 return semtok.TokVariable, mods
621 }
622
623 panic(obj)
624 }
625
626 // appendTypeModifiers appends optional modifiers that describe the top-level
627 // type constructor of t: "pointer", "map", etc.
628 func appendTypeModifiers(mods []semtok.Modifier, t types.Type) []semtok.Modifier {
629 // For a type parameter, don't report "interface".
630 if is[*types.TypeParam](types.Unalias(t)) {
631 return mods
632 }
633
634 switch t := t.Underlying().(type) {
635 case *types.Interface:
636 mods = append(mods, semtok.ModInterface)
637 case *types.Struct:
638 mods = append(mods, semtok.ModStruct)
639 case *types.Signature:
640 mods = append(mods, semtok.ModSignature)
641 case *types.Pointer:
642 mods = append(mods, semtok.ModPointer)
643 case *types.Array:
644 mods = append(mods, semtok.ModArray)
645 case *types.Map:
646 mods = append(mods, semtok.ModMap)
647 case *types.Slice:
648 mods = append(mods, semtok.ModSlice)
649 case *types.Chan:
650 mods = append(mods, semtok.ModChan)
651 case *types.Basic:
652 switch t.Kind() {
653 case types.Invalid:
654 // ignore (e.g. Builtin, PkgName, Label)
655 case types.String:
656 mods = append(mods, semtok.ModString)
657 case types.Bool:
658 mods = append(mods, semtok.ModBool)
659 case types.UnsafePointer:
660 mods = append(mods, semtok.ModPointer)
661 default:
662 if t.Info()&types.IsNumeric != 0 {
663 mods = append(mods, semtok.ModNumber)
664 }
665 }
666 }
667 return mods
668 }
669
670 // isShadowing reports whether id is shadowing some other definiton from outer scopes.
671 func (tv *tokenVisitor) isShadowing(id *ast.Ident) bool {
672 if obj, ok := tv.info.Defs[id]; obj != nil {
673 // obj.Parent.Parent is the surrounding scope. If we can find another declaration
674 // starting from there id is a shadowing identifier.
675 if obj.Parent() != nil && obj.Parent().Parent() != nil {
676 if s, _ := obj.Parent().Parent().LookupParent(id.Name, id.Pos()); s != nil {
677 for i, n := range slices.Backward(tv.stack) {
678 // A FuncType may be the signature of a Func{Decl,Lit} or just a func type.
679 // Any object declared within a FuncType must be a TypeParam, Param, or Result.
680 // The only reference to such an object can be within a function body.
681 // Since a func type has no function body, there can be no references to the
682 // object, and shadowing is irrelevant. So omit the modifier in that case.
683 if is[*ast.FuncType](n) {
684 switch tv.stack[i-1].(type) {
685 case *ast.FuncDecl, *ast.FuncLit:
686 return true // parameter of function with body
687 }
688 return false // parameter in a func type
689 }
690 }
691 return true
692 }
693 }
694 } else if ok {
695 // Find the scope of the symbolic variable of the type-switch header.
696 // id := foo.(type)
697 for _, n := range slices.Backward(tv.stack) {
698 if typeSwitchStmt, ok := n.(*ast.TypeSwitchStmt); ok {
699 if assign, ok := typeSwitchStmt.Assign.(*ast.AssignStmt); ok && len(assign.Lhs) != 0 {
700 if ident, ok := assign.Lhs[0].(*ast.Ident); ok && ident == id {
701 if s, _ := tv.info.Scopes[n].LookupParent(id.Name, id.Pos()); s != nil {
702 return true
703 }
704 break
705 }
706 }
707 }
708 }
709 }
710 return false
711 }
712
713 func (tv *tokenVisitor) ident(id *ast.Ident) {
714 var (
715 tok semtok.Type
716 mods []semtok.Modifier
717 obj types.Object
718 ok bool
719 )
720 if obj, _ = tv.info.Defs[id]; obj != nil {
721 // definition
722 mods = append(mods, semtok.ModDefinition)
723 tok, mods = tv.appendObjectModifiers(mods, obj)
724
725 } else if obj, ok = tv.info.Uses[id]; ok {
726 // use
727 tok, mods = tv.appendObjectModifiers(mods, obj)
728
729 } else if tok, mods = tv.unkIdent(id); tok != "" {
730 // ok
731
732 } else {
733 return
734 }
735
736 if tv.isShadowing(id) {
737 mods = append(mods, semtok.ModShadowing)
738 }
739
740 // Emit a token for the identifier's extent.
741 tv.token(id.Pos(), len(id.Name), tok, mods...)
742
743 if semDebug {
744 q := "nil"
745 if obj != nil {
746 q = fmt.Sprintf("%T", obj.Type()) // e.g. "*types.Map"
747 }
748 log.Printf(" use %s/%T/%s got %s %v (%s)",
749 id.Name, obj, q, tok, mods, tv.strStack())
750 }
751 }
752
753 // unkIdent handles identifiers with no types.Object (neither use nor
754 // def), use the parse stack.
755 // A lot of these only happen when the package doesn't compile,
756 // but in that case it is all best-effort from the parse tree.
757 func (tv *tokenVisitor) unkIdent(id *ast.Ident) (semtok.Type, []semtok.Modifier) {
758 def := []semtok.Modifier{semtok.ModDefinition}
759 n := len(tv.stack) - 2 // parent of Ident; stack is [File ... Ident]
760 if n < 0 {
761 tv.errorf("no stack") // can't happen
762 return "", nil
763 }
764 switch parent := tv.stack[n].(type) {
765 case *ast.BinaryExpr, *ast.UnaryExpr, *ast.ParenExpr, *ast.StarExpr,
766 *ast.IncDecStmt, *ast.SliceExpr, *ast.ExprStmt, *ast.IndexExpr,
767 *ast.ReturnStmt, *ast.ChanType, *ast.SendStmt,
768 *ast.ForStmt, // possibly incomplete
769 *ast.IfStmt, /* condition */
770 *ast.KeyValueExpr, // either key or value
771 *ast.IndexListExpr:
772 return semtok.TokVariable, nil
773 case *ast.Ellipsis:
774 return semtok.TokType, nil
775 case *ast.CaseClause:
776 if n-2 >= 0 && is[ast.TypeSwitchStmt](tv.stack[n-2]) {
777 return semtok.TokType, nil
778 }
779 return semtok.TokVariable, nil
780 case *ast.ArrayType:
781 if id == parent.Len {
782 // or maybe a Type Param, but we can't just from the parse tree
783 return semtok.TokVariable, nil
784 } else {
785 return semtok.TokType, nil
786 }
787 case *ast.MapType:
788 return semtok.TokType, nil
789 case *ast.CallExpr:
790 if id == parent.Fun {
791 return semtok.TokFunction, nil
792 }
793 return semtok.TokVariable, nil
794 case *ast.SwitchStmt:
795 return semtok.TokVariable, nil
796 case *ast.TypeAssertExpr:
797 if id == parent.X {
798 return semtok.TokVariable, nil
799 } else if id == parent.Type {
800 return semtok.TokType, nil
801 }
802 case *ast.ValueSpec:
803 if slices.Contains(parent.Names, id) {
804 return semtok.TokVariable, def
805 }
806 for _, p := range parent.Values {
807 if p == id {
808 return semtok.TokVariable, nil
809 }
810 }
811 return semtok.TokType, nil
812 case *ast.SelectorExpr: // e.ti.Selections[nd] is nil, so no help
813 if n-1 >= 0 {
814 if ce, ok := tv.stack[n-1].(*ast.CallExpr); ok {
815 // ... CallExpr SelectorExpr Ident (_.x())
816 if ce.Fun == parent && parent.Sel == id {
817 return semtok.TokFunction, nil
818 }
819 }
820 }
821 return semtok.TokVariable, nil
822 case *ast.AssignStmt:
823 for _, p := range parent.Lhs {
824 // x := ..., or x = ...
825 if p == id {
826 if parent.Tok != token.DEFINE {
827 def = nil
828 }
829 return semtok.TokVariable, def // '_' in _ = ...
830 }
831 }
832 // RHS, = x
833 return semtok.TokVariable, nil
834 case *ast.TypeSpec: // it's a type if it is either the Name or the Type
835 if id == parent.Type {
836 def = nil
837 }
838 return semtok.TokType, def
839 case *ast.Field:
840 // ident could be type in a field, or a method in an interface type, or a variable
841 if id == parent.Type {
842 return semtok.TokType, nil
843 }
844 if n > 2 &&
845 is[*ast.InterfaceType](tv.stack[n-2]) &&
846 is[*ast.FieldList](tv.stack[n-1]) {
847
848 return semtok.TokMethod, def
849 }
850 return semtok.TokVariable, nil
851 case *ast.LabeledStmt:
852 if id == parent.Label {
853 return semtok.TokLabel, def
854 }
855 case *ast.BranchStmt:
856 if id == parent.Label {
857 return semtok.TokLabel, nil
858 }
859 case *ast.CompositeLit:
860 if parent.Type == id {
861 return semtok.TokType, nil
862 }
863 return semtok.TokVariable, nil
864 case *ast.RangeStmt:
865 if parent.Tok != token.DEFINE {
866 def = nil
867 }
868 return semtok.TokVariable, def
869 case *ast.FuncDecl:
870 return semtok.TokFunction, def
871 default:
872 tv.errorf("%T unexpected: %s %s%q", parent, id.Name, tv.strStack(), tv.srcLine(id))
873 }
874 return "", nil
875 }
876
877 // multiline emits a multiline token (`string` or /*comment*/).
878 func (tv *tokenVisitor) multiline(start, end token.Pos, tok semtok.Type) {
879 // TODO(adonovan): test with non-ASCII.
880
881 f := tv.fset.File(start)
882 // the hard part is finding the lengths of lines. include the \n
883 length := func(line int) int {
884 n := f.LineStart(line)
885 if line >= f.LineCount() {
886 return f.Size() - int(n)
887 }
888 return int(f.LineStart(line+1) - n)
889 }
890 spos := safetoken.StartPosition(tv.fset, start)
891 epos := safetoken.EndPosition(tv.fset, end)
892 sline := spos.Line
893 eline := epos.Line
894 // first line is from spos.Column to end
895 tv.token(start, length(sline)-spos.Column, tok) // leng(sline)-1 - (spos.Column-1)
896 for i := sline + 1; i < eline; i++ {
897 // intermediate lines are from 1 to end
898 tv.token(f.LineStart(i), length(i)-1, tok) // avoid the newline
899 }
900 // last line is from 1 to epos.Column
901 tv.token(f.LineStart(eline), epos.Column-1, tok) // columns are 1-based
902 }
903
904 // findKeyword returns the position of a keyword by searching within
905 // the specified range, for when it cannot be exactly known from the AST.
906 // It returns NoPos if the keyword was not present in the source due to parse error.
907 func (tv *tokenVisitor) findKeyword(keyword string, start, end token.Pos) token.Pos {
908 // TODO(adonovan): use safetoken.Offset.
909 offset := int(start) - tv.pgf.Tok.Base()
910 last := int(end) - tv.pgf.Tok.Base()
911 buf := tv.pgf.Src
912 idx := bytes.Index(buf[offset:last], []byte(keyword))
913 if idx < 0 {
914 // Ill-formed code may form syntax trees without their usual tokens.
915 // For example, "type _ <-<-chan int" parses as <-chan (chan int),
916 // with two nested ChanTypes but only one chan keyword.
917 return token.NoPos
918 }
919 return start + token.Pos(idx)
920 }
921
922 func (tv *tokenVisitor) importSpec(spec *ast.ImportSpec) {
923 // a local package name or the last component of the Path
924 if spec.Name != nil {
925 name := spec.Name.String()
926 if name != "_" && name != "." {
927 tv.token(spec.Name.Pos(), len(name), semtok.TokNamespace)
928 }
929 return // don't mark anything for . or _
930 }
931 importPath := metadata.UnquoteImportPath(spec)
932 if importPath == "" {
933 return
934 }
935 // Import strings are implementation defined. Try to match with parse information.
936 depID := tv.metadata.DepsByImpPath[importPath]
937 if depID == "" {
938 return
939 }
940 depMD := tv.metadataSource.Metadata(depID)
941 if depMD == nil {
942 // unexpected, but impact is that maybe some import is not colored
943 return
944 }
945 // Check whether the original literal contains the package's declared name.
946 j := strings.LastIndex(spec.Path.Value, string(depMD.Name))
947 if j < 0 {
948 // Package name does not match import path, so there is nothing to report.
949 return
950 }
951 // Report virtual declaration at the position of the substring.
952 start := spec.Path.Pos() + token.Pos(j)
953 tv.token(start, len(depMD.Name), semtok.TokNamespace)
954 }
955
956 // errorf logs an error and reports a bug.
957 func (tv *tokenVisitor) errorf(format string, args ...any) {
958 msg := fmt.Sprintf(format, args...)
959 bug.Report(msg)
960 event.Error(tv.ctx, tv.strStack(), errors.New(msg))
961 }
962
963 var godirectives = map[string]struct{}{
964 // https://pkg.go.dev/cmd/compile
965 "noescape": {},
966 "uintptrescapes": {},
967 "noinline": {},
968 "norace": {},
969 "nosplit": {},
970 "linkname": {},
971
972 // https://pkg.go.dev/go/build
973 "build": {},
974 "binary-only-package": {},
975 "embed": {},
976 }
977
978 // Tokenize godirective at the start of the comment c, if any, and the surrounding comment.
979 // If there is any failure, emits the entire comment as a TokComment token.
980 // Directives are highlighted as-is, even if used incorrectly. Typically there are
981 // dedicated analyzers that will warn about misuse.
982 func (tv *tokenVisitor) godirective(c *ast.Comment) {
983 // First check if '//go:directive args...' is a valid directive.
984 directive, args, _ := strings.Cut(c.Text, " ")
985 kind, _ := stringsCutPrefix(directive, "//go:")
986 if _, ok := godirectives[kind]; !ok {
987 // Unknown 'go:' directive.
988 tv.token(c.Pos(), len(c.Text), semtok.TokComment)
989 return
990 }
991
992 // Make the 'go:directive' part stand out, the rest is comments.
993 tv.token(c.Pos(), len("//"), semtok.TokComment)
994
995 directiveStart := c.Pos() + token.Pos(len("//"))
996 tv.token(directiveStart, len(directive[len("//"):]), semtok.TokNamespace)
997
998 if len(args) > 0 {
999 tailStart := c.Pos() + token.Pos(len(directive)+len(" "))
1000 tv.token(tailStart, len(args), semtok.TokComment)
1001 }
1002 }
1003
1004 // Go 1.20 strings.CutPrefix.
1005 func stringsCutPrefix(s, prefix string) (after string, found bool) {
1006 if !strings.HasPrefix(s, prefix) {
1007 return s, false
1008 }
1009 return s[len(prefix):], true
1010 }
1011
1012 func is[T any](x any) bool {
1013 _, ok := x.(T)
1014 return ok
1015 }