-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoxFunction.cs
61 lines (53 loc) · 1.79 KB
/
LoxFunction.cs
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
using System.Collections.Generic;
// group members: Peter Zhang, Madeline Moore, Cara Cannarozzi
// Crafting Interpreters book by Robert Nystrom used as a reference
// https://craftinginterpreters.com/contents.html
namespace LoxInterpreter
{
/// <summary>
/// implements ILoxCallable so it can be implemented
/// </summary>
public class LoxFunction : ILoxCallable
{
private readonly Environment closure;
private readonly Stmt.Function declaration;
/// <summary>
/// initializes environment from closure (constructor)
/// </summary>
/// <param name="declaration"></param>
/// <param name="closure"></param>
public LoxFunction(Stmt.Function declaration, Environment closure)
{
this.closure = closure;
this.declaration = declaration;
}
// returns arity of function
public int Arity()
{
return declaration.parms.Count;
}
// implements call() of ILoxCallable
public object Call(Interpreter interpreter, List<object> arguments)
{
// creates environment from args
var environment = new Environment(closure);
for (var i = 0; i < declaration.parms.Count; i++)
environment.Define(declaration.parms[i].lexeme, arguments[i]);
// executes function call
try
{
interpreter.ExecuteBlock(declaration.body, environment);
}
catch (Return returnValue)
{
return returnValue.Value;
}
return null;
}
// turns function into a string
public override string ToString()
{
return "<fn " + declaration.name.lexeme + ">";
}
}
}