/
scope.go
73 lines (61 loc) · 1.45 KB
/
scope.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package ast
import (
"bytes"
"fmt"
)
type Scope struct {
Parent *Scope
Objects map[string]*Object
}
func NewScope(parent *Scope) *Scope {
return &Scope{Parent: parent, Objects: make(map[string]*Object, 4)}
}
func (s *Scope) Lookup(name string) *Object {
return s.Objects[name]
}
func (s *Scope) Insert(obj *Object) (alt *Object) {
if alt = s.Objects[obj.Name]; alt == nil {
s.Objects[obj.Name] = obj
}
return
}
// Debugging support
func (s *Scope) String() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "Scope %p {", s)
if s != nil && len(s.Objects) > 0 {
fmt.Fprintln(&buf)
for _, obj := range s.Objects {
fmt.Fprintf(&buf, "\t%s %s\n", obj.Kind, obj.Name)
}
}
fmt.Fprintf(&buf, "}\n")
return buf.String()
}
type Object struct {
Name string
Kind ObjectKind
Decl interface{}
}
// ObjectKind describes what an object represents.
type ObjectKind int
// The list of possible Object kinds.
const (
Bad ObjectKind = iota // for error handling
Pkg // package
Var // variable
Fun // function
Mixin // mixin
)
var objectKindStrings = [...]string{
Bad: "bad",
Pkg: "package",
Var: "var",
Fun: "func",
Mixin: "mixin",
}
func (kind ObjectKind) String() string { return objectKindStrings[kind] }
// This function creates a new object of a given kind and name.
func NewObject(kind ObjectKind, name string) *Object {
return &Object{Kind: kind, Name: name}
}