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