-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpreter.cs
229 lines (198 loc) · 7.35 KB
/
Interpreter.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JC.MiniLisp_Interpreter.Grammar;
using JC.MiniLisp_Interpreter.Utility;
namespace JC.MiniLisp_Interpreter
{
/// <summary>
/// MiniLisp Interpreter
/// </summary>
public class Interpreter
{
public static Interpreter Instance;
/// <summary>
/// Code
/// </summary>
private string code = "";
/// <summary>
/// Holder of variables defined in this STMT / PROGRAM
/// </summary>
/// <typeparam name="string"></typeparam>
/// <typeparam name="EXP"></typeparam>
/// <returns></returns>
private Dictionary<string, EXP> variables = new Dictionary<string, EXP>();
/// <summary>
/// This value becomes non-null when a func declaration is parsed, and currently parsing its scope.
/// Use Stack because there might be nested fun. NASTY!
/// </summary>
private List<FUN_EXP> funConstructorStack = new List<FUN_EXP>();
/// <summary>
/// Current fun constructor.
/// null = at global scope
/// </summary>
/// <returns></returns>
private FUN_EXP funConstructor => funConstructorStack.Count == 0 ? null : funConstructorStack[funConstructorStack.Count()-1];
/* -------------------------------------------------------------------------- */
public Interpreter() { }
public Interpreter(string lispCode)
{
this.code = lispCode;
Instance = this;
}
/// <summary>
/// Evaluate the code, output result
/// </summary>
/// <returns></returns>
public string Evaluate()
{
// token is either IGrammar or string
List<object> tokens = Scanner(code);
PROGRAM program = Parser(tokens);
return program.Evaluate().ToString();
}
/// <summary>
/// Scan the incomming code to tokens
/// </summary>
/// <returns>token is either IGrammar or string</returns>
private List<object> Scanner(string code)
{
List<object> tokens = new List<object>();
List<string> splitedCode = code
.Replace("(", " ( ")
.Replace(")", " ) ")
.Split(' ', '\n', '\t', '\r') // note: NTR is BADBADBAD!!
.Where(s => !string.IsNullOrWhiteSpace(s))
.ToList();
// scan each string s into token (IGrammar form)
foreach(string s in splitedCode)
{
if(double.TryParse(s, out double value))
{
// token is number
tokens.Add( new EXP(typeof(double), value) );
}
else if(s == "#t" || s == "#f")
{
// token is bool
tokens.Add( new EXP(typeof(bool), s == "#t"));
}
else
{
// fallback: add str
tokens.Add(s);
}
}
return tokens;
}
/// <summary>
/// Top-down parser
/// </summary>
/// <param name="tokens"></param>
public PROGRAM Parser(List<object> tokens)
{
// parser stack
Stack<object> stack = new Stack<object>();
// one in one push the token into stack
foreach(object token in tokens)
{
// Shift one token to stack
// Console.WriteLine("[TOKEN]"+token);
stack.Push(token);
// [Debug] print Stack
stack.DebugLog();
// Fun mode
var funMode = FUN_EXP.CheckFunMode(stack);
if(funMode is FUN_EXP)
{
// start fun mode!
funConstructorStack.Add(funMode);
continue;
}
// fun has its own parser
if(funConstructor?.FeedingFUN_IDs(stack) ?? false)
{
// still fedding the FUN_ID
continue;
}
// flag of end of fun constructor
bool endOfFunConstrutor = funConstructor?.ScanEndOfConstructor(stack) ?? false;
// Check if the stack is altered,
// if it IS altered, keep running.
while( NUM_OP.TryParse(stack)
|| LOGICAL_OP.TryParse(stack)
|| PRINT_STMT.TryParse(stack)
|| DEF_STMT.TryParse(stack)
|| IF_EXP.TryParse(stack)
|| FUN_CALL.TryParse(stack)
|| EXP.TryParse(stack)
)
{
if(stack.Count == 0)
throw new Exception("OMG! Stack is empty!? That's impossipa!!");
}
// end of fun
if(endOfFunConstrutor)
{
funConstructor.EndOfConstructor(stack);
funConstructorStack.RemoveAt(funConstructorStack.Count()-1);
EXP.TryParse(stack); // convert the FUN_CALL directly to EXP
Debug.Log($"[Fun Constructor] Ended {funConstructorStack.Count()+1}, Thank you.");
}
}
// finish parse, now try sum up to PROGRAM
STMT.ParseAll(stack);
return PROGRAM.ParseAll(stack);
}
/// <summary>
/// Check if a variable exist
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public bool ContainsVariable(string id)
{
// find in local var
for(int i = funConstructorStack.Count()-1; i >= 0; i--)
{
var localVar = funConstructorStack[i].HasLocalVar(id);
if(localVar != null)
return true;
}
// get global var
return variables.ContainsKey(id);
}
/// <summary>
/// Get a variable
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public EXP GetVariable(string id)
{
if(!ContainsVariable(id))
throw new Exception($"Undefined variable \"{id}\".");
// local var
for(int i = funConstructorStack.Count()-1; i >= 0; i--)
{
var localVar = funConstructorStack[i].HasLocalVar(id);
if(localVar != null)
return localVar;
}
return variables[id];
}
/// <summary>
/// Set a variable
/// throw error when the variable exist OR id is invalid
/// </summary>
/// <param name="id"></param>
/// <param name="exp"></param>
public void SetVariable(string id, EXP exp)
{
// setting local var is not here, should be at FUN constructor.
id.CheckLegalId();
if(variables.ContainsKey(id))
throw new Exception($"Variable \"{id}\" is already exist.");
variables.Add(id, exp);
}
}
}