golang.org/x/tools/gopls@v0.15.3/internal/cache/parse.go (about)

     1  // Copyright 2019 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 cache
     6  
     7  import (
     8  	"context"
     9  	"fmt"
    10  	"go/parser"
    11  	"go/token"
    12  	"path/filepath"
    13  
    14  	"golang.org/x/tools/gopls/internal/file"
    15  	"golang.org/x/tools/gopls/internal/cache/parsego"
    16  )
    17  
    18  // ParseGo parses the file whose contents are provided by fh.
    19  // The resulting tree may have been fixed up.
    20  // If the file is not available, returns nil and an error.
    21  func (s *Snapshot) ParseGo(ctx context.Context, fh file.Handle, mode parser.Mode) (*ParsedGoFile, error) {
    22  	pgfs, err := s.view.parseCache.parseFiles(ctx, token.NewFileSet(), mode, false, fh)
    23  	if err != nil {
    24  		return nil, err
    25  	}
    26  	return pgfs[0], nil
    27  }
    28  
    29  // parseGoImpl parses the Go source file whose content is provided by fh.
    30  func parseGoImpl(ctx context.Context, fset *token.FileSet, fh file.Handle, mode parser.Mode, purgeFuncBodies bool) (*ParsedGoFile, error) {
    31  	ext := filepath.Ext(fh.URI().Path())
    32  	if ext != ".go" && ext != "" { // files generated by cgo have no extension
    33  		return nil, fmt.Errorf("cannot parse non-Go file %s", fh.URI())
    34  	}
    35  	content, err := fh.Content()
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  	// Check for context cancellation before actually doing the parse.
    40  	if ctx.Err() != nil {
    41  		return nil, ctx.Err()
    42  	}
    43  	pgf, _ := parsego.Parse(ctx, fset, fh.URI(), content, mode, purgeFuncBodies)
    44  	return pgf, nil
    45  }