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.
14 // pkgMap maps a package path to a package.
15 var pkgMap = make(map[string]*Pkg)
18 Path string // string literal used in import statement, e.g. "runtime/internal/sys"
19 Name string // package name, e.g. "sys"
21 Prefix string // escaped path for use in symbol table
22 Imported bool // export data of this package was parsed
23 Direct bool // imported directly
27 // NewPkg returns a new Pkg for the given package path and name.
28 // Unless name is the empty string, if the package exists already,
29 // the existing package name and the provided name must match.
30 func NewPkg(path, name string) *Pkg {
31 if p := pkgMap[path]; p != nil {
32 if name != "" && p.Name != name {
33 panic(fmt.Sprintf("conflicting package names %s and %s for path %q", p.Name, name, path))
41 p.Prefix = objabi.PathToPrefix(path)
42 p.Syms = make(map[string]*Sym)
48 // ImportedPkgList returns the list of directly imported packages.
49 // The list is sorted by package path.
50 func ImportedPkgList() []*Pkg {
52 for _, p := range pkgMap {
54 list = append(list, p)
57 sort.Sort(byPath(list))
63 func (a byPath) Len() int { return len(a) }
64 func (a byPath) Less(i, j int) bool { return a[i].Path < a[j].Path }
65 func (a byPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
68 Syms: make(map[string]*Sym),
71 func (pkg *Pkg) Lookup(name string) *Sym {
72 s, _ := pkg.LookupOK(name)
78 // LookupOK looks up name in pkg and reports whether it previously existed.
79 func (pkg *Pkg) LookupOK(name string) (s *Sym, existed bool) {
80 // TODO(gri) remove this check in favor of specialized lookup
84 if s := pkg.Syms[name]; s != nil {
93 InitSyms = append(InitSyms, s)
99 func (pkg *Pkg) LookupBytes(name []byte) *Sym {
100 // TODO(gri) remove this check in favor of specialized lookup
104 if s := pkg.Syms[string(name)]; s != nil {
107 str := InternString(name)
108 return pkg.Lookup(str)
111 var internedStrings = map[string]string{}
113 func InternString(b []byte) string {
114 s, ok := internedStrings[string(b)] // string(b) here doesn't allocate
117 internedStrings[s] = s
122 // CleanroomDo invokes f in an environment with with no preexisting packages.
123 // For testing of import/export only.
124 func CleanroomDo(f func()) {
126 pkgMap = make(map[string]*Pkg)