Black Lives Matter. Support the Equal Justice Initiative.

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

View as plain text