-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModuleCompilationTests.cs
More file actions
556 lines (475 loc) · 22.9 KB
/
Copy pathModuleCompilationTests.cs
File metadata and controls
556 lines (475 loc) · 22.9 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
using AuroraScript.Core;
using AuroraScript.Runtime;
using AuroraScript.Source;
using AuroraScript.Tests.Infrastructure;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace AuroraScript.Tests;
public sealed class ModuleCompilationTests
{
[Fact]
public async Task ResolvesImportIncludeAndRelativePaths()
{
using var workspace = new TestWorkspace();
workspace.WriteSource("lib/value.as", "@module(VALUE); export const number = 40;");
workspace.WriteSource("shared.as", "export const INCLUDED = 2;");
var main = workspace.WriteSource(
"main.as",
"""
@module(TEST);
import value from './lib/value';
include './shared';
export func run() { return value.number + INCLUDED; }
""");
var engine = workspace.CreateEngine(maxDegreeOfParallelism: 4);
await engine.BuildAsync(main);
var domain = engine.CreateDomain();
ScriptAssert.Equal(42, TestWorkspace.Execute(domain, "run"));
}
[Fact]
public async Task ResolvesImportedSourceOutsideRootAndIncludesFromImportedDirectory()
{
using var workspace = new TestWorkspace();
var testsRoot = Path.Combine(workspace.Root, "tests");
workspace.WriteSource("tests/unit.as", """
@module(UNIT);
import debug_test from '../temp/debug_test';
export func run() { return debug_test.main(); }
""");
workspace.WriteSource("temp/debug_test.as", """
@module(DEBUG_TEST);
include 'debug_inc';
export func main() { return includedValue(); }
""");
workspace.WriteSource("temp/debug_inc.as", """
export func includedValue() { return 42; }
""");
var options = EngineOptions.Default
.WithCompiler(compiler => compiler.SourceResolver = ScriptSources.FileSystem(testsRoot, Encoding.UTF8))
.WithCompiler(compiler => compiler.Mode = CompilationMode.Dynamic)
.WithOptimization(optimization => optimization.Level = OptimizeOptions.Release);
var engine = new AuroraEngine(options);
await engine.BuildAsync("unit");
var domain = engine.CreateDomain();
ScriptAssert.Equal(42, domain.Execute("UNIT", "run"));
ScriptAssert.Equal(42, domain.Execute("DEBUG_TEST", "main"));
var debugModule = Assert.IsType<ScriptModule>(domain.GetModule("DEBUG_TEST"));
Assert.EndsWith("../temp/debug_test.as", debugModule.ModulePath, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task PathBaseModuleResolvesFromCurrentModuleDirectory()
{
using var workspace = new TestWorkspace();
var main = workspace.WriteSource(
"app/main.as",
"""
@module(TEST);
export func run() {
return [
Path.baseModule('../assets', './config'),
Path.baseModule(),
Path.join(Path.currentDirectory(), './local')
];
}
""");
var engine = workspace.CreateEngine();
await engine.BuildAsync(main);
var domain = engine.CreateDomain();
var mainDirectory = ScriptPath.GetDirectoryName(ScriptPath.GetFullPath(workspace.Root, "app/main.as"));
ScriptAssert.Equal(
new object?[]
{
ScriptPath.GetFullPath(mainDirectory, "../assets/config"),
mainDirectory,
ScriptPath.GetFullPath(mainDirectory, "local")
},
TestWorkspace.Execute(domain, "run"));
}
[Fact]
public async Task ResolvesDependenciesThroughCustomSourceResolver()
{
const string root = "memory://aurora-tests";
var files = new Dictionary<string, string>(StringComparer.Ordinal)
{
["memory://aurora-tests/lib/value.as"] = "@module(VALUE); export const number = 40;",
["memory://aurora-tests/shared.as"] = "export const INCLUDED = 2;"
};
var options = EngineOptions.Default
.WithCompiler(compiler => compiler.SourceResolver = AuroraScript.Core.ScriptSources.FileSystem(root))
.WithCompiler(compiler => compiler.Mode = CompilationMode.Dynamic)
.WithCompiler(compiler => compiler.SourceResolver = new InMemoryResolver(root, files));
var engine = new AuroraEngine(options);
var main = new MemorySource(
root,
"memory://aurora-tests/main.as",
"""
@module(TEST);
import value from './lib/value';
include './shared';
export func run() { return [value.number + INCLUDED, Path.baseModule('assets', 'config')]; }
""");
await engine.BuildAsync(main);
ScriptAssert.Equal(
new object?[] { 42, "memory://aurora-tests/assets/config" },
TestWorkspace.Execute(engine.CreateDomain(), "run"));
}
[Fact]
public async Task GlobalDeclarationFilesArePreloadedFromCustomSourceResolver()
{
const string root = "memory://aurora-global-tests";
var files = new Dictionary<string, string>(StringComparer.Ordinal)
{
["memory://aurora-global-tests/globals.as"] = "@global();\ndeclare const HOST_CONST;",
["memory://aurora-global-tests/main.as"] = "@module(TEST); export func run() { return HOST_CONST; }"
};
var options = EngineOptions.Default
.WithCompiler(compiler => compiler.SourceResolver = new InMemoryResolver(root, files))
.WithCompiler(compiler => compiler.Mode = CompilationMode.Dynamic);
var engine = new AuroraEngine(options);
await engine.BuildAsync("main.as");
var domain = engine.CreateDomain(global => global.Define("HOST_CONST", 42));
ScriptAssert.Equal(42, TestWorkspace.Execute(domain, "run"));
}
[Fact]
public async Task ReportsDuplicateGlobalDeclarationsFromCustomSourceResolver()
{
const string root = "memory://aurora-global-duplicate-tests";
var files = new Dictionary<string, string>(StringComparer.Ordinal)
{
["memory://aurora-global-duplicate-tests/main.as"] = "@module(TEST); export func run() { return VERSION; }",
["memory://aurora-global-duplicate-tests/a.as"] = "@global();\ndeclare const VERSION;",
["memory://aurora-global-duplicate-tests/b.as"] = "@global();\ndeclare var VERSION;"
};
var options = EngineOptions.Default
.WithCompiler(compiler => compiler.SourceResolver = new InMemoryResolver(root, files))
.WithCompiler(compiler => compiler.Mode = CompilationMode.Dynamic);
var engine = new AuroraEngine(options);
var error = await Assert.ThrowsAsync<AuroraCompilationException>(() => engine.BuildAsync("main.as"));
Assert.Contains("Duplicate global declaration 'VERSION'", error.ToString(), StringComparison.Ordinal);
}
[Fact]
public async Task ExplicitMemoryGlobalDeclarationSourceIsAvailableToModules()
{
using var workspace = new TestWorkspace();
var globalSource = workspace.MemorySource("globals.as", "@global();\ndeclare const HOST_CONST;");
var mainSource = workspace.MemorySource("main.as", "@module(TEST); export func run() { return HOST_CONST; }");
var engine = workspace.CreateEngine();
await engine.BuildAsync(globalSource, mainSource);
var domain = engine.CreateDomain(global => global.Define("HOST_CONST", 42));
ScriptAssert.Equal(42, TestWorkspace.Execute(domain, "run"));
}
[Fact]
public async Task IncludeOnlyExposesExportedDeclarations()
{
using var workspace = new TestWorkspace();
workspace.WriteSource("shared.as", "const HIDDEN = 40; export const INCLUDED = 2;");
var main = workspace.WriteSource(
"main.as",
"""
@module(TEST);
include './shared';
export func visible() { return INCLUDED; }
export func hidden() { return HIDDEN; }
""");
var engine = workspace.CreateEngine();
await engine.BuildAsync(main);
var domain = engine.CreateDomain();
ScriptAssert.Equal(2, TestWorkspace.Execute(domain, "visible"));
ScriptAssert.Equal(null, TestWorkspace.Execute(domain, "hidden"));
}
[Fact]
public async Task IncludeConflictRejectsDuplicateModuleDeclaration()
{
using var workspace = new TestWorkspace();
workspace.WriteSource("shared.as", "export const VALUE = 1;");
var main = workspace.WriteSource(
"main.as",
"""
@module(TEST);
include './shared';
export const VALUE = 2;
export func run() { return VALUE; }
""");
var engine = workspace.CreateEngine();
var error = await Assert.ThrowsAsync<AuroraCompilationException>(() => engine.BuildAsync(main));
var diagnostic = Assert.Single(error.Diagnostics);
Assert.Contains("Duplicate declaration 'VALUE'", diagnostic.Message);
}
[Fact]
public async Task DeduplicatesDiamondDependenciesAndDuplicateRoots()
{
using var workspace = new TestWorkspace();
workspace.WriteSource("base.as", "@module(BASE); export const value = 20;");
workspace.WriteSource("left.as", "@module(LEFT); import b from 'base'; export const value = b.value + 1;");
workspace.WriteSource("right.as", "@module(RIGHT); import b from 'base'; export const value = b.value + 1;");
workspace.WriteSource(
"main.as",
"@module(TEST); import l from 'left'; import r from 'right'; export func run() { return l.value + r.value; }");
var engine = workspace.CreateEngine(maxDegreeOfParallelism: 8);
await engine.BuildAsync(["main.as", "main.as"]);
ScriptAssert.Equal(42, TestWorkspace.Execute(engine.CreateDomain(), "run"));
}
[Fact]
public async Task CompilesWideDependencyGraphWithParallelWorkers()
{
using var workspace = new TestWorkspace();
const int dependencyCount = 24;
var imports = new StringBuilder("@module(TEST);\n");
var sum = new StringBuilder("export func run() { return ");
for (var i = 0; i < dependencyCount; i++)
{
workspace.WriteSource($"deps/d{i}.as", $"@module(D{i}); export const value = {i};");
imports.Append("import d").Append(i).Append(" from './deps/d").Append(i).Append("';\n");
if (i > 0) sum.Append(" + ");
sum.Append('d').Append(i).Append(".value");
}
sum.Append("; }");
var main = workspace.WriteSource("main.as", imports.Append(sum).ToString());
var engine = workspace.CreateEngine(maxDegreeOfParallelism: 8);
await engine.BuildAsync(main);
ScriptAssert.Equal(276, TestWorkspace.Execute(engine.CreateDomain(), "run"));
}
[Fact]
public async Task RejectsCircularModuleDependency()
{
using var workspace = new TestWorkspace();
var first = workspace.WriteSource("first.as", "@module(FIRST); import second from 'second';");
workspace.WriteSource("second.as", "@module(SECOND); import first from 'first';");
var engine = workspace.CreateEngine();
var error = await Assert.ThrowsAsync<AuroraCompilationException>(
() => engine.BuildAsync(first));
Assert.Contains("Circular", error.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task RejectsDuplicateModuleNamesWithBothPathsInDiagnostic()
{
using var workspace = new TestWorkspace();
workspace.WriteSource("first.as", "@module(CONFLICT);");
workspace.WriteSource("second.as", "@module(CONFLICT);");
var engine = workspace.CreateEngine();
var error = await Assert.ThrowsAsync<AuroraCompilationException>(() => engine.BuildAsync(["first.as", "second.as"]));
Assert.Contains("first.as", error.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("second.as", error.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task RejectsDuplicateDeclarationsInSameScope()
{
using var workspace = new TestWorkspace();
var moduleEngine = workspace.CreateEngine();
var moduleDuplicate = workspace.MemorySource(
"duplicate-module.as",
"""
@module(TEST);
export func testTextTemplate() { return 1; }
export func testTextTemplate(n) { return n; }
""");
var moduleError = await Assert.ThrowsAsync<AuroraCompilationException>(() => moduleEngine.BuildAsync(moduleDuplicate));
var moduleDiagnostic = Assert.Single(moduleError.Diagnostics);
Assert.Contains("Duplicate declaration 'testTextTemplate'", moduleDiagnostic.Message);
Assert.Contains("Duplicate declaration 'testTextTemplate'", moduleError.ToString());
var localEngine = workspace.CreateEngine();
var localDuplicate = workspace.MemorySource(
"duplicate-local.as",
"""
@module(TEST2);
export func run(n) {
const n = { a: 1, b: 2 };
return n;
}
""");
var localError = await Assert.ThrowsAsync<AuroraCompilationException>(() => localEngine.BuildAsync(localDuplicate));
var localDiagnostic = Assert.Single(localError.Diagnostics);
Assert.Contains("Duplicate declaration 'n'", localDiagnostic.Message);
Assert.Contains("Previous declaration:", localDiagnostic.Message);
Assert.Contains("line:2", localDiagnostic.Message);
Assert.DoesNotContain("line:-1", localDiagnostic.Message);
Assert.Contains("Duplicate declaration 'n'", localError.ToString());
}
[Fact]
public async Task ParallelBackendFailuresAreReportedAsCompileReport()
{
using var workspace = new TestWorkspace();
workspace.WriteSource("valid.as", "@module(VALID); export func ok() { return 1; }");
workspace.WriteSource(
"invalid.as",
"""
@module(INVALID);
export func run(n) {
const n = 1;
return n;
}
""");
var engine = workspace.CreateEngine(maxDegreeOfParallelism: 8);
var error = await Assert.ThrowsAsync<AuroraCompilationException>(() => engine.BuildAsync(["valid.as", "invalid.as"]));
var diagnostic = Assert.Single(error.Diagnostics);
Assert.Contains("Duplicate declaration 'n'", error.ToString());
}
[Fact]
public async Task ReportsEveryIndependentCompilationFailureInStablePathOrder()
{
using var workspace = new TestWorkspace();
var engine = workspace.CreateEngine(maxDegreeOfParallelism: 8);
ScriptSource z = workspace.MemorySource("z-error.as", "@module(Z); var z = ;");
ScriptSource a = workspace.MemorySource("a-error.as", "@module(A); var a = ;");
var report = await Assert.ThrowsAsync<AuroraCompilationException>(() => engine.BuildAsync(z, a));
Assert.Equal(2, report.Diagnostics.Count);
Assert.EndsWith("a-error.as", report.Diagnostics[0].FileName, StringComparison.OrdinalIgnoreCase);
Assert.EndsWith("z-error.as", report.Diagnostics[1].FileName, StringComparison.OrdinalIgnoreCase);
Assert.All(report.Diagnostics, diagnostic => Assert.Contains("requires an expression", diagnostic.Message, StringComparison.OrdinalIgnoreCase));
}
[Fact]
public async Task MissingImportedFileIsReportedWithoutHangingWorkers()
{
using var workspace = new TestWorkspace();
var main = workspace.WriteSource("main.as", "@module(TEST); import missing from 'missing';");
var engine = workspace.CreateEngine(maxDegreeOfParallelism: 8);
var build = engine.BuildAsync(main);
var completed = await Task.WhenAny(build, Task.Delay(TimeSpan.FromSeconds(10)));
Assert.Same(build, completed);
var report = await Assert.ThrowsAsync<AuroraCompilationException>(() => build);
Assert.Single(report.Diagnostics);
}
[Fact]
public async Task HonorsPreCanceledBuild()
{
using var workspace = new TestWorkspace();
var engine = workspace.CreateEngine();
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => engine.BuildAsync(
cancellation.Token,
workspace.MemorySource("main.as", "@module(TEST);")));
}
[Fact]
public async Task SerializesConcurrentBuildsOnOneEngine()
{
using var workspace = new TestWorkspace();
var engine = workspace.CreateEngine(maxDegreeOfParallelism: 4);
var source = workspace.MemorySource("main.as", "@module(TEST); export func run() { return 42; }");
await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => engine.BuildAsync(source)));
ScriptAssert.Equal(42, TestWorkspace.Execute(engine.CreateDomain(), "run"));
}
[Fact]
public async Task FailedRebuildPreservesLastSuccessfulEntryPoint()
{
using var workspace = new TestWorkspace();
var engine = workspace.CreateEngine();
await engine.BuildAsync(workspace.MemorySource("valid.as", "@module(TEST); export func run() { return 42; }"));
await Assert.ThrowsAsync<AuroraCompilationException>(() => engine.BuildAsync(
workspace.MemorySource("invalid.as", "@module(BROKEN); var value = ;")));
ScriptAssert.Equal(42, TestWorkspace.Execute(engine.CreateDomain(), "run"));
}
[Fact]
public async Task GlobalDeclarationFilesAreSkippedWhenBuildingAllSources()
{
using var workspace = new TestWorkspace();
workspace.WriteSource(
"globals.as",
"""
@global();
declare const HOST_CONST;
""");
workspace.WriteSource("main.as", "@module(TEST); export func run() { return HOST_CONST; }");
var engine = workspace.CreateEngine();
await engine.BuildAsync();
var domain = engine.CreateDomain(global => global.Define("HOST_CONST", 42));
ScriptAssert.Equal(42, TestWorkspace.Execute(domain, "run"));
Assert.False(domain.Global.TryGetModule("globals", out _));
}
[Fact]
public async Task RejectsImportOrIncludeOfGlobalDeclarationFile()
{
using var workspace = new TestWorkspace();
workspace.WriteSource("globals.as", "@global();\ndeclare const HOST_CONST;");
workspace.WriteSource("importer.as", "@module(IMPORTER); import globals from 'globals';");
workspace.WriteSource("includer.as", "@module(INCLUDER); include 'globals';");
var engine = workspace.CreateEngine();
var importError = await Assert.ThrowsAsync<AuroraCompilationException>(() => engine.BuildAsync("importer.as"));
var includeError = await Assert.ThrowsAsync<AuroraCompilationException>(() => engine.BuildAsync("includer.as"));
Assert.Contains("cannot be imported", importError.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("cannot be included", includeError.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task ReportsDuplicateGlobalDeclarationsAcrossProject()
{
using var workspace = new TestWorkspace();
workspace.WriteSource("main.as", "@module(TEST); export func run() { return VERSION; }");
workspace.WriteSource("a.as", "@global();\ndeclare const VERSION;");
workspace.WriteSource("b.as", "@global();\ndeclare func VERSION();");
var engine = workspace.CreateEngine();
var error = await Assert.ThrowsAsync<AuroraCompilationException>(() => engine.BuildAsync("main.as"));
Assert.Contains("Duplicate global declaration 'VERSION'", error.ToString(), StringComparison.Ordinal);
}
private sealed class InMemoryResolver : IScriptSourceResolver
{
private readonly string _baseDirectory;
private readonly IReadOnlyDictionary<string, string> _sources;
public InMemoryResolver(string baseDirectory, IReadOnlyDictionary<string, string> sources)
{
_baseDirectory = ScriptPath.NormalizeBaseDirectory(baseDirectory);
_sources = sources;
}
public string Root => _baseDirectory;
public ValueTask<ScriptSourceReference?> ResolveAsync(
ScriptSourceReference? importer,
string requestedPath,
ScriptResolveContext context,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var currentSourcePath = ResolveCurrentPath(importer);
var currentDirectory = importer == null ? _baseDirectory : ScriptPath.GetDirectoryName(currentSourcePath);
var fullPath = ScriptPath.EnsureExtension(ScriptPath.Combine(currentDirectory, requestedPath), context.Extension);
if (!ScriptPath.IsWithinNormalizedRoot(_baseDirectory, fullPath))
{
return new ValueTask<ScriptSourceReference?>((ScriptSourceReference?)null);
}
if (!_sources.ContainsKey(fullPath))
{
return new ValueTask<ScriptSourceReference?>((ScriptSourceReference?)null);
}
return new ValueTask<ScriptSourceReference?>(new ScriptSourceReference(_baseDirectory, fullPath));
}
public ValueTask<ScriptSource> GetSourceAsync(
ScriptSourceReference source,
CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
if (!ScriptPath.IsWithinNormalizedRoot(_baseDirectory, source.FullPath))
{
throw new FileNotFoundException("Script source not found.", source.FullPath);
}
if (!_sources.TryGetValue(source.FullPath, out var text))
{
throw new FileNotFoundException("Script source not found.", 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();
yield return new MemorySource(_baseDirectory, pair.Key, pair.Value);
}
}
private string ResolveCurrentPath(ScriptSourceReference? importer)
{
if (importer == null)
{
return _baseDirectory;
}
return importer.Value.FullPath;
}
}
}