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 Direct bool // imported directly
37 // NewPkg returns a new Pkg for the given package path and name.
38 // Unless name is the empty string, if the package exists already,
39 // the existing package name and the provided name must match.
40 func NewPkg(path, name string) *Pkg {
41 if p := pkgMap[path]; p != nil {
42 if name != "" && p.Name != name {
43 panic(fmt.Sprintf("conflicting package names %s and %s for path %q", p.Name, name, path))
51 if path == "go.shape" {
52 // Don't escape "go.shape", since it's not needed (it's a builtin
53 // package), and we don't want escape codes showing up in shape type
54 // names, which also appear in names of function/method
58 p.Prefix = objabi.PathToPrefix(path)
60 p.Syms = make(map[string]*Sym)
66 // ImportedPkgList returns the list of directly imported packages.
67 // The list is sorted by package path.
68 func ImportedPkgList() []*Pkg {
70 for _, p := range pkgMap {
72 list = append(list, p)
75 sort.Sort(byPath(list))
81 func (a byPath) Len() int { return len(a) }
82 func (a byPath) Less(i, j int) bool { return a[i].Path < a[j].Path }
83 func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
86 Syms: make(map[string]*Sym),
89 func (pkg *Pkg) Lookup(name string) *Sym {
90 s, _ := pkg.LookupOK(name)
94 // LookupOK looks up name in pkg and reports whether it previously existed.
95 func (pkg *Pkg) LookupOK(name string) (s *Sym, existed bool) {
96 // TODO(gri) remove this check in favor of specialized lookup
100 if s := pkg.Syms[name]; s != nil {
112 func (pkg *Pkg) LookupBytes(name []byte) *Sym {
113 // TODO(gri) remove this check in favor of specialized lookup
117 if s := pkg.Syms[string(name)]; s != nil {
120 str := InternString(name)
121 return pkg.Lookup(str)
125 internedStringsmu sync.Mutex // protects internedStrings
126 internedStrings = map[string]string{}
129 func InternString(b []byte) string {
130 internedStringsmu.Lock()
131 s, ok := internedStrings[string(b)] // string(b) here doesn't allocate
134 internedStrings[s] = s
136 internedStringsmu.Unlock()
140 // CleanroomDo invokes f in an environment with no preexisting packages.
141 // For testing of import/export only.
142 func CleanroomDo(f func()) {
144 pkgMap = make(map[string]*Pkg)