1 // Copyright 2017 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.
16 // pkgMap maps a package path to a package.
17 var pkgMap = make(map[string]*Pkg)
19 // MaxPkgHeight is a height greater than any likely package height.
20 const MaxPkgHeight = 1e9
23 Path string // string literal used in import statement, e.g. "runtime/internal/sys"
24 Name string // package name, e.g. "sys"
25 Prefix string // escaped path for use in symbol table
29 // Height is the package's height in the import graph. Leaf
30 // packages (i.e., packages with no imports) have height 0,
31 // and all other packages have height 1 plus the maximum
32 // height of their imported packages.
35 Direct bool // imported directly
38 // NewPkg returns a new Pkg for the given package path and name.
39 // Unless name is the empty string, if the package exists already,
40 // the existing package name and the provided name must match.
41 func NewPkg(path, name string) *Pkg {
42 if p := pkgMap[path]; p != nil {
43 if name != "" && p.Name != name {
44 panic(fmt.Sprintf("conflicting package names %s and %s for path %q", p.Name, name, path))
52 if strings.HasPrefix(path, "go.") {
53 // Special compiler-internal packages don't need to be escaped.
54 // This particularly helps with the go.shape package.
57 p.Prefix = objabi.PathToPrefix(path)
59 p.Syms = make(map[string]*Sym)
65 // ImportedPkgList returns the list of directly imported packages.
66 // The list is sorted by package path.
67 func ImportedPkgList() []*Pkg {
69 for _, p := range pkgMap {
71 list = append(list, p)
74 sort.Sort(byPath(list))
80 func (a byPath) Len() int { return len(a) }
81 func (a byPath) Less(i, j int) bool { return a[i].Path < a[j].Path }
82 func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
85 Syms: make(map[string]*Sym),
88 func (pkg *Pkg) Lookup(name string) *Sym {
89 s, _ := pkg.LookupOK(name)
93 // LookupOK looks up name in pkg and reports whether it previously existed.
94 func (pkg *Pkg) LookupOK(name string) (s *Sym, existed bool) {
95 // TODO(gri) remove this check in favor of specialized lookup
99 if s := pkg.Syms[name]; s != nil {
111 func (pkg *Pkg) LookupBytes(name []byte) *Sym {
112 // TODO(gri) remove this check in favor of specialized lookup
116 if s := pkg.Syms[string(name)]; s != nil {
119 str := InternString(name)
120 return pkg.Lookup(str)
124 internedStringsmu sync.Mutex // protects internedStrings
125 internedStrings = map[string]string{}
128 func InternString(b []byte) string {
129 internedStringsmu.Lock()
130 s, ok := internedStrings[string(b)] // string(b) here doesn't allocate
133 internedStrings[s] = s
135 internedStringsmu.Unlock()
139 // CleanroomDo invokes f in an environment with no preexisting packages.
140 // For testing of import/export only.
141 func CleanroomDo(f func()) {
143 pkgMap = make(map[string]*Pkg)