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 var lastPosition token.Position
131 func (e *encoded) token(start token.Pos, leng int, typ tokenType, mods []string) {
133 e.unexpected("token at token.NoPos")
135 if start >= e.end || start+token.Pos(leng) <= e.start {
138 // want a line and column from start (in LSP coordinates)
139 // [//line directives should be ignored]
140 rng := source.NewMappedRange(e.fset, e.pgf.Mapper, start, start+token.Pos(leng))
141 lspRange, err := rng.Range()
143 // possibly a //line directive. TODO(pjw): fix this somehow
144 // "column mapper is for file...instead of..."
145 // "line is beyond end of file..."
146 // see line 116 of internal/span/token.go which uses Position not PositionFor
147 event.Error(e.ctx, "failed to convert to range", err)
150 if lspRange.End.Line != lspRange.Start.Line {
151 // abrupt end of file, without \n. TODO(pjw): fix?
152 pos := e.fset.PositionFor(start, false)
153 msg := fmt.Sprintf("token at %s:%d.%d overflows", pos.Filename, pos.Line, pos.Column)
154 event.Log(e.ctx, msg)
157 // token is all on one line
158 length := lspRange.End.Character - lspRange.Start.Character
159 e.add(lspRange.Start.Line, lspRange.Start.Character, length, typ, mods)
162 func (e *encoded) add(line, start float64, len float64, tok tokenType, mod []string) {
163 x := semItem{line, start, len, tok, mod}
164 e.items = append(e.items, x)
167 // semItem represents a token found walking the parse tree
168 type semItem struct {
175 type encoded struct {
176 // the generated data
180 tokTypes, tokMods []string
181 pgf *source.ParsedGoFile
185 // allowed starting and ending token.Pos, set by init
186 // used to avoid looking at declarations not in range
188 // path from the root of the parse tree, used for debugging
192 // convert the stack to a string, for debugging
193 func (e *encoded) strStack() string {
195 for _, s := range e.stack {
196 msg = append(msg, fmt.Sprintf("%T", s)[5:])
198 if len(e.stack) > 0 {
199 loc := e.stack[len(e.stack)-1].Pos()
200 add := e.pgf.Tok.PositionFor(loc, false)
201 msg = append(msg, fmt.Sprintf("(%d:%d)", add.Line, add.Column))
203 msg = append(msg, "]")
204 return strings.Join(msg, " ")
207 func (e *encoded) inspector(n ast.Node) bool {
209 e.stack = e.stack[:len(e.stack)-1]
215 e.stack = append(e.stack, n)
216 switch x := n.(type) {
218 case *ast.AssignStmt:
219 e.token(x.TokPos, len(x.Tok.String()), tokOperator, nil)
221 // if it extends across a line, skip it
222 // better would be to mark each line as string TODO(pjw)
223 if strings.Contains(x.Value, "\n") {
228 if x.Kind == token.STRING {
230 if _, ok := e.stack[len(e.stack)-2].(*ast.Field); ok {
231 // struct tags (this is probably pointless, as the
232 // TextMate grammar will treat all the other comments the same)
236 e.token(x.Pos(), ln, what, nil)
237 case *ast.BinaryExpr:
238 e.token(x.OpPos, len(x.Op.String()), tokOperator, nil)
240 case *ast.BranchStmt:
241 e.token(x.TokPos, len(x.Tok.String()), tokKeyword, nil)
242 // There's no semantic encoding for labels
244 if x.Ellipsis != token.NoPos {
245 e.token(x.Ellipsis, len("..."), tokOperator, nil)
247 case *ast.CaseClause:
252 e.token(x.Case, len(iam), tokKeyword, nil)
254 // chan | chan <- | <- chan
255 if x.Arrow == token.NoPos || x.Arrow != x.Begin {
256 e.token(x.Begin, len("chan"), tokKeyword, nil)
259 pos := e.findKeyword("chan", x.Begin+2, x.Value.Pos())
260 e.token(pos, len("chan"), tokKeyword, nil)
261 case *ast.CommClause:
266 e.token(x.Case, iam, tokKeyword, nil)
267 case *ast.CompositeLit:
270 e.token(x.Defer, len("defer"), tokKeyword, nil)
272 e.token(x.Ellipsis, len("..."), tokOperator, nil)
278 e.token(x.For, len("for"), tokKeyword, nil)
282 if x.Func != token.NoPos {
283 e.token(x.Func, len("func"), tokKeyword, nil)
286 e.token(x.TokPos, len(x.Tok.String()), tokKeyword, nil)
288 e.token(x.Go, len("go"), tokKeyword, nil)
292 e.token(x.If, len("if"), tokKeyword, nil)
294 // x.Body.End() or x.Body.End()+1, not that it matters
295 pos := e.findKeyword("else", x.Body.End(), x.Else.Pos())
296 e.token(pos, len("else"), tokKeyword, nil)
298 case *ast.ImportSpec:
302 case *ast.IncDecStmt:
303 e.token(x.TokPos, len(x.Tok.String()), tokOperator, nil)
305 case *ast.InterfaceType:
306 e.token(x.Interface, len("interface"), tokKeyword, nil)
307 case *ast.KeyValueExpr:
308 case *ast.LabeledStmt:
310 e.token(x.Map, len("map"), tokKeyword, nil)
313 e.token(x.For, len("for"), tokKeyword, nil)
314 // x.TokPos == token.NoPos is legal (for range foo {})
316 if offset == token.NoPos {
319 pos := e.findKeyword("range", offset, x.X.Pos())
320 e.token(pos, len("range"), tokKeyword, nil)
321 case *ast.ReturnStmt:
322 e.token(x.Return, len("return"), tokKeyword, nil)
323 case *ast.SelectStmt:
324 e.token(x.Select, len("select"), tokKeyword, nil)
325 case *ast.SelectorExpr:
327 e.token(x.Arrow, len("<-"), tokOperator, nil)
330 e.token(x.Star, len("*"), tokOperator, nil)
331 case *ast.StructType:
332 e.token(x.Struct, len("struct"), tokKeyword, nil)
333 case *ast.SwitchStmt:
334 e.token(x.Switch, len("switch"), tokKeyword, nil)
335 case *ast.TypeAssertExpr:
337 pos := e.findKeyword("type", x.Lparen, x.Rparen)
338 e.token(pos, len("type"), tokKeyword, nil)
341 case *ast.TypeSwitchStmt:
342 e.token(x.Switch, len("switch"), tokKeyword, nil)
344 e.token(x.OpPos, len(x.Op.String()), tokOperator, nil)
346 // things we won't see
347 case *ast.BadDecl, *ast.BadExpr, *ast.BadStmt,
348 *ast.File, *ast.Package:
349 log.Printf("implement %T %s", x, e.pgf.Tok.PositionFor(x.Pos(), false))
350 // things we knowingly ignore
351 case *ast.Comment, *ast.CommentGroup:
354 default: // just to be super safe.
355 e.unexpected(fmt.Sprintf("failed to implement %T", x))
359 func (e *encoded) ident(x *ast.Ident) {
362 what, mods := e.definitionFor(x)
364 e.token(x.Pos(), len(x.String()), what, mods)
369 switch y := use.(type) {
371 e.token(x.NamePos, len(x.Name), tokVariable, []string{"definition"})
373 e.token(x.NamePos, len(x.Name), tokFunction, []string{"defaultLibrary"})
375 mods := []string{"readonly"}
377 if ttx, ok := tt.(*types.Basic); ok {
378 switch bi := ttx.Info(); {
379 case bi&types.IsNumeric != 0:
381 if x.String() == "iota" {
385 e.token(x.Pos(), len(x.String()), me, mods)
386 case bi&types.IsString != 0:
387 e.token(x.Pos(), len(x.String()), tokString, mods)
388 case bi&types.IsBoolean != 0:
389 e.token(x.Pos(), len(x.Name), tokKeyword, nil)
391 e.token(x.Pos(), len(x.String()), tokVariable, mods)
393 msg := fmt.Sprintf("unexpected %x at %s", bi, e.pgf.Tok.PositionFor(x.Pos(), false))
398 if ttx, ok := tt.(*types.Named); ok {
399 if x.String() == "iota" {
400 e.unexpected(fmt.Sprintf("iota:%T", ttx))
402 if _, ok := ttx.Underlying().(*types.Basic); ok {
403 e.token(x.Pos(), len(x.String()), tokVariable, mods)
406 e.unexpected(fmt.Sprintf("%q/%T", x.String(), tt))
408 // can this happen? Don't think so
409 e.unexpected(fmt.Sprintf("%s %T %#v", x.String(), tt, tt))
411 e.token(x.Pos(), len(x.Name), tokFunction, nil)
413 // nothing to map it to
415 // nil is a predeclared identifier
416 e.token(x.Pos(), len("nil"), tokKeyword, []string{"readonly"})
418 e.token(x.Pos(), len(x.Name), tokNamespace, nil)
419 case *types.TypeName:
420 e.token(x.Pos(), len(x.String()), tokType, nil)
422 e.token(x.Pos(), len(x.Name), tokVariable, nil)
424 // replace with panic after extensive testing
426 msg := fmt.Sprintf("%#v/%#v %#v %#v", x, x.Obj, e.ti.Defs[x], e.ti.Uses[x])
429 if use.Type() != nil {
430 e.unexpected(fmt.Sprintf("%s %T/%T,%#v", x.String(), use, use.Type(), use))
432 e.unexpected(fmt.Sprintf("%s %T", x.String(), use))
437 func (e *encoded) definitionFor(x *ast.Ident) (tokenType, []string) {
438 mods := []string{"definition"}
439 for i := len(e.stack) - 1; i >= 0; i-- {
441 switch y := s.(type) {
442 case *ast.AssignStmt, *ast.RangeStmt:
444 return "", nil // not really a variable
446 return "variable", mods
448 if y.Tok == token.CONST {
449 mods = append(mods, "readonly")
451 return tokVariable, mods
453 // If x is immediately under a FuncDecl, it is a function or method
454 if i == len(e.stack)-2 {
456 return tokMember, mods
458 return tokFunction, mods
460 // if x < ... < FieldList < FuncDecl, this is the receiver, a variable
461 if _, ok := e.stack[i+1].(*ast.FieldList); ok {
462 return tokVariable, nil
464 // if x < ... < FieldList < FuncType < FuncDecl, this is a param
465 return tokParameter, mods
466 case *ast.InterfaceType:
467 return tokMember, mods
472 // panic after extensive testing
473 msg := fmt.Sprintf("failed to find the decl for %s", e.pgf.Tok.PositionFor(x.Pos(), false))
475 return "", []string{""}
478 // findKeyword finds a keyword rather than guessing its location
479 func (e *encoded) findKeyword(keyword string, start, end token.Pos) token.Pos {
480 offset := int(start) - e.pgf.Tok.Base()
481 last := int(end) - e.pgf.Tok.Base()
483 idx := bytes.Index(buf[offset:last], []byte(keyword))
485 return start + token.Pos(idx)
488 e.unexpected(fmt.Sprintf("not found:%s %v", keyword, e.fset.PositionFor(start, false)))
492 func (e *encoded) init() error {
493 e.start = token.Pos(e.pgf.Tok.Base())
494 e.end = e.start + token.Pos(e.pgf.Tok.Size())
498 span, err := e.pgf.Mapper.RangeSpan(*e.rng)
500 return errors.Errorf("range span error for %s", e.pgf.File.Name)
502 e.end = e.start + token.Pos(span.End().Offset())
503 e.start += token.Pos(span.Start().Offset())
507 func (e *encoded) Data() ([]float64, error) {
508 // binary operators, at least, will be out of order
509 sort.Slice(e.items, func(i, j int) bool {
510 if e.items[i].line != e.items[j].line {
511 return e.items[i].line < e.items[j].line
513 return e.items[i].start < e.items[j].start
515 typeMap, modMap := e.maps()
516 // each semantic token needs five values
517 // (see Integer Encoding for Tokens in the LSP spec)
518 x := make([]float64, 5*len(e.items))
519 for i := 0; i < len(e.items); i++ {
522 x[0] = e.items[0].line
524 x[j] = e.items[i].line - e.items[i-1].line
526 x[j+1] = e.items[i].start
527 if i > 0 && e.items[i].line == e.items[i-1].line {
528 x[j+1] = e.items[i].start - e.items[i-1].start
530 x[j+2] = e.items[i].len
531 x[j+3] = float64(typeMap[e.items[i].typeStr])
533 for _, s := range e.items[i].mods {
536 x[j+4] = float64(mask)
541 func (e *encoded) importSpec(d *ast.ImportSpec) {
542 // a local package name or the last component of the Path
544 nm := d.Name.String()
545 // import . x => x is not a namespace
546 // import _ x => x is a namespace
547 if nm != "_" && nm != "." {
548 e.token(d.Name.Pos(), len(nm), tokNamespace, nil)
554 // and fall through for _
556 nm := d.Path.Value[1 : len(d.Path.Value)-1] // trailing "
557 v := strings.LastIndex(nm, "/")
561 start := d.Path.End() - token.Pos(1+len(nm))
562 e.token(start, len(nm), tokNamespace, nil)
565 // panic on unexpected state
566 func (e *encoded) unexpected(msg string) {
568 log.Print(e.strStack())
572 // SemType returns a string equivalent of the type, for gopls semtok
573 func SemType(n int) string {
574 tokTypes := SemanticTypes()
575 tokMods := SemanticModifiers()
576 if n >= 0 && n < len(tokTypes) {
579 return fmt.Sprintf("?%d[%d,%d]?", n, len(tokTypes), len(tokMods))
582 // SemMods returns the []string equivalent of the mods, for gopls semtok.
583 func SemMods(n int) []string {
584 tokMods := SemanticModifiers()
586 for i := 0; i < len(tokMods); i++ {
587 if (n & (1 << uint(i))) != 0 {
588 mods = append(mods, tokMods[i])
594 func (e *encoded) maps() (map[tokenType]int, map[string]int) {
595 tmap := make(map[tokenType]int)
596 mmap := make(map[string]int)
597 for i, t := range e.tokTypes {
598 tmap[tokenType(t)] = i
600 for i, m := range e.tokMods {
601 mmap[m] = 1 << uint(i) // go 1.12 compatibility
606 // SemanticTypes to use in case there is no client, as in the command line, or tests
607 func SemanticTypes() []string {
608 return semanticTypes[:]
611 // SemanticModifiers to use in case there is no client.
612 func SemanticModifiers() []string {
613 return semanticModifiers[:]
617 semanticTypes = [...]string{
618 "namespace", "type", "class", "enum", "interface",
619 "struct", "typeParameter", "parameter", "variable", "property", "enumMember",
620 "event", "function", "member", "macro", "keyword", "modifier", "comment",
621 "string", "number", "regexp", "operator"}
622 semanticModifiers = [...]string{
623 "declaration", "definition", "readonly", "static",
624 "deprecated", "abstract", "async", "modification", "documentation", "defaultLibrary"}