1 // Copyright 2020 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.
19 "golang.org/x/tools/internal/event"
20 "golang.org/x/tools/internal/lsp/protocol"
21 "golang.org/x/tools/internal/lsp/source"
22 errors "golang.org/x/xerrors"
25 func (s *Server) semanticTokensFull(ctx context.Context, p *protocol.SemanticTokensParams) (*protocol.SemanticTokens, error) {
26 ret, err := s.computeSemanticTokens(ctx, p.TextDocument, nil)
30 func (s *Server) semanticTokensFullDelta(ctx context.Context, p *protocol.SemanticTokensDeltaParams) (interface{}, error) {
31 return nil, errors.Errorf("implement SemanticTokensFullDelta")
34 func (s *Server) semanticTokensRange(ctx context.Context, p *protocol.SemanticTokensRangeParams) (*protocol.SemanticTokens, error) {
35 ret, err := s.computeSemanticTokens(ctx, p.TextDocument, &p.Range)
39 func (s *Server) semanticTokensRefresh(ctx context.Context) error {
40 // in the code, but not in the protocol spec
41 return errors.Errorf("implement SemanticTokensRefresh")
44 func (s *Server) computeSemanticTokens(ctx context.Context, td protocol.TextDocumentIdentifier, rng *protocol.Range) (*protocol.SemanticTokens, error) {
45 ans := protocol.SemanticTokens{
48 snapshot, _, ok, release, err := s.beginFileRequest(ctx, td.URI, source.Go)
54 if !vv.Options().SemanticTokens {
55 // return an error, so if the option changes
56 // the client won't remember the wrong answer
57 return nil, errors.Errorf("semantictokens are disabled")
59 pkg, err := snapshot.PackageForFile(ctx, td.URI.SpanURI(), source.TypecheckFull, source.WidestPackage)
63 info := pkg.GetTypesInfo()
64 pgf, err := pkg.File(td.URI.SpanURI())
68 if pgf.ParseErr != nil {
69 return nil, pgf.ParseErr
76 fset: snapshot.FileSet(),
77 tokTypes: s.session.Options().SemanticTypes,
78 tokMods: s.session.Options().SemanticMods,
80 if err := e.init(); err != nil {
84 ans.Data, err = e.Data()
86 // this is an internal error, likely caused by a typo
87 // for a token or modifier
90 // for small cache, some day. for now, the client ignores this
91 ans.ResultID = fmt.Sprintf("%v", time.Now())
95 func (e *encoded) semantics() {
97 e.token(f.Package, len("package"), tokKeyword, nil)
98 e.token(f.Name.NamePos, len(f.Name.Name), tokNamespace, nil)
99 inspect := func(n ast.Node) bool {
100 return e.inspector(n)
102 for _, d := range f.Decls {
103 // only look at the decls that overlap the range
104 start, end := d.Pos(), d.End()
105 if end <= e.start || start >= e.end {
108 ast.Inspect(d, inspect)
112 type tokenType string
115 tokNamespace tokenType = "namespace"
116 tokType tokenType = "type"
117 tokInterface tokenType = "interface"
118 tokParameter tokenType = "parameter"
119 tokVariable tokenType = "variable"
120 tokMember tokenType = "member"
121 tokFunction tokenType = "function"
122 tokKeyword tokenType = "keyword"
123 tokComment tokenType = "comment"
124 tokString tokenType = "string"
125 tokNumber tokenType = "number"
126 tokOperator tokenType = "operator"
129 func (e *encoded) token(start token.Pos, leng int, typ tokenType, mods []string) {
131 e.unexpected("token at token.NoPos")
133 if start >= e.end || start+token.Pos(leng) <= e.start {
136 // want a line and column from start (in LSP coordinates)
137 // [//line directives should be ignored]
138 rng := source.NewMappedRange(e.fset, e.pgf.Mapper, start, start+token.Pos(leng))
139 lspRange, err := rng.Range()
141 // possibly a //line directive. TODO(pjw): fix this somehow
142 // "column mapper is for file...instead of..."
143 // "line is beyond end of file..."
144 // see line 116 of internal/span/token.go which uses Position not PositionFor
145 event.Error(e.ctx, "failed to convert to range", err)
148 if lspRange.End.Line != lspRange.Start.Line {
149 // abrupt end of file, without \n. TODO(pjw): fix?
150 pos := e.fset.PositionFor(start, false)
151 msg := fmt.Sprintf("token at %s:%d.%d overflows", pos.Filename, pos.Line, pos.Column)
152 event.Log(e.ctx, msg)
155 // token is all on one line
156 length := lspRange.End.Character - lspRange.Start.Character
157 e.add(lspRange.Start.Line, lspRange.Start.Character, length, typ, mods)
160 func (e *encoded) add(line, start uint32, len uint32, tok tokenType, mod []string) {
161 x := semItem{line, start, len, tok, mod}
162 e.items = append(e.items, x)
165 // semItem represents a token found walking the parse tree
166 type semItem struct {
173 type encoded struct {
174 // the generated data
178 tokTypes, tokMods []string
179 pgf *source.ParsedGoFile
183 // allowed starting and ending token.Pos, set by init
184 // used to avoid looking at declarations not in range
186 // path from the root of the parse tree, used for debugging
190 // convert the stack to a string, for debugging
191 func (e *encoded) strStack() string {
193 for _, s := range e.stack {
194 msg = append(msg, fmt.Sprintf("%T", s)[5:])
196 if len(e.stack) > 0 {
197 loc := e.stack[len(e.stack)-1].Pos()
198 add := e.pgf.Tok.PositionFor(loc, false)
199 msg = append(msg, fmt.Sprintf("(line:%d,col:%d)", add.Line, add.Column))
201 msg = append(msg, "]")
202 return strings.Join(msg, " ")
205 func (e *encoded) inspector(n ast.Node) bool {
207 e.stack = e.stack[:len(e.stack)-1]
213 e.stack = append(e.stack, n)
214 switch x := n.(type) {
216 case *ast.AssignStmt:
217 e.token(x.TokPos, len(x.Tok.String()), tokOperator, nil)
219 // if it extends across a line, skip it
220 // better would be to mark each line as string TODO(pjw)
221 if strings.Contains(x.Value, "\n") {
226 if x.Kind == token.STRING {
228 if _, ok := e.stack[len(e.stack)-2].(*ast.Field); ok {
229 // struct tags (this is probably pointless, as the
230 // TextMate grammar will treat all the other comments the same)
234 e.token(x.Pos(), ln, what, nil)
235 case *ast.BinaryExpr:
236 e.token(x.OpPos, len(x.Op.String()), tokOperator, nil)
238 case *ast.BranchStmt:
239 e.token(x.TokPos, len(x.Tok.String()), tokKeyword, nil)
240 // There's no semantic encoding for labels
242 if x.Ellipsis != token.NoPos {
243 e.token(x.Ellipsis, len("..."), tokOperator, nil)
245 case *ast.CaseClause:
250 e.token(x.Case, len(iam), tokKeyword, nil)
252 // chan | chan <- | <- chan
253 if x.Arrow == token.NoPos || x.Arrow != x.Begin {
254 e.token(x.Begin, len("chan"), tokKeyword, nil)
257 pos := e.findKeyword("chan", x.Begin+2, x.Value.Pos())
258 e.token(pos, len("chan"), tokKeyword, nil)
259 case *ast.CommClause:
264 e.token(x.Case, iam, tokKeyword, nil)
265 case *ast.CompositeLit:
268 e.token(x.Defer, len("defer"), tokKeyword, nil)
270 e.token(x.Ellipsis, len("..."), tokOperator, nil)
276 e.token(x.For, len("for"), tokKeyword, nil)
280 if x.Func != token.NoPos {
281 e.token(x.Func, len("func"), tokKeyword, nil)
284 e.token(x.TokPos, len(x.Tok.String()), tokKeyword, nil)
286 e.token(x.Go, len("go"), tokKeyword, nil)
290 e.token(x.If, len("if"), tokKeyword, nil)
292 // x.Body.End() or x.Body.End()+1, not that it matters
293 pos := e.findKeyword("else", x.Body.End(), x.Else.Pos())
294 e.token(pos, len("else"), tokKeyword, nil)
296 case *ast.ImportSpec:
300 case *ast.IncDecStmt:
301 e.token(x.TokPos, len(x.Tok.String()), tokOperator, nil)
303 case *ast.InterfaceType:
304 e.token(x.Interface, len("interface"), tokKeyword, nil)
305 case *ast.KeyValueExpr:
306 case *ast.LabeledStmt:
308 e.token(x.Map, len("map"), tokKeyword, nil)
311 e.token(x.For, len("for"), tokKeyword, nil)
312 // x.TokPos == token.NoPos is legal (for range foo {})
314 if offset == token.NoPos {
317 pos := e.findKeyword("range", offset, x.X.Pos())
318 e.token(pos, len("range"), tokKeyword, nil)
319 case *ast.ReturnStmt:
320 e.token(x.Return, len("return"), tokKeyword, nil)
321 case *ast.SelectStmt:
322 e.token(x.Select, len("select"), tokKeyword, nil)
323 case *ast.SelectorExpr:
325 e.token(x.Arrow, len("<-"), tokOperator, nil)
328 e.token(x.Star, len("*"), tokOperator, nil)
329 case *ast.StructType:
330 e.token(x.Struct, len("struct"), tokKeyword, nil)
331 case *ast.SwitchStmt:
332 e.token(x.Switch, len("switch"), tokKeyword, nil)
333 case *ast.TypeAssertExpr:
335 pos := e.findKeyword("type", x.Lparen, x.Rparen)
336 e.token(pos, len("type"), tokKeyword, nil)
339 case *ast.TypeSwitchStmt:
340 e.token(x.Switch, len("switch"), tokKeyword, nil)
342 e.token(x.OpPos, len(x.Op.String()), tokOperator, nil)
344 // things we won't see
345 case *ast.BadDecl, *ast.BadExpr, *ast.BadStmt,
346 *ast.File, *ast.Package:
347 log.Printf("implement %T %s", x, e.pgf.Tok.PositionFor(x.Pos(), false))
348 // things we knowingly ignore
349 case *ast.Comment, *ast.CommentGroup:
352 default: // just to be super safe.
353 e.unexpected(fmt.Sprintf("failed to implement %T", x))
357 func (e *encoded) ident(x *ast.Ident) {
360 what, mods := e.definitionFor(x)
362 e.token(x.Pos(), len(x.String()), what, mods)
367 switch y := use.(type) {
369 e.token(x.NamePos, len(x.Name), tokVariable, []string{"definition"})
371 e.token(x.NamePos, len(x.Name), tokFunction, []string{"defaultLibrary"})
373 mods := []string{"readonly"}
375 if _, ok := tt.(*types.Basic); ok {
376 e.token(x.Pos(), len(x.String()), tokVariable, mods)
379 if ttx, ok := tt.(*types.Named); ok {
380 if x.String() == "iota" {
381 e.unexpected(fmt.Sprintf("iota:%T", ttx))
383 if _, ok := ttx.Underlying().(*types.Basic); ok {
384 e.token(x.Pos(), len(x.String()), tokVariable, mods)
387 e.unexpected(fmt.Sprintf("%q/%T", x.String(), tt))
389 // can this happen? Don't think so
390 e.unexpected(fmt.Sprintf("%s %T %#v", x.String(), tt, tt))
392 e.token(x.Pos(), len(x.Name), tokFunction, nil)
394 // nothing to map it to
396 // nil is a predeclared identifier
397 e.token(x.Pos(), len("nil"), tokVariable, []string{"readonly"})
399 e.token(x.Pos(), len(x.Name), tokNamespace, nil)
400 case *types.TypeName:
401 e.token(x.Pos(), len(x.String()), tokType, nil)
403 e.token(x.Pos(), len(x.Name), tokVariable, nil)
405 // replace with panic after extensive testing
407 msg := fmt.Sprintf("%#v/%#v %#v %#v", x, x.Obj, e.ti.Defs[x], e.ti.Uses[x])
410 if use.Type() != nil {
411 e.unexpected(fmt.Sprintf("%s %T/%T,%#v", x.String(), use, use.Type(), use))
413 e.unexpected(fmt.Sprintf("%s %T", x.String(), use))
418 func (e *encoded) definitionFor(x *ast.Ident) (tokenType, []string) {
419 mods := []string{"definition"}
420 for i := len(e.stack) - 1; i >= 0; i-- {
422 switch y := s.(type) {
423 case *ast.AssignStmt, *ast.RangeStmt:
425 return "", nil // not really a variable
427 return "variable", mods
429 if y.Tok == token.CONST {
430 mods = append(mods, "readonly")
432 return tokVariable, mods
434 // If x is immediately under a FuncDecl, it is a function or method
435 if i == len(e.stack)-2 {
437 return tokMember, mods
439 return tokFunction, mods
441 // if x < ... < FieldList < FuncDecl, this is the receiver, a variable
442 if _, ok := e.stack[i+1].(*ast.FieldList); ok {
443 return tokVariable, nil
445 // if x < ... < FieldList < FuncType < FuncDecl, this is a param
446 return tokParameter, mods
447 case *ast.InterfaceType:
448 return tokMember, mods
453 // panic after extensive testing
454 msg := fmt.Sprintf("failed to find the decl for %s", e.pgf.Tok.PositionFor(x.Pos(), false))
456 return "", []string{""}
459 // findKeyword finds a keyword rather than guessing its location
460 func (e *encoded) findKeyword(keyword string, start, end token.Pos) token.Pos {
461 offset := int(start) - e.pgf.Tok.Base()
462 last := int(end) - e.pgf.Tok.Base()
464 idx := bytes.Index(buf[offset:last], []byte(keyword))
466 return start + token.Pos(idx)
469 e.unexpected(fmt.Sprintf("not found:%s %v", keyword, e.fset.PositionFor(start, false)))
473 func (e *encoded) init() error {
474 e.start = token.Pos(e.pgf.Tok.Base())
475 e.end = e.start + token.Pos(e.pgf.Tok.Size())
479 span, err := e.pgf.Mapper.RangeSpan(*e.rng)
481 return errors.Errorf("range span error for %s", e.pgf.File.Name)
483 e.end = e.start + token.Pos(span.End().Offset())
484 e.start += token.Pos(span.Start().Offset())
488 func (e *encoded) Data() ([]uint32, error) {
489 // binary operators, at least, will be out of order
490 sort.Slice(e.items, func(i, j int) bool {
491 if e.items[i].line != e.items[j].line {
492 return e.items[i].line < e.items[j].line
494 return e.items[i].start < e.items[j].start
496 typeMap, modMap := e.maps()
497 // each semantic token needs five values
498 // (see Integer Encoding for Tokens in the LSP spec)
499 x := make([]uint32, 5*len(e.items))
500 for i := 0; i < len(e.items); i++ {
503 x[0] = e.items[0].line
505 x[j] = e.items[i].line - e.items[i-1].line
507 x[j+1] = e.items[i].start
508 if i > 0 && e.items[i].line == e.items[i-1].line {
509 x[j+1] = e.items[i].start - e.items[i-1].start
511 x[j+2] = e.items[i].len
512 x[j+3] = uint32(typeMap[e.items[i].typeStr])
514 for _, s := range e.items[i].mods {
517 x[j+4] = uint32(mask)
522 func (e *encoded) importSpec(d *ast.ImportSpec) {
523 // a local package name or the last component of the Path
525 nm := d.Name.String()
526 // import . x => x is not a namespace
527 // import _ x => x is a namespace
528 if nm != "_" && nm != "." {
529 e.token(d.Name.Pos(), len(nm), tokNamespace, nil)
535 // and fall through for _
537 nm := d.Path.Value[1 : len(d.Path.Value)-1] // trailing "
538 v := strings.LastIndex(nm, "/")
542 start := d.Path.End() - token.Pos(1+len(nm))
543 e.token(start, len(nm), tokNamespace, nil)
546 // panic on unexpected state
547 func (e *encoded) unexpected(msg string) {
549 log.Print(e.strStack())
553 // SemType returns a string equivalent of the type, for gopls semtok
554 func SemType(n int) string {
555 tokTypes := SemanticTypes()
556 tokMods := SemanticModifiers()
557 if n >= 0 && n < len(tokTypes) {
560 return fmt.Sprintf("?%d[%d,%d]?", n, len(tokTypes), len(tokMods))
563 // SemMods returns the []string equivalent of the mods, for gopls semtok.
564 func SemMods(n int) []string {
565 tokMods := SemanticModifiers()
567 for i := 0; i < len(tokMods); i++ {
568 if (n & (1 << uint(i))) != 0 {
569 mods = append(mods, tokMods[i])
575 func (e *encoded) maps() (map[tokenType]int, map[string]int) {
576 tmap := make(map[tokenType]int)
577 mmap := make(map[string]int)
578 for i, t := range e.tokTypes {
579 tmap[tokenType(t)] = i
581 for i, m := range e.tokMods {
582 mmap[m] = 1 << uint(i) // go 1.12 compatibility
587 // SemanticTypes to use in case there is no client, as in the command line, or tests
588 func SemanticTypes() []string {
589 return semanticTypes[:]
592 // SemanticModifiers to use in case there is no client.
593 func SemanticModifiers() []string {
594 return semanticModifiers[:]
598 semanticTypes = [...]string{
599 "namespace", "type", "class", "enum", "interface",
600 "struct", "typeParameter", "parameter", "variable", "property", "enumMember",
601 "event", "function", "member", "macro", "keyword", "modifier", "comment",
602 "string", "number", "regexp", "operator"}
603 semanticModifiers = [...]string{
604 "declaration", "definition", "readonly", "static",
605 "deprecated", "abstract", "async", "modification", "documentation", "defaultLibrary"}