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

View as plain text