github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/go/build/build.go (about)

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