-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomSourceResolverUsageTests.cs
More file actions
307 lines (265 loc) · 11.5 KB
/
Copy pathCustomSourceResolverUsageTests.cs
File metadata and controls
307 lines (265 loc) · 11.5 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
using AuroraScript.Core;
using AuroraScript.Source;
using AuroraScript.Tests.Infrastructure;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AuroraScript.Tests;
public sealed class CustomSourceResolverUsageTests
{
[Fact]
public async Task BuildsModuleGraphFromVirtualFileSystem()
{
const string root = "vfs://aurora-script-tests/app";
var resolver = new VirtualFileSystemSourceResolver(root)
.AddSource(
"main.as",
"""
@module(TEST);
import math from './lib/math';
include './shared/constants';
export func run() {
return math.add(BASE, OFFSET);
}
""")
.AddSource(
"lib/math.as",
"""
@module(MATH);
export func add(left, right) {
return left + right;
}
""")
.AddSource(
"shared/constants.as",
"""
export const BASE = 40;
export const OFFSET = 2;
""");
var engine = CreateEngine(root, resolver);
await engine.BuildAsync("main.as");
ScriptAssert.Equal(42, TestWorkspace.Execute(engine.CreateDomain(), "run"));
Assert.Contains("vfs://aurora-script-tests/app/main.as", resolver.OpenedPaths);
Assert.Contains("vfs://aurora-script-tests/app/lib/math.as", resolver.OpenedPaths);
Assert.Contains("vfs://aurora-script-tests/app/shared/constants.as", resolver.OpenedPaths);
}
[Fact]
public async Task HonorsConfiguredScriptExtension()
{
const string root = "vfs://aurora-script-tests/custom-extension";
var resolver = new VirtualFileSystemSourceResolver(root)
.AddSource(
"main.aurora",
"""
@module(TEST);
import value from './feature/value';
export func run() {
return value.number;
}
""")
.AddSource("feature/value.aurora", "@module(VALUE); export const number = 42;");
var engine = CreateEngine(root, resolver, ".aurora");
await engine.BuildAsync("main.aurora");
ScriptAssert.Equal(42, TestWorkspace.Execute(engine.CreateDomain(), "run"));
Assert.Contains("vfs://aurora-script-tests/custom-extension/feature/value.aurora", resolver.OpenedPaths);
}
[Fact]
public async Task ReportsMissingVirtualDependency()
{
const string root = "vfs://aurora-script-tests/missing-dependency";
var resolver = new VirtualFileSystemSourceResolver(root)
.AddSource(
"main.as",
"""
@module(TEST);
import missing from './missing';
export func run() {
return 1;
}
""");
var engine = CreateEngine(root, resolver);
var error = await Assert.ThrowsAsync<AuroraCompilationException>(() => engine.BuildAsync("main.as"));
var diagnostic = Assert.Single(error.Diagnostics);
Assert.Contains("Import file not found", diagnostic.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("./missing", diagnostic.Message, StringComparison.Ordinal);
}
[Fact]
public async Task BuildsAllSourcesFromConfiguredResolver()
{
const string root = "vfs://aurora-script-tests/all";
var resolver = new VirtualFileSystemSourceResolver(root)
.AddSource("main.as", "@module(TEST); export func run() { return 42; }")
.AddSource("helper.as", "@module(HELPER); export const value = 1;");
var engine = CreateEngine(root, resolver);
await engine.BuildAsync();
ScriptAssert.Equal(42, TestWorkspace.Execute(engine.CreateDomain(), "run"));
Assert.Contains("vfs://aurora-script-tests/all/main.as", resolver.OpenedPaths);
Assert.Contains("vfs://aurora-script-tests/all/helper.as", resolver.OpenedPaths);
}
[Fact]
public async Task BuildAwaitsAsynchronousResolverOperations()
{
const string root = "vfs://aurora-script-tests/async";
var resolver = new AsyncVirtualFileSystemSourceResolver(root)
.AddSource(
"main.as",
"""
@module(TEST);
import value from './value';
export func run() {
return value.number;
}
""")
.AddSource("value.as", "@module(VALUE); export const number = 42;");
var engine = CreateEngine(root, resolver);
await engine.BuildAsync("main.as");
ScriptAssert.Equal(42, TestWorkspace.Execute(engine.CreateDomain(), "run"));
Assert.True(resolver.ResolveAwaitCount >= 2);
Assert.True(resolver.SourceAwaitCount >= 2);
}
private static AuroraEngine CreateEngine(
string root,
IScriptSourceResolver resolver,
string extension = ".as")
{
var options = EngineOptions.Default
.WithCompiler(compiler => compiler.SourceResolver = AuroraScript.Core.ScriptSources.FileSystem(root))
.WithCompiler(compiler => compiler.Mode = CompilationMode.Dynamic)
.WithCompiler(compiler => compiler.ExtName = extension)
.WithCompiler(compiler => compiler.SourceResolver = resolver)
.WithOptimization(optimization => optimization.Level = OptimizeOptions.Release);
return new AuroraEngine(options);
}
private sealed class VirtualFileSystemSourceResolver : IScriptSourceResolver
{
private readonly string _root;
private readonly Dictionary<string, string> _sources = new(StringComparer.Ordinal);
private readonly ConcurrentBag<string> _openedPaths = new();
public VirtualFileSystemSourceResolver(string root)
{
_root = ScriptPath.NormalizeBaseDirectory(root);
}
public IReadOnlyCollection<string> OpenedPaths => _openedPaths.ToArray();
public VirtualFileSystemSourceResolver AddSource(string path, string source)
{
_sources[ScriptPath.GetFullPath(_root, path)] = source ?? string.Empty;
return this;
}
public ScriptSource OpenSource(string path)
{
var fullPath = ScriptPath.GetFullPath(_root, path);
return GetSourceAsync(new ScriptSourceReference(_root, fullPath))
.AsTask()
.GetAwaiter()
.GetResult();
}
public string Root => _root;
public ValueTask<ScriptSourceReference?> ResolveAsync(
ScriptSourceReference? importer,
string requestedPath,
ScriptResolveContext context,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var currentSourcePath = ResolveCurrentPath(importer);
var currentDirectory = importer == null ? _root : ScriptPath.GetDirectoryName(currentSourcePath);
var fullPath = ScriptPath.EnsureExtension(ScriptPath.Combine(currentDirectory, requestedPath), context.Extension);
if (!ScriptPath.IsWithinNormalizedRoot(_root, fullPath))
{
return new ValueTask<ScriptSourceReference?>((ScriptSourceReference?)null);
}
if (_sources.ContainsKey(fullPath))
{
return new ValueTask<ScriptSourceReference?>(new ScriptSourceReference(_root, fullPath));
}
return new ValueTask<ScriptSourceReference?>((ScriptSourceReference?)null);
}
public ValueTask<ScriptSource> GetSourceAsync(
ScriptSourceReference source,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
if (!ScriptPath.IsWithinNormalizedRoot(_root, source.FullPath))
{
throw new FileNotFoundException("Virtual script source not found.", source.FullPath);
}
if (!_sources.TryGetValue(source.FullPath, out var text))
{
throw new FileNotFoundException("Virtual script source not found.", source.FullPath);
}
_openedPaths.Add(source.FullPath);
return new ValueTask<ScriptSource>(new MemorySource(source.BaseDirectory, source.FullPath, text));
}
public async IAsyncEnumerable<ScriptSource> GetAllSourcesAsync(
ScriptSourceQuery query,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
foreach (var pair in _sources)
{
cancellationToken.ThrowIfCancellationRequested();
await Task.Yield();
_openedPaths.Add(pair.Key);
yield return new MemorySource(_root, pair.Key, pair.Value);
}
}
private string ResolveCurrentPath(ScriptSourceReference? importer)
{
if (importer == null)
{
return _root;
}
return importer.Value.FullPath;
}
}
private sealed class AsyncVirtualFileSystemSourceResolver : IScriptSourceResolver
{
private readonly VirtualFileSystemSourceResolver _inner;
private int _resolveAwaitCount;
private int _sourceAwaitCount;
public AsyncVirtualFileSystemSourceResolver(string root)
{
_inner = new VirtualFileSystemSourceResolver(root);
}
public int ResolveAwaitCount => Volatile.Read(ref _resolveAwaitCount);
public int SourceAwaitCount => Volatile.Read(ref _sourceAwaitCount);
public string Root => _inner.Root;
public AsyncVirtualFileSystemSourceResolver AddSource(string path, string source)
{
_inner.AddSource(path, source);
return this;
}
public async ValueTask<ScriptSourceReference?> ResolveAsync(
ScriptSourceReference? importer,
string requestedPath,
ScriptResolveContext context,
CancellationToken cancellationToken = default)
{
await Task.Delay(1, cancellationToken).ConfigureAwait(false);
Interlocked.Increment(ref _resolveAwaitCount);
return await _inner.ResolveAsync(importer, requestedPath, context, cancellationToken).ConfigureAwait(false);
}
public async ValueTask<ScriptSource> GetSourceAsync(
ScriptSourceReference source,
CancellationToken cancellationToken = default)
{
await Task.Delay(1, cancellationToken).ConfigureAwait(false);
Interlocked.Increment(ref _sourceAwaitCount);
return await _inner.GetSourceAsync(source, cancellationToken).ConfigureAwait(false);
}
public async IAsyncEnumerable<ScriptSource> GetAllSourcesAsync(
ScriptSourceQuery query,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await foreach (var source in _inner.GetAllSourcesAsync(query, cancellationToken).ConfigureAwait(false))
{
await Task.Delay(1, cancellationToken).ConfigureAwait(false);
yield return source;
}
}
}
}