Source file
src/go/ast/scope.go
1
2
3
4
5
6
7 package ast
8
9 import (
10 "fmt"
11 "go/token"
12 "strings"
13 )
14
15
16
17
18 type Scope struct {
19 Outer *Scope
20 Objects map[string]*Object
21 }
22
23
24 func NewScope(outer *Scope) *Scope {
25 const n = 4
26 return &Scope{outer, make(map[string]*Object, n)}
27 }
28
29
30
31
32 func (s *Scope) Lookup(name string) *Object {
33 return s.Objects[name]
34 }
35
36
37
38
39
40 func (s *Scope) Insert(obj *Object) (alt *Object) {
41 if alt = s.Objects[obj.Name]; alt == nil {
42 s.Objects[obj.Name] = obj
43 }
44 return
45 }
46
47
48 func (s *Scope) String() string {
49 var buf strings.Builder
50 fmt.Fprintf(&buf, "scope %p {", s)
51 if s != nil && len(s.Objects) > 0 {
52 fmt.Fprintln(&buf)
53 for _, obj := range s.Objects {
54 fmt.Fprintf(&buf, "\t%s %s\n", obj.Kind, obj.Name)
55 }
56 }
57 fmt.Fprintf(&buf, "}\n")
58 return buf.String()
59 }
60
61
62
63
64
65
66
67
68
69
70
71
72 type Object struct {
73 Kind ObjKind
74 Name string
75 Decl any
76 Data any
77 Type any
78 }
79
80
81 func NewObj(kind ObjKind, name string) *Object {
82 return &Object{Kind: kind, Name: name}
83 }
84
85
86
87
88 func (obj *Object) Pos() token.Pos {
89 name := obj.Name
90 switch d := obj.Decl.(type) {
91 case *Field:
92 for _, n := range d.Names {
93 if n.Name == name {
94 return n.Pos()
95 }
96 }
97 case *ImportSpec:
98 if d.Name != nil && d.Name.Name == name {
99 return d.Name.Pos()
100 }
101 return d.Path.Pos()
102 case *ValueSpec:
103 for _, n := range d.Names {
104 if n.Name == name {
105 return n.Pos()
106 }
107 }
108 case *TypeSpec:
109 if d.Name.Name == name {
110 return d.Name.Pos()
111 }
112 case *FuncDecl:
113 if d.Name.Name == name {
114 return d.Name.Pos()
115 }
116 case *LabeledStmt:
117 if d.Label.Name == name {
118 return d.Label.Pos()
119 }
120 case *AssignStmt:
121 for _, x := range d.Lhs {
122 if ident, isIdent := x.(*Ident); isIdent && ident.Name == name {
123 return ident.Pos()
124 }
125 }
126 case *Scope:
127
128 }
129 return token.NoPos
130 }
131
132
133 type ObjKind int
134
135
136 const (
137 Bad ObjKind = iota
138 Pkg
139 Con
140 Typ
141 Var
142 Fun
143 Lbl
144 )
145
146 var objKindStrings = [...]string{
147 Bad: "bad",
148 Pkg: "package",
149 Con: "const",
150 Typ: "type",
151 Var: "var",
152 Fun: "func",
153 Lbl: "label",
154 }
155
156 func (kind ObjKind) String() string { return objKindStrings[kind] }
157
View as plain text