-
Notifications
You must be signed in to change notification settings - Fork 0
/
lox_class.go
72 lines (63 loc) · 1.38 KB
/
lox_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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import "fmt"
type LoxClass struct {
superclass *LoxClass
name string
methods map[string]*LoxFunction
}
func newLoxClass(name string) *LoxClass {
return &LoxClass{
name: name,
}
}
func newLoxClassWithMethods(name string, methods map[string]*LoxFunction) *LoxClass {
return &LoxClass{
name: name,
methods: methods,
}
}
func newLoxClassWithSuperClass(name string, superclass *LoxClass, methods map[string]*LoxFunction) *LoxClass {
return &LoxClass{
name: name,
methods: methods,
superclass: superclass,
}
}
func (c *LoxClass) String() string {
return fmt.Sprintf("<class: %s >", c.name)
}
func (c *LoxClass) Arity() int {
initFunction, err := c.FindMethod("init")
if err != nil {
return 0
}
if initFunction != nil {
return initFunction.Arity()
}
return 0
}
func (c *LoxClass) Call(intp Interpreter, args []interface{}) (interface{}, error) {
instance := newLoxInstance(c)
initFunction, err := c.FindMethod("init")
if err != nil {
return nil, err
}
if initFunction != nil {
initliazer, err := initFunction.Bind(instance)
if err != nil {
return nil, err
}
return initliazer.Call(intp, args)
}
return instance, nil
}
func (c *LoxClass) FindMethod(name string) (*LoxFunction, error) {
v, ok := c.methods[name]
if ok {
return v, nil
}
if c.superclass != nil {
return c.superclass.FindMethod(name)
}
return nil, nil
}