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

     1  package langserver
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  
     7  	"github.com/sourcegraph/jsonrpc2"
     8  
     9  	"github.com/thought-machine/please/tools/build_langserver/lsp"
    10  )
    11  
    12  const referenceMethod = "textDocument/references"
    13  
    14  func (h *LsHandler) handleReferences(ctx context.Context, req *jsonrpc2.Request) (result interface{}, err error) {
    15  	if req.Params == nil {
    16  		return nil, nil
    17  	}
    18  
    19  	var params lsp.ReferenceParams
    20  	if err := json.Unmarshal(*req.Params, &params); err != nil {
    21  		return nil, err
    22  	}
    23  
    24  	documentURI, err := getURIAndHandleErrors(params.TextDocument.URI, referenceMethod)
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  
    29  	h.mu.Lock()
    30  	defer h.mu.Unlock()
    31  
    32  	refs, err := h.getReferences(ctx, documentURI, params.Position)
    33  	if err != nil && len(refs) == 0 {
    34  		log.Warning("error occurred when trying to get references: %s", err)
    35  		return nil, nil
    36  	}
    37  
    38  	return refs, nil
    39  }
    40  
    41  func (h *LsHandler) getReferences(ctx context.Context, uri lsp.DocumentURI, pos lsp.Position) ([]lsp.Location, error) {
    42  	def, err := h.analyzer.BuildDefsFromPos(ctx, uri, pos)
    43  	if def == nil || err != nil || def.Pos.Line != pos.Line {
    44  		return nil, err
    45  	}
    46  
    47  	revDeps, err := h.analyzer.RevDepsFromBuildDef(def, uri)
    48  	if err != nil {
    49  		log.Info("error occurred computing the reverse dependency of %")
    50  		return nil, err
    51  	}
    52  
    53  	var locs []lsp.Location
    54  	for _, label := range revDeps {
    55  		buildLabel, err := h.analyzer.BuildLabelFromCoreBuildLabel(ctx, label)
    56  		if err != nil {
    57  			// In the case of error, we still return the current available locs
    58  			return locs, nil
    59  		}
    60  
    61  		loc := lsp.Location{
    62  			URI: lsp.DocumentURI("file://" + buildLabel.Path),
    63  			Range: lsp.Range{
    64  				Start: buildLabel.BuildDef.Pos,
    65  				End:   buildLabel.BuildDef.EndPos,
    66  			},
    67  		}
    68  		locs = append(locs, loc)
    69  	}
    70  
    71  	return locs, nil
    72  }