-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLoxFunction.js
48 lines (39 loc) · 1.24 KB
/
LoxFunction.js
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
const Environment = require('./Environment');
class LoxFunction {
constructor(declaration, closure, isInitializer) {
this.declaration = declaration;
this.closure = closure;
this.isInitializer = isInitializer;
this.call = this.call.bind(this);
this.arity = this.arity.bind(this);
this.bind = this.bind.bind(this);
}
bind(instance) {
const environment = new Environment(this.closure);
environment.define('this', instance);
return new LoxFunction(this.declaration, environment,
this.isInitializer);
}
call(interpreter, args) {
const environment = new Environment(this.closure);
for (let i = 0; i < this.declaration.params.length; i++) {
environment.define(this.declaration.params[i].lexeme,
args[i]);
}
try {
interpreter.executeBlock(this.declaration.body, environment);
} catch (returnValue) {
if (this.isInitializer) return this.closure.getAt(0, 'this');
return returnValue.value;
}
if (this.isInitializer) return this.closure.getAt(0, 'this');
return null;
}
arity() {
return this.declaration.params.length;
}
toString() {
return `<fn ${this.declaration.name.lexeme}>`;
}
}
module.exports = LoxFunction;