Skip to content
Navigation Menu
{{ message }}
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
265 lines (213 loc) · 9.25 KB
/
Copy pathLibraryLoader.cs
File metadata and controls
265 lines (213 loc) · 9.25 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
/*----------------------------------------------------------
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.Machine;
using ScriptEngine.Machine.Contexts;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using OneScript.Commons;
using OneScript.Contexts;
using OneScript.Exceptions;
using OneScript.Execution;
namespace ScriptEngine.HostedScript
{
public class LibraryLoader : AutoScriptDrivenObject<LibraryLoader>
{
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 LibraryLoader(IExecutableModule moduleHandle, RuntimeEnvironment env, ScriptingEngine engine): base(moduleHandle)
{
_env = env;
_engine = engine;
_customized = true;
_engine.InitializeSDO(this);
}
private LibraryLoader(RuntimeEnvironment env, ScriptingEngine engine)
{
_env = env;
_engine = engine;
_customized = false;
}
#region Static part
public static LibraryLoader Create(ScriptingEngine engine, string processingScript)
{
var compiler = engine.GetCompilerService();
var code = engine.Loader.FromFile(processingScript);
var module = CompileModule(compiler, code, typeof(LibraryLoader));
return new LibraryLoader(module, engine.Environment, engine);
}
public static LibraryLoader Create(ScriptingEngine engine)
{
return new LibraryLoader(engine.Environment, 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
{
TraceLoadLibrary(
Locale.NStr($"ru = 'Загружаю модуль ={moduleName}= в область видимости из файла {file}';"+
$"en = 'Load module ={moduleName}= in to context from file {file}'")
);
_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.AttachExternalAssembly(assembly, _env);
}
[ContextMethod("ДобавитьМакет", "AddTemplate")]
public void AddTemplate(string file, string name, TemplateKind kind = TemplateKind.File)
{
var manager = _engine.GlobalsManager.GetInstance<TemplateStorage>();
manager.RegisterTemplate(file, name, kind);
}
public ExternalLibraryDef ProcessLibrary(string libraryPath)
{
bool success;
_delayLoadedScripts.Clear();
if(!_customized)
{
TraceLoadLibrary(
Locale.NStr($"ru = 'Использую НЕ кастомизированный загрузчик пакетов по умолчанию для библиотеки {libraryPath}';"+
$"en = 'Use NOT customized package loader for library {libraryPath}'")
);
success = DefaultProcessing(libraryPath);
}
else
{
TraceLoadLibrary(
Locale.NStr($"ru = 'Использую КАСТОМИЗИРОВАННЫЙ загрузчик пакетов для библиотеки {libraryPath}';"+
$"en = 'Use CUSTOMIZED package loader for library {libraryPath}'")
);
success = CustomizedProcessing(libraryPath);
}
if (!success)
return default;
var library = new ExternalLibraryDef(Path.GetFileName(libraryPath));
CompileDelayedModules(library);
return library;
}
private bool CustomizedProcessing(string libraryPath)
{
var libPathValue = ValueFactory.Create(libraryPath);
var defaultLoading = Variable.Create(ValueFactory.Create(true), "$internalDefaultLoading");
var cancelLoading = Variable.Create(ValueFactory.Create(false), "$internalCancelLoading");
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))
.ToList();
bool hasFiles = false;
TraceLoadLibrary(
Locale.NStr($"ru = 'Обнаружено {files.Count} модулей в библиотеке {libraryPath}';"+
$"en = 'Found {files.Count} modules in library {libraryPath}'")
);
foreach (var file in files)
{
TraceLoadLibrary(
Locale.NStr($"ru = 'Загружаю модуль библиотеки из {file.Path}';"+
$"en = 'Load library module from {file.Path}'")
);
hasFiles = true;
AddModule(file.Path, file.Name);
}
return hasFiles;
}
private void CompileDelayedModules(ExternalLibraryDef library)
{
foreach (var scriptFile in _delayLoadedScripts)
{
if (scriptFile.asClass)
{
library.AddClass(scriptFile.identifier, scriptFile.path);
}
else
{
library.AddModule(scriptFile.identifier, scriptFile.path);
}
}
library.Modules.ForEach(moduleFile =>
{
var module = CompileFile(moduleFile.FilePath);
moduleFile.Module = module;
});
library.Classes.ForEach(classFile =>
{
var module = CompileFile(classFile.FilePath);
_engine.AttachedScriptsFactory.RegisterTypeModule(classFile.Symbol, module);
classFile.Module = module;
});
_env.InitExternalLibrary(_engine, library);
}
private IExecutableModule CompileFile(string path)
{
var compiler = _engine.GetCompilerService();
var source = _engine.Loader.FromFile(path);
var module = _engine.AttachedScriptsFactory.CompileModuleFromSource(compiler, source, null);
return module;
}
private static Lazy<bool> TraceEnabled =
new Lazy<bool>(() => System.Environment.GetEnvironmentVariable("OS_LRE_TRACE") == "1");
public static void TraceLoadLibrary(string message)
{
if (TraceEnabled.Value) {
SystemLogger.Write("LRE: " + message);
}
}
}
}
You can’t perform that action at this time.
