-
Notifications
You must be signed in to change notification settings - Fork 1
/
scope.go
84 lines (73 loc) · 1.87 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
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"errors"
"fmt"
"log"
"os"
)
type Scope struct {
parent *Scope
variables map[string]RuntimeVal
}
func NewScope(parent *Scope) *Scope {
return &Scope{
parent: parent,
variables: make(map[string]RuntimeVal),
}
}
func NewGlobalScope() *Scope {
globalScope := NewScope(nil)
globalScope.DeclareVar("true", NewBoolVal(true))
globalScope.DeclareVar("false", NewBoolVal(false))
globalScope.DeclareVar("đúng", NewBoolVal(true))
globalScope.DeclareVar("sai", NewBoolVal(false))
globalScope.DeclareVar("print", PrintFunc)
globalScope.DeclareVar("in", PrintFunc)
globalScope.DeclareVar("count", CountFunc)
globalScope.DeclareVar("đếm", CountFunc)
globalScope.DeclareVar("input", InputFunc)
globalScope.DeclareVar("nhập", InputFunc)
globalScope.DeclareVar("abs", NewNativeFuncVal(func(scope *Scope, args ...RuntimeVal) RuntimeVal {
if args[0].Value().(int) < 0 {
return NewIntVal(-args[0].Value().(int))
}
return args[0]
}))
globalScope.DeclareVar("exit", NewNativeFuncVal(func(scope *Scope, args ...RuntimeVal) RuntimeVal {
fmt.Println("Good bye")
os.Exit(0)
return NullVal{}
}))
return globalScope
}
func (s *Scope) DeclareVar(name string, value RuntimeVal) RuntimeVal {
if s.variables[name] != nil {
log.Panic("variable already defined")
}
s.variables[name] = value
return value
}
func (s *Scope) AssignVar(name string, value RuntimeVal) RuntimeVal {
scope, err := s.resolve(name)
if err != nil {
return NullVal{}
}
scope.variables[name] = value
return value
}
func (s *Scope) GetVarVal(name string) RuntimeVal {
scope, err := s.resolve(name)
if err != nil {
return NullVal{}
}
return scope.variables[name]
}
func (s *Scope) resolve(name string) (*Scope, error) {
if s.variables[name] != nil {
return s, nil
}
if s.parent == nil {
return nil, errors.New("variable not found")
}
return s.parent.resolve(name)
}