forked from EvilBeaver/OneScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLibraryResolver.cs
More file actions
313 lines (261 loc) · 9.49 KB
/
LibraryResolver.cs
File metadata and controls
313 lines (261 loc) · 9.49 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
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
/*----------------------------------------------------------
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.Compiler;
using ScriptEngine.Environment;
using ScriptEngine.HostedScript.Library;
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 LibraryResolver : IDirectiveResolver
{
private const string USE_DIRECTIVE_RU = "использовать";
private const string USE_DIRECTIVE_EN = "use";
private const string PREDEFINED_LOADER_FILE = "package-loader.os";
private readonly RuntimeEnvironment _env;
private readonly ScriptingEngine _engine;
private readonly List<Library> _libs;
private LibraryLoader _defaultLoader;
private string _libraryRoot;
#region Private classes
private class Library
{
public string id;
public ProcessingState state;
public LibraryLoader customLoader;
}
private enum ProcessingState
{
Discovered,
Processed
}
#endregion
public LibraryResolver(ScriptingEngine engine, RuntimeEnvironment env)
{
_env = env;
_engine = engine;
_libs = new List<Library>();
this.SearchDirectories = new List<string>();
}
public string LibraryRoot
{
get
{
if (_libraryRoot == null)
_libraryRoot = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
return _libraryRoot;
}
set
{
_libraryRoot = value;
}
}
public List<string> SearchDirectories { get; private set; }
//TODO: Тут совсем ужасно спроектировано взаимодействие слоев и передача контекста
// нужно снова заняться версией 2.0 ((
private readonly Stack<ICodeSource> _compiledSourcesStack = new Stack<ICodeSource>();
public ICodeSource Source
{
get
{
if (_compiledSourcesStack.Count == 0)
return null;
return _compiledSourcesStack.Peek();
}
set
{
if(value == null)
{
if (_compiledSourcesStack.Count > 0)
_compiledSourcesStack.Pop();
}
else
{
_compiledSourcesStack.Push(value);
}
}
}
private LibraryLoader DefaultLoader
{
get
{
if (_defaultLoader == null)
CreateDefaultLoader();
return _defaultLoader;
}
set { _defaultLoader = value; }
}
private void CreateDefaultLoader()
{
var loaderscript = Path.Combine(LibraryRoot, PREDEFINED_LOADER_FILE);
if (File.Exists(loaderscript))
{
_defaultLoader = LibraryLoader.Create(_engine, _env, loaderscript);
}
else
{
_defaultLoader = LibraryLoader.Create(_engine, _env);
}
}
public bool Resolve(string directive, string value, bool codeEntered)
{
if (codeEntered) {
return false;
}
if (DirectiveSupported(directive))
{
LoadLibrary(value);
return true;
}
else
return false;
}
private bool DirectiveSupported(string directive)
{
return StringComparer.InvariantCultureIgnoreCase.Compare(directive, USE_DIRECTIVE_RU) == 0
|| StringComparer.InvariantCultureIgnoreCase.Compare(directive, USE_DIRECTIVE_EN) == 0;
}
private void LoadLibrary(string value)
{
if (String.IsNullOrWhiteSpace(value))
throw new ArgumentException("Ошибка в имени библиотеки", "value");
bool loaded;
if (IsQuoted(value))
loaded = LoadByRelativePath(value.Substring(1, value.Length - 2));
else
loaded = LoadByName(value);
if(!loaded)
throw new CompilerException(String.Format("Библиотека не найдена {0}", value));
}
private bool LoadByRelativePath(string libraryPath)
{
string realPath;
if (!Path.IsPathRooted(libraryPath) && Source != null)
{
var currentPath = Source.SourceDescription;
// Загружаем относительно текущего скрипта, однако,
// если CurrentScript не файловый (TestApp или другой хост), то загружаем относительно рабочего каталога.
// немного костыльно, ага ((
//
if (!PathHasInvalidChars(currentPath))
realPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(currentPath), libraryPath));
else
realPath = libraryPath;
}
else
{
realPath = libraryPath;
}
return LoadByPath(realPath);
}
private static bool PathHasInvalidChars(string path)
{
return (!string.IsNullOrEmpty(path) && path.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0);
}
private bool IsQuoted(string value)
{
const char QUOTE = '"';
if(value[0] == QUOTE && value.Length > 1)
{
return value[0] == QUOTE && value[value.Length - 1] == QUOTE;
}
else
return false;
}
private bool LoadByPath(string libraryPath)
{
if (Directory.Exists(libraryPath))
{
return LoadLibraryInternal(libraryPath);
}
return false;
}
private bool LoadByName(string value)
{
var rootPath = Path.Combine(LibraryRoot, value);
if (LoadByPath(rootPath))
return true;
foreach (var path in SearchDirectories)
{
if(!Directory.Exists(path))
continue;
var libraryPath = Path.Combine(path, value);
if (LoadByPath(libraryPath))
return true;
}
return false;
}
private bool LoadLibraryInternal(string libraryPath)
{
var id = GetLibraryId(libraryPath);
var existedLib = _libs.FirstOrDefault(x => x.id == id);
if(existedLib != null)
{
if (existedLib.state == ProcessingState.Discovered)
{
string libStack = listToStringStack(_libs, id);
throw new RuntimeException($"Ошибка загрузки библиотеки {id}. Обнаружены циклические зависимости.\n" +
$"{libStack}");
}
return true;
}
var newLib = new Library() { id = id, state = ProcessingState.Discovered };
bool hasFiles;
int newLibIndex = _libs.Count;
var customLoaderFile = Path.Combine(libraryPath, PREDEFINED_LOADER_FILE);
if (File.Exists(customLoaderFile))
newLib.customLoader = LibraryLoader.Create(_engine, _env, customLoaderFile);
try
{
_libs.Add(newLib);
hasFiles = ProcessLibrary(newLib);
newLib.state = ProcessingState.Processed;
}
catch (Exception)
{
_libs.RemoveAt(newLibIndex);
throw;
}
return hasFiles;
}
private string listToStringStack(List<Library> libs, string stopToken)
{
var builder = new StringBuilder();
string offset = "";
foreach (var library in libs)
{
builder.Append(offset);
builder.Append("-> ");
builder.AppendLine(library.id);
offset += " ";
if (library.id == stopToken)
{
break;
}
}
return builder.ToString();
}
private string GetLibraryId(string libraryPath)
{
return Path.GetFullPath(libraryPath);
}
private bool ProcessLibrary(Library lib)
{
LibraryLoader loader;
if (lib.customLoader != null)
loader = lib.customLoader;
else
loader = this.DefaultLoader;
return loader.ProcessLibrary(lib.id);
}
}
}