-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglox_class.go
More file actions
87 lines (75 loc) · 1.8 KB
/
glox_class.go
File metadata and controls
87 lines (75 loc) · 1.8 KB
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
85
86
87
package main
import (
"fmt"
)
type GloxClass struct {
Name string
Methods map[string]GloxFunction
Superclass *GloxClass
}
type GloxInstance struct {
Klass *GloxClass
Fields map[string]interface{}
}
func NewGloxClass(name string, methods map[string]GloxFunction, superclass *GloxClass) GloxClass {
return GloxClass{
Name: name,
Methods: methods,
Superclass: superclass,
}
}
func NewGloxInstance(klass GloxClass) GloxInstance {
return GloxInstance{
Klass: &klass,
Fields: make(map[string]interface{}),
}
}
func (c GloxClass) String() string {
return fmt.Sprintf("%s", c.Name)
}
func (c *GloxClass) FindMethod(name string) *GloxFunction {
if value, ok := c.Methods[name]; ok {
return &value
} else {
if c.Superclass != nil {
return c.Superclass.FindMethod(name)
}
return nil
}
}
func (i GloxInstance) String() string {
return fmt.Sprintf("%s Instance", i.Klass.Name)
}
func (f GloxClass) Arity() int {
if initializer, ok := f.Methods["init"]; ok {
return initializer.Arity()
}
return 0
}
func (f GloxClass) Call(interpreter *Interpreter, arguments []interface{}) (interface{}, error) {
instance := NewGloxInstance(f)
if initializer, ok := f.Methods["init"]; ok {
_, err := initializer.Bind(&instance).Call(interpreter, arguments)
if err != nil {
return nil, err
}
}
return instance, nil
}
func (i *GloxInstance) Get(name Token) (interface{}, error) {
if value, ok := i.Fields[name.Lexeme]; ok {
return value, nil
} else {
method := i.Klass.FindMethod(name.Lexeme)
if method != nil {
return method.Bind(i), nil
}
return nil, &RuntimeError{
token: name,
message: fmt.Sprintf("Undefined propety '%v'", name.Lexeme),
}
}
}
func (i *GloxInstance) Set(name Token, value interface{}) {
i.Fields[name.Lexeme] = value
}