-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgolox_class.go
51 lines (43 loc) · 1.05 KB
/
golox_class.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
package golox
type GoLoxClass struct {
Name string
Superclass *GoLoxClass
Methods map[string]*GoLoxFunction
}
func NewGoLoxClass(name string, superclass *GoLoxClass, methods map[string]*GoLoxFunction) *GoLoxClass {
return &GoLoxClass{
Name: name,
Superclass: superclass,
Methods: methods,
}
}
func (lc *GoLoxClass) FindMethod(name string) (*GoLoxFunction, error) {
if v, ok := lc.Methods[name]; ok {
return v, nil
}
if lc.Superclass != nil {
return lc.Superclass.FindMethod(name)
}
return nil, nil
}
func (lc *GoLoxClass) Call(interpreter *Interpreter, arguments []interface{}) (interface{}, error) {
instance := NewGoLoxInstance(lc)
initializer, err := lc.FindMethod("init")
if err != nil {
return nil, err
}
if initializer != nil {
initializer.Bind(instance).Call(interpreter, arguments)
}
return instance, nil
}
func (lc *GoLoxClass) Arity() int {
initializer, _ := lc.FindMethod("init")
if initializer == nil {
return 0
}
return initializer.Arity()
}
func (lc *GoLoxClass) String() string {
return lc.Name
}