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