This repository has been archived by the owner on May 19, 2019. It is now read-only.
/
FunctionExpression.cs
103 lines (91 loc) · 2.63 KB
/
FunctionExpression.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System;
using System.Collections.Generic;
namespace LPS.ToolScript.Parser
{
/// <summary>
/// This is not function call,
/// this is function declaration % definition
/// </summary>
public class FunctionExpression: ExpressionBase, IFunction
{
/// <summary>
/// can be null
/// </summary>
public string Name { get; private set; }
public NamedArgumentList Parameters { get; private set; }
public IStatement Body { get; private set; }
public FunctionExpression(string name, NamedArgumentList parameters, IStatement body)
{
this.Name = name;
this.Parameters = parameters;
this.Body = body;
}
private IExecutionContext Context;
public override object Eval (IExecutionContext context)
{
this.Context = context.CreateChildContext();
Parameters.Run(context);
if(this.Name != null)
context.InitVariable(this.Name, this);
return this;
}
public object Execute(NamedArgumentList arguments)
{
try
{
Parameters.InitVariables(this.Context, arguments);
Body.Run(this.Context);
return SpecialValue.Void;
}
catch(IterationTermination info)
{
if(info.Reason == TerminationReason.Return)
return info.ReturnValue;
else
throw new InvalidOperationException("volání funkce bylo přerušeno jiným důvodem než return: " + info.Reason.ToString());
}
}
private class EventHandlerHelper
{
private FunctionExpression Func;
private IExecutionContext CustomContext;
public EventHandlerHelper(FunctionExpression Func, IExecutionContext CustomContext)
{
this.Func = Func;
this.CustomContext = CustomContext;
}
public void Invoke(object sender, EventArgs args)
{
IExecutionContext context;
if(CustomContext != null)
context = CustomContext.CreateChildContext();
else
context = Func.Context.CreateChildContext();
try
{
context.InitVariable("sender", sender);
context.InitVariable("args", args);
Func.Body.Run(context);
}
catch(IterationTermination info)
{
if(info.Reason != TerminationReason.Return)
throw new InvalidOperationException("volání funkce bylo přerušeno jiným důvodem než return: " + info.Reason.ToString());
}
finally
{
context.Dispose();
}
}
}
public Delegate GetEventHandler(Type EventHandlerType, IExecutionContext CustomContext)
{
EventHandlerHelper helper = new EventHandlerHelper(this, CustomContext);
return Delegate.CreateDelegate(EventHandlerType, helper, typeof(EventHandlerHelper).GetMethod("Invoke"));
}
public override string ToString ()
{
return string.Format("function({0})", Parameters.ToString());
}
}
}