-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMuftecLibSystem.cs
333 lines (286 loc) · 11.9 KB
/
MuftecLibSystem.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Muftec.Lib
{
public delegate void OpCodePointer(OpCodeData stack);
public class MuftecLibSystem
{
public class OpCodeItem
{
public OpCodeAttribute Attribute { get; set; }
public OpCodePointer Pointer { get; set; }
}
private readonly Dictionary<string, OpCodeItem> _opcodeCache = new Dictionary<string, OpCodeItem>();
private readonly Dictionary<string, MuftecStackItem> _globalVariableList = new Dictionary<string, MuftecStackItem>();
private readonly Dictionary<string, Queue<MuftecStackItem>> _globalFunctionList = new Dictionary<string, Queue<MuftecStackItem>>();
private readonly Dictionary<string, string> _globalDefineList = new Dictionary<string, string>();
private readonly List<IMuftecClassLibrary> _libraryList = new List<IMuftecClassLibrary>();
/// <summary>
/// Register special opcodes that must be handled from inside THIS class
/// </summary>
public MuftecLibSystem()
{
var internalOps = new OpCodePointer[] {ReadVariable, SetVariable, LoadLibraryDLL};
AddOpToCache(internalOps);
}
#region Opcode cache functions
/// <summary>
/// Add an opcode to the cache.
/// </summary>
/// <param name="item">Opcode item to add.</param>
private void AddOpToCache(OpCodeItem item)
{
_opcodeCache.Add(item.Attribute.OpCodeName, item);
if (item.Attribute.Aliases != null)
{
foreach (var alias in item.Attribute.Aliases)
{
_opcodeCache.Add(alias, item);
}
}
}
/// <summary>
/// Add an opcode to the cache.
/// </summary>
/// <param name="pointer">Opcode pointer to add.</param>
private void AddOpToCache(OpCodePointer pointer)
{
var newItem = new OpCodeItem
{
Pointer = pointer,
Attribute = pointer.Method.GetCustomAttributes(typeof(OpCodeAttribute), false).FirstOrDefault() as OpCodeAttribute
};
AddOpToCache(newItem);
}
/// <summary>
/// Add multiple opcodes to the cache.
/// </summary>
/// <param name="pointers">Opcode pointers to add.</param>
private void AddOpToCache(IEnumerable<OpCodePointer> pointers)
{
foreach (var pointer in pointers)
{
AddOpToCache(pointer);
}
}
#endregion
#region Internal opcodes
[OpCode("!", Extern = true)]
private void ReadVariable(OpCodeData data)
{
var item = data.RuntimeStack.Pop(MuftecType.Variable);
if (_globalVariableList.ContainsKey(item.Item.ToString()))
{
data.RuntimeStack.Push(_globalVariableList[item.Item.ToString()]);
}
else
{
throw new MuftecInvalidStackItemTypeException(data.RuntimeStack);
}
}
[OpCode("@", Extern = true)]
private void SetVariable(OpCodeData data)
{
var item1 = data.RuntimeStack.Pop(MuftecType.Variable);
var item2 = data.RuntimeStack.Pop();
_globalVariableList.Add((string)item1.Item, item2);
}
[OpCode("loadlibdll", Extern = true)]
private void LoadLibraryDLL(OpCodeData data)
{
var library = data.RuntimeStack.PopStr();
AddLibrary(library);
}
#endregion
#region Library functions
/// <summary>
/// Add an external library DLL that inherits <see>IMuftecClassLibrary</see>
/// </summary>
/// <param name="path"></param>
public void AddLibrary(string path)
{
AddLibrary(Assembly.LoadFile(path));
}
/// <summary>
/// Add an assembly with a <see>IMuftecClassLibrary</see>
/// </summary>
/// <param name="classAssembly">Assembly containing opcodes</param>
public void AddLibrary(Assembly classAssembly)
{
var baseReference = classAssembly.GetTypes().Where(w => w.GetInterfaces().Contains(typeof(IMuftecClassLibrary))).ToList();
foreach (var br in baseReference)
{
var classConstructor = br.GetConstructor(Type.EmptyTypes);
if (classConstructor == null) return;
var classLibrary = classConstructor.Invoke(null) as IMuftecClassLibrary;
AddLibrary(classLibrary);
}
}
/// <summary>
/// Add a library inherited from <see>IMuftecClassLibrary</see>
/// </summary>
/// <param name="classLibrary">Class containing opcodes</param>
public void AddLibrary(IMuftecClassLibrary classLibrary)
{
// Ignore if already loaded
if (_libraryList.Contains(classLibrary)) return;
// Get all opcode methods
var methods = classLibrary.Classes.SelectMany(t => t.GetMethods()).Where(m => m.GetCustomAttributes(typeof(OpCodeAttribute), false).Length > 0);
// Add opcodes to index
foreach (var info in methods)
{
var code = info.GetCustomAttributes(typeof(OpCodeAttribute), false).FirstOrDefault() as OpCodeAttribute;
if (code != null)
{
var opc = (OpCodePointer)Delegate.CreateDelegate(typeof(OpCodePointer), info);
var opi = new OpCodeItem {Attribute = code, Pointer = opc};
try
{
AddOpToCache(opi);
}
catch (ArgumentException)
{
// OpCode already exists, ignore
if (!Shared.IsDebug()) continue;
}
}
Console.WriteLine();
}
// Add fixed defines to index
foreach (var def in classLibrary.Defines)
{
if (_globalDefineList.ContainsKey(def.Key))
{
_globalDefineList[def.Key] = def.Value;
}
else
{
_globalDefineList.Add(def.Key, def.Value);
}
}
// Add to library list
_libraryList.Add(classLibrary);
}
#endregion
#region Execution functions
public OpCodeItem FindOpCode(string opCode)
{
return _opcodeCache[opCode];
}
/// <summary>
/// Execute an opcode.
/// </summary>
/// <param name="opCode">Opcode name to execute.</param>
/// <param name="data">Opcode data to pass.</param>
/// <returns>The magic opcode used, if any.</returns>
public MagicOpcodes ExecOpCode(string opCode, OpCodeData data)
{
if (!_opcodeCache.ContainsKey(opCode))
{
throw new MuftecGeneralException(data.RuntimeStack, "Unknown symbol '" + opCode + "' on line " + data.LineNumber);
}
if (Shared.IsDebug())
{
//MuftecGeneralException.MuftecStackTrace(runtimeStack);
}
// Get the opcode pointer
var opCodeItem = FindOpCode(opCode);
// Handle exception catching inside the language here
opCodeItem.Pointer(data);
return opCodeItem.Attribute.Magic;
}
/// <summary>
/// Run an execution stack.
/// </summary>
/// <param name="execStack">Execution stack to run.</param>
/// <param name="runtimeStack">Runtime stack to use.</param>
/// <param name="variableList">List of variables.</param>
/// <param name="functionList">List of defined functions.</param>
/// <returns>Stop execution if true.</returns>
public bool Run(Queue<MuftecStackItem> execStack, Stack<MuftecStackItem> runtimeStack, IEnumerable<string> variableList = null, IEnumerable<KeyValuePair<string, Queue<MuftecStackItem>>> functionList = null)
{
// Add variables to global variable list
if (variableList != null)
{
foreach (var variable in variableList.Where(w => !_globalVariableList.ContainsKey(w)))
{
_globalVariableList.Add(variable, 0);
}
}
// Add functions to function list
if (functionList != null)
{
foreach (var function in functionList)
{
if (_globalFunctionList.ContainsKey(function.Key))
{
_globalFunctionList[function.Key] = function.Value;
}
else
{
_globalFunctionList.Add(function.Key, function.Value);
}
}
}
// Iterate through each item on the execution stack
while (execStack.Count > 0)
{
var currStackItem = execStack.Dequeue();
switch (currStackItem.Type)
{
// Run a user defined function
case MuftecType.Function:
var funcName = currStackItem.Item.ToString();
if (_globalFunctionList.ContainsKey(funcName))
{
// Make a copy of the function as it will be popped to execute
var queue = new Queue<MuftecStackItem>(_globalFunctionList[funcName]);
// TODO: Support local variables
if (Run(queue, runtimeStack))
return true;
}
else
{
throw new MuftecInvalidStackItemTypeException(runtimeStack);
}
break;
// Execute a library opcode
case MuftecType.OpCode:
// Collect opcode data
var data = new OpCodeData(runtimeStack, currStackItem.LineNumber);
// Execute the opcode
var magic = ExecOpCode(currStackItem.Item.ToString(), data);
// Handle post-execution magic
switch (magic)
{
case MagicOpcodes.Abort:
// Abort by exiting loop with true
return true;
case MagicOpcodes.Exit:
// Exit by returning from this run depth
return false;
}
break;
// Handle a conditional container
case MuftecType.Conditional:
var container = currStackItem.Item as ConditionalContainer;
if (container == null)
throw new MuftecGeneralException(runtimeStack, "Unable to process conditional statement.");
var check = runtimeStack.PopInt();
var queueToExecute = (check > 0) ? container.TrueQueue : container.FalseQueue;
if (Run(queueToExecute, runtimeStack))
return true;
break;
// Add item to runtime stack
default:
runtimeStack.Push(currStackItem);
break;
}
}
return false;
}
#endregion
}
}