-
Notifications
You must be signed in to change notification settings - Fork 0
/
lox_functions.go
56 lines (49 loc) · 1.28 KB
/
lox_functions.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
package main
import (
"errors"
)
type LoxFunction struct {
name string
declaration FunctionStmt
closure *Env
isInitlializer bool
}
func newLoxFunction(stmt FunctionStmt, env *Env, isInitlializer bool) *LoxFunction {
return &LoxFunction{
declaration: stmt,
name: stmt.name.Lexeme,
closure: env,
isInitlializer: isInitlializer,
}
}
func (f *LoxFunction) String() string {
return "<function: " + f.name + ">"
}
func (f *LoxFunction) Arity() int {
return len(f.declaration.params)
}
func (f *LoxFunction) Call(intp Interpreter, args []interface{}) (interface{}, error) {
env := newEnvWithEnclosing(f.closure)
for i, v := range f.declaration.params {
env.Define(v.Lexeme, args[i])
}
if err := intp.ExecuteBlock(f.declaration.stmts, env); err != nil {
var returnValue Return
if errors.As(err, &returnValue) {
if f.isInitlializer {
return f.closure.GetAtByVarName(0, "this")
}
return returnValue.Value, nil
}
return nil, err
}
if f.isInitlializer {
return f.closure.GetAtByVarName(0, "this")
}
return nil, nil
}
func (f *LoxFunction) Bind(instance *LoxInstance) (*LoxFunction, error) {
env := newEnvWithEnclosing(f.closure)
env.Define("this", instance)
return newLoxFunction(f.declaration, env, f.isInitlializer), nil
}