-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass.go
69 lines (57 loc) · 1.44 KB
/
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
package main
// LoxClass implements LoxCallable
type LoxClass struct {
name string
superclass *LoxClass
methods map[string]LoxFunction
}
func NewLoxClass(name string, superclass *LoxClass, methods map[string]LoxFunction) *LoxClass {
return &LoxClass{name, superclass, methods}
}
func (l *LoxClass) arity() int {
initializer := l.findMethod("init")
if initializer == nil {
return 0
}
return initializer.arity()
}
func (l *LoxClass) call(interpreter *Interpreter, args []interface{}) interface{} {
instance := LoxInstance{*l, map[string]interface{}{}}
initializer := l.findMethod("init")
if initializer != nil {
initializer.bind(&instance).call(interpreter, args)
}
return instance
}
func (l *LoxClass) findMethod(name string) *LoxFunction {
if v, ok := l.methods[name]; ok {
return &v
}
if l.superclass != nil {
return l.superclass.findMethod(name)
}
return nil
}
func (l LoxClass) String() string {
return l.name
}
type LoxInstance struct {
class LoxClass
fields map[string]interface{}
}
func (l *LoxInstance) get(name Token) interface{} {
if v, ok := l.fields[name.lexeme]; ok {
return v
}
method := l.class.findMethod(name.lexeme)
if method != nil {
return method.bind(l)
}
panic(NewRuntimeError(name, "undefined property '"+name.lexeme+"'."))
}
func (l *LoxInstance) set(name Token, value interface{}) {
l.fields[name.lexeme] = value
}
func (l LoxInstance) String() string {
return l.class.name + " instance"
}