golang.org/x/tools/gopls@v0.15.3/internal/server/semantic.go (about)

     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.
     4  
     5  package server
     6  
     7  import (
     8  	"context"
     9  	"fmt"
    10  
    11  	"golang.org/x/tools/gopls/internal/file"
    12  	"golang.org/x/tools/gopls/internal/golang"
    13  	"golang.org/x/tools/gopls/internal/protocol"
    14  	"golang.org/x/tools/gopls/internal/template"
    15  	"golang.org/x/tools/internal/event"
    16  	"golang.org/x/tools/internal/event/tag"
    17  )
    18  
    19  func (s *server) SemanticTokensFull(ctx context.Context, params *protocol.SemanticTokensParams) (*protocol.SemanticTokens, error) {
    20  	return s.semanticTokens(ctx, params.TextDocument, nil)
    21  }
    22  
    23  func (s *server) SemanticTokensRange(ctx context.Context, params *protocol.SemanticTokensRangeParams) (*protocol.SemanticTokens, error) {
    24  	return s.semanticTokens(ctx, params.TextDocument, &params.Range)
    25  }
    26  
    27  func (s *server) semanticTokens(ctx context.Context, td protocol.TextDocumentIdentifier, rng *protocol.Range) (*protocol.SemanticTokens, error) {
    28  	ctx, done := event.Start(ctx, "lsp.Server.semanticTokens", tag.URI.Of(td.URI))
    29  	defer done()
    30  
    31  	fh, snapshot, release, err := s.fileOf(ctx, td.URI)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  	defer release()
    36  	if !snapshot.Options().SemanticTokens {
    37  		// return an error, so if the option changes
    38  		// the client won't remember the wrong answer
    39  		return nil, fmt.Errorf("semantictokens are disabled")
    40  	}
    41  
    42  	switch snapshot.FileKind(fh) {
    43  	case file.Tmpl:
    44  		return template.SemanticTokens(ctx, snapshot, fh.URI())
    45  
    46  	case file.Go:
    47  		return golang.SemanticTokens(ctx, snapshot, fh, rng)
    48  
    49  	default:
    50  		// TODO(adonovan): should return an error!
    51  		return nil, nil // empty result
    52  	}
    53  }