github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/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 ) 27 28 // A Context specifies the supporting context for a build. 29 type Context struct { 30 GOARCH string // target architecture 31 GOOS string // target operating system 32 GOROOT string // Go root 33 GOPATH string // Go path 34 CgoEnabled bool // whether cgo can be used 35 UseAllFiles bool // use files regardless of +build lines, file names 36 Compiler string // compiler to assume when computing target paths 37 38 // The build and release tags specify build constraints 39 // that should be considered satisfied when processing +build lines. 40 // Clients creating a new context may customize BuildTags, which 41 // defaults to empty, but it is usually an error to customize ReleaseTags, 42 // which defaults to the list of Go releases the current release is compatible with. 43 // In addition to the BuildTags and ReleaseTags, build constraints 44 // consider the values of GOARCH and GOOS as satisfied tags. 45 BuildTags []string 46 ReleaseTags []string 47 48 // The install suffix specifies a suffix to use in the name of the installation 49 // directory. By default it is empty, but custom builds that need to keep 50 // their outputs separate can set InstallSuffix to do so. For example, when 51 // using the race detector, the go command uses InstallSuffix = "race", so 52 // that on a Linux/386 system, packages are written to a directory named 53 // "linux_386_race" instead of the usual "linux_386". 54 InstallSuffix string 55 56 // By default, Import uses the operating system's file system calls 57 // to read directories and files. To read from other sources, 58 // callers can set the following functions. They all have default 59 // behaviors that use the local file system, so clients need only set 60 // the functions whose behaviors they wish to change. 61 62 // JoinPath joins the sequence of path fragments into a single path. 63 // If JoinPath is nil, Import uses filepath.Join. 64 JoinPath func(elem ...string) string 65 66 // SplitPathList splits the path list into a slice of individual paths. 67 // If SplitPathList is nil, Import uses filepath.SplitList. 68 SplitPathList func(list string) []string 69 70 // IsAbsPath reports whether path is an absolute path. 71 // If IsAbsPath is nil, Import uses filepath.IsAbs. 72 IsAbsPath func(path string) bool 73 74 // IsDir reports whether the path names a directory. 75 // If IsDir is nil, Import calls os.Stat and uses the result's IsDir method. 76 IsDir func(path string) bool 77 78 // HasSubdir reports whether dir is a subdirectory of 79 // (perhaps multiple levels below) root. 80 // If so, HasSubdir sets rel to a slash-separated path that 81 // can be joined to root to produce a path equivalent to dir. 82 // If HasSubdir is nil, Import uses an implementation built on 83 // filepath.EvalSymlinks. 84 HasSubdir func(root, dir string) (rel string, ok bool) 85 86 // ReadDir returns a slice of os.FileInfo, sorted by Name, 87 // describing the content of the named directory. 88 // If ReadDir is nil, Import uses ioutil.ReadDir. 89 ReadDir func(dir string) (fi []os.FileInfo, err error) 90 91 // OpenFile opens a file (not a directory) for reading. 92 // If OpenFile is nil, Import uses os.Open. 93 OpenFile func(path string) (r io.ReadCloser, err error) 94 } 95 96 // joinPath calls ctxt.JoinPath (if not nil) or else filepath.Join. 97 func (ctxt *Context) joinPath(elem ...string) string { 98 if f := ctxt.JoinPath; f != nil { 99 return f(elem...) 100 } 101 return filepath.Join(elem...) 102 } 103 104 // splitPathList calls ctxt.SplitPathList (if not nil) or else filepath.SplitList. 105 func (ctxt *Context) splitPathList(s string) []string { 106 if f := ctxt.SplitPathList; f != nil { 107 return f(s) 108 } 109 return filepath.SplitList(s) 110 } 111 112 // isAbsPath calls ctxt.IsAbsSPath (if not nil) or else filepath.IsAbs. 113 func (ctxt *Context) isAbsPath(path string) bool { 114 if f := ctxt.IsAbsPath; f != nil { 115 return f(path) 116 } 117 return filepath.IsAbs(path) 118 } 119 120 // isDir calls ctxt.IsDir (if not nil) or else uses os.Stat. 121 func (ctxt *Context) isDir(path string) bool { 122 if f := ctxt.IsDir; f != nil { 123 return f(path) 124 } 125 fi, err := os.Stat(path) 126 return err == nil && fi.IsDir() 127 } 128 129 // hasSubdir calls ctxt.HasSubdir (if not nil) or else uses 130 // the local file system to answer the question. 131 func (ctxt *Context) hasSubdir(root, dir string) (rel string, ok bool) { 132 if f := ctxt.HasSubdir; f != nil { 133 return f(root, dir) 134 } 135 136 // Try using paths we received. 137 if rel, ok = hasSubdir(root, dir); ok { 138 return 139 } 140 141 // Try expanding symlinks and comparing 142 // expanded against unexpanded and 143 // expanded against expanded. 144 rootSym, _ := filepath.EvalSymlinks(root) 145 dirSym, _ := filepath.EvalSymlinks(dir) 146 147 if rel, ok = hasSubdir(rootSym, dir); ok { 148 return 149 } 150 if rel, ok = hasSubdir(root, dirSym); ok { 151 return 152 } 153 return hasSubdir(rootSym, dirSym) 154 } 155 156 func hasSubdir(root, dir string) (rel string, ok bool) { 157 const sep = string(filepath.Separator) 158 root = filepath.Clean(root) 159 if !strings.HasSuffix(root, sep) { 160 root += sep 161 } 162 dir = filepath.Clean(dir) 163 if !strings.HasPrefix(dir, root) { 164 return "", false 165 } 166 return filepath.ToSlash(dir[len(root):]), true 167 } 168 169 // readDir calls ctxt.ReadDir (if not nil) or else ioutil.ReadDir. 170 func (ctxt *Context) readDir(path string) ([]os.FileInfo, error) { 171 if f := ctxt.ReadDir; f != nil { 172 return f(path) 173 } 174 return ioutil.ReadDir(path) 175 } 176 177 // openFile calls ctxt.OpenFile (if not nil) or else os.Open. 178 func (ctxt *Context) openFile(path string) (io.ReadCloser, error) { 179 if fn := ctxt.OpenFile; fn != nil { 180 return fn(path) 181 } 182 183 f, err := os.Open(path) 184 if err != nil { 185 return nil, err // nil interface 186 } 187 return f, nil 188 } 189 190 // isFile determines whether path is a file by trying to open it. 191 // It reuses openFile instead of adding another function to the 192 // list in Context. 193 func (ctxt *Context) isFile(path string) bool { 194 f, err := ctxt.openFile(path) 195 if err != nil { 196 return false 197 } 198 f.Close() 199 return true 200 } 201 202 // gopath returns the list of Go path directories. 203 func (ctxt *Context) gopath() []string { 204 var all []string 205 for _, p := range ctxt.splitPathList(ctxt.GOPATH) { 206 if p == "" || p == ctxt.GOROOT { 207 // Empty paths are uninteresting. 208 // If the path is the GOROOT, ignore it. 209 // People sometimes set GOPATH=$GOROOT, which is useless 210 // but would cause us to find packages with import paths 211 // like "pkg/math". 212 // Do not get confused by this common mistake. 213 continue 214 } 215 if strings.HasPrefix(p, "~") { 216 // Path segments starting with ~ on Unix are almost always 217 // users who have incorrectly quoted ~ while setting GOPATH, 218 // preventing it from expanding to $HOME. 219 // The situation is made more confusing by the fact that 220 // bash allows quoted ~ in $PATH (most shells do not). 221 // Do not get confused by this, and do not try to use the path. 222 // It does not exist, and printing errors about it confuses 223 // those users even more, because they think "sure ~ exists!". 224 // The go command diagnoses this situation and prints a 225 // useful error. 226 // On Windows, ~ is used in short names, such as c:\progra~1 227 // for c:\program files. 228 continue 229 } 230 all = append(all, p) 231 } 232 return all 233 } 234 235 // SrcDirs returns a list of package source root directories. 236 // It draws from the current Go root and Go path but omits directories 237 // that do not exist. 238 func (ctxt *Context) SrcDirs() []string { 239 var all []string 240 if ctxt.GOROOT != "" { 241 dir := ctxt.joinPath(ctxt.GOROOT, "src", "pkg") 242 if ctxt.isDir(dir) { 243 all = append(all, dir) 244 } 245 } 246 for _, p := range ctxt.gopath() { 247 dir := ctxt.joinPath(p, "src") 248 if ctxt.isDir(dir) { 249 all = append(all, dir) 250 } 251 } 252 return all 253 } 254 255 // Default is the default Context for builds. 256 // It uses the GOARCH, GOOS, GOROOT, and GOPATH environment variables 257 // if set, or else the compiled code's GOARCH, GOOS, and GOROOT. 258 var Default Context = defaultContext() 259 260 var cgoEnabled = map[string]bool{ 261 "darwin/386": true, 262 "darwin/amd64": true, 263 "freebsd/386": true, 264 "freebsd/amd64": true, 265 "freebsd/arm": true, 266 "linux/386": true, 267 "linux/amd64": true, 268 "linux/arm": true, 269 "netbsd/386": true, 270 "netbsd/amd64": true, 271 "netbsd/arm": true, 272 "openbsd/386": true, 273 "openbsd/amd64": true, 274 "windows/386": true, 275 "windows/amd64": true, 276 } 277 278 func defaultContext() Context { 279 var c Context 280 281 c.GOARCH = envOr("GOARCH", runtime.GOARCH) 282 c.GOOS = envOr("GOOS", runtime.GOOS) 283 c.GOROOT = runtime.GOROOT() 284 c.GOPATH = envOr("GOPATH", "") 285 c.Compiler = runtime.Compiler 286 287 // Each major Go release in the Go 1.x series should add a tag here. 288 // Old tags should not be removed. That is, the go1.x tag is present 289 // in all releases >= Go 1.x. Code that requires Go 1.x or later should 290 // say "+build go1.x", and code that should only be built before Go 1.x 291 // (perhaps it is the stub to use in that case) should say "+build !go1.x". 292 // 293 // When we reach Go 1.3 the line will read 294 // c.ReleaseTags = []string{"go1.1", "go1.2", "go1.3"} 295 // and so on. 296 c.ReleaseTags = []string{"go1.1"} 297 298 switch os.Getenv("CGO_ENABLED") { 299 case "1": 300 c.CgoEnabled = true 301 case "0": 302 c.CgoEnabled = false 303 default: 304 // golang.org/issue/5141 305 // cgo should be disabled for cross compilation builds 306 if runtime.GOARCH == c.GOARCH && runtime.GOOS == c.GOOS { 307 c.CgoEnabled = cgoEnabled[c.GOOS+"/"+c.GOARCH] 308 break 309 } 310 c.CgoEnabled = false 311 } 312 313 return c 314 } 315 316 func envOr(name, def string) string { 317 s := os.Getenv(name) 318 if s == "" { 319 return def 320 } 321 return s 322 } 323 324 // An ImportMode controls the behavior of the Import method. 325 type ImportMode uint 326 327 const ( 328 // If FindOnly is set, Import stops after locating the directory 329 // that should contain the sources for a package. It does not 330 // read any files in the directory. 331 FindOnly ImportMode = 1 << iota 332 333 // If AllowBinary is set, Import can be satisfied by a compiled 334 // package object without corresponding sources. 335 AllowBinary 336 ) 337 338 // A Package describes the Go package found in a directory. 339 type Package struct { 340 Dir string // directory containing package sources 341 Name string // package name 342 Doc string // documentation synopsis 343 ImportPath string // import path of package ("" if unknown) 344 Root string // root of Go tree where this package lives 345 SrcRoot string // package source root directory ("" if unknown) 346 PkgRoot string // package install root directory ("" if unknown) 347 BinDir string // command install directory ("" if unknown) 348 Goroot bool // package found in Go root 349 PkgObj string // installed .a file 350 AllTags []string // tags that can influence file selection in this directory 351 352 // Source files 353 GoFiles []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles) 354 CgoFiles []string // .go source files that import "C" 355 IgnoredGoFiles []string // .go source files ignored for this build 356 CFiles []string // .c source files 357 CXXFiles []string // .cc, .cpp and .cxx source files 358 HFiles []string // .h, .hh, .hpp and .hxx source files 359 SFiles []string // .s source files 360 SwigFiles []string // .swig files 361 SwigCXXFiles []string // .swigcxx files 362 SysoFiles []string // .syso system object files to add to archive 363 364 // Cgo directives 365 CgoCFLAGS []string // Cgo CFLAGS directives 366 CgoCPPFLAGS []string // Cgo CPPFLAGS directives 367 CgoCXXFLAGS []string // Cgo CXXFLAGS directives 368 CgoLDFLAGS []string // Cgo LDFLAGS directives 369 CgoPkgConfig []string // Cgo pkg-config directives 370 371 // Dependency information 372 Imports []string // imports from GoFiles, CgoFiles 373 ImportPos map[string][]token.Position // line information for Imports 374 375 // Test information 376 TestGoFiles []string // _test.go files in package 377 TestImports []string // imports from TestGoFiles 378 TestImportPos map[string][]token.Position // line information for TestImports 379 XTestGoFiles []string // _test.go files outside package 380 XTestImports []string // imports from XTestGoFiles 381 XTestImportPos map[string][]token.Position // line information for XTestImports 382 } 383 384 // IsCommand reports whether the package is considered a 385 // command to be installed (not just a library). 386 // Packages named "main" are treated as commands. 387 func (p *Package) IsCommand() bool { 388 return p.Name == "main" 389 } 390 391 // ImportDir is like Import but processes the Go package found in 392 // the named directory. 393 func (ctxt *Context) ImportDir(dir string, mode ImportMode) (*Package, error) { 394 return ctxt.Import(".", dir, mode) 395 } 396 397 // NoGoError is the error used by Import to describe a directory 398 // containing no buildable Go source files. (It may still contain 399 // test files, files hidden by build tags, and so on.) 400 type NoGoError struct { 401 Dir string 402 } 403 404 func (e *NoGoError) Error() string { 405 return "no buildable Go source files in " + e.Dir 406 } 407 408 // Import returns details about the Go package named by the import path, 409 // interpreting local import paths relative to the srcDir directory. 410 // If the path is a local import path naming a package that can be imported 411 // using a standard import path, the returned package will set p.ImportPath 412 // to that path. 413 // 414 // In the directory containing the package, .go, .c, .h, and .s files are 415 // considered part of the package except for: 416 // 417 // - .go files in package documentation 418 // - files starting with _ or . (likely editor temporary files) 419 // - files with build constraints not satisfied by the context 420 // 421 // If an error occurs, Import returns a non-nil error and a non-nil 422 // *Package containing partial information. 423 // 424 func (ctxt *Context) Import(path string, srcDir string, mode ImportMode) (*Package, error) { 425 p := &Package{ 426 ImportPath: path, 427 } 428 if path == "" { 429 return p, fmt.Errorf("import %q: invalid import path", path) 430 } 431 432 var pkga string 433 var pkgerr error 434 switch ctxt.Compiler { 435 case "gccgo": 436 dir, elem := pathpkg.Split(p.ImportPath) 437 pkga = "pkg/gccgo/" + dir + "lib" + elem + ".a" 438 case "gc": 439 suffix := "" 440 if ctxt.InstallSuffix != "" { 441 suffix = "_" + ctxt.InstallSuffix 442 } 443 pkga = "pkg/" + ctxt.GOOS + "_" + ctxt.GOARCH + suffix + "/" + p.ImportPath + ".a" 444 default: 445 // Save error for end of function. 446 pkgerr = fmt.Errorf("import %q: unknown compiler %q", path, ctxt.Compiler) 447 } 448 449 binaryOnly := false 450 if IsLocalImport(path) { 451 pkga = "" // local imports have no installed path 452 if srcDir == "" { 453 return p, fmt.Errorf("import %q: import relative to unknown directory", path) 454 } 455 if !ctxt.isAbsPath(path) { 456 p.Dir = ctxt.joinPath(srcDir, path) 457 } 458 // Determine canonical import path, if any. 459 if ctxt.GOROOT != "" { 460 root := ctxt.joinPath(ctxt.GOROOT, "src", "pkg") 461 if sub, ok := ctxt.hasSubdir(root, p.Dir); ok { 462 p.Goroot = true 463 p.ImportPath = sub 464 p.Root = ctxt.GOROOT 465 goto Found 466 } 467 } 468 all := ctxt.gopath() 469 for i, root := range all { 470 rootsrc := ctxt.joinPath(root, "src") 471 if sub, ok := ctxt.hasSubdir(rootsrc, p.Dir); ok { 472 // We found a potential import path for dir, 473 // but check that using it wouldn't find something 474 // else first. 475 if ctxt.GOROOT != "" { 476 if dir := ctxt.joinPath(ctxt.GOROOT, "src", "pkg", sub); ctxt.isDir(dir) { 477 goto Found 478 } 479 } 480 for _, earlyRoot := range all[:i] { 481 if dir := ctxt.joinPath(earlyRoot, "src", sub); ctxt.isDir(dir) { 482 goto Found 483 } 484 } 485 486 // sub would not name some other directory instead of this one. 487 // Record it. 488 p.ImportPath = sub 489 p.Root = root 490 goto Found 491 } 492 } 493 // It's okay that we didn't find a root containing dir. 494 // Keep going with the information we have. 495 } else { 496 if strings.HasPrefix(path, "/") { 497 return p, fmt.Errorf("import %q: cannot import absolute path", path) 498 } 499 500 // tried records the location of unsuccessful package lookups 501 var tried struct { 502 goroot string 503 gopath []string 504 } 505 506 // Determine directory from import path. 507 if ctxt.GOROOT != "" { 508 dir := ctxt.joinPath(ctxt.GOROOT, "src", "pkg", path) 509 isDir := ctxt.isDir(dir) 510 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(ctxt.GOROOT, pkga)) 511 if isDir || binaryOnly { 512 p.Dir = dir 513 p.Goroot = true 514 p.Root = ctxt.GOROOT 515 goto Found 516 } 517 tried.goroot = dir 518 } 519 for _, root := range ctxt.gopath() { 520 dir := ctxt.joinPath(root, "src", path) 521 isDir := ctxt.isDir(dir) 522 binaryOnly = !isDir && mode&AllowBinary != 0 && pkga != "" && ctxt.isFile(ctxt.joinPath(root, pkga)) 523 if isDir || binaryOnly { 524 p.Dir = dir 525 p.Root = root 526 goto Found 527 } 528 tried.gopath = append(tried.gopath, dir) 529 } 530 531 // package was not found 532 var paths []string 533 if tried.goroot != "" { 534 paths = append(paths, fmt.Sprintf("\t%s (from $GOROOT)", tried.goroot)) 535 } else { 536 paths = append(paths, "\t($GOROOT not set)") 537 } 538 var i int 539 var format = "\t%s (from $GOPATH)" 540 for ; i < len(tried.gopath); i++ { 541 if i > 0 { 542 format = "\t%s" 543 } 544 paths = append(paths, fmt.Sprintf(format, tried.gopath[i])) 545 } 546 if i == 0 { 547 paths = append(paths, "\t($GOPATH not set)") 548 } 549 return p, fmt.Errorf("cannot find package %q in any of:\n%s", path, strings.Join(paths, "\n")) 550 } 551 552 Found: 553 if p.Root != "" { 554 if p.Goroot { 555 p.SrcRoot = ctxt.joinPath(p.Root, "src", "pkg") 556 } else { 557 p.SrcRoot = ctxt.joinPath(p.Root, "src") 558 } 559 p.PkgRoot = ctxt.joinPath(p.Root, "pkg") 560 p.BinDir = ctxt.joinPath(p.Root, "bin") 561 if pkga != "" { 562 p.PkgObj = ctxt.joinPath(p.Root, pkga) 563 } 564 } 565 566 if mode&FindOnly != 0 { 567 return p, pkgerr 568 } 569 if binaryOnly && (mode&AllowBinary) != 0 { 570 return p, pkgerr 571 } 572 573 dirs, err := ctxt.readDir(p.Dir) 574 if err != nil { 575 return p, err 576 } 577 578 var Sfiles []string // files with ".S" (capital S) 579 var firstFile string 580 imported := make(map[string][]token.Position) 581 testImported := make(map[string][]token.Position) 582 xTestImported := make(map[string][]token.Position) 583 allTags := make(map[string]bool) 584 fset := token.NewFileSet() 585 for _, d := range dirs { 586 if d.IsDir() { 587 continue 588 } 589 name := d.Name() 590 if strings.HasPrefix(name, "_") || 591 strings.HasPrefix(name, ".") { 592 continue 593 } 594 595 i := strings.LastIndex(name, ".") 596 if i < 0 { 597 i = len(name) 598 } 599 ext := name[i:] 600 601 if !ctxt.goodOSArchFile(name, allTags) && !ctxt.UseAllFiles { 602 if ext == ".go" { 603 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name) 604 } 605 continue 606 } 607 608 switch ext { 609 case ".go", ".c", ".cc", ".cxx", ".cpp", ".s", ".h", ".hh", ".hpp", ".hxx", ".S", ".swig", ".swigcxx": 610 // tentatively okay - read to make sure 611 case ".syso": 612 // binary objects to add to package archive 613 // Likely of the form foo_windows.syso, but 614 // the name was vetted above with goodOSArchFile. 615 p.SysoFiles = append(p.SysoFiles, name) 616 continue 617 default: 618 // skip 619 continue 620 } 621 622 filename := ctxt.joinPath(p.Dir, name) 623 f, err := ctxt.openFile(filename) 624 if err != nil { 625 return p, err 626 } 627 628 var data []byte 629 if strings.HasSuffix(filename, ".go") { 630 data, err = readImports(f, false) 631 } else { 632 data, err = readComments(f) 633 } 634 f.Close() 635 if err != nil { 636 return p, fmt.Errorf("read %s: %v", filename, err) 637 } 638 639 // Look for +build comments to accept or reject the file. 640 if !ctxt.shouldBuild(data, allTags) && !ctxt.UseAllFiles { 641 if ext == ".go" { 642 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name) 643 } 644 continue 645 } 646 647 // Going to save the file. For non-Go files, can stop here. 648 switch ext { 649 case ".c": 650 p.CFiles = append(p.CFiles, name) 651 continue 652 case ".cc", ".cpp", ".cxx": 653 p.CXXFiles = append(p.CXXFiles, name) 654 continue 655 case ".h", ".hh", ".hpp", ".hxx": 656 p.HFiles = append(p.HFiles, name) 657 continue 658 case ".s": 659 p.SFiles = append(p.SFiles, name) 660 continue 661 case ".S": 662 Sfiles = append(Sfiles, name) 663 continue 664 case ".swig": 665 p.SwigFiles = append(p.SwigFiles, name) 666 continue 667 case ".swigcxx": 668 p.SwigCXXFiles = append(p.SwigCXXFiles, name) 669 continue 670 } 671 672 pf, err := parser.ParseFile(fset, filename, data, parser.ImportsOnly|parser.ParseComments) 673 if err != nil { 674 return p, err 675 } 676 677 pkg := pf.Name.Name 678 if pkg == "documentation" { 679 p.IgnoredGoFiles = append(p.IgnoredGoFiles, name) 680 continue 681 } 682 683 isTest := strings.HasSuffix(name, "_test.go") 684 isXTest := false 685 if isTest && strings.HasSuffix(pkg, "_test") { 686 isXTest = true 687 pkg = pkg[:len(pkg)-len("_test")] 688 } 689 690 if p.Name == "" { 691 p.Name = pkg 692 firstFile = name 693 } else if pkg != p.Name { 694 return p, fmt.Errorf("found packages %s (%s) and %s (%s) in %s", p.Name, firstFile, pkg, name, p.Dir) 695 } 696 if pf.Doc != nil && p.Doc == "" { 697 p.Doc = doc.Synopsis(pf.Doc.Text()) 698 } 699 700 // Record imports and information about cgo. 701 isCgo := false 702 for _, decl := range pf.Decls { 703 d, ok := decl.(*ast.GenDecl) 704 if !ok { 705 continue 706 } 707 for _, dspec := range d.Specs { 708 spec, ok := dspec.(*ast.ImportSpec) 709 if !ok { 710 continue 711 } 712 quoted := spec.Path.Value 713 path, err := strconv.Unquote(quoted) 714 if err != nil { 715 log.Panicf("%s: parser returned invalid quoted string: <%s>", filename, quoted) 716 } 717 if isXTest { 718 xTestImported[path] = append(xTestImported[path], fset.Position(spec.Pos())) 719 } else if isTest { 720 testImported[path] = append(testImported[path], fset.Position(spec.Pos())) 721 } else { 722 imported[path] = append(imported[path], fset.Position(spec.Pos())) 723 } 724 if path == "C" { 725 if isTest { 726 return p, fmt.Errorf("use of cgo in test %s not supported", filename) 727 } 728 cg := spec.Doc 729 if cg == nil && len(d.Specs) == 1 { 730 cg = d.Doc 731 } 732 if cg != nil { 733 if err := ctxt.saveCgo(filename, p, cg); err != nil { 734 return p, err 735 } 736 } 737 isCgo = true 738 } 739 } 740 } 741 if isCgo { 742 allTags["cgo"] = true 743 if ctxt.CgoEnabled { 744 p.CgoFiles = append(p.CgoFiles, name) 745 } 746 } else if isXTest { 747 p.XTestGoFiles = append(p.XTestGoFiles, name) 748 } else if isTest { 749 p.TestGoFiles = append(p.TestGoFiles, name) 750 } else { 751 p.GoFiles = append(p.GoFiles, name) 752 } 753 } 754 if p.Name == "" { 755 return p, &NoGoError{p.Dir} 756 } 757 758 for tag := range allTags { 759 p.AllTags = append(p.AllTags, tag) 760 } 761 sort.Strings(p.AllTags) 762 763 p.Imports, p.ImportPos = cleanImports(imported) 764 p.TestImports, p.TestImportPos = cleanImports(testImported) 765 p.XTestImports, p.XTestImportPos = cleanImports(xTestImported) 766 767 // add the .S files only if we are using cgo 768 // (which means gcc will compile them). 769 // The standard assemblers expect .s files. 770 if len(p.CgoFiles) > 0 { 771 p.SFiles = append(p.SFiles, Sfiles...) 772 sort.Strings(p.SFiles) 773 } 774 775 return p, pkgerr 776 } 777 778 func cleanImports(m map[string][]token.Position) ([]string, map[string][]token.Position) { 779 all := make([]string, 0, len(m)) 780 for path := range m { 781 all = append(all, path) 782 } 783 sort.Strings(all) 784 return all, m 785 } 786 787 // Import is shorthand for Default.Import. 788 func Import(path, srcDir string, mode ImportMode) (*Package, error) { 789 return Default.Import(path, srcDir, mode) 790 } 791 792 // ImportDir is shorthand for Default.ImportDir. 793 func ImportDir(dir string, mode ImportMode) (*Package, error) { 794 return Default.ImportDir(dir, mode) 795 } 796 797 var slashslash = []byte("//") 798 799 // shouldBuild reports whether it is okay to use this file, 800 // The rule is that in the file's leading run of // comments 801 // and blank lines, which must be followed by a blank line 802 // (to avoid including a Go package clause doc comment), 803 // lines beginning with '// +build' are taken as build directives. 804 // 805 // The file is accepted only if each such line lists something 806 // matching the file. For example: 807 // 808 // // +build windows linux 809 // 810 // marks the file as applicable only on Windows and Linux. 811 // 812 func (ctxt *Context) shouldBuild(content []byte, allTags map[string]bool) bool { 813 // Pass 1. Identify leading run of // comments and blank lines, 814 // which must be followed by a blank line. 815 end := 0 816 p := content 817 for len(p) > 0 { 818 line := p 819 if i := bytes.IndexByte(line, '\n'); i >= 0 { 820 line, p = line[:i], p[i+1:] 821 } else { 822 p = p[len(p):] 823 } 824 line = bytes.TrimSpace(line) 825 if len(line) == 0 { // Blank line 826 end = len(content) - len(p) 827 continue 828 } 829 if !bytes.HasPrefix(line, slashslash) { // Not comment line 830 break 831 } 832 } 833 content = content[:end] 834 835 // Pass 2. Process each line in the run. 836 p = content 837 allok := true 838 for len(p) > 0 { 839 line := p 840 if i := bytes.IndexByte(line, '\n'); i >= 0 { 841 line, p = line[:i], p[i+1:] 842 } else { 843 p = p[len(p):] 844 } 845 line = bytes.TrimSpace(line) 846 if bytes.HasPrefix(line, slashslash) { 847 line = bytes.TrimSpace(line[len(slashslash):]) 848 if len(line) > 0 && line[0] == '+' { 849 // Looks like a comment +line. 850 f := strings.Fields(string(line)) 851 if f[0] == "+build" { 852 ok := false 853 for _, tok := range f[1:] { 854 if ctxt.match(tok, allTags) { 855 ok = true 856 } 857 } 858 if !ok { 859 allok = false 860 } 861 } 862 } 863 } 864 } 865 866 return allok 867 } 868 869 // saveCgo saves the information from the #cgo lines in the import "C" comment. 870 // These lines set CFLAGS, CPPFLAGS, CXXFLAGS and LDFLAGS and pkg-config directives 871 // that affect the way cgo's C code is built. 872 // 873 // TODO(rsc): This duplicates code in cgo. 874 // Once the dust settles, remove this code from cgo. 875 func (ctxt *Context) saveCgo(filename string, di *Package, cg *ast.CommentGroup) error { 876 text := cg.Text() 877 for _, line := range strings.Split(text, "\n") { 878 orig := line 879 880 // Line is 881 // #cgo [GOOS/GOARCH...] LDFLAGS: stuff 882 // 883 line = strings.TrimSpace(line) 884 if len(line) < 5 || line[:4] != "#cgo" || (line[4] != ' ' && line[4] != '\t') { 885 continue 886 } 887 888 // Split at colon. 889 line = strings.TrimSpace(line[4:]) 890 i := strings.Index(line, ":") 891 if i < 0 { 892 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig) 893 } 894 line, argstr := line[:i], line[i+1:] 895 896 // Parse GOOS/GOARCH stuff. 897 f := strings.Fields(line) 898 if len(f) < 1 { 899 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig) 900 } 901 902 cond, verb := f[:len(f)-1], f[len(f)-1] 903 if len(cond) > 0 { 904 ok := false 905 for _, c := range cond { 906 if ctxt.match(c, nil) { 907 ok = true 908 break 909 } 910 } 911 if !ok { 912 continue 913 } 914 } 915 916 args, err := splitQuoted(argstr) 917 if err != nil { 918 return fmt.Errorf("%s: invalid #cgo line: %s", filename, orig) 919 } 920 for _, arg := range args { 921 if !safeName(arg) { 922 return fmt.Errorf("%s: malformed #cgo argument: %s", filename, arg) 923 } 924 } 925 926 switch verb { 927 case "CFLAGS": 928 di.CgoCFLAGS = append(di.CgoCFLAGS, args...) 929 case "CPPFLAGS": 930 di.CgoCPPFLAGS = append(di.CgoCPPFLAGS, args...) 931 case "CXXFLAGS": 932 di.CgoCXXFLAGS = append(di.CgoCXXFLAGS, args...) 933 case "LDFLAGS": 934 di.CgoLDFLAGS = append(di.CgoLDFLAGS, args...) 935 case "pkg-config": 936 di.CgoPkgConfig = append(di.CgoPkgConfig, args...) 937 default: 938 return fmt.Errorf("%s: invalid #cgo verb: %s", filename, orig) 939 } 940 } 941 return nil 942 } 943 944 var safeBytes = []byte("+-.,/0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz:") 945 946 func safeName(s string) bool { 947 if s == "" { 948 return false 949 } 950 for i := 0; i < len(s); i++ { 951 if c := s[i]; c < 0x80 && bytes.IndexByte(safeBytes, c) < 0 { 952 return false 953 } 954 } 955 return true 956 } 957 958 // splitQuoted splits the string s around each instance of one or more consecutive 959 // white space characters while taking into account quotes and escaping, and 960 // returns an array of substrings of s or an empty list if s contains only white space. 961 // Single quotes and double quotes are recognized to prevent splitting within the 962 // quoted region, and are removed from the resulting substrings. If a quote in s 963 // isn't closed err will be set and r will have the unclosed argument as the 964 // last element. The backslash is used for escaping. 965 // 966 // For example, the following string: 967 // 968 // a b:"c d" 'e''f' "g\"" 969 // 970 // Would be parsed as: 971 // 972 // []string{"a", "b:c d", "ef", `g"`} 973 // 974 func splitQuoted(s string) (r []string, err error) { 975 var args []string 976 arg := make([]rune, len(s)) 977 escaped := false 978 quoted := false 979 quote := '\x00' 980 i := 0 981 for _, rune := range s { 982 switch { 983 case escaped: 984 escaped = false 985 case rune == '\\': 986 escaped = true 987 continue 988 case quote != '\x00': 989 if rune == quote { 990 quote = '\x00' 991 continue 992 } 993 case rune == '"' || rune == '\'': 994 quoted = true 995 quote = rune 996 continue 997 case unicode.IsSpace(rune): 998 if quoted || i > 0 { 999 quoted = false 1000 args = append(args, string(arg[:i])) 1001 i = 0 1002 } 1003 continue 1004 } 1005 arg[i] = rune 1006 i++ 1007 } 1008 if quoted || i > 0 { 1009 args = append(args, string(arg[:i])) 1010 } 1011 if quote != 0 { 1012 err = errors.New("unclosed quote") 1013 } else if escaped { 1014 err = errors.New("unfinished escaping") 1015 } 1016 return args, err 1017 } 1018 1019 // match returns true if the name is one of: 1020 // 1021 // $GOOS 1022 // $GOARCH 1023 // cgo (if cgo is enabled) 1024 // !cgo (if cgo is disabled) 1025 // ctxt.Compiler 1026 // !ctxt.Compiler 1027 // tag (if tag is listed in ctxt.BuildTags or ctxt.ReleaseTags) 1028 // !tag (if tag is not listed in ctxt.BuildTags or ctxt.ReleaseTags) 1029 // a comma-separated list of any of these 1030 // 1031 func (ctxt *Context) match(name string, allTags map[string]bool) bool { 1032 if name == "" { 1033 if allTags != nil { 1034 allTags[name] = true 1035 } 1036 return false 1037 } 1038 if i := strings.Index(name, ","); i >= 0 { 1039 // comma-separated list 1040 ok1 := ctxt.match(name[:i], allTags) 1041 ok2 := ctxt.match(name[i+1:], allTags) 1042 return ok1 && ok2 1043 } 1044 if strings.HasPrefix(name, "!!") { // bad syntax, reject always 1045 return false 1046 } 1047 if strings.HasPrefix(name, "!") { // negation 1048 return len(name) > 1 && !ctxt.match(name[1:], allTags) 1049 } 1050 1051 if allTags != nil { 1052 allTags[name] = true 1053 } 1054 1055 // Tags must be letters, digits, underscores or dots. 1056 // Unlike in Go identifiers, all digits are fine (e.g., "386"). 1057 for _, c := range name { 1058 if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' { 1059 return false 1060 } 1061 } 1062 1063 // special tags 1064 if ctxt.CgoEnabled && name == "cgo" { 1065 return true 1066 } 1067 if name == ctxt.GOOS || name == ctxt.GOARCH || name == ctxt.Compiler { 1068 return true 1069 } 1070 1071 // other tags 1072 for _, tag := range ctxt.BuildTags { 1073 if tag == name { 1074 return true 1075 } 1076 } 1077 for _, tag := range ctxt.ReleaseTags { 1078 if tag == name { 1079 return true 1080 } 1081 } 1082 1083 return false 1084 } 1085 1086 // goodOSArchFile returns false if the name contains a $GOOS or $GOARCH 1087 // suffix which does not match the current system. 1088 // The recognized name formats are: 1089 // 1090 // name_$(GOOS).* 1091 // name_$(GOARCH).* 1092 // name_$(GOOS)_$(GOARCH).* 1093 // name_$(GOOS)_test.* 1094 // name_$(GOARCH)_test.* 1095 // name_$(GOOS)_$(GOARCH)_test.* 1096 // 1097 func (ctxt *Context) goodOSArchFile(name string, allTags map[string]bool) bool { 1098 if dot := strings.Index(name, "."); dot != -1 { 1099 name = name[:dot] 1100 } 1101 l := strings.Split(name, "_") 1102 if n := len(l); n > 0 && l[n-1] == "test" { 1103 l = l[:n-1] 1104 } 1105 n := len(l) 1106 if n >= 2 && knownOS[l[n-2]] && knownArch[l[n-1]] { 1107 allTags[l[n-2]] = true 1108 allTags[l[n-1]] = true 1109 return l[n-2] == ctxt.GOOS && l[n-1] == ctxt.GOARCH 1110 } 1111 if n >= 1 && knownOS[l[n-1]] { 1112 allTags[l[n-1]] = true 1113 return l[n-1] == ctxt.GOOS 1114 } 1115 if n >= 1 && knownArch[l[n-1]] { 1116 allTags[l[n-1]] = true 1117 return l[n-1] == ctxt.GOARCH 1118 } 1119 return true 1120 } 1121 1122 var knownOS = make(map[string]bool) 1123 var knownArch = make(map[string]bool) 1124 1125 func init() { 1126 for _, v := range strings.Fields(goosList) { 1127 knownOS[v] = true 1128 } 1129 for _, v := range strings.Fields(goarchList) { 1130 knownArch[v] = true 1131 } 1132 } 1133 1134 // ToolDir is the directory containing build tools. 1135 var ToolDir = filepath.Join(runtime.GOROOT(), "pkg/tool/"+runtime.GOOS+"_"+runtime.GOARCH) 1136 1137 // IsLocalImport reports whether the import path is 1138 // a local import path, like ".", "..", "./foo", or "../foo". 1139 func IsLocalImport(path string) bool { 1140 return path == "." || path == ".." || 1141 strings.HasPrefix(path, "./") || strings.HasPrefix(path, "../") 1142 } 1143 1144 // ArchChar returns the architecture character for the given goarch. 1145 // For example, ArchChar("amd64") returns "6". 1146 func ArchChar(goarch string) (string, error) { 1147 switch goarch { 1148 case "386": 1149 return "8", nil 1150 case "amd64": 1151 return "6", nil 1152 case "arm": 1153 return "5", nil 1154 } 1155 return "", errors.New("unsupported GOARCH " + goarch) 1156 }