...
Run Format

Source file src/go/build/build.go

Documentation: go/build

     1  // Copyright 2011 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 build
     6  
     7  import (
     8  	"bytes"
     9  	"errors"
    10  	"fmt"
    11  	"go/ast"
    12  	"go/doc"
    13  	"go/parser"
    14  	"go/token"
    15  	"io"
    16  	"io/ioutil"
    17  	"log"
    18  	"os"
    19  	"os/exec"
    20  	pathpkg "path"
    21  	"path/filepath"
    22  	"runtime"
    23  	"sort"
    24  	"strconv"
    25  	"strings"
    26  	"unicode"
    27  	"unicode/utf8"
    28  )
    29  
    30  // A Context specifies the supporting context for a build.
    31  type Context struct {
    32  	GOARCH      string // target architecture
    33  	GOOS        string // target operating system
    34  	GOROOT      string // Go root
    35  	GOPATH      string // Go path
    36  	CgoEnabled  bool   // whether cgo can be used
    37  	UseAllFiles bool   // use files regardless of +build lines, file names
    38  	Compiler    string // compiler to assume when computing target paths
    39  
    40  	// The build and release tags specify build constraints
    41  	// that should be considered satisfied when processing +build lines.
    42  	// Clients creating a new context may customize BuildTags, which
    43  	// defaults to empty, but it is usually an error to customize ReleaseTags,
    44  	// which defaults to the list of Go releases the current release is compatible with.
    45  	// In addition to the BuildTags and ReleaseTags, build constraints
    46  	// consider the values of GOARCH and GOOS as satisfied tags.
    47  	BuildTags   []string
    48  	ReleaseTags []string
    49  
    50  	// The install suffix specifies a suffix to use in the name of the installation
    51  	// directory. By default it is empty, but custom builds that need to keep
    52  	// their outputs separate can set InstallSuffix to do so. For example, when
    53  	// using the race detector, the go command uses InstallSuffix = "race", so
    54  	// that on a Linux/386 system, packages are written to a directory named
    55  	// "linux_386_race" instead of the usual "linux_386".
    56  	InstallSuffix string
    57  
    58  	// By default, Import uses the operating system's file system calls
    59  	// to read directories and files. To read from other sources,
    60  	// callers can set the following functions. They all have default
    61  	// behaviors that use the local file system, so clients need only set
    62  	// the functions whose behaviors they wish to change.
    63  
    64  	// JoinPath joins the sequence of path fragments into a single path.
    65  	// If JoinPath is nil, Import uses filepath.Join.
    66  	JoinPath func(elem ...string) string
    67  
    68  	// SplitPathList splits the path list into a slice of individual paths.
    69  	// If SplitPathList is nil, Import uses filepath.SplitList.
    70  	SplitPathList func(list string) []string
    71  
    72  	// IsAbsPath reports whether path is an absolute path.
    73  	// If IsAbsPath is nil, Import uses filepath.IsAbs.
    74  	IsAbsPath func(path string) bool
    75  
    76  	// IsDir reports whether the path names a directory.
    77  	// If IsDir is nil, Import calls os.Stat and uses the result's IsDir method.
    78  	IsDir func(path string) bool
    79  
    80  	// HasSubdir reports whether dir is lexically a subdirectory of
    81  	// root, perhaps multiple levels below. It does not try to check
    82  	// whether dir exists.
    83  	// If so, HasSubdir sets rel to a slash-separated path that
    84  	// can be joined to root to produce a path equivalent to dir.
    85  	// If HasSubdir is nil, Import uses an implementation built on
    86  	// filepath.EvalSymlinks.
    87  	HasSubdir func(root, dir string) (rel string, ok bool)
    88  
    89  	// ReadDir returns a slice of os.FileInfo, sorted by Name,
    90  	// describing the content of the named directory.
    91  	// If ReadDir is nil, Import uses ioutil.ReadDir.
    92  	ReadDir func(dir string) ([]os.FileInfo, error)
    93  
    94  	// OpenFile opens a file (not a directory) for reading.
    95  	// If OpenFile is nil, Import uses os.Open.
    96  	OpenFile func(path string) (io.ReadCloser, error)
    97  }
    98  
    99  // joinPath calls ctxt.JoinPath (if not nil) or else filepath.Join.
   100  func (ctxt *Context) joinPath(elem ...string) string {
   101  	if f := ctxt.JoinPath; f != nil {
   102  		return f(elem...)
   103  	}
   104  	return filepath.Join(elem...)
   105  }
   106  
   107  // splitPathList calls ctxt.SplitPathList (if not nil) or else filepath.SplitList.
   108  func (ctxt *Context) splitPathList(s string) []string {
   109  	if f := ctxt.SplitPathList; f != nil {
   110  		return f(s)
   111  	}
   112  	return filepath.SplitList(s)
   113  }
   114  
   115  // isAbsPath calls ctxt.IsAbsPath (if not nil) or else filepath.IsAbs.
   116  func (ctxt *Context) isAbsPath(path string) bool {
   117  	if f := ctxt.IsAbsPath; f != nil {
   118  		return f(path)
   119  	}
   120  	return filepath.IsAbs(path)
   121  }
   122  
   123  // isDir calls ctxt.IsDir (if not nil) or else uses os.Stat.
   124  func (ctxt *Context) isDir(path string) bool {
   125  	if f := ctxt.IsDir; f != nil {
   126  		return f(path)
   127  	}
   128  	fi, err := os.Stat(path)
   129  	return err == nil && fi.IsDir()
   130  }
   131  
   132  // hasSubdir calls ctxt.HasSubdir (if not nil) or else uses
   133  // the local file system to answer the question.
   134  func (ctxt *Context) hasSubdir(root, dir string) (rel string, ok bool) {
   135  	if f := ctxt.HasSubdir; f != nil {
   136  		return f(root, dir)
   137  	}
   138  
   139  	// Try using paths we received.
   140  	if rel, ok = hasSubdir(root, dir); ok {
   141  		return
   142  	}
   143  
   144  	// Try expanding symlinks and comparing
   145  	// expanded against unexpanded and
   146  	// expanded against expanded.
   147  	rootSym, _ := filepath.EvalSymlinks(root)
   148  	dirSym, _ := filepath.EvalSymlinks(dir)
   149  
   150  	if rel, ok = hasSubdir(rootSym, dir); ok {
   151  		return
   152  	}
   153  	if rel, ok = hasSubdir(root, dirSym); ok {
   154  		return
   155  	}
   156  	return hasSubdir(rootSym, dirSym)
   157  }
   158  
   159  // hasSubdir reports if dir is within root by performing lexical analysis only.
   160  func hasSubdir(root, dir string) (rel string, ok bool) {
   161  	const sep = string(filepath.Separator)
   162  	root = filepath.Clean(root)
   163  	if !strings.HasSuffix(root, sep) {
   164  		root += sep
   165  	}
   166  	dir = filepath.Clean(dir)
   167  	if !strings.HasPrefix(dir, root) {
   168  		return "", false
   169  	}
   170  	return filepath.ToSlash(dir[len(root):]), true
   171  }
   172  
   173  // readDir calls ctxt.ReadDir (if not nil) or else ioutil.ReadDir.
   174  func (ctxt *Context) readDir(path string) ([]os.FileInfo, error) {
   175  	if f := ctxt.ReadDir; f != nil {
   176  		return f(path)
   177  	}
   178  	return ioutil.ReadDir(path)
   179  }
   180  
   181  // openFile calls ctxt.OpenFile (if not nil) or else os.Open.
   182  func (ctxt *Context) openFile(path string) (io.ReadCloser, error) {
   183  	if fn := ctxt.OpenFile; fn != nil {
   184  		return fn(path)
   185  	}
   186  
   187  	f, err := os.Open(path)
   188  	if err != nil {
   189  		return nil, err // nil interface
   190  	}
   191  	return f, nil
   192  }
   193  
   194  // isFile determines whether path is a file by trying to open it.
   195  // It reuses openFile instead of adding another function to the
   196  // list in Context.
   197  func (ctxt *Context) isFile(path string) bool {
   198  	f, err := ctxt.openFile(path)
   199  	if err != nil {
   200  		return false
   201  	}
   202  	f.Close()
   203  	return true
   204  }
   205  
   206  // gopath returns the list of Go path directories.
   207  func (ctxt *Context) gopath() []string {
   208  	var all []string
   209  	for _, p := range ctxt.splitPathList(ctxt.GOPATH) {
   210  		if p == "" || p == ctxt.GOROOT {
   211  			// Empty paths are uninteresting.
   212  			// If the path is the GOROOT, ignore it.
   213  			// People sometimes set GOPATH=$GOROOT.
   214  			// Do not get confused by this common mistake.
   215  			continue
   216  		}
   217  		if strings.HasPrefix(p, "~") {
   218  			// Path segments starting with ~ on Unix are almost always
   219  			// users who have incorrectly quoted ~ while setting GOPATH,
   220  			// preventing it from expanding to $HOME.
   221  			// The situation is made more confusing by the fact that
   222  			// bash allows quoted ~ in $PATH (most shells do not).
   223  			// Do not get confused by this, and do not try to use the path.
   224  			// It does not exist, and printing errors about it confuses
   225  			// those users even more, because they think "sure ~ exists!".
   226  			// The go command diagnoses this situation and prints a
   227  			// useful error.
   228  			// On Windows, ~ is used in short names, such as c:\progra~1
   229  			// for c:\program files.
   230  			continue
   231  		}
   232  		all = append(all, p)
   233  	}
   234  	return all
   235  }
   236  
   237  // SrcDirs returns a list of package source root directories.
   238  // It draws from the current Go root and Go path but omits directories
   239  // that do not exist.
   240  func (ctxt *Context) SrcDirs() []string {
   241  	var all []string
   242  	if ctxt.GOROOT != "" && ctxt.Compiler != "gccgo" {
   243  		dir := ctxt.joinPath(ctxt.GOROOT, "src")
   244  		if ctxt.isDir(dir) {
   245  			all = append(all, dir)
   246  		}
   247  	}
   248  	for _, p := range ctxt.gopath() {
   249  		dir := ctxt.joinPath(p, "src")
   250  		if ctxt.isDir(dir) {
   251  			all = append(all, dir)
   252  		}
   253  	}
   254  	return all
   255  }
   256  
   257  // Default is the default Context for builds.
   258  // It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variables
   259  // if set, or else the compiled code's GOARCH, GOOS, and GOROOT.
   260  var Default Context = defaultContext()
   261  
   262  func defaultGOPATH() string {
   263  	env := "HOME"
   264  	if runtime.GOOS == "windows" {
   265  		env = "USERPROFILE"
   266  	} else if runtime.GOOS == "plan9" {
   267  		env = "home"
   268  	}
   269  	if home := os.Getenv(env); home != "" {
   270  		def := filepath.Join(home, "go")
   271  		if filepath.Clean(def) == filepath.Clean(runtime.GOROOT()) {
   272  			// Don't set the default GOPATH to GOROOT,
   273  			// as that will trigger warnings from the go tool.
   274  			return ""
   275  		}
   276  		return def
   277  	}
   278  	return ""
   279  }
   280  
   281  var defaultReleaseTags []string
   282  
   283  func defaultContext() Context {
   284  	var c Context
   285  
   286  	c.GOARCH = envOr("GOARCH", runtime.GOARCH)
   287  	c.GOOS = envOr("GOOS", runtime.GOOS)
   288  	c.GOROOT = pathpkg.Clean(runtime.GOROOT())
   289  	c.GOPATH = envOr("GOPATH", defaultGOPATH())
   290  	c.Compiler = runtime.Compiler
   291  
   292  	// Each major Go release in the Go 1.x series should add a tag here.
   293  	// Old tags should not be removed. That is, the go1.x tag is present
   294  	// in all releases >= Go 1.x. Code that requires Go 1.x or later should
   295  	// say "+build go1.x", and code that should only be built before Go 1.x
   296  	// (perhaps it is the stub to use in that case) should say "+build !go1.x".
   297  	// NOTE: If you add to this list, also update the doc comment in doc.go.
   298  	const version = 11 // go1.11
   299  	for i := 1; i <= version; i++ {
   300  		c.ReleaseTags = append(c.ReleaseTags, "go1."+strconv.Itoa(i))
   301  	}
   302  
   303  	defaultReleaseTags = append([]string{}, c.ReleaseTags...) // our own private copy
   304  
   305  	env := os.Getenv("CGO_ENABLED")
   306  	if env == "" {
   307  		env = defaultCGO_ENABLED
   308  	}
   309  	switch env {
   310  	case "1":
   311  		c.CgoEnabled = true
   312  	case "0":
   313  		c.CgoEnabled = false
   314  	default:
   315  		// cgo must be explicitly enabled for cross compilation builds
   316  		if runtime.GOARCH == c.GOARCH && runtime.GOOS == c.GOOS {
   317  			c.CgoEnabled = cgoEnabled[c.GOOS+"/"+c.GOARCH]
   318  			break
   319  		}
   320  		c.CgoEnabled = false
   321  	}
   322  
   323  	return c
   324  }
   325  
   326  func envOr(name, def string) string {
   327  	s := os.Getenv(name)
   328  	if s == "" {
   329  		return def
   330  	}
   331  	return s
   332  }
   333  
   334  // An ImportMode controls the behavior of the Import method.
   335  type ImportMode uint
   336  
   337  const (
   338  	// If FindOnly is set, Import stops after locating the directory
   339  	// that should contain the sources for a package. It does not
   340  	// read any files in the directory.
   341  	FindOnly ImportMode = 1 << iota
   342  
   343  	// If AllowBinary is set, Import can be satisfied by a compiled
   344  	// package object without corresponding sources.
   345  	//
   346  	// Deprecated:
   347  	// The supported way to create a compiled-only package is to
   348  	// write source code containing a //go:binary-only-package comment at
   349  	// the top of the file. Such a package will be recognized
   350  	// regardless of this flag setting (because it has source code)
   351  	// and will have BinaryOnly set to true in the returned Package.
   352  	AllowBinary
   353  
   354  	// If ImportComment is set, parse import comments on package statements.
   355  	// Import returns an error if it finds a comment it cannot understand
   356  	// or finds conflicting comments in multiple source files.
   357  	// See golang.org/s/go14customimport for more information.
   358  	ImportComment
   359  
   360  	// By default, Import searches vendor directories
   361  	// that apply in the given source directory before searching
   362  	// the GOROOT and GOPATH roots.
   363  	// If an Import finds and returns a package using a vendor
   364  	// directory, the resulting ImportPath is the complete path
   365  	// to the package, including the path elements leading up
   366  	// to and including "vendor".
   367  	// For example, if Import("y", "x/subdir", 0) finds
   368  	// "x/vendor/y", the returned package's ImportPath is "x/vendor/y",
   369  	// not plain "y".
   370  	// See golang.org/s/go15vendor for more information.
   371  	//
   372  	// Setting IgnoreVendor ignores vendor directories.
   373  	//
   374  	// In contrast to the package's ImportPath,
   375  	// the returned package's Imports, TestImports, and XTestImports
   376  	// are always the exact import paths from the source files:
   377  	// Import makes no attempt to resolve or check those paths.
   378  	IgnoreVendor
   379  )
   380  
   381  // A Package describes the Go package found in a directory.
   382  type Package struct {
   383  	Dir           string   // directory containing package sources
   384  	Name          string   // package name
   385  	ImportComment string   // path in import comment on package statement
   386  	Doc           string   // documentation synopsis
   387  	ImportPath    string   // import path of package ("" if unknown)
   388  	Root          string   // root of Go tree where this package lives
   389  	SrcRoot       string   // package source root directory ("" if unknown)
   390  	PkgRoot       string   // package install root directory ("" if unknown)
   391  	PkgTargetRoot string   // architecture dependent install root directory ("" if unknown)
   392  	BinDir        string   // command install directory ("" if unknown)
   393  	Goroot        bool     // package found in Go root
   394  	PkgObj        string   // installed .a file
   395  	AllTags       []string // tags that can influence file selection in this directory
   396  	ConflictDir   string   // this directory shadows Dir in $GOPATH
   397  	BinaryOnly    bool     // cannot be rebuilt from source (has //go:binary-only-package comment)
   398  
   399  	// Source files
   400  	GoFiles        []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles)
   401  	CgoFiles       []string // .go source files that import "C"
   402  	IgnoredGoFiles []string // .go source files ignored for this build
   403  	InvalidGoFiles []string // .go source files with detected problems (parse error, wrong package name, and so on)
   404  	CFiles         []string // .c source files
   405  	CXXFiles       []string // .cc, .cpp and .cxx source files
   406  	MFiles         []string // .m (Objective-C) source files
   407  	HFiles         []string // .h, .hh, .hpp and .hxx source files
   408  	FFiles         []string // .f, .F, .for and .f90 Fortran source files
   409  	SFiles         []string // .s source files
   410  	SwigFiles      []string // .swig files
   411  	SwigCXXFiles   []string // .swigcxx files
   412  	SysoFiles      []string // .syso system object files to add to archive
   413  
   414  	// Cgo directives
   415  	CgoCFLAGS    []string // Cgo CFLAGS directives
   416  	CgoCPPFLAGS  []string // Cgo CPPFLAGS directives
   417  	CgoCXXFLAGS  []string // Cgo CXXFLAGS directives
   418  	CgoFFLAGS    []string // Cgo FFLAGS directives
   419  	CgoLDFLAGS   []string // Cgo LDFLAGS directives
   420  	CgoPkgConfig []string // Cgo pkg-config directives
   421  
   422  	// Dependency information
   423  	Imports   []string                    // import paths from GoFiles, CgoFiles
   424  	ImportPos map[string][]token.Position // line information for Imports
   425  
   426  	// Test information
   427  	TestGoFiles    []string                    // _test.go files in package
   428  	TestImports    []string                    // import paths from TestGoFiles
   429  	TestImportPos  map[string][]token.Position // line information for TestImports
   430  	XTestGoFiles   []string                    // _test.go files outside package
   431  	XTestImports   []string                    // import paths from XTestGoFiles
   432  	XTestImportPos map[string][]token.Position // line information for XTestImports
   433  }
   434  
   435  // IsCommand reports whether the package is considered a
   436  // command to be installed (not just a library).
   437  // Packages named "main" are treated as commands.
   438  func (p *Package) IsCommand() bool {
   439  	return p.Name == "main"
   440  }
   441  
   442  // ImportDir is like Import but processes the Go package found in
   443  // the named directory.
   444  func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error) {
   445  	return ctxt.Import(".", dir, mode)
   446  }
   447  
   448  // NoGoError is the error used by Import to describe a directory
   449  // containing no buildable Go source files. (It may still contain
   450  // test files, files hidden by build tags, and so on.)
   451  type NoGoError struct {
   452  	Dir string
   453  }
   454  
   455  func (e *NoGoError) Error() string {
   456  	return "no buildable Go source files in " + e.Dir
   457  }
   458  
   459  // MultiplePackageError describes a directory containing
   460  // multiple buildable Go source files for multiple packages.
   461  type MultiplePackageError struct {
   462  	Dir      string   // directory containing files
   463  	Packages []string // package names found
   464  	Files    []string // corresponding files: Files[i] declares package Packages[i]
   465  }
   466  
   467  func (e *MultiplePackageError) Error() string {
   468  	// Error string limited to two entries for compatibility.
   469  	return fmt.Sprintf("found packages %s (%s) and %s (%s) in %s", e.Packages[0], e.Files[0], e.Packages[1], e.Files[1], e.Dir)
   470  }
   471  
   472  func nameExt(name string) string {
   473  	i := strings.LastIndex(name, ".")
   474  	if i < 0 {
   475  		return ""
   476  	}
   477  	return name[i:]
   478  }
   479  
   480  // Import returns details about the Go package named by the import path,
   481  // interpreting local import paths relative to the srcDir directory.
   482  // If the path is a local import path naming a package that can be imported
   483  // using a standard import path, the returned package will set p.ImportPath
   484  // to that path.
   485  //
   486  // In the directory containing the package, .go, .c, .h, and .s files are
   487  // considered part of the package except for:
   488  //
   489  //	- .go files in package documentation
   490  //	- files starting with _ or . (likely editor temporary files)
   491  //	- files with build constraints not satisfied by the context
   492  //
   493  // If an error occurs, Import returns a non-nil error and a non-nil
   494  // *Package containing partial information.
   495  //
   496  func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error) {
   497  	p := &Package{
   498  		ImportPath: path,
   499  	}
   500  	if path == "" {
   501  		return p, fmt.Errorf("import %q: invalid import path", path)
   502  	}
   503  
   504  	var pkgtargetroot string
   505  	var pkga string
   506  	var pkgerr error
   507  	suffix := ""
   508  	if ctxt.InstallSuffix != "" {
   509  		suffix = "_" + ctxt.InstallSuffix
   510  	}
   511  	switch ctxt.Compiler {
   512  	case "gccgo":
   513  		pkgtargetroot = "pkg/gccgo_" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
   514  	case "gc":
   515  		pkgtargetroot = "pkg/" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix
   516  	default:
   517  		// Save error for end of function.
   518  		pkgerr = fmt.Errorf("import %q: unknown compiler %q", path, ctxt.Compiler)
   519  	}
   520  	setPkga := func() {
   521  		switch ctxt.Compiler {
   522  		case "gccgo":
   523  			dir, elem := pathpkg.Split(p.ImportPath)
   524  			pkga = pkgtargetroot + "/" + dir + "lib" + elem + ".a"
   525  		case "gc":
   526  			pkga = pkgtargetroot + "/" + p.ImportPath + ".a"
   527  		}
   528  	}
   529  	setPkga()
   530  
   531  	binaryOnly := false
   532  	if IsLocalImport(path) {
   533  		pkga = "" // local imports have no installed path
   534  		if srcDir == "" {
   535  			return p, fmt.Errorf("import %q: import relative to unknown directory", path)
   536  		}
   537  		if !ctxt.isAbsPath(path) {
   538  			p.Dir = ctxt.joinPath(srcDir, path)
   539  		}
   540  		// p.Dir directory may or may not exist. Gather partial information first, check if it exists later.
   541  		// Determine canonical import path, if any.
   542  		// Exclude results where the import path would include /testdata/.
   543  		inTestdata := func(sub string) bool {
   544  			return strings.Contains(sub, "/testdata/") || strings.HasSuffix(sub, "/testdata") || strings.HasPrefix(sub, "testdata/") || sub == "testdata"
   545  		}
   546  		if ctxt.GOROOT != "" && ctxt.Compiler != "gccgo" {
   547  			root := ctxt.joinPath(ctxt.GOROOT, "src")
   548  			if sub, ok := ctxt.hasSubdir(root, p.Dir); ok && !inTestdata(sub) {
   549  				p.Goroot = true
   550  				p.ImportPath = sub
   551  				p.Root = ctxt.GOROOT
   552  				setPkga() // p.ImportPath changed
   553  				goto Found
   554  			}
   555  		}
   556  		all := ctxt.gopath()
   557  		for i, root := range all {
   558  			rootsrc := ctxt.joinPath(root, "src")
   559  			if sub, ok := ctxt.hasSubdir(rootsrc, p.Dir); ok && !inTestdata(sub) {
   560  				// We found a potential import path for dir,
   561  				// but check that using it wouldn't find something
   562  				// else first.
   563  				if ctxt.GOROOT != "" && ctxt.Compiler != "gccgo" {
   564  					if dir := ctxt.joinPath(ctxt.GOROOT, "src", sub); ctxt.isDir(dir) {
   565  						p.ConflictDir = dir
   566  						goto Found
   567  					}
   568  				}
   569  				for _, earlyRoot := range all[:i] {
   570  					if dir := ctxt.joinPath(earlyRoot, "src", sub); ctxt.isDir(dir) {
   571  						p.ConflictDir = dir
   572  						goto Found
   573  					}
   574  				}
   575  
   576  				// sub would not name some other directory instead of this one.
   577  				// Record it.
   578  				p.ImportPath = sub
   579  				p.Root = root
   580  				setPkga() // p.ImportPath changed
   581  				goto Found
   582  			}
   583  		}
   584  		// It's okay that we didn't find a root containing dir.
   585  		// Keep going with the information we have.
   586  	} else {
   587  		if strings.HasPrefix(path, "/") {
   588  			return p, fmt.Errorf("import %q: cannot import absolute path", path)
   589  		}
   590  
   591  		gopath := ctxt.gopath() // needed by both importGo and below; avoid computing twice
   592  		if err := ctxt.importGo(p, path, srcDir, mode, gopath); err == nil {
   593  			goto Found
   594  		} else if err != errNoModules {
   595  			return p, err
   596  		}
   597  
   598  		// tried records the location of unsuccessful package lookups
   599  		var tried struct {
   600  			vendor []string
   601  			goroot string
   602  			gopath []string
   603  		}
   604  
   605  		// Vendor directories get first chance to satisfy import.
   606  		if mode&IgnoreVendor == 0 && srcDir != "" {
   607  			searchVendor := func(root string, isGoroot bool) bool {
   608  				sub, ok := ctxt.hasSubdir(root, srcDir)
   609  				if !ok || !strings.HasPrefix(sub, "src/") || strings.Contains(sub, "/testdata/") {
   610  					return false
   611  				}
   612  				for {
   613  					vendor := ctxt.joinPath(root, sub, "vendor")
   614  					if ctxt.isDir(vendor) {
   615  						dir := ctxt.joinPath(vendor, path)
   616  						if ctxt.isDir(dir) && hasGoFiles(ctxt, dir) {
   617  							p.Dir = dir
   618  							p.ImportPath = strings.TrimPrefix(pathpkg.Join(sub, "vendor", path), "src/")
   619  							p.Goroot = isGoroot
   620  							p.Root = root
   621  							setPkga() // p.ImportPath changed
   622  							return true
   623  						}
   624  						tried.vendor = append(tried.vendor, dir)
   625  					}
   626  					i := strings.LastIndex(sub, "/")
   627  					if i < 0 {
   628  						break
   629  					}
   630  					sub = sub[:i]
   631  				}
   632  				return false
   633  			}
   634  			if ctxt.Compiler != "gccgo" && searchVendor(ctxt.GOROOT, true) {
   635  				goto Found
   636  			}
   637  			for _, root := range gopath {
   638  				if searchVendor(root, false) {
   639  					goto Found
   640  				}
   641  			}
   642  		}
   643  
   644  		// Determine directory from import path.
   645  		if ctxt.GOROOT != "" {
   646  			dir := ctxt.joinPath(ctxt.GOROOT, "src", path)
   647  			if ctxt.Compiler != "gccgo" {
   648  				isDir := ctxt.isDir(dir)
   649  				binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga))
   650  				if isDir || binaryOnly {
   651  					p.Dir = dir
   652  					p.Goroot = true
   653  					p.Root = ctxt.GOROOT
   654  					goto Found
   655  				}
   656  			}
   657  			tried.goroot = dir
   658  		}
   659  		if ctxt.Compiler == "gccgo" && isStandardPackage(path) {
   660  			p.Dir = ctxt.joinPath(ctxt.GOROOT, "src", path)
   661  			p.Goroot = true
   662  			p.Root = ctxt.GOROOT
   663  			goto Found
   664  		}
   665  		for _, root := range gopath {
   666  			dir := ctxt.joinPath(root, "src", path)
   667  			isDir := ctxt.isDir(dir)
   668  			binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(root, pkga))
   669  			if isDir || binaryOnly {
   670  				p.Dir = dir
   671  				p.Root = root
   672  				goto Found
   673  			}
   674  			tried.gopath = append(tried.gopath, dir)
   675  		}
   676  
   677  		// package was not found
   678  		var paths []string
   679  		format := "\t%s (vendor tree)"
   680  		for _, dir := range tried.vendor {
   681  			paths = append(paths, fmt.Sprintf(format, dir))
   682  			format = "\t%s"
   683  		}
   684  		if tried.goroot != "" {
   685  			paths = append(paths, fmt.Sprintf("\t%s (from $GOROOT)", tried.goroot))
   686  		} else {
   687  			paths = append(paths, "\t($GOROOT not set)")
   688  		}
   689  		format = "\t%s (from $GOPATH)"
   690  		for _, dir := range tried.gopath {
   691  			paths = append(paths, fmt.Sprintf(format, dir))
   692  			format = "\t%s"
   693  		}
   694  		if len(tried.gopath) == 0 {
   695  			paths = append(paths, "\t($GOPATH not set. For more details see: 'go help gopath')")
   696  		}
   697  		return p, fmt.Errorf("cannot find package %q in any of:\n%s", path, strings.Join(paths, "\n"))
   698  	}
   699  
   700  Found:
   701  	if p.Root != "" {
   702  		p.SrcRoot = ctxt.joinPath(p.Root, "src")
   703  		p.PkgRoot = ctxt.joinPath(p.Root, "pkg")
   704  		p.BinDir = ctxt.joinPath(p.Root, "bin")
   705  		if pkga != "" {
   706  			p.PkgTargetRoot = ctxt.joinPath(p.Root, pkgtargetroot)
   707  			p.PkgObj = ctxt.joinPath(p.Root, pkga)
   708  		}
   709  	}
   710  
   711  	// If it's a local import path, by the time we get here, we still haven't checked
   712  	// that p.Dir directory exists. This is the right time to do that check.
   713  	// We can't do it earlier, because we want to gather partial information for the
   714  	// non-nil *Package returned when an error occurs.
   715  	// We need to do this before we return early on FindOnly flag.
   716  	if IsLocalImport(path) && !ctxt.isDir(p.Dir) {
   717  		// package was not found
   718  		return p, fmt.Errorf("cannot find package %q in:\n\t%s", path, p.Dir)
   719  	}
   720  
   721  	if mode&FindOnly != 0 {
   722  		return p, pkgerr
   723  	}
   724  	if binaryOnly && (mode&AllowBinary) != 0 {
   725  		return p, pkgerr
   726  	}
   727  
   728  	if ctxt.Compiler == "gccgo" && p.Goroot {
   729  		// gccgo has no sources for GOROOT packages.
   730  		return p, nil
   731  	}
   732  
   733  	dirs, err := ctxt.readDir(p.Dir)
   734  	if err != nil {
   735  		return p, err
   736  	}
   737  
   738  	var badGoError error
   739  	var Sfiles []string // files with ".S" (capital S)
   740  	var firstFile, firstCommentFile string
   741  	imported := make(map[string][]token.Position)
   742  	testImported := make(map[string][]token.Position)
   743  	xTestImported := make(map[string][]token.Position)
   744  	allTags := make(map[string]bool)
   745  	fset := token.NewFileSet()
   746  	for _, d := range dirs {
   747  		if d.IsDir() {
   748  			continue
   749  		}
   750  
   751  		name := d.Name()
   752  		ext := nameExt(name)
   753  
   754  		badFile := func(err error) {
   755  			if badGoError == nil {
   756  				badGoError = err
   757  			}
   758  			p.InvalidGoFiles = append(p.InvalidGoFiles, name)
   759  		}
   760  
   761  		match, data, filename, err := ctxt.matchFile(p.Dir, name, allTags, &p.BinaryOnly)
   762  		if err != nil {
   763  			badFile(err)
   764  			continue
   765  		}
   766  		if !match {
   767  			if ext == ".go" {
   768  				p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
   769  			}
   770  			continue
   771  		}
   772  
   773  		// Going to save the file. For non-Go files, can stop here.
   774  		switch ext {
   775  		case ".c":
   776  			p.CFiles = append(p.CFiles, name)
   777  			continue
   778  		case ".cc", ".cpp", ".cxx":
   779  			p.CXXFiles = append(p.CXXFiles, name)
   780  			continue
   781  		case ".m":
   782  			p.MFiles = append(p.MFiles, name)
   783  			continue
   784  		case ".h", ".hh", ".hpp", ".hxx":
   785  			p.HFiles = append(p.HFiles, name)
   786  			continue
   787  		case ".f", ".F", ".for", ".f90":
   788  			p.FFiles = append(p.FFiles, name)
   789  			continue
   790  		case ".s":
   791  			p.SFiles = append(p.SFiles, name)
   792  			continue
   793  		case ".S":
   794  			Sfiles = append(Sfiles, name)
   795  			continue
   796  		case ".swig":
   797  			p.SwigFiles = append(p.SwigFiles, name)
   798  			continue
   799  		case ".swigcxx":
   800  			p.SwigCXXFiles = append(p.SwigCXXFiles, name)
   801  			continue
   802  		case ".syso":
   803  			// binary objects to add to package archive
   804  			// Likely of the form foo_windows.syso, but
   805  			// the name was vetted above with goodOSArchFile.
   806  			p.SysoFiles = append(p.SysoFiles, name)
   807  			continue
   808  		}
   809  
   810  		pf, err := parser.ParseFile(fset, filename, data, parser.ImportsOnly|parser.ParseComments)
   811  		if err != nil {
   812  			badFile(err)
   813  			continue
   814  		}
   815  
   816  		pkg := pf.Name.Name
   817  		if pkg == "documentation" {
   818  			p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
   819  			continue
   820  		}
   821  
   822  		isTest := strings.HasSuffix(name, "_test.go")
   823  		isXTest := false
   824  		if isTest && strings.HasSuffix(pkg, "_test") {
   825  			isXTest = true
   826  			pkg = pkg[:len(pkg)-len("_test")]
   827  		}
   828  
   829  		if p.Name == "" {
   830  			p.Name = pkg
   831  			firstFile = name
   832  		} else if pkg != p.Name {
   833  			badFile(&MultiplePackageError{
   834  				Dir:      p.Dir,
   835  				Packages: []string{p.Name, pkg},
   836  				Files:    []string{firstFile, name},
   837  			})
   838  			p.InvalidGoFiles = append(p.InvalidGoFiles, name)
   839  		}
   840  		// Grab the first package comment as docs, provided it is not from a test file.
   841  		if pf.Doc != nil && p.Doc == "" && !isTest && !isXTest {
   842  			p.Doc = doc.Synopsis(pf.Doc.Text())
   843  		}
   844  
   845  		if mode&ImportComment != 0 {
   846  			qcom, line := findImportComment(data)
   847  			if line != 0 {
   848  				com, err := strconv.Unquote(qcom)
   849  				if err != nil {
   850  					badFile(fmt.Errorf("%s:%d: cannot parse import comment", filename, line))
   851  				} else if p.ImportComment == "" {
   852  					p.ImportComment = com
   853  					firstCommentFile = name
   854  				} else if p.ImportComment != com {
   855  					badFile(fmt.Errorf("found import comments %q (%s) and %q (%s) in %s", p.ImportComment, firstCommentFile, com, name, p.Dir))
   856  				}
   857  			}
   858  		}
   859  
   860  		// Record imports and information about cgo.
   861  		isCgo := false
   862  		for _, decl := range pf.Decls {
   863  			d, ok := decl.(*ast.GenDecl)
   864  			if !ok {
   865  				continue
   866  			}
   867  			for _, dspec := range d.Specs {
   868  				spec, ok := dspec.(*ast.ImportSpec)
   869  				if !ok {
   870  					continue
   871  				}
   872  				quoted := spec.Path.Value
   873  				path, err := strconv.Unquote(quoted)
   874  				if err != nil {
   875  					log.Panicf("%s: parser returned invalid quoted string: <%s>", filename, quoted)
   876  				}
   877  				if isXTest {
   878  					xTestImported[path] = append(xTestImported[path], fset.Position(spec.Pos()))
   879  				} else if isTest {
   880  					testImported[path] = append(testImported[path], fset.Position(spec.Pos()))
   881  				} else {
   882  					imported[path] = append(imported[path], fset.Position(spec.Pos()))
   883  				}
   884  				if path == "C" {
   885  					if isTest {
   886  						badFile(fmt.Errorf("use of cgo in test %s not supported", filename))
   887  					} else {
   888  						cg := spec.Doc
   889  						if cg == nil && len(d.Specs) == 1 {
   890  							cg = d.Doc
   891  						}
   892  						if cg != nil {
   893  							if err := ctxt.saveCgo(filename, p, cg); err != nil {
   894  								badFile(err)
   895  							}
   896  						}
   897  						isCgo = true
   898  					}
   899  				}
   900  			}
   901  		}
   902  		if isCgo {
   903  			allTags["cgo"] = true
   904  			if ctxt.CgoEnabled {
   905  				p.CgoFiles = append(p.CgoFiles, name)
   906  			} else {
   907  				p.IgnoredGoFiles = append(p.IgnoredGoFiles, name)
   908  			}
   909  		} else if isXTest {
   910  			p.XTestGoFiles = append(p.XTestGoFiles, name)
   911  		} else if isTest {
   912  			p.TestGoFiles = append(p.TestGoFiles, name)
   913  		} else {
   914  			p.GoFiles = append(p.GoFiles, name)
   915  		}
   916  	}
   917  	if badGoError != nil {
   918  		return p, badGoError
   919  	}
   920  	if len(p.GoFiles)+len(p.CgoFiles)+len(p.TestGoFiles)+len(p.XTestGoFiles) == 0 {
   921  		return p, &NoGoError{p.Dir}
   922  	}
   923  
   924  	for tag := range allTags {
   925  		p.AllTags = append(p.AllTags, tag)
   926  	}
   927  	sort.Strings(p.AllTags)
   928  
   929  	p.Imports, p.ImportPos = cleanImports(imported)
   930  	p.TestImports, p.TestImportPos = cleanImports(testImported)
   931  	p.XTestImports, p.XTestImportPos = cleanImports(xTestImported)
   932  
   933  	// add the .S files only if we are using cgo
   934  	// (which means gcc will compile them).
   935  	// The standard assemblers expect .s files.
   936  	if len(p.CgoFiles) > 0 {
   937  		p.SFiles = append(p.SFiles, Sfiles...)
   938  		sort.Strings(p.SFiles)
   939  	}
   940  
   941  	return p, pkgerr
   942  }
   943  
   944  var errNoModules = errors.New("not using modules")
   945  
   946  // importGo checks whether it can use the go command to find the directory for path.
   947  // If using the go command is not appopriate, importGo returns errNoModules.
   948  // Otherwise, importGo tries using the go command and reports whether that succeeded.
   949  // Using the go command lets build.Import and build.Context.Import find code
   950  // in Go modules. In the long term we want tools to use go/packages (currently golang.org/x/tools/go/packages),
   951  // which will also use the go command.
   952  // Invoking the go command here is not very efficient in that it computes information
   953  // about the requested package and all dependencies and then only reports about the requested package.
   954  // Then we reinvoke it for every dependency. But this is still better than not working at all.
   955  // See golang.org/issue/26504.
   956  func (ctxt *Context) importGo(p *Package, path, srcDir string, mode ImportMode, gopath []string) error {
   957  	const debugImportGo = false
   958  
   959  	// To invoke the go command, we must know the source directory,
   960  	// we must not being doing special things like AllowBinary or IgnoreVendor,
   961  	// and all the file system callbacks must be nil (we're meant to use the local file system).
   962  	if srcDir == "" || mode&AllowBinary != 0 || mode&IgnoreVendor != 0 ||
   963  		ctxt.JoinPath != nil || ctxt.SplitPathList != nil || ctxt.IsAbsPath != nil || ctxt.IsDir != nil || ctxt.HasSubdir != nil || ctxt.ReadDir != nil || ctxt.OpenFile != nil || !equal(ctxt.ReleaseTags, defaultReleaseTags) {
   964  		return errNoModules
   965  	}
   966  
   967  	// If modules are not enabled, then the in-process code works fine and we should keep using it.
   968  	switch os.Getenv("GO111MODULE") {
   969  	case "off":
   970  		return errNoModules
   971  	case "on":
   972  		// ok
   973  	default: // "", "auto", anything else
   974  		// Automatic mode: no module use in $GOPATH/src.
   975  		for _, root := range gopath {
   976  			sub, ok := ctxt.hasSubdir(root, srcDir)
   977  			if ok && strings.HasPrefix(sub, "src/") {
   978  				return errNoModules
   979  			}
   980  		}
   981  	}
   982  
   983  	// For efficiency, if path is a standard library package, let the usual lookup code handle it.
   984  	if ctxt.GOROOT != "" {
   985  		dir := ctxt.joinPath(ctxt.GOROOT, "src", path)
   986  		if ctxt.isDir(dir) {
   987  			return errNoModules
   988  		}
   989  	}
   990  
   991  	// Look to see if there is a go.mod.
   992  	abs, err := filepath.Abs(srcDir)
   993  	if err != nil {
   994  		return errNoModules
   995  	}
   996  	for {
   997  		info, err := os.Stat(filepath.Join(abs, "go.mod"))
   998  		if err == nil && !info.IsDir() {
   999  			break
  1000  		}
  1001  		d := filepath.Dir(abs)
  1002  		if len(d) >= len(abs) {
  1003  			return errNoModules // reached top of file system, no go.mod
  1004  		}
  1005  		abs = d
  1006  	}
  1007  
  1008  	cmd := exec.Command("go", "list", "-compiler="+ctxt.Compiler, "-tags="+strings.Join(ctxt.BuildTags, ","), "-installsuffix="+ctxt.InstallSuffix, "-f={{.Dir}}\n{{.ImportPath}}\n{{.Root}}\n{{.Goroot}}\n", path)
  1009  	cmd.Dir = srcDir
  1010  	var stdout, stderr strings.Builder
  1011  	cmd.Stdout = &stdout
  1012  	cmd.Stderr = &stderr
  1013  
  1014  	cgo := "0"
  1015  	if ctxt.CgoEnabled {
  1016  		cgo = "1"
  1017  	}
  1018  	cmd.Env = append(os.Environ(),
  1019  		"GOOS="+ctxt.GOOS,
  1020  		"GOARCH="+ctxt.GOARCH,
  1021  		"GOROOT="+ctxt.GOROOT,
  1022  		"GOPATH="+ctxt.GOPATH,
  1023  		"CGO_ENABLED="+cgo,
  1024  	)
  1025  
  1026  	if err := cmd.Run(); err != nil {
  1027  		return fmt.Errorf("go/build: importGo %s: %v\n%s\n", path, err, stderr.String())
  1028  	}
  1029  
  1030  	f := strings.Split(stdout.String(), "\n")
  1031  	if len(f) != 5 || f[4] != "" {
  1032  		return fmt.Errorf("go/build: importGo %s: unexpected output:\n%s\n", path, stdout.String())
  1033  	}
  1034  
  1035  	p.Dir = f[0]
  1036  	p.ImportPath = f[1]
  1037  	p.Root = f[2]
  1038  	p.Goroot = f[3] == "true"
  1039  	return nil
  1040  }
  1041  
  1042  func equal(x, y []string) bool {
  1043  	if len(x) != len(y) {
  1044  		return false
  1045  	}
  1046  	for i, xi := range x {
  1047  		if xi != y[i] {
  1048  			return false
  1049  		}
  1050  	}
  1051  	return true
  1052  }
  1053  
  1054  // hasGoFiles reports whether dir contains any files with names ending in .go.
  1055  // For a vendor check we must exclude directories that contain no .go files.
  1056  // Otherwise it is not possible to vendor just a/b/c and still import the
  1057  // non-vendored a/b. See golang.org/issue/13832.
  1058  func hasGoFiles(ctxt *Context, dir string) bool {
  1059  	ents, _ := ctxt.readDir(dir)
  1060  	for _, ent := range ents {
  1061  		if !ent.IsDir() && strings.HasSuffix(ent.Name(), ".go") {
  1062  			return true
  1063  		}
  1064  	}
  1065  	return false
  1066  }
  1067  
  1068  func findImportComment(data []byte) (s string, line int) {
  1069  	// expect keyword package
  1070  	word, data := parseWord(data)
  1071  	if string(word) != "package" {
  1072  		return "", 0
  1073  	}
  1074  
  1075  	// expect package name
  1076  	_, data = parseWord(data)
  1077  
  1078  	// now ready for import comment, a // or /* */ comment
  1079  	// beginning and ending on the current line.
  1080  	for len(data) > 0 && (data[0] == ' ' || data[0] == '\t' || data[0] == '\r') {
  1081  		data = data[1:]
  1082  	}
  1083  
  1084  	var comment []byte
  1085  	switch {
  1086  	case bytes.HasPrefix(data, slashSlash):
  1087  		i := bytes.Index(data, newline)
  1088  		if i < 0 {
  1089  			i = len(data)
  1090  		}
  1091  		comment = data[2:i]
  1092  	case bytes.HasPrefix(data, slashStar):
  1093  		data = data[2:]
  1094  		i := bytes.Index(data, starSlash)
  1095  		if i < 0 {
  1096  			// malformed comment
  1097  			return "", 0
  1098  		}
  1099  		comment = data[:i]
  1100  		if bytes.Contains(comment, newline) {
  1101  			return "", 0
  1102  		}
  1103  	}
  1104  	comment = bytes.TrimSpace(comment)
  1105  
  1106  	// split comment into `import`, `"pkg"`
  1107  	word, arg := parseWord(comment)
  1108  	if string(word) != "import" {
  1109  		return "", 0
  1110  	}
  1111  
  1112  	line = 1 + bytes.Count(data[:cap(data)-cap(arg)], newline)
  1113  	return strings.TrimSpace(string(arg)), line
  1114  }
  1115  
  1116  var (
  1117  	slashSlash = []byte("//")
  1118  	slashStar  = []byte("/*")
  1119  	starSlash  = []byte("*/")
  1120  	newline    = []byte("\n")
  1121  )
  1122  
  1123  // skipSpaceOrComment returns data with any leading spaces or comments removed.
  1124  func skipSpaceOrComment(data []byte) []byte {
  1125  	for len(data) > 0 {
  1126  		switch data[0] {
  1127  		case ' ', '\t', '\r', '\n':
  1128  			data = data[1:]
  1129  			continue
  1130  		case '/':
  1131  			if bytes.HasPrefix(data, slashSlash) {
  1132  				i := bytes.Index(data, newline)
  1133  				if i < 0 {
  1134  					return nil
  1135  				}
  1136  				data = data[i+1:]
  1137  				continue
  1138  			}
  1139  			if bytes.HasPrefix(data, slashStar) {
  1140  				data = data[2:]
  1141  				i := bytes.Index(data, starSlash)
  1142  				if i < 0 {
  1143  					return nil
  1144  				}
  1145  				data = data[i+2:]
  1146  				continue
  1147  			}
  1148  		}
  1149  		break
  1150  	}
  1151  	return data
  1152  }
  1153  
  1154  // parseWord skips any leading spaces or comments in data
  1155  // and then parses the beginning of data as an identifier or keyword,
  1156  // returning that word and what remains after the word.
  1157  func parseWord(data []byte) (word, rest []byte) {
  1158  	data = skipSpaceOrComment(data)
  1159  
  1160  	// Parse past leading word characters.
  1161  	rest = data
  1162  	for {
  1163  		r, size := utf8.DecodeRune(rest)
  1164  		if unicode.IsLetter(r) || '0' <= r && r <= '9' || r == '_' {
  1165  			rest = rest[size:]
  1166  			continue
  1167  		}
  1168  		break
  1169  	}
  1170  
  1171  	word = data[:len(data)-len(rest)]
  1172  	if len(word) == 0 {
  1173  		return nil, nil
  1174  	}
  1175  
  1176  	return word, rest
  1177  }
  1178  
  1179  // MatchFile reports whether the file with the given name in the given directory
  1180  // matches the context and would be included in a Package created by ImportDir
  1181  // of that directory.
  1182  //
  1183  // MatchFile considers the name of the file and may use ctxt.OpenFile to
  1184  // read some or all of the file's content.
  1185  func (ctxt *Context) MatchFile(dir, name string) (match bool, err error) {
  1186  	match, _, _, err = ctxt.matchFile(dir, name, nil, nil)
  1187  	return
  1188  }
  1189  
  1190  // matchFile determines whether the file with the given name in the given directory
  1191  // should be included in the package being constructed.
  1192  // It returns the data read from the file.
  1193  // If name denotes a Go program, matchFile reads until the end of the
  1194  // imports (and returns that data) even though it only considers text
  1195  // until the first non-comment.
  1196  // If allTags is non-nil, matchFile records any encountered build tag
  1197  // by setting allTags[tag] = true.
  1198  func (ctxt *Context) matchFile(dir, name string, allTags map[string]bool, binaryOnly *bool) (match bool, data []byte, filename string, err error) {
  1199  	if strings.HasPrefix(name, "_") ||
  1200  		strings.HasPrefix(name, ".") {
  1201  		return
  1202  	}
  1203  
  1204  	i := strings.LastIndex(name, ".")
  1205  	if i < 0 {
  1206  		i = len(name)
  1207  	}
  1208  	ext := name[i:]
  1209  
  1210  	if !ctxt.goodOSArchFile(name, allTags) && !ctxt.UseAllFiles {
  1211  		return
  1212  	}
  1213  
  1214  	switch ext {
  1215  	case ".go", ".c", ".cc", ".cxx", ".cpp", ".m", ".s", ".h", ".hh", ".hpp", ".hxx", ".f", ".F", ".f90", ".S", ".swig", ".swigcxx":
  1216  		// tentatively okay - read to make sure
  1217  	case ".syso":
  1218  		// binary, no reading
  1219  		match = true
  1220  		return
  1221  	default:
  1222  		// skip
  1223  		return
  1224  	}
  1225  
  1226  	filename = ctxt.joinPath(dir, name)
  1227  	f, err := ctxt.openFile(filename)
  1228  	if err != nil {
  1229  		return
  1230  	}
  1231  
  1232  	if strings.HasSuffix(filename, ".go") {
  1233  		data, err = readImports(f, false, nil)
  1234  		if strings.HasSuffix(filename, "_test.go") {
  1235  			binaryOnly = nil // ignore //go:binary-only-package comments in _test.go files
  1236  		}
  1237  	} else {
  1238  		binaryOnly = nil // ignore //go:binary-only-package comments in non-Go sources
  1239  		data, err = readComments(f)
  1240  	}
  1241  	f.Close()
  1242  	if err != nil {
  1243  		err = fmt.Errorf("read %s: %v", filename, err)
  1244  		return
  1245  	}
  1246  
  1247  	// Look for +build comments to accept or reject the file.
  1248  	var sawBinaryOnly bool
  1249  	if !ctxt.shouldBuild(data, allTags, &sawBinaryOnly) && !ctxt.UseAllFiles {
  1250  		return
  1251  	}
  1252  
  1253  	if binaryOnly != nil && sawBinaryOnly {
  1254  		*binaryOnly = true
  1255  	}
  1256  	match = true
  1257  	return
  1258  }
  1259  
  1260  func cleanImports(m map[string][]token.Position) ([]string, map[string][]token.Position) {
  1261  	all := make([]string, 0, len(m))
  1262  	for path := range m {
  1263  		all = append(all, path)
  1264  	}
  1265  	sort.Strings(all)
  1266  	return all, m
  1267  }
  1268  
  1269  // Import is shorthand for Default.Import.
  1270  func Import(path, srcDir string, mode ImportMode) (*Package, error) {
  1271  	return Default.Import(path, srcDir, mode)
  1272  }
  1273  
  1274  // ImportDir is shorthand for Default.ImportDir.
  1275  func ImportDir(dir string, mode ImportMode) (*Package, error) {
  1276  	return Default.ImportDir(dir, mode)
  1277  }
  1278  
  1279  var slashslash = []byte("//")
  1280  
  1281  // Special comment denoting a binary-only package.
  1282  // See https://golang.org/design/2775-binary-only-packages
  1283  // for more about the design of binary-only packages.
  1284  var binaryOnlyComment = []byte("//go:binary-only-package")
  1285  
  1286  // shouldBuild reports whether it is okay to use this file,
  1287  // The rule is that in the file's leading run of // comments
  1288  // and blank lines, which must be followed by a blank line
  1289  // (to avoid including a Go package clause doc comment),
  1290  // lines beginning with '// +build' are taken as build directives.
  1291  //
  1292  // The file is accepted only if each such line lists something
  1293  // matching the file. For example:
  1294  //
  1295  //	// +build windows linux
  1296  //
  1297  // marks the file as applicable only on Windows and Linux.
  1298  //
  1299  // If shouldBuild finds a //go:binary-only-package comment in the file,
  1300  // it sets *binaryOnly to true. Otherwise it does not change *binaryOnly.
  1301  //
  1302  func (ctxt *Context) shouldBuild(content []byte, allTags map[string]bool, binaryOnly *bool) bool {
  1303  	sawBinaryOnly := false
  1304  
  1305  	// Pass 1. Identify leading run of // comments and blank lines,
  1306  	// which must be followed by a blank line.
  1307  	end := 0
  1308  	p := content
  1309  	for len(p) > 0 {
  1310  		line := p
  1311  		if i := bytes.IndexByte(line, '\n'); i >= 0 {
  1312  			line, p = line[:i], p[i+1:]
  1313  		} else {
  1314  			p = p[len(p):]
  1315  		}
  1316  		line = bytes.TrimSpace(line)
  1317  		if len(line) == 0 { // Blank line
  1318  			end = len(content) - len(p)
  1319  			continue
  1320  		}
  1321  		if !bytes.HasPrefix(line, slashslash) { // Not comment line
  1322  			break
  1323  		}
  1324  	}
  1325  	content = content[:end]
  1326  
  1327  	// Pass 2.  Process each line in the run.
  1328  	p = content
  1329  	allok := true
  1330  	for len(p) > 0 {
  1331  		line := p
  1332  		if i := bytes.IndexByte(line, '\n'); i >= 0 {
  1333  			line, p = line[:i], p[i+1:]
  1334  		} else {
  1335  			p = p[len(p):]
  1336  		}
  1337  		line = bytes.TrimSpace(line)
  1338  		if !bytes.HasPrefix(line, slashslash) {
  1339  			continue
  1340  		}
  1341  		if bytes.Equal(line, binaryOnlyComment) {
  1342  			sawBinaryOnly = true
  1343  		}
  1344  		line = bytes.TrimSpace(line[len(slashslash):])
  1345  		if len(line) > 0 && line[0] == '+' {
  1346  			// Looks like a comment +line.
  1347  			f := strings.Fields(string(line))
  1348  			if f[0] == "+build" {
  1349  				ok := false
  1350  				for _, tok := range f[1:] {
  1351  					if ctxt.match(tok, allTags) {
  1352  						ok = true
  1353  					}
  1354  				}
  1355  				if !ok {
  1356  					allok = false
  1357  				}
  1358  			}
  1359  		}
  1360  	}
  1361  
  1362  	if binaryOnly != nil && sawBinaryOnly {
  1363  		*binaryOnly = true
  1364  	}
  1365  
  1366  	return allok
  1367  }
  1368  
  1369  // saveCgo saves the information from the #cgo lines in the import "C" comment.
  1370  // These lines set CFLAGS, CPPFLAGS, CXXFLAGS and LDFLAGS and pkg-config directives
  1371  // that affect the way cgo's C code is built.
  1372  func (ctxt *Context) saveCgo(filename string, di *Package, cg *ast.CommentGroup) error {
  1373  	text := cg.Text()
  1374  	for _, line := range strings.Split(text, "\n") {
  1375  		orig := line
  1376  
  1377  		// Line is
  1378  		//	#cgo [GOOS/GOARCH...] LDFLAGS: stuff
  1379  		//
  1380  		line = strings.TrimSpace(line)
  1381  		if len(line) < 5 || line[:4] != "#cgo" || (line[4] != ' ' && line[4] != '\t') {
  1382  			continue
  1383  		}
  1384  
  1385  		// Split at colon.
  1386  		line = strings.TrimSpace(line[4:])
  1387  		i := strings.Index(line, ":")
  1388  		if i < 0 {
  1389  			return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
  1390  		}
  1391  		line, argstr := line[:i], line[i+1:]
  1392  
  1393  		// Parse GOOS/GOARCH stuff.
  1394  		f := strings.Fields(line)
  1395  		if len(f) < 1 {
  1396  			return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
  1397  		}
  1398  
  1399  		cond, verb := f[:len(f)-1], f[len(f)-1]
  1400  		if len(cond) > 0 {
  1401  			ok := false
  1402  			for _, c := range cond {
  1403  				if ctxt.match(c, nil) {
  1404  					ok = true
  1405  					break
  1406  				}
  1407  			}
  1408  			if !ok {
  1409  				continue
  1410  			}
  1411  		}
  1412  
  1413  		args, err := splitQuoted(argstr)
  1414  		if err != nil {
  1415  			return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig)
  1416  		}
  1417  		var ok bool
  1418  		for i, arg := range args {
  1419  			if arg, ok = expandSrcDir(arg, di.Dir); !ok {
  1420  				return fmt.Errorf("%s: malformed #cgo argument: %s", filename, arg)
  1421  			}
  1422  			args[i] = arg
  1423  		}
  1424  
  1425  		switch verb {
  1426  		case "CFLAGS", "CPPFLAGS", "CXXFLAGS", "FFLAGS", "LDFLAGS":
  1427  			// Change relative paths to absolute.
  1428  			ctxt.makePathsAbsolute(args, di.Dir)
  1429  		}
  1430  
  1431  		switch verb {
  1432  		case "CFLAGS":
  1433  			di.CgoCFLAGS = append(di.CgoCFLAGS, args...)
  1434  		case "CPPFLAGS":
  1435  			di.CgoCPPFLAGS = append(di.CgoCPPFLAGS, args...)
  1436  		case "CXXFLAGS":
  1437  			di.CgoCXXFLAGS = append(di.CgoCXXFLAGS, args...)
  1438  		case "FFLAGS":
  1439  			di.CgoFFLAGS = append(di.CgoFFLAGS, args...)
  1440  		case "LDFLAGS":
  1441  			di.CgoLDFLAGS = append(di.CgoLDFLAGS, args...)
  1442  		case "pkg-config":
  1443  			di.CgoPkgConfig = append(di.CgoPkgConfig, args...)
  1444  		default:
  1445  			return fmt.Errorf("%s: invalid #cgo verb: %s", filename, orig)
  1446  		}
  1447  	}
  1448  	return nil
  1449  }
  1450  
  1451  // expandSrcDir expands any occurrence of ${SRCDIR}, making sure
  1452  // the result is safe for the shell.
  1453  func expandSrcDir(str string, srcdir string) (string, bool) {
  1454  	// "\" delimited paths cause safeCgoName to fail
  1455  	// so convert native paths with a different delimiter
  1456  	// to "/" before starting (eg: on windows).
  1457  	srcdir = filepath.ToSlash(srcdir)
  1458  
  1459  	chunks := strings.Split(str, "${SRCDIR}")
  1460  	if len(chunks) < 2 {
  1461  		return str, safeCgoName(str)
  1462  	}
  1463  	ok := true
  1464  	for _, chunk := range chunks {
  1465  		ok = ok && (chunk == "" || safeCgoName(chunk))
  1466  	}
  1467  	ok = ok && (srcdir == "" || safeCgoName(srcdir))
  1468  	res := strings.Join(chunks, srcdir)
  1469  	return res, ok && res != ""
  1470  }
  1471  
  1472  // makePathsAbsolute looks for compiler options that take paths and
  1473  // makes them absolute. We do this because through the 1.8 release we
  1474  // ran the compiler in the package directory, so any relative -I or -L
  1475  // options would be relative to that directory. In 1.9 we changed to
  1476  // running the compiler in the build directory, to get consistent
  1477  // build results (issue #19964). To keep builds working, we change any
  1478  // relative -I or -L options to be absolute.
  1479  //
  1480  // Using filepath.IsAbs and filepath.Join here means the results will be
  1481  // different on different systems, but that's OK: -I and -L options are
  1482  // inherently system-dependent.
  1483  func (ctxt *Context) makePathsAbsolute(args []string, srcDir string) {
  1484  	nextPath := false
  1485  	for i, arg := range args {
  1486  		if nextPath {
  1487  			if !filepath.IsAbs(arg) {
  1488  				args[i] = filepath.Join(srcDir, arg)
  1489  			}
  1490  			nextPath = false
  1491  		} else if strings.HasPrefix(arg, "-I") || strings.HasPrefix(arg, "-L") {
  1492  			if len(arg) == 2 {
  1493  				nextPath = true
  1494  			} else {
  1495  				if !filepath.IsAbs(arg[2:]) {
  1496  					args[i] = arg[:2] + filepath.Join(srcDir, arg[2:])
  1497  				}
  1498  			}
  1499  		}
  1500  	}
  1501  }
  1502  
  1503  // NOTE: $ is not safe for the shell, but it is allowed here because of linker options like -Wl,$ORIGIN.
  1504  // We never pass these arguments to a shell (just to programs we construct argv for), so this should be okay.
  1505  // See golang.org/issue/6038.
  1506  // The @ is for OS X. See golang.org/issue/13720.
  1507  // The % is for Jenkins. See golang.org/issue/16959.
  1508  // The ! is because module paths may use them. See golang.org/issue/26716.
  1509  const safeString = "+-.,/0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz:$@%! "
  1510  
  1511  func safeCgoName(s string) bool {
  1512  	if s == "" {
  1513  		return false
  1514  	}
  1515  	for i := 0; i < len(s); i++ {
  1516  		if c := s[i]; c < utf8.RuneSelf && strings.IndexByte(safeString, c) < 0 {
  1517  			return false
  1518  		}
  1519  	}
  1520  	return true
  1521  }
  1522  
  1523  // splitQuoted splits the string s around each instance of one or more consecutive
  1524  // white space characters while taking into account quotes and escaping, and
  1525  // returns an array of substrings of s or an empty list if s contains only white space.
  1526  // Single quotes and double quotes are recognized to prevent splitting within the
  1527  // quoted region, and are removed from the resulting substrings. If a quote in s
  1528  // isn't closed err will be set and r will have the unclosed argument as the
  1529  // last element. The backslash is used for escaping.
  1530  //
  1531  // For example, the following string:
  1532  //
  1533  //     a b:"c d" 'e''f'  "g\""
  1534  //
  1535  // Would be parsed as:
  1536  //
  1537  //     []string{"a", "b:c d", "ef", `g"`}
  1538  //
  1539  func splitQuoted(s string) (r []string, err error) {
  1540  	var args []string
  1541  	arg := make([]rune, len(s))
  1542  	escaped := false
  1543  	quoted := false
  1544  	quote := '\x00'
  1545  	i := 0
  1546  	for _, rune := range s {
  1547  		switch {
  1548  		case escaped:
  1549  			escaped = false
  1550  		case rune == '\\':
  1551  			escaped = true
  1552  			continue
  1553  		case quote != '\x00':
  1554  			if rune == quote {
  1555  				quote = '\x00'
  1556  				continue
  1557  			}
  1558  		case rune == '"' || rune == '\'':
  1559  			quoted = true
  1560  			quote = rune
  1561  			continue
  1562  		case unicode.IsSpace(rune):
  1563  			if quoted || i > 0 {
  1564  				quoted = false
  1565  				args = append(args, string(arg[:i]))
  1566  				i = 0
  1567  			}
  1568  			continue
  1569  		}
  1570  		arg[i] = rune
  1571  		i++
  1572  	}
  1573  	if quoted || i > 0 {
  1574  		args = append(args, string(arg[:i]))
  1575  	}
  1576  	if quote != 0 {
  1577  		err = errors.New("unclosed quote")
  1578  	} else if escaped {
  1579  		err = errors.New("unfinished escaping")
  1580  	}
  1581  	return args, err
  1582  }
  1583  
  1584  // match reports whether the name is one of:
  1585  //
  1586  //	$GOOS
  1587  //	$GOARCH
  1588  //	cgo (if cgo is enabled)
  1589  //	!cgo (if cgo is disabled)
  1590  //	ctxt.Compiler
  1591  //	!ctxt.Compiler
  1592  //	tag (if tag is listed in ctxt.BuildTags or ctxt.ReleaseTags)
  1593  //	!tag (if tag is not listed in ctxt.BuildTags or ctxt.ReleaseTags)
  1594  //	a comma-separated list of any of these
  1595  //
  1596  func (ctxt *Context) match(name string, allTags map[string]bool) bool {
  1597  	if name == "" {
  1598  		if allTags != nil {
  1599  			allTags[name] = true
  1600  		}
  1601  		return false
  1602  	}
  1603  	if i := strings.Index(name, ","); i >= 0 {
  1604  		// comma-separated list
  1605  		ok1 := ctxt.match(name[:i], allTags)
  1606  		ok2 := ctxt.match(name[i+1:], allTags)
  1607  		return ok1 && ok2
  1608  	}
  1609  	if strings.HasPrefix(name, "!!") { // bad syntax, reject always
  1610  		return false
  1611  	}
  1612  	if strings.HasPrefix(name, "!") { // negation
  1613  		return len(name) > 1 && !ctxt.match(name[1:], allTags)
  1614  	}
  1615  
  1616  	if allTags != nil {
  1617  		allTags[name] = true
  1618  	}
  1619  
  1620  	// Tags must be letters, digits, underscores or dots.
  1621  	// Unlike in Go identifiers, all digits are fine (e.g., "386").
  1622  	for _, c := range name {
  1623  		if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' {
  1624  			return false
  1625  		}
  1626  	}
  1627  
  1628  	// special tags
  1629  	if ctxt.CgoEnabled && name == "cgo" {
  1630  		return true
  1631  	}
  1632  	if name == ctxt.GOOS || name == ctxt.GOARCH || name == ctxt.Compiler {
  1633  		return true
  1634  	}
  1635  	if ctxt.GOOS == "android" && name == "linux" {
  1636  		return true
  1637  	}
  1638  
  1639  	// other tags
  1640  	for _, tag := range ctxt.BuildTags {
  1641  		if tag == name {
  1642  			return true
  1643  		}
  1644  	}
  1645  	for _, tag := range ctxt.ReleaseTags {
  1646  		if tag == name {
  1647  			return true
  1648  		}
  1649  	}
  1650  
  1651  	return false
  1652  }
  1653  
  1654  // goodOSArchFile returns false if the name contains a $GOOS or $GOARCH
  1655  // suffix which does not match the current system.
  1656  // The recognized name formats are:
  1657  //
  1658  //     name_$(GOOS).*
  1659  //     name_$(GOARCH).*
  1660  //     name_$(GOOS)_$(GOARCH).*
  1661  //     name_$(GOOS)_test.*
  1662  //     name_$(GOARCH)_test.*
  1663  //     name_$(GOOS)_$(GOARCH)_test.*
  1664  //
  1665  // An exception: if GOOS=android, then files with GOOS=linux are also matched.
  1666  func (ctxt *Context) goodOSArchFile(name string, allTags map[string]bool) bool {
  1667  	if dot := strings.Index(name, "."); dot != -1 {
  1668  		name = name[:dot]
  1669  	}
  1670  
  1671  	// Before Go 1.4, a file called "linux.go" would be equivalent to having a
  1672  	// build tag "linux" in that file. For Go 1.4 and beyond, we require this
  1673  	// auto-tagging to apply only to files with a non-empty prefix, so
  1674  	// "foo_linux.go" is tagged but "linux.go" is not. This allows new operating
  1675  	// systems, such as android, to arrive without breaking existing code with
  1676  	// innocuous source code in "android.go". The easiest fix: cut everything
  1677  	// in the name before the initial _.
  1678  	i := strings.Index(name, "_")
  1679  	if i < 0 {
  1680  		return true
  1681  	}
  1682  	name = name[i:] // ignore everything before first _
  1683  
  1684  	l := strings.Split(name, "_")
  1685  	if n := len(l); n > 0 && l[n-1] == "test" {
  1686  		l = l[:n-1]
  1687  	}
  1688  	n := len(l)
  1689  	if n >= 2 && knownOS[l[n-2]] && knownArch[l[n-1]] {
  1690  		return ctxt.match(l[n-1], allTags) && ctxt.match(l[n-2], allTags)
  1691  	}
  1692  	if n >= 1 && (knownOS[l[n-1]] || knownArch[l[n-1]]) {
  1693  		return ctxt.match(l[n-1], allTags)
  1694  	}
  1695  	return true
  1696  }
  1697  
  1698  var knownOS = make(map[string]bool)
  1699  var knownArch = make(map[string]bool)
  1700  
  1701  func init() {
  1702  	for _, v := range strings.Fields(goosList) {
  1703  		knownOS[v] = true
  1704  	}
  1705  	for _, v := range strings.Fields(goarchList) {
  1706  		knownArch[v] = true
  1707  	}
  1708  }
  1709  
  1710  // ToolDir is the directory containing build tools.
  1711  var ToolDir = getToolDir()
  1712  
  1713  // IsLocalImport reports whether the import path is
  1714  // a local import path, like ".", "..", "./foo", or "../foo".
  1715  func IsLocalImport(path string) bool {
  1716  	return path == "." || path == ".." ||
  1717  		strings.HasPrefix(path, "./") || strings.HasPrefix(path, "../")
  1718  }
  1719  
  1720  // ArchChar returns "?" and an error.
  1721  // In earlier versions of Go, the returned string was used to derive
  1722  // the compiler and linker tool names, the default object file suffix,
  1723  // and the default linker output name. As of Go 1.5, those strings
  1724  // no longer vary by architecture; they are compile, link, .o, and a.out, respectively.
  1725  func ArchChar(goarch string) (string, error) {
  1726  	return "?", errors.New("architecture letter no longer used")
  1727  }
  1728  

View as plain text