forked from EvilBeaver/OneScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibraryLoader.cs
More file actions
279 lines (224 loc) · 8.63 KB
/
LibraryLoader.cs
File metadata and controls
279 lines (224 loc) · 8.63 KB
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
/*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/
using ScriptEngine.Environment;
using ScriptEngine.Machine;
using ScriptEngine.Machine.Contexts;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ScriptEngine.HostedScript
{
class LibraryLoader : ScriptDrivenObject
{
private readonly RuntimeEnvironment _env;
private readonly ScriptingEngine _engine;
readonly bool _customized;
readonly List<DelayLoadedScriptData> _delayLoadedScripts = new List<DelayLoadedScriptData>();
private struct DelayLoadedScriptData
{
public string path;
public string identifier;
public bool asClass;
}
private enum MethodNumbers
{
AddClass,
AddProperty,
LastNotAMethod
}
private LibraryLoader(LoadedModuleHandle moduleHandle, RuntimeEnvironment _env, ScriptingEngine _engine): base(moduleHandle)
{
this._env = _env;
this._engine = _engine;
this._customized = true;
_engine.InitializeSDO(this);
}
private LibraryLoader(RuntimeEnvironment _env, ScriptingEngine _engine)
: base(new LoadedModuleHandle(), true)
{
this._env = _env;
this._engine = _engine;
this._customized = false;
}
#region Static part
private static readonly ContextMethodsMapper<LibraryLoader> _methods = new ContextMethodsMapper<LibraryLoader>();
public static LibraryLoader Create(ScriptingEngine engine, RuntimeEnvironment env, string processingScript)
{
var code = engine.Loader.FromFile(processingScript);
var compiler = engine.GetCompilerService();
compiler.DefineVariable("ЭтотОбъект", SymbolType.ContextProperty);
for (int i = 0; i < _methods.Count; i++)
{
var mi = _methods.GetMethodInfo(i);
compiler.DefineMethod(mi);
}
var module = compiler.CreateModule(code);
var loadedModule = engine.LoadModuleImage(module);
return new LibraryLoader(loadedModule, env, engine);
}
public static LibraryLoader Create(ScriptingEngine engine, RuntimeEnvironment env)
{
return new LibraryLoader(env, engine);
}
#endregion
[ContextMethod("ДобавитьКласс","AddClass")]
public void AddClass(string file, string className)
{
if (!Utils.IsValidIdentifier(className))
throw RuntimeException.InvalidArgumentValue();
_delayLoadedScripts.Add(new DelayLoadedScriptData()
{
path = file,
identifier = className,
asClass = true
});
}
[ContextMethod("ДобавитьМодуль", "AddModule")]
public void AddModule(string file, string moduleName)
{
if (!Utils.IsValidIdentifier(moduleName))
throw RuntimeException.InvalidArgumentValue();
_delayLoadedScripts.Add(new DelayLoadedScriptData()
{
path = file,
identifier = moduleName,
asClass = false
});
try
{
_env.InjectGlobalProperty(null, moduleName, true);
}
catch (InvalidOperationException e)
{
// символ уже определен
throw new RuntimeException(String.Format("Невозможно загрузить модуль {0}. Такой символ уже определен.", moduleName), e);
}
}
[ContextMethod("ЗагрузитьБиблиотеку", "LoadLibrary")]
public void LoadLibrary(string dllPath)
{
var assembly = System.Reflection.Assembly.LoadFrom(dllPath);
_engine.AttachAssembly(assembly, _env);
}
protected override int GetOwnVariableCount()
{
return 1;
}
protected override int FindOwnProperty(string name)
{
if(StringComparer.OrdinalIgnoreCase.Compare(name, "ЭтотОбъект") == 0)
{
return 0;
}
return base.FindOwnProperty(name);
}
protected override bool IsOwnPropReadable(int index)
{
return true;
}
protected override IValue GetOwnPropValue(int index)
{
if (index == 0)
return this;
else
throw new ArgumentException(String.Format("Неверный индекс свойства {0}", index), "index");
}
protected override int GetOwnMethodCount()
{
return _methods.Count;
}
protected override void UpdateState()
{
}
protected override int FindOwnMethod(string name)
{
return _methods.FindMethod(name);
}
protected override MethodInfo GetOwnMethod(int index)
{
return _methods.GetMethodInfo(index);
}
protected override void CallOwnProcedure(int index, IValue[] arguments)
{
_methods.GetMethod(index)(this, arguments);
}
protected override IValue CallOwnFunction(int index, IValue[] arguments)
{
return _methods.GetMethod(index)(this, arguments);
}
public bool ProcessLibrary(string libraryPath)
{
bool success;
if(!_customized)
{
success = DefaultProcessing(libraryPath);
}
else
{
success = CustomizedProcessing(libraryPath);
}
if(success)
CompileDelayedModules();
return success;
}
private bool CustomizedProcessing(string libraryPath)
{
var libPathValue = ValueFactory.Create(libraryPath);
var defaultLoading = Variable.Create(ValueFactory.Create(true));
var cancelLoading = Variable.Create(ValueFactory.Create(false));
int eventIdx = GetScriptMethod("ПриЗагрузкеБиблиотеки", "OnLibraryLoad");
if(eventIdx == -1)
{
return DefaultProcessing(libraryPath);
}
CallScriptMethod(eventIdx, new[] { libPathValue, defaultLoading, cancelLoading });
if (cancelLoading.AsBoolean()) // Отказ = Ложь
return false;
if (defaultLoading.AsBoolean())
return DefaultProcessing(libraryPath);
return true;
}
private bool DefaultProcessing(string libraryPath)
{
var files = Directory.EnumerateFiles(libraryPath, "*.os")
.Select(x => new { Name = Path.GetFileNameWithoutExtension(x), Path = x })
.Where(x => Utils.IsValidIdentifier(x.Name));
bool hasFiles = false;
foreach (var file in files)
{
hasFiles = true;
AddModule(file.Path, file.Name);
}
return hasFiles;
}
private void CompileDelayedModules()
{
var ordered = _delayLoadedScripts.OrderBy(x => x.asClass ? 1 : 0).ToArray();
_delayLoadedScripts.Clear();
foreach (var script in ordered)
{
var compiler = _engine.GetCompilerService();
var source = _engine.Loader.FromFile(script.path);
var module = _engine.AttachedScriptsFactory.CreateModuleFromSource(compiler, source, null);
if(script.asClass)
{
_engine.AttachedScriptsFactory.LoadAndRegister(script.identifier, module);
_env.NotifyClassAdded(module, script.identifier);
}
else
{
var loaded = _engine.LoadModuleImage(module);
var instance = (IValue)_engine.NewObject(loaded);
_env.SetGlobalProperty(script.identifier, instance);
_env.NotifyModuleAdded(module, script.identifier);
}
}
}
}
}