-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass.go
More file actions
55 lines (44 loc) · 1.14 KB
/
Copy pathclass.go
File metadata and controls
55 lines (44 loc) · 1.14 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
package main
// Classes implement Callable and Object
type Class struct {
Name string
Methods map[string]*Function
StaticMethods map[string]*Function
}
func (c *Class) Get(name Token) (any, error) {
if meth, ok := c.StaticMethods[name.lexeme]; ok {
return meth, nil
}
return nil, RuntimeError{
name, "Undefined class method '" + name.lexeme + "'.",
}
}
func (c *Class) Set(name Token, value any) error {
if meth, ok := value.(*Function); ok {
c.StaticMethods[name.lexeme] = meth
return nil
}
// For now, I won't allow for class variables (i.e. cls.foo = "bar")
return RuntimeError{
name, "Can only assign non-anonymous methods to classes.",
}
}
func (c *Class) Call(interpreter *Interpreter, arguments []any) any {
instance := &Instance{c, make(map[string]any)}
if initializer, ok := c.Methods["init"]; ok {
ret := initializer.Bind(instance).Call(interpreter, arguments)
if err, ok := ret.(error); ok {
return err
}
}
return instance
}
func (c Class) Arity() int {
if initializer, ok := c.Methods["init"]; ok {
return initializer.Arity()
}
return 0
}
func (c Class) String() string {
return c.Name
}