-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompilerDriver.cs
More file actions
1402 lines (1280 loc) · 59.6 KB
/
Copy pathCompilerDriver.cs
File metadata and controls
1402 lines (1280 loc) · 59.6 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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Diagnostics;
using System.Collections.Immutable;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
using System.Text;
using RustSharp.CodeGen.IL;
using RustSharp.Semantics;
using RustSharp.Syntax;
namespace RustSharp.Compiler;
public sealed class CompilerDriver
{
private const int MaximumSourceBytes = 16 * 1024 * 1024;
private const int SourceReadBufferBytes = 64 * 1024;
// The sidecar lock is intentionally bounded. A compiler invocation that
// cannot acquire its output lease within this window fails with a useful
// diagnostic instead of waiting forever behind a crashed or hung writer.
private const int OutputLockAttempts = 120;
private const int OutputLockRetryMilliseconds = 50;
private const long OutputLockRegionLength = 1;
private const int MaximumTransactionDiagnosticCharacters = 512;
// A stream is allowed to return one byte per read. Keep the upper bound
// finite even for that worst case while normal files finish in a few reads.
private const int MaximumSourceReadChunks = MaximumSourceBytes + 1;
private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
private static readonly object OutputLockRegistryGate = new();
private static readonly Dictionary<string, OutputLockEntry> OutputLockEntries = new(StringComparer.Ordinal);
public static CompilationResult CheckFile(string sourcePath,
CompilationProfile profile = CompilationProfile.VerticalSlice, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(sourcePath);
var fullSourcePath = Path.GetFullPath(sourcePath);
if ((profile == CompilationProfile.SafeCoreGenerics || profile is CompilationProfile.SafeCoreMir or CompilationProfile.SafeCoreMirV2) && IsCargoManifest(fullSourcePath))
{
GenericPackageWorkspaceResult packages = GenericPackageWorkspace.Load(fullSourcePath, cancellationToken);
if (!packages.IsSuccessful) return CompilationResult.Failed(packages.Diagnostics);
CompilationResult checkedPackages = profile is CompilationProfile.SafeCoreMir or CompilationProfile.SafeCoreMirV2
? CheckSafeCoreMir(packages.SourceText, packages.RootSourcePath, cancellationToken, packages.Crates,
profile == CompilationProfile.SafeCoreMirV2)
: CheckSafeCoreGenerics(packages.SourceText, packages.RootSourcePath, cancellationToken, packages.Crates);
return checkedPackages with { Diagnostics = MapDiagnostics(checkedPackages.Diagnostics, packages.SourceMap!) };
}
var cargo = TryResolveCargo(fullSourcePath, cancellationToken, out var cargoDiagnostics);
if (cargoDiagnostics is not null) return CompilationResult.Failed(cargoDiagnostics);
fullSourcePath = cargo ?? fullSourcePath;
if (profile is CompilationProfile.SafeCorePrimitives or CompilationProfile.SafeCoreTypes or
CompilationProfile.SafeCoreGenerics or CompilationProfile.SafeCoreMir or CompilationProfile.SafeCoreMirV2)
{
SafeCoreWorkspaceResult workspace = SafeCoreWorkspace.Load(fullSourcePath, cancellationToken: cancellationToken);
if (!workspace.IsSuccessful) return CompilationResult.Failed(workspace.Diagnostics);
CompilationResult result = Check(workspace.SourceText, fullSourcePath, profile, cancellationToken);
return result with { Diagnostics = MapDiagnostics(result.Diagnostics, workspace.SourceMap!) };
}
var readResult = ReadSource(fullSourcePath);
if (readResult.Diagnostic is not null)
{
return CompilationResult.Failed([readResult.Diagnostic]);
}
return Check(readResult.Document!.Source, fullSourcePath, profile, cancellationToken);
}
public static CompilationResult Check(string source, string sourcePath = "<memory>",
CompilationProfile profile = CompilationProfile.VerticalSlice, CancellationToken cancellationToken = default)
=> CheckCore(source, sourcePath, profile, default, cancellationToken);
private static CompilationResult CheckCore(
string source,
string sourcePath,
CompilationProfile profile,
ImmutableArray<SafeCoreCrate> crates,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentException.ThrowIfNullOrWhiteSpace(sourcePath);
Diagnostic? sourceDiagnostic = ValidateSourceText(source, sourcePath);
if (sourceDiagnostic is not null)
{
return CompilationResult.Failed([sourceDiagnostic]);
}
cancellationToken.ThrowIfCancellationRequested();
if (profile == CompilationProfile.SafeCoreTypes)
return CheckSafeCoreTypes(source, sourcePath, cancellationToken);
if (profile == CompilationProfile.SafeCoreGenerics)
return CheckSafeCoreGenerics(source, sourcePath, cancellationToken, crates);
if (profile is CompilationProfile.SafeCoreMir or CompilationProfile.SafeCoreMirV2)
return CheckSafeCoreMir(source, sourcePath, cancellationToken, crates,
profile == CompilationProfile.SafeCoreMirV2);
if (profile != CompilationProfile.VerticalSlice)
{
SafeCoreClrResult result = AnalyzeSafeCore(source, sourcePath, profile, cancellationToken, crates);
return result.IsSuccessful ? new(true, [], null) : CompilationResult.Failed(result.Diagnostics);
}
var syntaxTree = SyntaxTree.Parse(source, sourcePath);
return syntaxTree.Diagnostics.Count == 0
? new CompilationResult(true, [], null)
: CompilationResult.Failed(syntaxTree.Diagnostics);
}
/// <summary>
/// Checks a consumer source after importing one or more independently
/// emitted Rust# assemblies. Import validation is deliberately explicit;
/// the source checker never loads producer code or uses reflection.
/// </summary>
public static CompilationResult CheckWithMetadataReferences(
string source,
string sourcePath,
CompilationProfile profile,
IEnumerable<string> metadataReferences,
IEnumerable<string>? requiredFunctions = null,
CancellationToken cancellationToken = default)
{
MetadataCrateLoadResult references = LoadMetadataCrates(
metadataReferences, profile, requiredFunctions, cancellationToken);
if (references.Diagnostics.Count != 0)
return CompilationResult.Failed(references.Diagnostics);
return CheckCore(source, sourcePath, profile, references.Crates, cancellationToken);
}
public static CompilationResult CompileFile(
string sourcePath,
string outputPath,
string? assemblyName = null,
CompilationProfile profile = CompilationProfile.VerticalSlice,
CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(sourcePath);
ArgumentException.ThrowIfNullOrWhiteSpace(outputPath);
cancellationToken.ThrowIfCancellationRequested();
if (profile == CompilationProfile.SafeCoreTypes)
return RejectTypeProfileEmission(sourcePath);
var fullSourcePath = Path.GetFullPath(sourcePath);
if ((profile == CompilationProfile.SafeCoreGenerics || profile is CompilationProfile.SafeCoreMir or CompilationProfile.SafeCoreMirV2) && IsCargoManifest(fullSourcePath))
{
GenericPackageWorkspaceResult packages = GenericPackageWorkspace.Load(fullSourcePath, cancellationToken);
if (!packages.IsSuccessful) return CompilationResult.Failed(packages.Diagnostics);
return CompileCore(packages.SourceText, packages.RootSourcePath, Path.GetFullPath(outputPath), assemblyName,
packages.SourceMap!.Documents[0].Bytes, profile, cancellationToken, packages.SourceMap, packages.Crates);
}
var cargo = TryResolveCargo(fullSourcePath, cancellationToken, out var cargoDiagnostics);
if (cargoDiagnostics is not null) return CompilationResult.Failed(cargoDiagnostics);
fullSourcePath = cargo ?? fullSourcePath;
if (profile is CompilationProfile.SafeCorePrimitives or CompilationProfile.SafeCoreGenerics or
CompilationProfile.SafeCoreMir or CompilationProfile.SafeCoreMirV2)
{
SafeCoreWorkspaceResult workspace = SafeCoreWorkspace.Load(fullSourcePath, cancellationToken: cancellationToken);
if (!workspace.IsSuccessful) return CompilationResult.Failed(workspace.Diagnostics);
return CompileCore(workspace.SourceText, fullSourcePath, Path.GetFullPath(outputPath),
assemblyName, workspace.SourceMap!.Documents[0].Bytes, profile, cancellationToken, workspace.SourceMap);
}
var readResult = ReadSource(fullSourcePath);
if (readResult.Diagnostic is not null)
{
return CompilationResult.Failed([readResult.Diagnostic]);
}
return CompileCore(
readResult.Document!.Source,
fullSourcePath,
Path.GetFullPath(outputPath),
assemblyName,
readResult.Document.Bytes,
profile,
cancellationToken);
}
public static CompilationResult Compile(
string source,
string sourcePath,
string outputPath,
string? assemblyName = null,
CompilationProfile profile = CompilationProfile.VerticalSlice,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentException.ThrowIfNullOrWhiteSpace(sourcePath);
ArgumentException.ThrowIfNullOrWhiteSpace(outputPath);
cancellationToken.ThrowIfCancellationRequested();
if (profile == CompilationProfile.SafeCoreTypes)
return RejectTypeProfileEmission(sourcePath);
Diagnostic? sourceDiagnostic = ValidateSourceText(source, sourcePath);
if (sourceDiagnostic is not null)
{
return CompilationResult.Failed([sourceDiagnostic]);
}
byte[] sourceBytes;
try
{
sourceBytes = StrictUtf8.GetBytes(source);
}
catch (EncoderFallbackException exception)
{
return CompilationResult.Failed(
[new Diagnostic(
"RSC0005",
$"Source text '{sourcePath}' is not valid UTF-8: {exception.Message}",
new TextSpan(0, 0))]);
}
var fullOutputPath = Path.GetFullPath(outputPath);
return CompileCore(
source,
sourcePath,
fullOutputPath,
assemblyName,
sourceBytes,
profile,
cancellationToken);
}
private static CompilationResult CompileCoreWithCrates(
string source,
string sourcePath,
string outputPath,
string? assemblyName,
CompilationProfile profile,
ImmutableArray<SafeCoreCrate> crates,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentException.ThrowIfNullOrWhiteSpace(sourcePath);
ArgumentException.ThrowIfNullOrWhiteSpace(outputPath);
cancellationToken.ThrowIfCancellationRequested();
if (profile == CompilationProfile.SafeCoreTypes)
return RejectTypeProfileEmission(sourcePath);
Diagnostic? sourceDiagnostic = ValidateSourceText(source, sourcePath);
if (sourceDiagnostic is not null)
return CompilationResult.Failed([sourceDiagnostic]);
byte[] sourceBytes;
try
{
sourceBytes = StrictUtf8.GetBytes(source);
}
catch (EncoderFallbackException exception)
{
return CompilationResult.Failed([new Diagnostic(
"RSC0005",
$"Source text '{sourcePath}' is not valid UTF-8: {exception.Message}",
new TextSpan(0, 0))]);
}
return CompileCore(source, sourcePath, Path.GetFullPath(outputPath), assemblyName,
sourceBytes, profile, cancellationToken, crates: crates);
}
/// <summary>Compiles a consumer after validating independent Rust# metadata references.</summary>
public static CompilationResult CompileWithMetadataReferences(
string source,
string sourcePath,
string outputPath,
string? assemblyName,
CompilationProfile profile,
IEnumerable<string> metadataReferences,
IEnumerable<string>? requiredFunctions = null,
CancellationToken cancellationToken = default)
{
MetadataCrateLoadResult references = LoadMetadataCrates(
metadataReferences, profile, requiredFunctions, cancellationToken);
if (references.Diagnostics.Count != 0)
return CompilationResult.Failed(references.Diagnostics);
return CompileCoreWithCrates(source, sourcePath, outputPath, assemblyName, profile,
references.Crates, cancellationToken);
}
private static CompilationResult CompileCore(
string source,
string sourcePath,
string outputPath,
string? assemblyName,
ReadOnlyMemory<byte> sourceBytes,
CompilationProfile profile,
CancellationToken cancellationToken,
SafeCoreSourceMap? sourceMap = null, ImmutableArray<SafeCoreCrate> crates = default)
{
cancellationToken.ThrowIfCancellationRequested();
SyntaxTree? syntaxTree = null;
SafeCoreClrResult? safeCore = null;
if (profile == CompilationProfile.VerticalSlice)
{
syntaxTree = SyntaxTree.Parse(source, sourcePath);
if (syntaxTree.Diagnostics.Count != 0 || syntaxTree.Root is null)
return CompilationResult.Failed(syntaxTree.Diagnostics);
}
else
{
safeCore = AnalyzeSafeCore(source, sourcePath, profile, cancellationToken, crates);
if (!safeCore.IsSuccessful) return CompilationResult.Failed(MapDiagnostics(safeCore.Diagnostics, sourceMap));
}
var resolvedAssemblyName = assemblyName ?? Path.GetFileNameWithoutExtension(outputPath);
if (!IsValidAssemblyName(resolvedAssemblyName))
{
return CompilationResult.Failed(
[new Diagnostic(
"RSC0002",
$"'{resolvedAssemblyName}' is not a valid generated assembly name.",
new TextSpan(0, 0))]);
}
var fullSourcePath = Path.GetFullPath(sourcePath);
var fullOutputPath = Path.GetFullPath(outputPath);
var pdbPath = Path.ChangeExtension(fullOutputPath, ".pdb");
var runtimeConfigPath = Path.ChangeExtension(fullOutputPath, ".runtimeconfig.json");
if (sourceMap is not null)
{
// Every loaded document is an input, including modules whose names resemble output files.
foreach (SafeCoreSourceDocument document in sourceMap.Documents)
{
cancellationToken.ThrowIfCancellationRequested();
if (PathsCollide(document.Path, fullOutputPath) || PathsCollide(document.Path, pdbPath) ||
PathsCollide(document.Path, runtimeConfigPath))
return CompilationResult.Failed([new Diagnostic("RSC0006",
"The source and compiler output paths must be distinct.", new TextSpan(0, 0))
{ SourcePath = document.Path }]);
}
}
if (PathsCollide(fullSourcePath, fullOutputPath) ||
PathsCollide(fullSourcePath, pdbPath) ||
PathsCollide(fullSourcePath, runtimeConfigPath) ||
PathsCollide(fullOutputPath, pdbPath) ||
PathsCollide(fullOutputPath, runtimeConfigPath) ||
PathsCollide(pdbPath, runtimeConfigPath))
{
return CompilationResult.Failed(
[new Diagnostic(
"RSC0006",
"The source and compiler output paths must be distinct.",
new TextSpan(0, 0))]);
}
try
{
cancellationToken.ThrowIfCancellationRequested();
RustSharpMetadataDocument? metadataDocument = safeCore is null
? null
: RustSharpMetadataDocument.ForProgram(
profile switch
{
CompilationProfile.SafeCoreGenerics => "safe-core-generics-v1",
CompilationProfile.SafeCoreMir => SafeCoreMirPipeline.Profile,
CompilationProfile.SafeCoreMirV2 => SafeCoreMirPipeline.ProfileV2,
_ => "safe-core-primitives-v1",
},
sourceBytes.Span,
safeCore.Methods,
safeCore.GenericInstances,
safeCore.TraitImplementations,
safeCore.MirSnapshot,
safeCore.Ownership,
safeCore.CleanupSnapshot,
safeCore.Ownership.Select(static function =>
new RustSharpMetadataCallContract(
function.FunctionId.EndsWith("#value", StringComparison.Ordinal)
? function.FunctionId[..^6]
: function.FunctionId,
function.PanicStrategy)));
GeneratedAssembly generated;
try
{
generated = safeCore is not null
? ClrLirAssemblyEmitter.EmitProgram(safeCore, resolvedAssemblyName, source,
fullSourcePath, Path.GetFileName(pdbPath), sourceBytes, sourceMap,
metadataDocument, cancellationToken)
: IlAssemblyEmitter.Emit(
syntaxTree!.Root!,
source,
fullSourcePath,
resolvedAssemblyName,
Path.GetFileName(pdbPath),
sourceBytes);
}
catch (Exception exception) when ((profile == CompilationProfile.SafeCoreGenerics || profile is CompilationProfile.SafeCoreMir or CompilationProfile.SafeCoreMirV2) &&
exception is ArgumentException or InvalidOperationException or TimeoutException)
{
return CompilationResult.Failed([new Diagnostic(SafeCoreGenericDiagnosticCodes.LimitReached,
"Generic CLR emission exceeded its supported layout or validation limits: " + TrimDiagnostic(exception.Message),
new TextSpan(0, 0)) { SourcePath = sourcePath }]);
}
WriteArtifactsTransactionally(
fullOutputPath,
pdbPath,
runtimeConfigPath,
generated);
return new CompilationResult(
true,
[],
new CompilationOutput(fullOutputPath, pdbPath, runtimeConfigPath));
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return CompilationResult.Failed(
[new Diagnostic(
"RSC0003",
$"Could not write compiler output: {exception.Message}",
new TextSpan(0, 0))]);
}
catch (TimeoutException)
{
return CompilationResult.Failed([new Diagnostic("RSC0008",
"Compiler emission exceeded its time budget.", new TextSpan(0, 0))]);
}
}
private static CompilationResult RejectTypeProfileEmission(string sourcePath)
{
return CompilationResult.Failed([new Diagnostic("RSC0009",
$"The {SafeCoreTypeAnalysis.Profile} profile supports type checking only. Use 'rsc check'; " +
"build, compile, run and publish require an executable profile.", new TextSpan(0, 0))
{ SourcePath = sourcePath }]);
}
private static CompilationResult CheckSafeCoreTypes(string source, string sourcePath,
CancellationToken cancellationToken)
{
SafeCoreSyntaxResult syntax;
try { syntax = SafeCoreSyntax.Parse(source, sourcePath, null, cancellationToken); }
catch (TimeoutException)
{
return CompilationResult.Failed([new Diagnostic(SafeCoreSyntaxDiagnosticCodes.LimitReached,
"Safe-core parsing exceeded its time budget.", new TextSpan(0, 0))]);
}
if (!syntax.IsSuccessful) return CompilationResult.Failed(syntax.Diagnostics);
cancellationToken.ThrowIfCancellationRequested();
SafeCoreHirResult hir = SafeCoreHirLowering.Lower(syntax, new SafeCoreHirLoweringOptions
{
CancellationToken = cancellationToken,
NameResolution = new SafeCoreNameResolutionOptions
{
CancellationToken = cancellationToken,
EnableTypeSystemExtensions = true,
},
});
if (!hir.IsSuccessful) return CompilationResult.Failed(hir.Diagnostics);
var result = SafeCoreTypeAnalysis.Check(hir, cancellationToken: cancellationToken);
return result.IsSuccessful ? new(true, [], null) : CompilationResult.Failed(result.Diagnostics);
}
private static CompilationResult CheckSafeCoreGenerics(string source, string sourcePath,
CancellationToken cancellationToken, ImmutableArray<SafeCoreCrate> crates = default)
{
SafeCoreSyntaxResult syntax;
try { syntax = SafeCoreSyntax.Parse(source, sourcePath, null, cancellationToken); }
catch (TimeoutException)
{
return CompilationResult.Failed([new Diagnostic(SafeCoreSyntaxDiagnosticCodes.LimitReached,
"Safe-core parsing exceeded its time budget.", new TextSpan(0, 0))]);
}
if (!syntax.IsSuccessful) return CompilationResult.Failed(syntax.Diagnostics);
var result = SafeCoreGenericAnalysis.Check(syntax, new() { Crates = crates.IsDefault ? [] : crates }, cancellationToken);
return result.IsSuccessful ? new(true, [], null) : CompilationResult.Failed(result.Diagnostics);
}
private static CompilationResult CheckSafeCoreMir(string source, string sourcePath,
CancellationToken cancellationToken, ImmutableArray<SafeCoreCrate> crates = default,
bool enableRepeatedArrays = false)
{
SafeCoreMirPipelineResult result = SafeCoreMirPipeline.Analyze(source, sourcePath,
new SafeCoreMirPipelineOptions
{
CancellationToken = cancellationToken,
RequireOwnershipEvidence = true,
RequireCleanupEvidence = true,
EnableRepeatedArrays = enableRepeatedArrays,
EnableP1Extensions = enableRepeatedArrays,
Crates = crates.IsDefault ? [] : crates,
});
if (!result.IsSuccessful)
{
return CompilationResult.Failed(result.Diagnostics.Count == 0
? result.Ownership?.Diagnostics ?? [new Diagnostic("RSC0007", "Typed MIR analysis failed.", new TextSpan(0, 0))]
: result.Diagnostics);
}
// The MIR validator deliberately checks the language IR contract, while
// the CLR backend has a smaller, representation-specific capability
// boundary. Run that same backend during `check` so a source cannot be
// accepted here and then rejected by `compile` for an LIR-only reason.
SafeCoreClrResult backend = SafeCoreMirClrLowering.Lower(
result.Mir!.Program!, cancellationToken);
backend = AttachMirEvidence(backend, result, requireOwnershipMetadata: true);
return backend.IsSuccessful
? new(true, [], null)
: CompilationResult.Failed(backend.Diagnostics.Count == 0
? [new Diagnostic("RSM2102", "Typed MIR CLR lowering failed.", new TextSpan(0, 0))]
: backend.Diagnostics);
}
private static SafeCoreClrResult AnalyzeSafeCore(string source, string sourcePath,
CompilationProfile profile, CancellationToken cancellationToken, ImmutableArray<SafeCoreCrate> crates = default)
{
if (profile is not (CompilationProfile.SafeCorePrimitives or CompilationProfile.SafeCoreGenerics or CompilationProfile.SafeCoreMir or CompilationProfile.SafeCoreMirV2))
return new([], [], [new("RSC0007", "Unknown compilation profile.", new TextSpan(0, 0))]);
cancellationToken.ThrowIfCancellationRequested();
SafeCoreSyntaxResult syntax;
try { syntax = SafeCoreSyntax.Parse(source, sourcePath, null, cancellationToken); }
catch (TimeoutException)
{
return new([], [], [new Diagnostic(SafeCoreSyntaxDiagnosticCodes.LimitReached,
"Safe-core parsing exceeded its time budget.", new TextSpan(0, 0))]);
}
if (!syntax.IsSuccessful) return new([], [], syntax.Diagnostics);
cancellationToken.ThrowIfCancellationRequested();
if (profile == CompilationProfile.SafeCoreGenerics)
{
SafeCoreGenericAnalysisResult generics = SafeCoreGenericAnalysis.Check(syntax,
new() { Crates = crates.IsDefault ? [] : crates }, cancellationToken);
return generics.IsSuccessful ? SafeCoreGenericClrLowering.Lower(generics.Program!, cancellationToken)
: new([], [], generics.Diagnostics);
}
if (profile is CompilationProfile.SafeCoreMir or CompilationProfile.SafeCoreMirV2)
{
SafeCoreMirPipelineResult evidence = SafeCoreMirPipeline.Analyze(syntax,
new SafeCoreMirPipelineOptions
{
CancellationToken = cancellationToken,
RequireOwnershipEvidence = true,
RequireCleanupEvidence = true,
EnableRepeatedArrays = profile == CompilationProfile.SafeCoreMirV2,
EnableP1Extensions = profile == CompilationProfile.SafeCoreMirV2,
Crates = crates.IsDefault ? [] : crates,
});
if (!evidence.IsSuccessful)
{
IReadOnlyList<Diagnostic> diagnostics = evidence.Diagnostics.Count != 0
? evidence.Diagnostics
: evidence.Ownership?.Diagnostics ??
[new Diagnostic("RSC0007", "Typed MIR analysis failed.", syntax.Root!.Span)
{ SourcePath = sourcePath }];
return new([], [], diagnostics);
}
// Consume the already validated MIR directly. Re-running the
// primitive HIR checker here used to make aggregate MIR evidence
// observational only and could let backend behavior drift from the
// source-to-MIR contract.
SafeCoreClrResult emitted = SafeCoreMirClrLowering.Lower(
evidence.Mir!.Program!, cancellationToken);
return AttachMirEvidence(emitted, evidence, requireOwnershipMetadata: true);
}
SafeCoreHirResult hir = SafeCoreHirLowering.Lower(syntax, new SafeCoreHirLoweringOptions
{
CancellationToken = cancellationToken,
NameResolution = new SafeCoreNameResolutionOptions
{
CancellationToken = cancellationToken,
EnableTypeSystemExtensions = false,
Crates = crates.IsDefault ? [] : crates,
},
});
SafeCoreTypeCheckResult types = SafeCoreTypeChecking.Check(hir, cancellationToken);
if (!types.IsSuccessful) return new([], [], types.Diagnostics);
SafeCoreClrResult lowered = SafeCoreClrLowering.Lower(types.Program!, cancellationToken);
// Primitive programs remain source-compatible with the existing
// profile. When the richer evidence pipeline accepts the same source,
// attach its deterministic MIR/ownership facts without making the
// legacy executable gate depend on optional constructs.
try
{
SafeCoreMirPipelineResult evidence = SafeCoreMirPipeline.Analyze(syntax,
new SafeCoreMirPipelineOptions
{
CancellationToken = cancellationToken,
RequireOwnershipEvidence = true,
Crates = crates.IsDefault ? [] : crates,
});
if (evidence.Mir is { IsSuccessful: true })
lowered = AttachMirEvidence(lowered, evidence);
}
catch (OperationCanceledException) { throw; }
catch (TimeoutException) { }
return lowered;
}
private static SafeCoreClrResult AttachMirEvidence(
SafeCoreClrResult emitted,
SafeCoreMirPipelineResult evidence,
bool requireOwnershipMetadata = false)
{
if (!emitted.IsSuccessful)
return emitted;
if (evidence.Mir is not { IsSuccessful: true } mir || mir.Program is null)
return emitted;
string snapshot = evidence.MirSnapshot ?? SafeCoreMirFormatting.Format(mir.Program);
SafeCoreClrResult result = emitted with
{
MirSnapshot = snapshot,
CleanupSnapshot = evidence.Cleanup?.Snapshot,
};
if (evidence.Ownership is { IsSuccessful: true } ownership)
{
try { result = SafeCoreOwnershipMetadata.Attach(result, ownership); }
catch (ArgumentException exception) when (requireOwnershipMetadata)
{
// SafeCoreMir is an evidence-carrying executable profile. A
// metadata-shape failure must remain a compilation diagnostic;
// silently emitting a MIR-only assembly would make ownership
// claims depend on whether the caller used check or compile.
result = result with
{
Diagnostics = [new Diagnostic("RSM2104",
"Safe-core ownership metadata could not be attached: " +
TrimDiagnostic(exception.Message), mir.Program.Functions[0].Source.Span)
{ SourcePath = mir.Program.Functions[0].Source.SourcePath }],
};
}
}
return result;
}
private static bool IsCargoManifest(string path) => string.Equals(Path.GetFileName(path), "Cargo.toml", StringComparison.OrdinalIgnoreCase);
private static string? TryResolveCargo(string path, CancellationToken cancellationToken, out IReadOnlyList<Diagnostic>? diagnostics)
{
diagnostics = null;
if (!string.Equals(Path.GetFileName(path), "Cargo.toml", StringComparison.OrdinalIgnoreCase)) return null;
CargoWorkspaceResult workspace = CargoWorkspace.Load(path, cancellationToken: cancellationToken);
if (!workspace.IsSuccessful)
{
diagnostics = workspace.Diagnostics;
return null;
}
return workspace.RootPackage.SourcePath;
}
private static IReadOnlyList<Diagnostic> MapDiagnostics(
IReadOnlyList<Diagnostic> diagnostics, SafeCoreSourceMap? sourceMap)
{
if (sourceMap is null || diagnostics.Count == 0) return diagnostics;
var mapped = new Diagnostic[diagnostics.Count];
for (var index = 0; index < diagnostics.Count; index++)
{
Diagnostic diagnostic = diagnostics[index];
SafeCoreSourceLocation location = sourceMap.MapSpan(diagnostic.Span);
mapped[index] = diagnostic with { SourcePath = location.Document.Path, Span = location.Span };
}
return mapped;
}
private static void WriteArtifactsTransactionally(
string assemblyPath,
string pdbPath,
string runtimeConfigPath,
GeneratedAssembly generated)
{
var outputDirectory = Path.GetDirectoryName(assemblyPath)
?? throw new InvalidOperationException("The output path has no parent directory.");
if (generated.RequiresMirRuntime && string.Equals(Path.GetFileName(assemblyPath),
"RustSharp.Runtime.dll", StringComparison.OrdinalIgnoreCase))
throw new IOException("The MIR output filename is reserved for its RustSharp.Runtime.dll dependency.");
Directory.CreateDirectory(outputDirectory);
// FileStream.Lock is an OS-level advisory/mandatory lock (depending on
// the platform), so it serializes compiler instances in this process
// and in other processes without leaving an ownership lease to expire.
// The directory scope also covers transactions whose derived artifact
// paths overlap despite having different assembly output names.
using var outputLock = AcquireOutputDirectoryLock(outputDirectory);
string transactionId = $".rsc-transaction-{Environment.ProcessId}-{Guid.NewGuid():N}";
string transactionDirectory = Path.Combine(outputDirectory, transactionId);
string stagingDirectory = Path.Combine(outputDirectory, transactionId, "staged");
string backupDirectory = Path.Combine(outputDirectory, transactionId, "backups");
var artifacts = new[]
{
new PendingArtifact(assemblyPath, Path.Combine(stagingDirectory, Path.GetFileName(assemblyPath)), generated.PeImage),
new PendingArtifact(pdbPath, Path.Combine(stagingDirectory, Path.GetFileName(pdbPath)), generated.PdbImage),
new PendingArtifact(
runtimeConfigPath,
Path.Combine(stagingDirectory, Path.GetFileName(runtimeConfigPath)),
new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(generated.RuntimeConfigJson)),
};
if (generated.RequiresMirRuntime)
{
string runtimePath = Path.Combine(outputDirectory, "RustSharp.Runtime.dll");
artifacts = [.. artifacts, new PendingArtifact(runtimePath,
Path.Combine(stagingDirectory, "RustSharp.Runtime.dll"),
File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "RustSharp.Runtime.dll")))];
}
var movedTargets = new List<string>(artifacts.Length);
var backups = new List<(string Target, string Backup)>(artifacts.Length);
var transactionDiagnostics = new List<string>(capacity: artifacts.Length + 1);
Exception? failure = null;
var committed = false;
try
{
Directory.CreateDirectory(stagingDirectory);
Directory.CreateDirectory(backupDirectory);
foreach (PendingArtifact artifact in artifacts)
{
WriteBytesDurably(artifact.StagedPath, artifact.Content);
}
foreach (PendingArtifact artifact in artifacts)
{
if (File.Exists(artifact.TargetPath))
{
string backupPath = Path.Combine(backupDirectory, Path.GetFileName(artifact.TargetPath));
File.Move(artifact.TargetPath, backupPath);
backups.Add((artifact.TargetPath, backupPath));
}
File.Move(artifact.StagedPath, artifact.TargetPath);
movedTargets.Add(artifact.TargetPath);
}
// Once every target has been installed, the transaction is
// committed. Removing old backups is cleanup only and must never
// cause the newly committed files to be rolled back.
committed = true;
DeleteBackupsBestEffort(backups, transactionDiagnostics);
}
catch (Exception exception)
{
failure = exception;
if (!committed)
{
transactionDiagnostics.AddRange(
RollbackArtifacts(movedTargets, backups));
}
}
finally
{
string? transactionCleanupDiagnostic = TryDeleteDirectory(transactionDirectory);
if (transactionCleanupDiagnostic is not null)
{
transactionDiagnostics.Add(transactionCleanupDiagnostic);
}
}
if (transactionDiagnostics.Count != 0)
{
Trace.WriteLine(
$"RustSharp output transaction '{transactionDirectory}' cleanup: " +
string.Join("; ", transactionDiagnostics));
}
if (failure is not null)
{
if (!committed && transactionDiagnostics.Count != 0)
{
throw new ArtifactTransactionException(failure, transactionDiagnostics);
}
ExceptionDispatchInfo.Capture(failure).Throw();
}
}
private static void DeleteBackupsBestEffort(
List<(string Target, string Backup)> backups,
List<string> diagnostics)
{
foreach ((_, string backupPath) in backups)
{
try
{
File.Delete(backupPath);
}
catch (Exception exception) when (IsFileSystemCleanupException(exception))
{
diagnostics.Add(
$"Could not remove backup '{backupPath}': {TrimDiagnostic(exception.Message)}");
}
}
}
private static List<string> RollbackArtifacts(
List<string> movedTargets,
List<(string Target, string Backup)> backups)
{
var diagnostics = new List<string>(capacity: movedTargets.Count + backups.Count);
// Delete only targets that this transaction moved. Each operation is
// independent so a locked artifact cannot prevent other backups from
// being restored.
for (var index = movedTargets.Count - 1; index >= 0; index--)
{
string targetPath = movedTargets[index];
try
{
File.Delete(targetPath);
}
catch (Exception exception) when (IsFileSystemCleanupException(exception))
{
diagnostics.Add(
$"Could not remove moved target '{targetPath}': {TrimDiagnostic(exception.Message)}");
}
}
for (var index = backups.Count - 1; index >= 0; index--)
{
(string targetPath, string backupPath) = backups[index];
try
{
if (File.Exists(backupPath) && !File.Exists(targetPath))
{
File.Move(backupPath, targetPath);
}
}
catch (Exception exception) when (IsFileSystemCleanupException(exception))
{
diagnostics.Add(
$"Could not restore backup '{backupPath}' to '{targetPath}': " +
TrimDiagnostic(exception.Message));
}
}
return diagnostics;
}
private static OutputPathLock AcquireOutputDirectoryLock(string outputDirectory)
{
string canonicalPath = GetCanonicalOutputDirectory(outputDirectory);
OutputLockEntry entry;
lock (OutputLockRegistryGate)
{
if (!OutputLockEntries.TryGetValue(canonicalPath, out entry!))
{
entry = new OutputLockEntry();
OutputLockEntries.Add(canonicalPath, entry);
}
entry.ReferenceCount++;
}
var monitorHeld = false;
try
{
if (!Monitor.TryEnter(
entry.Gate,
OutputLockAttempts * OutputLockRetryMilliseconds))
{
throw new IOException(
$"Could not acquire the in-process compiler output lock for '{outputDirectory}' after " +
$"{OutputLockAttempts * OutputLockRetryMilliseconds} ms.");
}
monitorHeld = true;
FileStream lockStream = AcquireCrossProcessOutputLock(outputDirectory);
return new OutputPathLock(canonicalPath, entry, lockStream);
}
catch
{
if (monitorHeld)
{
Monitor.Exit(entry.Gate);
}
ReleaseOutputLockEntry(canonicalPath, entry);
throw;
}
}
private static FileStream AcquireCrossProcessOutputLock(string outputDirectory)
{
string lockPath = GetOutputLockPath(outputDirectory);
IOException? lastException = null;
for (var attempt = 0; attempt < OutputLockAttempts; attempt++)
{
FileStream? lockStream = null;
try
{
lockStream = new FileStream(
lockPath,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
OperatingSystem.IsMacOS() ? FileShare.None : FileShare.ReadWrite,
bufferSize: 1,
FileOptions.None);
if (!OperatingSystem.IsMacOS())
{
lockStream.Lock(0, OutputLockRegionLength);
}
return lockStream;
}
catch (IOException exception)
{
lastException = exception;
DisposeLockStream(lockStream);
if (attempt + 1 < OutputLockAttempts)
{
Thread.Sleep(OutputLockRetryMilliseconds);
}
}
catch (PlatformNotSupportedException exception)
{
DisposeLockStream(lockStream);
throw new IOException(
"The current platform does not support output path locking.",
exception);
}
catch (NotSupportedException exception)
{
DisposeLockStream(lockStream);
throw new IOException(
"The current file system does not support output path locking.",
exception);
}
}
throw new IOException(
$"Could not acquire the compiler output lock for '{outputDirectory}' after " +
$"{OutputLockAttempts} attempts ({OutputLockAttempts * OutputLockRetryMilliseconds} ms).",
lastException);
}
private static void DisposeLockStream(FileStream? lockStream)
{
if (lockStream is null)
{
return;
}
try
{
lockStream.Dispose();
}
catch (Exception exception) when (IsFileSystemCleanupException(exception))
{
Trace.WriteLine($"Could not dispose output lock stream: {TrimDiagnostic(exception.Message)}");
}
}
private static string GetOutputLockPath(string outputDirectory)
{
string canonicalPath = GetCanonicalOutputDirectory(outputDirectory);
string pathHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(canonicalPath)));
// Keep the sidecar instead of deleting it on release: deleting a lock
// file races with a waiter that is opening the same path. OS locks are
// released automatically when the owning process exits.
return Path.Combine(outputDirectory, $".rsc-directory-{pathHash}.lock");
}
private static string GetCanonicalOutputDirectory(string outputDirectory)
{
string fullPath = Path.GetFullPath(outputDirectory);
string withoutTrailingSeparator = Path.TrimEndingDirectorySeparator(fullPath);
return OperatingSystem.IsWindows()
? withoutTrailingSeparator.ToUpperInvariant()
: withoutTrailingSeparator;
}
private static void ReleaseOutputLockEntry(string canonicalPath, OutputLockEntry entry)
{
lock (OutputLockRegistryGate)
{
if (entry.ReferenceCount > 0)
{
entry.ReferenceCount--;
}
if (entry.ReferenceCount == 0 &&
OutputLockEntries.TryGetValue(canonicalPath, out OutputLockEntry? current) &&
ReferenceEquals(current, entry))
{
_ = OutputLockEntries.Remove(canonicalPath);
}
}
}
private static string? TryDeleteDirectory(string path)
{
try
{
if (Directory.Exists(path))
{
Directory.Delete(path, recursive: true);
}
return null;
}
catch (Exception exception) when (IsFileSystemCleanupException(exception))
{
return $"Could not remove transaction directory '{path}': {TrimDiagnostic(exception.Message)}";
}
}
private static bool IsFileSystemCleanupException(Exception exception) =>
exception is IOException or