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)
19 Path string // string literal used in import statement, e.g. "runtime/internal/sys"
20 Name string // package name, e.g. "sys"
21 Prefix string // escaped path for use in symbol table
25 Direct bool // imported directly
28 // NewPkg returns a new Pkg for the given package path and name.
29 // Unless name is the empty string, if the package exists already,
30 // the existing package name and the provided name must match.
31 func NewPkg(path, name string) *Pkg {
32 if p := pkgMap[path]; p != nil {
33 if name != "" && p.Name != name {
34 panic(fmt.Sprintf("conflicting package names %s and %s for path %q", p.Name, name, path))
42 if path == "go.shape" {
43 // Don't escape "go.shape", since it's not needed (it's a builtin
44 // package), and we don't want escape codes showing up in shape type
45 // names, which also appear in names of function/method
49 p.Prefix = objabi.PathToPrefix(path)
51 p.Syms = make(map[string]*Sym)
57 func PkgMap() map[string]*Pkg {
62 Syms: make(map[string]*Sym),
65 func (pkg *Pkg) Lookup(name string) *Sym {
66 s, _ := pkg.LookupOK(name)
70 // LookupOK looks up name in pkg and reports whether it previously existed.
71 func (pkg *Pkg) LookupOK(name string) (s *Sym, existed bool) {
72 // TODO(gri) remove this check in favor of specialized lookup
76 if s := pkg.Syms[name]; s != nil {
88 func (pkg *Pkg) LookupBytes(name []byte) *Sym {
89 // TODO(gri) remove this check in favor of specialized lookup
93 if s := pkg.Syms[string(name)]; s != nil {
96 str := InternString(name)
97 return pkg.Lookup(str)
100 // LookupNum looks up the symbol starting with prefix and ending with
101 // the decimal n. If prefix is too long, LookupNum panics.
102 func (pkg *Pkg) LookupNum(prefix string, n int) *Sym {
103 var buf [20]byte // plenty long enough for all current users
105 b := strconv.AppendInt(buf[:len(prefix)], int64(n), 10)
106 return pkg.LookupBytes(b)
109 // Selector looks up a selector identifier.
110 func (pkg *Pkg) Selector(name string) *Sym {
111 if IsExported(name) {
114 return pkg.Lookup(name)
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)