forked from zhemao/glisp
/
scopes.go
53 lines (44 loc) · 1.2 KB
/
scopes.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
package glisp
import (
"errors"
"fmt"
)
type Scope map[int]Sexp
func (s Scope) IsStackElem() {}
func (stack *Stack) PushScope() {
stack.Push(Scope(make(map[int]Sexp)))
}
func (stack *Stack) PopScope() error {
_, err := stack.Pop()
return err
}
func (stack *Stack) lookupSymbol(sym SexpSymbol, minFrame int) (Sexp, error) {
if !stack.IsEmpty() {
for i := 0; i <= stack.tos-minFrame; i++ {
elem, err := stack.Get(i)
if err != nil {
return SexpNull, err
}
scope := map[int]Sexp(elem.(Scope))
expr, ok := scope[sym.number]
if ok {
return expr, nil
}
}
}
return SexpNull, errors.New(fmt.Sprint("symbol ", sym, " not found"))
}
func (stack *Stack) LookupSymbol(sym SexpSymbol) (Sexp, error) {
return stack.lookupSymbol(sym, 0)
}
// LookupSymbolNonGlobal - closures use this to only find symbols below the global scope, to avoid copying globals it'll always be-able to ref
func (stack *Stack) LookupSymbolNonGlobal(sym SexpSymbol) (Sexp, error) {
return stack.lookupSymbol(sym, 1)
}
func (stack *Stack) BindSymbol(sym SexpSymbol, expr Sexp) error {
if stack.IsEmpty() {
return errors.New("no scope available")
}
stack.elements[stack.tos].(Scope)[sym.number] = expr
return nil
}