Repository navigation
Expand file tree
/
Copy pathVerification.cs
More file actions
4531 lines (4172 loc) · 258 KB
/
Copy pathVerification.cs
File metadata and controls
4531 lines (4172 loc) · 258 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.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
partial class Program : IDisposable
{
#if LEANCIL_TOOL
static string Root { get; } = Path.Combine(AppContext.BaseDirectory, "verification");
#else
// Settable so a test can stand a few modules in for the framework; the tool's root is fixed.
static string Root { get; set; } = FixtureRoot() ??
Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Source())!, ".."));
// Only relocated binaries need the producer's source path replaced. Source-built children
// may belong to an isolated corpus and must retain their own Verification.cs location.
static string? FixtureRoot()
{
var root = Environment.GetEnvironmentVariable("LEANCIL_FIXTURE_ROOT");
var manifest = Environment.GetEnvironmentVariable("LEANCIL_FIXTURE_MANIFEST");
if (string.IsNullOrEmpty(root) || string.IsNullOrEmpty(manifest)) return null;
var directory = Path.GetDirectoryName(Path.GetFullPath(manifest))! + Path.DirectorySeparatorChar;
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
return typeof(Program).Assembly.Location.StartsWith(directory, comparison) ? Path.GetFullPath(root) : null;
}
#endif
static string Source([CallerFilePath] string path = "") => path;
/// <summary>The certified library, read in place; deleted on disposal only when this process built it.</summary>
string? library;
bool ownsLibrary;
/// <summary>The cache entry this process published from the library it built, which outlives the process.</summary>
string? publishedLibrary;
/// <summary>Length and write time of each file of a library read in place, as it was when opened.</summary>
SortedDictionary<string, string>? libraryStamps;
/// <summary>
/// Every module of the open library when it is a closure entry, which holds only those; null for the
/// whole library. <see cref="libraryKey"/> then names exactly this list.
/// </summary>
string[]? libraryModules;
/// <summary>A report was written against a closure entry, so the whole library is still to be built.</summary>
bool completesLibrary;
/// <summary>The use locks of the cache entries this process reads in place, held until it is disposed.</summary>
readonly List<FileStream> entryUses = [];
/// <summary>This process's writable package, which requires <see cref="library"/> by path.</summary>
string? session;
/// <summary>The base library's compiled module artifacts, taken from its validated manifest.</summary>
SortedDictionary<string, string>? baseModules;
const string CertifiedFingerprintsName = "canonical-fingerprints.json";
string? certifiedFingerprintsSha;
string? resolvedToolchain;
bool extractorBuilt;
const string ExtractorBuildEnvironment = "LEANCIL_PREPARED_EXTRACTOR";
const string PrebuiltToolsEnvironment = "LEANCIL_PREBUILT_TOOLS";
#if !LEANCIL_TOOL
const string FixtureManifestEnvironment = "LEANCIL_FIXTURE_MANIFEST";
const string FixtureDigestEnvironment = "LEANCIL_FIXTURE_MANIFEST_SHA256";
sealed record PreparedFixture(string Assembly, SortedDictionary<string, string> Inputs,
SortedDictionary<string, string> Outputs);
sealed record PreparedFixtures(string Sdk, string Runtime, Dictionary<string, PreparedFixture> Fixtures);
static string? fixtureSdk;
static SortedDictionary<string, string>? FixtureInputs(string script)
{
var inputs = new SortedDictionary<string, string>(StringComparer.Ordinal);
var supported = true;
void Add(string path)
{
path = Path.GetFullPath(path);
var relative = Path.GetRelativePath(Root, path).Replace('\\', '/');
if (relative.StartsWith("../", StringComparison.Ordinal) || Path.IsPathRooted(relative))
throw new InvalidOperationException("Fixture input is outside the checkout: " + path);
if (!inputs.TryAdd(relative, Sha(path))) return;
if (Path.GetExtension(path) != ".cs") return;
var source = File.ReadAllText(path);
// Project references bring in an MSBuild graph not described by file-app includes.
if (Regex.IsMatch(source, @"(?m)^[\t ]*#:project\b")) supported = false;
foreach (Match include in Regex.Matches(source, @"(?m)^[\t ]*#:include\s+([^\r\n]+)"))
Add(Path.Combine(Path.GetDirectoryName(path)!, include.Groups[1].Value.Trim()));
}
Add(At(script));
var root = Path.TrimEndingDirectorySeparator(Root);
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
for (var directory = Path.GetDirectoryName(Path.GetFullPath(script, Root)); directory is not null;
directory = Path.GetDirectoryName(directory))
{
foreach (var path in Directory.EnumerateFiles(directory))
if (Path.GetExtension(path).ToLowerInvariant() is ".props" or ".targets" ||
Path.GetFileName(path).ToLowerInvariant() is "global.json" or "nuget.config" or ".editorconfig")
Add(path);
if (directory.Equals(root, comparison)) break;
}
return supported ? inputs : null;
}
// The workflow pins this manifest's digest separately from its downloadable artifact.
static string[]? PreparedFixtureCommand(string script, string[] arguments)
{
var manifest = Environment.GetEnvironmentVariable(FixtureManifestEnvironment);
if (string.IsNullOrEmpty(manifest)) return null;
if (Sha(manifest) != Environment.GetEnvironmentVariable(FixtureDigestEnvironment))
throw new InvalidOperationException("Prepared fixture manifest changed");
var prepared = JsonSerializer.Deserialize<PreparedFixtures>(File.ReadAllText(manifest))!;
var relative = Path.GetRelativePath(Root, Path.GetFullPath(script, Root)).Replace('\\', '/');
if (!prepared.Fixtures.TryGetValue(relative, out var fixture)) return null;
fixtureSdk ??= Run(["dotnet", "--version"]).Trim();
if (prepared.Runtime != RuntimeInformation.RuntimeIdentifier || prepared.Sdk != fixtureSdk ||
FixtureInputs(relative) is not { } inputs || !Same(fixture.Inputs, inputs)) return null;
var directory = Path.GetDirectoryName(manifest)!;
directory = Path.GetFullPath(directory);
var assemblyDirectory = Path.GetDirectoryName(Path.GetFullPath(fixture.Assembly, directory))!;
if (!Directory.Exists(assemblyDirectory) ||
!fixture.Outputs.Keys.ToHashSet(StringComparer.Ordinal).SetEquals(
Directory.EnumerateFiles(assemblyDirectory, "*", SearchOption.AllDirectories)
.Select(path => Path.GetRelativePath(directory, path).Replace('\\', '/'))))
throw new InvalidOperationException("Prepared fixture output set changed: " + relative);
foreach (var (path, hash) in fixture.Outputs)
{
var full = Path.GetFullPath(path, directory);
if (!full.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) ||
!File.Exists(full) || Sha(full) != hash)
throw new InvalidOperationException("Prepared fixture output changed: " + path);
}
if (!fixture.Outputs.ContainsKey(fixture.Assembly))
throw new InvalidOperationException("Prepared fixture assembly is missing from the manifest");
return ["dotnet", Path.GetFullPath(fixture.Assembly, directory), .. arguments];
}
static string[] ReusePreparedFixture(string[] command, string cwd)
{
if (command.Length < 4 || command[0] != "dotnet" || command[1] != "run" || command[2] != "--file")
return command;
var separator = Array.IndexOf(command, "--", 4);
var options = command[4..(separator < 0 ? command.Length : separator)];
// Only the repository's standard Release build options match the producer.
if (options.Length != 0 && !options.SequenceEqual(new[] { "-c", "Release", "--no-build",
"-p:EnforceCodeStyleInBuild=true", "-p:GenerateDocumentationFile=true" }) &&
!options.SequenceEqual(new[] { "-c", "Release",
"-p:EnforceCodeStyleInBuild=true", "-p:GenerateDocumentationFile=true" })) return command;
var arguments = separator < 0 ? [] : command[(separator + 1)..];
// Nested fixtures share the parent's Release configuration but still rebuild changed sources.
return PreparedFixtureCommand(Path.GetFullPath(command[3], cwd), arguments) ??
(options.Length == 0 ? FixtureCommand(command[3], arguments, prepared: false) : command);
}
#endif
static string[] FixtureCommand(string script, string[] arguments, bool prepared)
{
string[] buildArguments = prepared
? ["-c", "Release", "--no-build", "-p:EnforceCodeStyleInBuild=true",
"-p:GenerateDocumentationFile=true"]
: ["-c", "Release", "-p:EnforceCodeStyleInBuild=true", "-p:GenerateDocumentationFile=true"];
return ["dotnet", "run", "--file", script, .. buildArguments, "--", .. arguments];
}
// A parent build can be reused only while its sources and complete output still match.
static string ExtractorBuildIdentity()
{
if (!File.Exists(ExtractorPath)) return "";
var inputs = CommonInputs();
foreach (var path in Directory.EnumerateFiles(Root))
inputs["root:" + Path.GetFileName(path)] = Sha(path);
foreach (var path in Directory.EnumerateFiles(At("Extractor"), "*", SearchOption.AllDirectories))
{
var relative = Path.GetRelativePath(Root, path).Replace('\\', '/');
if (!relative.Split('/').Any(part => part is "bin" or "obj"))
inputs[relative] = Sha(path);
}
foreach (var path in Directory.EnumerateFiles(Path.GetDirectoryName(ExtractorPath)!, "*",
SearchOption.AllDirectories))
inputs["output:" + Path.GetRelativePath(Root, path)] = Sha(path);
return ContentKey(Root + JsonSerializer.Serialize(inputs));
}
static bool PreparedExtractorMatches()
{
var prepared = Environment.GetEnvironmentVariable(ExtractorBuildEnvironment);
return !string.IsNullOrEmpty(prepared) && prepared == ExtractorBuildIdentity();
}
void EnsureExtractorBuilt()
{
if (extractorBuilt) return;
if (!PreparedExtractorMatches())
Run(["dotnet", "build", "Extractor", "-c", "Release",
"-p:EnforceCodeStyleInBuild=true", "-p:GenerateDocumentationFile=true"]);
extractorBuilt = true;
}
int extractionCacheHits;
int proofCacheHits;
int supportCacheHits;
SortedDictionary<string, string>? certifiedModules;
byte[]? receiptKey;
readonly HashSet<string> preparedSupport = new(StringComparer.Ordinal);
string? verificationPolicy;
string VerificationPolicy => verificationPolicy ??= Sha(typeof(Program).Assembly.Location);
readonly Dictionary<string, SortedDictionary<string, string>> supportSourceKeys = new(StringComparer.Ordinal);
bool forceFullVerification { get; init; }
sealed record FullImportResult(string Theorem, string Audit, PublishedImport[] Imports,
DeploymentDependency[] Dependencies);
Func<string, string, string, string, FullImportResult>? fullImportAudit { get; set; }
readonly AsyncLocal<bool> referenceOnlyContext = new();
bool referenceOnlyAuthoring { get => referenceOnlyContext.Value; set => referenceOnlyContext.Value = value; }
bool UseSuccessCache => !referenceOnlyAuthoring && !freshProofs && !freshLibrary &&
!string.Equals(Environment.GetEnvironmentVariable("LEANCIL_DISABLE_SUCCESS_CACHE"), "true", StringComparison.OrdinalIgnoreCase);
/// <summary>The directory of certified library entries, each named by its key, and of the success cache.</summary>
static string LibraryCacheRoot => Environment.GetEnvironmentVariable("LEANCIL_CACHE_DIR") ??
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LeanCIL",
"libraries");
static string SuccessCacheRoot => Path.Combine(LibraryCacheRoot, "success-v1");
byte[] ReceiptKey
{
get
{
if (receiptKey is not null) return receiptKey;
var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "LeanCIL", "receipts");
Directory.CreateDirectory(directory);
var path = Path.Combine(directory, "key-v1");
try
{
var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, Share = FileShare.None };
if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
using var file = new FileStream(path, options);
file.Write(RandomNumberGenerator.GetBytes(32));
}
catch (IOException) when (File.Exists(path)) { }
for (var attempt = 0; ; attempt++)
{
try
{
var bytes = File.ReadAllBytes(path);
if (bytes.Length != 32) throw new InvalidDataException("Invalid local certification key");
return receiptKey = bytes;
}
catch (IOException) when (attempt < 100) { Thread.Sleep(10); }
}
}
}
static string ContentKey(string value) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(value)));
SortedDictionary<string, string>? AuthenticatedSuccess(string key)
{
var cached = Path.Combine(SuccessCacheRoot, key);
try
{
var manifest = File.ReadAllBytes(Path.Combine(cached, "receipt.json"));
var signature = File.ReadAllBytes(Path.Combine(cached, "receipt.hmac"));
if (!CryptographicOperations.FixedTimeEquals(HMACSHA256.HashData(ReceiptKey, Encoding.UTF8.GetBytes(key).Concat(manifest).ToArray()), signature)) return null;
var expected = JsonSerializer.Deserialize<SortedDictionary<string, string>>(manifest);
return expected is not null && Same(expected, CacheFiles(Path.Combine(cached, "files"))) ? expected : null;
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException) { return null; }
}
bool RestoreSuccess(string key, string destination)
{
if (!UseSuccessCache) return false;
try
{
var expected = AuthenticatedSuccess(key);
if (expected is null) return false;
CopyTree(Path.Combine(SuccessCacheRoot, key, "files"), destination);
foreach (var (name, hash) in expected)
if (Sha(Path.Combine(destination, name)) != hash)
throw new InvalidOperationException("Certified cache changed while copying");
return true;
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException) { return false; }
}
// The cache only saves work: a full disk warns instead of failing a verified result.
void PublishSuccess(string key, string source, string? family = null)
{
if (!UseSuccessCache) return;
try { PublishCertified(key, source, family); }
catch (IOException error)
{
long? free = null;
try { free = new DriveInfo(Path.GetFullPath(SuccessCacheRoot)).AvailableFreeSpace; }
catch (Exception probe) when (probe is IOException or ArgumentException or UnauthorizedAccessException) { }
Console.Error.WriteLine($"warning: success cache {SuccessCacheRoot} not updated" +
(free is long bytes ? $" ({bytes / 1e9:0.0} GB free)" : "") + ": " + error.Message);
}
}
// Published entries are immutable: an authenticated entry is never duplicated
// or overwritten, and concurrent publishers race only on an atomic rename.
void PublishCertified(string key, string source, string? family)
{
Directory.CreateDirectory(SuccessCacheRoot);
var cached = Path.Combine(SuccessCacheRoot, key);
if (AuthenticatedSuccess(key) is not null)
{
TouchEntry(cached);
return;
}
var staging = cached + "." + Guid.NewGuid().ToString("N");
try
{
var files = Path.Combine(staging, "files");
Directory.CreateDirectory(files);
if (family is null) CopyTree(source, files);
else LinkOrCopyTree(source, files, family);
var manifest = JsonSerializer.SerializeToUtf8Bytes(CacheFiles(files));
File.WriteAllBytes(Path.Combine(staging, "receipt.json"), manifest);
File.WriteAllBytes(Path.Combine(staging, "receipt.hmac"), HMACSHA256.HashData(ReceiptKey, Encoding.UTF8.GetBytes(key).Concat(manifest).ToArray()));
try
{
Directory.Move(staging, cached);
return;
}
catch (IOException) when (Directory.Exists(cached)) { }
if (AuthenticatedSuccess(key) is not null) return;
// Replace a corrupt or unauthenticated entry; readers authenticate every file.
var invalid = cached + ".invalid-" + Guid.NewGuid().ToString("N");
try
{
Directory.Move(cached, invalid);
Directory.Move(staging, cached);
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
finally
{
try { if (Directory.Exists(invalid)) Directory.Delete(invalid, true); }
catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
}
}
finally { if (Directory.Exists(staging)) Directory.Delete(staging, true); }
}
string LeanExecutable => Path.Combine(Toolchain, "bin", OperatingSystem.IsWindows() ? "lean.exe" : "lean");
// Pin the sysroot that `lake env` would supply, so direct Lean runs use the trusted toolchain.
IReadOnlyDictionary<string, string> LeanEnvironment => new Dictionary<string, string> { ["LEAN_SYSROOT"] = Toolchain };
readonly byte[] bootstrapReplaySource = File.ReadAllBytes(At("CIL/Replay.lean"));
// Per-module replay re-imports each module's dependencies; one shared import of
// everything outside the targets makes large sets several times cheaper.
// Imported target declarations cannot be skipped as already-checked duplicate theorems.
// False when the set is ineligible or any declaration is rejected; callers then replay per module.
bool ReplayModulesJointly(string cwd, string[] targets, string leanPath, string progress)
{
var runner = Path.Combine(Path.GetTempPath(), "leancil-joint-replay-" + Guid.NewGuid().ToString("N") + ".lean");
var targetsPath = Path.ChangeExtension(runner, ".json");
try
{
File.WriteAllText(targetsPath, JsonSerializer.Serialize(targets));
string[] command;
if (auditExecutable is not null)
command = [CheckedAuditExecutable(), "--replay", targetsPath];
else
{
// Bootstrap certification cannot trust the native auditor before authenticating it.
if (Convert.ToHexStringLower(SHA256.HashData(bootstrapReplaySource)) != Sha(At("CIL/Replay.lean")))
throw new InvalidDataException("Kernel replay source changed before certification.");
File.WriteAllText(runner, Encoding.UTF8.GetString(bootstrapReplaySource) +
"\n#eval do\n let json ← IO.FS.readFile (String.fromUTF8! (ByteArray.mk #[" +
string.Join(",", System.Text.Encoding.UTF8.GetBytes(targetsPath)) +
"]))\n let args ← IO.ofExcept <| (Lean.Json.parse json).bind Lean.fromJson?\n" +
" CIL.Replay.replayModulesJointly args\n");
command = [LeanExecutable, runner];
}
var result = Execute(command, cwd, leanPath, progress: progress, environment: LeanEnvironment);
if (auditExecutable is not null) CheckedAuditExecutable();
if (result.Code != 0) return false;
var replayed = new HashSet<string>(StringComparer.Ordinal);
foreach (var line in result.Stdout.Split('\n', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
{
if (!line.StartsWith('{')) continue;
try
{
var record = JsonSerializer.Deserialize<JsonElement>(line);
if (record.ValueKind == JsonValueKind.Object && record.TryGetProperty("joint", out var joint) &&
joint.ValueKind == JsonValueKind.True && record.TryGetProperty("module", out var module) &&
module.ValueKind == JsonValueKind.String)
replayed.Add(module.GetString()!);
}
catch (JsonException) { }
}
return replayed.SetEquals(targets);
}
finally { File.Delete(runner); File.Delete(targetsPath); }
}
// Joint replay shares imported dependencies; rejected target sets retain the toolchain fallback.
void ReplayCheckedModules(string[] targets, string leanPath, string progress)
{
if ((targets.Length > 1 || (targets.Length == 1 && auditExecutable is not null)) &&
ReplayModulesJointly(Root, targets, leanPath, progress)) return;
Run([Path.Combine(Toolchain, "bin", OperatingSystem.IsWindows() ? "leanchecker.exe" : "leanchecker"),
.. targets], leanPath: leanPath, progress: progress);
}
static SortedDictionary<string, string> ModuleArtifacts(string session) =>
!Directory.Exists(Path.Combine(session, ".lake/build/lib/lean")) ? new(StringComparer.Ordinal) :
HashFiles(Directory.EnumerateFiles(Path.Combine(session, ".lake/build/lib/lean"), "*", SearchOption.AllDirectories)
.Where(path => Path.GetFileName(path).Contains(".olean", StringComparison.Ordinal))
.Select(path => (Path.GetRelativePath(Path.Combine(session, ".lake/build/lib/lean"), path)
.Replace('\\', '/'), path)));
// Publish a deterministic manifest only after every file has been hashed successfully.
static SortedDictionary<string, string> HashFiles(IEnumerable<(string Name, string Path)> files)
{
var entries = files.ToArray();
var hashes = new string[entries.Length];
var failures = new ExceptionDispatchInfo?[entries.Length];
const int maximumWorkers = 4;
Parallel.For(0, entries.Length,
new ParallelOptions { MaxDegreeOfParallelism = Math.Min(maximumWorkers, Environment.ProcessorCount) },
index =>
{
try { hashes[index] = Sha(entries[index].Path); }
catch (Exception error) { failures[index] = ExceptionDispatchInfo.Capture(error); }
});
var result = new SortedDictionary<string, string>(StringComparer.Ordinal);
for (var index = 0; index < entries.Length; index++)
{
// Preserve ordinary I/O exceptions so invalid-cache handling still applies.
failures[index]?.Throw();
result.Add(entries[index].Name, hashes[index]);
}
return result;
}
static string ModuleName(string artifact) => artifact.Split(".olean", 2)[0].Replace('/', '.');
string Toolchain => resolvedToolchain ??= Run(["lean", "--print-prefix"]).Trim();
SortedDictionary<string, string>? libraryInputs;
static string At(string path) => Path.Combine(Root, path);
/// <summary>Deletes a tree that may hold git objects, which git marks read-only and Windows refuses to delete.</summary>
static void DeleteTree(string directory)
{
EnumerationOptions ownFiles = new() { RecurseSubdirectories = true, AttributesToSkip = FileAttributes.ReparsePoint };
foreach (var file in Directory.EnumerateFiles(directory, "*", ownFiles))
File.SetAttributes(file, FileAttributes.Normal);
Directory.Delete(directory, recursive: true);
}
static string Sha(string path)
{
const int bufferSize = 64 * 1024;
using var file = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.Read);
var length = RandomAccess.GetLength(file);
if (length > Array.MaxLength) throw new IOException("The file is too long to read.");
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
var buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
// A positive initial length bounds the read; premature EOF must fail.
var offset = 0L;
while (length == 0 || offset < length)
{
var count = length == 0 ? bufferSize : (int)Math.Min(bufferSize, length - offset);
var read = RandomAccess.Read(file, buffer.AsSpan(0, count), offset);
if (read == 0)
{
if (length != 0) throw new EndOfStreamException();
break;
}
hash.AppendData(buffer, 0, read);
offset += read;
}
return Convert.ToHexStringLower(hash.GetHashAndReset());
}
finally { ArrayPool<byte>.Shared.Return(buffer); }
}
static void CacheProgress(string message)
{
#if !LEANCIL_TOOL
Console.WriteLine("CACHE " + message);
#endif
}
static readonly JsonSerializerOptions Json = new() { WriteIndented = true };
sealed class ProgressSummary(string label)
{
readonly object gate = new();
string latest = "";
int pending;
public void Add(string line, TextWriter writer)
{
if (string.IsNullOrWhiteSpace(line)) return;
lock (gate)
{
if (line.StartsWith("PASS ", StringComparison.Ordinal) || line.StartsWith("All ", StringComparison.Ordinal))
writer.WriteLine(line);
else
{
// Lake prints axiom details after its completed-target line.
// Keep the target count or proof phase as the summary instead.
if (latest.Length == 0 || (!line.StartsWith("info: ", StringComparison.Ordinal) &&
!line.Contains("depends on axioms:", StringComparison.Ordinal)))
latest = line.Length > 200 ? line[..200] + "…" : line;
pending++;
}
}
}
public void Report()
{
lock (gate)
{
if (pending == 0) return;
Console.WriteLine($"PROGRESS {label}: {latest} ({pending} output lines since last update)");
pending = 0;
}
}
}
/// <summary>The latest `[done/total]` job count that a Lake build printed, for progress lines.</summary>
sealed partial class JobCount
{
string latest = "";
public void Add(string line)
{
if (LakeJob().Match(line) is { Success: true } job)
Volatile.Write(ref latest, $": {job.Groups[1].Value} of {job.Groups[2].Value} Lake jobs");
}
public override string ToString() => Volatile.Read(ref latest);
[GeneratedRegex(@"\A(?:\S+ )?\[([0-9]+)/([0-9]+)\] ")]
private static partial Regex LakeJob();
}
static async Task<string> CaptureOutput(StreamReader reader, TextWriter writer, ProgressSummary? summary = null,
TextWriter? transcript = null, JobCount? jobs = null)
{
var captured = new StringBuilder();
var line = new StringBuilder();
var buffer = new char[4096];
int count;
while ((count = await reader.ReadAsync(buffer)) != 0)
{
captured.Append(buffer, 0, count);
if (transcript is not null)
{
await transcript.WriteAsync(buffer.AsMemory(0, count));
await transcript.FlushAsync();
}
if (summary is null)
{
await writer.WriteAsync(buffer.AsMemory(0, count));
await writer.FlushAsync();
}
if (summary is null && jobs is null) continue;
for (var i = 0; i < count; i++)
if (buffer[i] == '\n')
{
var text = line.ToString().TrimEnd('\r');
summary?.Add(text, writer);
jobs?.Add(text);
line.Clear();
}
else line.Append(buffer[i]);
}
if (summary is not null && line.Length > 0) summary.Add(line.ToString(), writer);
return captured.ToString();
}
/// <summary>Milliseconds between progress lines of one stage on a terminal.</summary>
const int InteractiveProgressInterval = 10_000;
/// <summary>Milliseconds between progress lines when stderr is redirected; a shorter stage prints none.</summary>
const int RedirectedProgressInterval = 20_000;
/// <summary>
/// Stderr without stage progress lines, which a run prints for any stage that outlasts an interval:
/// what remains is the command's own diagnostics.
/// </summary>
internal static string WithoutStageProgress(string stderr) => StageProgressLine().Replace(stderr, "");
[GeneratedRegex(@"^(?:START|PROGRESS|END) [^\n]*(?:\n|\z)", RegexOptions.Multiline)]
private static partial Regex StageProgressLine();
static readonly object TraceGate = new();
// A reused process id must not append to an earlier process's trace, which a reader treats as old.
static readonly string TraceFile = $"{Environment.ProcessId}-{Guid.NewGuid():N}.jsonl";
/// <summary>
/// Runs `command` and returns its exit code and output. A Lean command that exits 0 after printing an internal
/// error fails here, unless `internalErrors` is false and the caller attributes them itself.
/// </summary>
static (int Code, string Output, string Stdout, string Stderr) Execute(IEnumerable<string> command, string? cwd = null, string? leanPath = null,
bool streamOutput = false, string? progress = null, IReadOnlyDictionary<string, string>? environment = null,
bool internalErrors = true)
{
var traceStage = progress;
#if LEANCIL_TOOL
// Stdout stays the report. A redirected stderr names only a stage that outlasts one interval.
var interactive = !Console.IsErrorRedirected;
var announced = interactive && progress is not null;
if (announced) Console.Error.WriteLine("START " + progress);
var jobs = progress is null ? null : new JobCount();
progress = null;
streamOutput = false;
#else
JobCount? jobs = null;
#endif
// Aggregate at the suite boundary; nested build/proof phases feed this summary.
var summary = streamOutput && progress is not null ? new ProgressSummary(progress) : null;
streamOutput |= progress is not null;
var args = command.ToArray();
#if !LEANCIL_TOOL
args = ReusePreparedFixture(args, cwd ?? Root);
#endif
var start = new ProcessStartInfo(args[0])
{
WorkingDirectory = cwd ?? Root,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8,
CreateNoWindow = true
};
foreach (var arg in args.Skip(1))
start.ArgumentList.Add(arg);
if (leanPath is not null)
start.Environment["LEAN_PATH"] = leanPath;
#if !LEANCIL_TOOL
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(FixtureManifestEnvironment)))
start.Environment["LEANCIL_FIXTURE_ROOT"] = Root;
#endif
foreach (var (name, value) in environment ?? new Dictionary<string, string>())
start.Environment[name] = value;
if (ChecksLeanEnvironment(args, leanPath is not null))
RequireLeanEnvironmentFits(args, start.WorkingDirectory, start.Environment);
if (progress is not null) Console.WriteLine("START " + progress);
var startedAtUtc = DateTimeOffset.UtcNow;
var elapsed = Stopwatch.StartNew();
using var process = new Process { StartInfo = start };
try
{
if (!process.Start())
throw new InvalidOperationException("Process did not start");
}
catch (System.ComponentModel.Win32Exception exception) when (exception.NativeErrorCode is 2 or 3)
{
throw new InvalidOperationException("Required command not found: " + args[0], exception);
}
var traceDirectory = Environment.GetEnvironmentVariable("LEANCIL_TRACE_DIRECTORY");
var transcript = $"{Environment.ProcessId}-{Guid.NewGuid():N}.log";
if (!string.IsNullOrWhiteSpace(traceDirectory)) Directory.CreateDirectory(traceDirectory);
using var traceWriter = string.IsNullOrWhiteSpace(traceDirectory) ? null :
TextWriter.Synchronized(new StreamWriter(Path.Combine(traceDirectory, transcript), false, Encoding.UTF8));
var stdout = CaptureOutput(process.StandardOutput, streamOutput ? Console.Out : TextWriter.Null, summary,
traceWriter, jobs);
var stderr = CaptureOutput(process.StandardError, streamOutput ? Console.Error : TextWriter.Null, summary,
traceWriter, jobs);
if (summary is null)
{
#if LEANCIL_TOOL
if (traceStage is not null)
while (!process.WaitForExit(interactive ? InteractiveProgressInterval : RedirectedProgressInterval))
{
Console.Error.WriteLine($"PROGRESS {traceStage}{jobs} ({elapsed.Elapsed.TotalSeconds:F0}s)");
announced = true;
}
else
#endif
process.WaitForExit();
}
else
while (!process.WaitForExit(10_000)) summary.Report();
var output = stdout.GetAwaiter().GetResult();
var error = stderr.GetAwaiter().GetResult();
if (progress is not null)
Console.WriteLine($"END {progress} (exit {process.ExitCode}, {elapsed.Elapsed.TotalSeconds:F1}s)");
#if LEANCIL_TOOL
if (announced)
Console.Error.WriteLine($"END {traceStage} (exit {process.ExitCode}, {elapsed.Elapsed.TotalSeconds:F1}s)");
#endif
Trace(traceStage ?? string.Join(" ", args.Take(2)), startedAtUtc, start.WorkingDirectory, elapsed.Elapsed, process.ExitCode, transcript, args);
if (internalErrors && LeanOutput.RejectedSuccess(args, process.ExitCode, output + error) is { } rejected)
throw rejected;
return (process.ExitCode, output + error, output, error);
}
static void Trace(string stage, DateTimeOffset startedAtUtc, string cwd, TimeSpan elapsed, int exitCode, string transcript, string[] command)
{
var traceDirectory = Environment.GetEnvironmentVariable("LEANCIL_TRACE_DIRECTORY");
if (string.IsNullOrWhiteSpace(traceDirectory)) return;
Directory.CreateDirectory(traceDirectory);
// Concurrent commands in one process append to the same trace file.
lock (TraceGate)
File.AppendAllText(Path.Combine(traceDirectory, TraceFile), JsonSerializer.Serialize(new {
stage, startedAtUtc, processId = Environment.ProcessId, cwd, durationSeconds = elapsed.TotalSeconds,
exitCode, transcript, command, suite = Environment.GetEnvironmentVariable("LEANCIL_SUITE")
}) + "\n");
}
static string Run(IEnumerable<string> command, string? cwd = null, string? leanPath = null,
bool streamOutput = false, string? progress = null, IReadOnlyDictionary<string, string>? environment = null)
{
var args = command.ToArray();
var result = Execute(args, cwd, leanPath, streamOutput, progress, environment);
if (result.Code != 0)
throw new InvalidOperationException($"Command failed ({result.Code}): {string.Join(' ', args)}\n{result.Output}");
return result.Output;
}
/// <summary>
/// Lean on Windows builds a child's environment in one buffer of this many bytes: inherited entries are copied
/// unchecked, and an override that no longer fits is dropped silently, with every override after it.
/// </summary>
const int LeanEnvironmentBuffer = 0x7fff;
/// <summary>Lowers, never raises, the enforced block size; set on another OS, it enables the check.</summary>
const string LeanEnvironmentLimitVariable = "LEANCIL_LEAN_ENVIRONMENT_LIMIT";
const int LargestVariablesShown = 6;
static readonly System.Collections.Concurrent.ConcurrentDictionary<string, KeyValuePair<string, string>[]?>
LakeVariables = new(StringComparer.Ordinal);
/// <summary>One `name=value` entry of an environment block, and whether Lake set it.</summary>
sealed record EnvironmentEntry(string Name, string Value, bool SetByLake)
{
/// <summary>The entry's bytes with its terminator; Lean's executables use the UTF-8 code page.</summary>
public int Bytes => Encoding.UTF8.GetByteCount(Name) + Encoding.UTF8.GetByteCount(Value) + 2;
}
/// <summary>The largest environment block a Lean process can pass on; null where Lean has no limit.</summary>
static int? LeanEnvironmentLimit()
{
int? limit = OperatingSystem.IsWindows() ? LeanEnvironmentBuffer : null;
var configured = Environment.GetEnvironmentVariable(LeanEnvironmentLimitVariable);
if (string.IsNullOrEmpty(configured)) return limit;
if (!int.TryParse(configured, System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out var lowered) || lowered <= 0)
throw new ArgumentException(LeanEnvironmentLimitVariable + " must be a positive number of bytes.");
return Math.Min(limit ?? lowered, lowered);
}
/// <summary>Whether `command` starts Lean processes that may start others with their own environment.</summary>
static bool ChecksLeanEnvironment(string[] command, bool leanSearchPath) =>
(leanSearchPath || Path.GetFileNameWithoutExtension(command[0]) == "lake") &&
LeanEnvironmentLimit() is not null;
/// <summary>
/// Fails before `command` starts when the environment its Lean processes would hand their children exceeds the
/// limit, naming the size and the largest variables, instead of letting Lean drop LEAN_PATH without an error.
/// </summary>
static void RequireLeanEnvironmentFits(string[] command, string cwd, IDictionary<string, string?> environment)
{
if (LeanEnvironmentLimit() is not { } limit ||
PredictedLeanChildEnvironment(command, cwd, environment) is not { } entries) return;
var size = EnvironmentBlockBytes(entries);
if (size > limit)
throw new InvalidOperationException(LeanEnvironmentOverflow(command, cwd, entries, size, limit));
}
/// <summary>
/// The block a Lean process started by `command` builds for its own children: for Lake, its inherited
/// environment after the elan proxy's changes plus the variables Lake sets; for another Lean program, the
/// environment it is given. Null when the command starts no child with an environment of its own.
/// </summary>
static EnvironmentEntry[]? PredictedLeanChildEnvironment(string[] command, string cwd,
IDictionary<string, string?> environment)
{
var inherited = environment.Where(entry => entry.Value is not null)
.Select(entry => KeyValuePair.Create(entry.Key, entry.Value!)).ToList();
if (Path.GetFileNameWithoutExtension(command[0]) != "lake") return LeanChildEnvironment(inherited, []);
var subcommand = command.Skip(1).FirstOrDefault(argument => !argument.StartsWith('-'));
// Printing its variables and updating dependencies start no Lean process with an environment.
if (subcommand is null or "update" || subcommand == "env" && command[^1] == "env") return null;
if (LakeEnvironment(cwd, inherited) is not { } lake) return LeanChildEnvironment(inherited, []);
ApplyElanProxy(inherited, lake);
// A build starts Lean with LEAN_PATH alone; the printed value also holds Lake's own library directory.
return LeanChildEnvironment(inherited,
subcommand == "build" ? [.. lake.Where(entry => entry.Key == "LEAN_PATH")] : lake);
}
/// <summary>
/// The block Lean builds from `inherited` and `overrides`: the inherited entries whose name no override spells
/// exactly, since Lean compares names case-sensitively even on Windows, then every override.
/// </summary>
static EnvironmentEntry[] LeanChildEnvironment(IEnumerable<KeyValuePair<string, string>> inherited,
IReadOnlyCollection<KeyValuePair<string, string>> overrides)
{
var replaced = overrides.Select(entry => entry.Key).ToHashSet(StringComparer.Ordinal);
return [.. inherited.Where(entry => !replaced.Contains(entry.Key))
.Select(entry => new EnvironmentEntry(entry.Key, entry.Value, false)),
.. overrides.Select(entry => new EnvironmentEntry(entry.Key, entry.Value, true))];
}
/// <summary>The block's size in bytes: every entry with its terminator, then the block's own terminator.</summary>
static int EnvironmentBlockBytes(IEnumerable<EnvironmentEntry> entries) => entries.Sum(entry => entry.Bytes) + 1;
/// <summary>
/// The variables Lake sets for Lean in `cwd` under `environment`, as `lake env` prints them, or null when Lake
/// cannot load the workspace. Lake prints a variable it unsets as empty, so counting it can only overcount.
/// </summary>
static KeyValuePair<string, string>[]? LakeEnvironment(string cwd,
IReadOnlyCollection<KeyValuePair<string, string>> environment)
{
var given = environment.ToDictionary(entry => entry.Key, entry => entry.Value);
// Lake's paths follow the package's libraries and dependencies, so an edited lakefile or manifest re-asks.
var workspace = new[] { "lakefile.toml", "lakefile.lean", "lake-manifest.json" }
.Select(name => Path.Combine(cwd, name)).Where(File.Exists).Select(path => path + "=" + Sha(path));
var key = Path.GetFullPath(cwd) + "\n" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(
string.Join('\0', given.OrderBy(entry => entry.Key, StringComparer.Ordinal)
.Select(entry => entry.Key + "=" + entry.Value).Concat(workspace)))));
return LakeVariables.GetOrAdd(key, _ =>
{
var printed = Execute(["lake", "env"], cwd, environment: given);
// A workspace Lake cannot load fails the command itself, with Lake's own error.
return printed.Code != 0 ? null : [.. printed.Stdout.Split('\n')
.Select(line => line.TrimEnd('\r')).Where(line => line.Contains('='))
.Select(line => KeyValuePair.Create(line[..line.IndexOf('=')], line[(line.IndexOf('=') + 1)..]))];
});
}
/// <summary>
/// Applies what elan's proxy sets before it starts the toolchain's Lake, when a bare `lake` resolves to it:
/// elan's and (on Windows) the toolchain's bin directories ahead of PATH, a raised LEAN_RECURSION_COUNT, and
/// ELAN_TOOLCHAIN and ELAN_HOME, each under the spelling the environment already uses.
/// </summary>
static void ApplyElanProxy(List<KeyValuePair<string, string>> inherited,
IReadOnlyCollection<KeyValuePair<string, string>> lake)
{
string Printed(string name) => lake.FirstOrDefault(entry => entry.Key == name).Value ?? "";
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
var elanBin = Printed("ELAN_HOME") is { Length: > 0 } home ? Path.Combine(home, "bin") : null;
if (elanBin is null || LakeOnPath() is not { } proxy ||
!string.Equals(Path.GetDirectoryName(proxy), elanBin, comparison)) return;
void Set(string name, Func<string?, string> value)
{
var index = inherited.FindIndex(entry => entry.Key.Equals(name, comparison));
var entry = KeyValuePair.Create(index < 0 ? name : inherited[index].Key,
value(index < 0 ? null : inherited[index].Value));
if (index < 0) inherited.Add(entry);
else inherited[index] = entry;
}
string[] prefix = OperatingSystem.IsWindows()
? [elanBin, Path.Combine(Printed("LEAN_SYSROOT"), "bin")] : [elanBin];
Set("PATH", current => string.Join(Path.PathSeparator, current is null ? prefix : [.. prefix, current]));
Set("LEAN_RECURSION_COUNT", current => ((uint.TryParse(current, System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out var count) ? count : 0) + 1)
.ToString(System.Globalization.CultureInfo.InvariantCulture));
Set("ELAN_TOOLCHAIN", _ => Printed("ELAN_TOOLCHAIN"));
Set("ELAN_HOME", _ => Printed("ELAN_HOME"));
}
/// <summary>The executable a bare `lake` command starts: the first one on this process's PATH.</summary>
static string? LakeOnPath() =>
(Environment.GetEnvironmentVariable("PATH") ?? "")
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(directory => Path.Combine(directory.Trim('"'), OperatingSystem.IsWindows() ? "lake.exe" : "lake"))
.FirstOrDefault(File.Exists);
static string LeanEnvironmentOverflow(string[] command, string cwd, EnvironmentEntry[] entries, int size,
int limit)
{
var invariant = System.Globalization.CultureInfo.InvariantCulture;
var largest = entries.OrderByDescending(entry => entry.Bytes).Take(LargestVariablesShown)
.Select(entry => string.Create(invariant,
$"\n {entry.Name} {entry.Bytes:N0}{(entry.SetByLake ? " (set by Lake)" : "")}"));
var doubled = entries.GroupBy(entry => entry.Name, StringComparer.OrdinalIgnoreCase)
.Where(group => group.Count() > 1).Select(group => string.Join(" and ", group.Select(entry => entry.Name)))
.Select(names => "\n" + names + " are both passed: Lean keeps an inherited spelling beside Lake's.");
return string.Create(invariant, $"`{string.Join(' ', command.Take(2))}` in {cwd} would start Lean ") +
string.Create(invariant, $"processes that pass on a {size:N0}-byte environment, over the ") +
string.Create(invariant, $"{limit:N0}-byte limit ") +
"of the environment Lean on Windows can pass to a process. Lean would drop LEAN_PATH and the other " +
"variables set for it without an error, so imports would not resolve.\n" +
"Largest variables (bytes of name=value):" +
string.Concat(largest) + string.Concat(doubled) +
"\nRemove unneeded variables or PATH entries from the environment leancil runs in.";
}
static SortedDictionary<string, string> Inputs(string proof, string? settings = null)
=> Inputs(CommonInputs(), proof, settings);
static SortedDictionary<string, string> CommonInputs()
{
var result = new SortedDictionary<string, string>(StringComparer.Ordinal);
foreach (var name in new[] { "lean-toolchain", "lake-manifest.json", "CIL.lean" })
result[name] = Sha(At(name));
// Checkout identities see every declaration; the certified library sees only what builds it.
var lakefile = File.ReadAllBytes(At("lakefile.toml"));
result[CheckoutLakefileInput] = Convert.ToHexStringLower(SHA256.HashData(lakefile));
result["lakefile.toml"] = ContentKey(LibraryLakefile(Encoding.UTF8.GetString(lakefile)));
var folders = new List<(string, string[])> { ("CIL", [".lean"]) };
#if !LEANCIL_TOOL
// The repository's examples and tests are checkout inputs; the tool ships only the framework.
foreach (var name in new[] { "global.json", "Directory.Build.props", "Directory.Packages.props", ".editorconfig" })
result[name] = Sha(At(name));
folders.AddRange([("Examples", [".lean"]), ("Tests", [".lean"]), ("Extractor", [".cs", ".csproj"]),
("scripts", [".cs"])]);
#endif
foreach (var (folder, extensions) in folders)
foreach (var path in Directory.EnumerateFiles(At(folder), "*", SearchOption.AllDirectories))
{
var relative = Path.GetRelativePath(Root, path).Replace('\\', '/');
if (extensions.Contains(Path.GetExtension(path)) && !relative.Split('/').Any(p => p is "bin" or "obj"))
result[relative] = Sha(path);
}
return result;
}
/// <summary>The snapshot key of the complete checkout lakefile, which no certified library contains.</summary>
const string CheckoutLakefileInput = "checkout:lakefile.toml";
/// <summary>
/// The lakefile the certified library is built from: the checkout's, without blank lines, comments,
/// the editor library, or any plain <c>[[lean_lib]]</c> table that declares only a library outside CIL.
/// </summary>
static string LibraryLakefile(string lakefile)
{
var lines = lakefile.ReplaceLineEndings("\n").Split('\n');
// A multi-line string can hold header-like lines, so such a file is kept whole.
if (lakefile.Contains("\"\"\"", StringComparison.Ordinal) ||
lakefile.Contains("'''", StringComparison.Ordinal))
return string.Join("\n", lines);
var tables = new List<List<string>> { new() };
foreach (var line in lines)
{
if (line.StartsWith('[')) tables.Add([]);
if (!string.IsNullOrWhiteSpace(line) && !line.TrimStart().StartsWith('#')) tables[^1].Add(line);
}
static string? OtherLibrary(List<string> table) =>
table is ["[[lean_lib]]", var declaration] &&
LibraryName().Match(declaration) is { Success: true } match && match.Groups[1].Value is var name &&
name != "CIL" && !name.StartsWith("CIL.", StringComparison.Ordinal) ? name : null;
// A certificate must never resolve Extracted to the editor's sources.
static bool EditorLibrary(List<string> table) =>
table is ["[[lean_lib]]", var declaration, ..] && declaration == $"name = \"{EditorLibraryName}\"";
tables.RemoveAll(EditorLibrary);
var named = string.Join("\n", tables.Where(table => OtherLibrary(table) is null).SelectMany(table => table));
// A library that a kept table names, such as a default target, stays declared.
return string.Concat(tables.Where(table => OtherLibrary(table) is not { } name ||
named.Contains('"' + name + '"', StringComparison.Ordinal))
.SelectMany(table => table).Select(line => line + "\n"));
}
/// <summary>The framework library whose modules are the editor's extraction, below `.lake/leancil`.</summary>
const string EditorLibraryName = "LeanCILEditor";
[GeneratedRegex(@"\Aname = ""([A-Za-z_][A-Za-z0-9_.]*)""\z")]
private static partial Regex LibraryName();
/// <summary>Copies one certified library source from the checkout; the lakefile is its library view.</summary>
static void CopyLibrarySource(string name, string destination)
{
if (name == "lakefile.toml")
File.WriteAllText(destination,
LibraryLakefile(Encoding.UTF8.GetString(File.ReadAllBytes(At(name)))));
else File.Copy(At(name), destination, true);
}
static SortedDictionary<string, string> Inputs(SortedDictionary<string, string> common, string proof,
string? settings = null)
{
var result = new SortedDictionary<string, string>(common, StringComparer.Ordinal);
result["proof:" + proof] = Sha(proof);
if (settings is not null)
result["settings:" + settings] = Sha(settings);
return result;
}
static bool Same(SortedDictionary<string, string> left, SortedDictionary<string, string> right) =>
left.Count == right.Count && left.All(p => right.TryGetValue(p.Key, out var value) && value == p.Value);
bool freshLibrary { get; init; }
/// <summary>An editor's library is no certificate input, so it is cached where certification never is.</summary>
bool editorLibrary { get; init; }
/// <summary>
/// With no whole library cached, verify one proof against a closure entry of the modules it imports and
/// build the whole library after reporting. Only for a process that verifies a single proof.