github.com/tiagovtristao/plz@v13.4.0+incompatible/tools/build_langserver/langserver/definition.go (about)

     1  package langserver
     2  
     3  import (
     4  	"context"
     5  	"github.com/thought-machine/please/tools/build_langserver/lsp"
     6  
     7  	"github.com/sourcegraph/jsonrpc2"
     8  )
     9  
    10  const definitionMethod = "textDocument/definition"
    11  
    12  func (h *LsHandler) handleDefinition(ctx context.Context, req *jsonrpc2.Request) (result interface{}, err error) {
    13  	params, err := h.getParamFromTDPositionReq(req, definitionMethod)
    14  	if err != nil {
    15  		return nil, err
    16  	}
    17  	documentURI := params.TextDocument.URI
    18  
    19  	h.mu.Lock()
    20  	defer h.mu.Unlock()
    21  	definitionLocations := h.getDefinitionLocation(ctx, documentURI, params.Position)
    22  	log.Info("definition locations: %s", definitionLocations)
    23  
    24  	return definitionLocations, nil
    25  }
    26  
    27  func (h *LsHandler) getDefinitionLocation(ctx context.Context, uri lsp.DocumentURI, pos lsp.Position) []lsp.Location {
    28  	fileContent := h.workspace.documents[uri].textInEdit
    29  	lineContent := h.ensureLineContent(uri, pos)
    30  
    31  	log.Info("goto definition lineContent: %s", lineContent)
    32  
    33  	if isEmpty(lineContent, pos) {
    34  		return nil
    35  	}
    36  
    37  	stmts := h.analyzer.AspStatementFromContent(JoinLines(fileContent, true))
    38  
    39  	buildLabel := h.analyzer.BuildLabelFromAST(ctx, stmts, uri, pos)
    40  
    41  	if buildLabel != nil {
    42  		uri, err := EnsureURL(lsp.DocumentURI(buildLabel.Path), "file")
    43  		if err != nil {
    44  			log.Error("fail to get file: %s", buildLabel.Path)
    45  			return nil
    46  		}
    47  
    48  		if buildLabel.BuildDef != nil {
    49  			loc := lsp.Location{
    50  				URI: uri,
    51  				Range: lsp.Range{
    52  					Start: buildLabel.BuildDef.Pos,
    53  					End:   buildLabel.BuildDef.EndPos,
    54  				},
    55  			}
    56  			return []lsp.Location{loc}
    57  		}
    58  	}
    59  
    60  	return nil
    61  }