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.
15 // pkgMap maps a package path to a package.
16 var pkgMap = make(map[string]*Pkg)
18 // MaxPkgHeight is a height greater than any likely package height.
19 const MaxPkgHeight = 1e9
22 Path string // string literal used in import statement, e.g. "runtime/internal/sys"
23 Name string // package name, e.g. "sys"
24 Prefix string // escaped path for use in symbol table
28 // Height is the package's height in the import graph. Leaf
29 // packages (i.e., packages with no imports) have height 0,
30 // and all other packages have height 1 plus the maximum
31 // height of their imported packages.
34 Imported bool // export data of this package was parsed
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 p.Prefix = objabi.PathToPrefix(path)
53 p.Syms = make(map[string]*Sym)
59 // ImportedPkgList returns the list of directly imported packages.
60 // The list is sorted by package path.
61 func ImportedPkgList() []*Pkg {
63 for _, p := range pkgMap {
65 list = append(list, p)
68 sort.Sort(byPath(list))
74 func (a byPath) Len() int { return len(a) }
75 func (a byPath) Less(i, j int) bool { return a[i].Path < a[j].Path }
76 func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
79 Syms: make(map[string]*Sym),
82 func (pkg *Pkg) Lookup(name string) *Sym {
83 s, _ := pkg.LookupOK(name)
87 // LookupOK looks up name in pkg and reports whether it previously existed.
88 func (pkg *Pkg) LookupOK(name string) (s *Sym, existed bool) {
89 // TODO(gri) remove this check in favor of specialized lookup
93 if s := pkg.Syms[name]; s != nil {
105 func (pkg *Pkg) LookupBytes(name []byte) *Sym {
106 // TODO(gri) remove this check in favor of specialized lookup
110 if s := pkg.Syms[string(name)]; s != nil {
113 str := InternString(name)
114 return pkg.Lookup(str)
118 internedStringsmu sync.Mutex // protects internedStrings
119 internedStrings = map[string]string{}
122 func InternString(b []byte) string {
123 internedStringsmu.Lock()
124 s, ok := internedStrings[string(b)] // string(b) here doesn't allocate
127 internedStrings[s] = s
129 internedStringsmu.Unlock()
133 // CleanroomDo invokes f in an environment with no preexisting packages.
134 // For testing of import/export only.
135 func CleanroomDo(f func()) {
137 pkgMap = make(map[string]*Pkg)