-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathMain.lean
More file actions
2334 lines (2275 loc) · 120 KB
/
Copy pathMain.lean
File metadata and controls
2334 lines (2275 loc) · 120 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
import Concrete
import Concrete.Proof.ObligationCore
import Concrete.Report.CompilerLedger
import Concrete.Backend.Backend
import Concrete.Resolve.Project
open Concrete
-- Shared CLI exit-code taxonomy (ROADMAP Phase 4 #14). One source of truth for
-- every command's exit code AND the documented `EXIT CODES` help block, so the
-- codes and their documentation cannot drift.
namespace ExitCode
def ok : UInt32 := 0
def usage : UInt32 := 1
def obligationsMissing : UInt32 := 2
def staleEvidence : UInt32 := 3
def proofCheckFailure : UInt32 := 4
def solverFailure : UInt32 := 5
def internalError : UInt32 := 6
/-- (code, meaning) — the single source for both exits and the help block. -/
def taxonomy : List (UInt32 × String) :=
[ (ok, "success (proved / clean / info printed)"),
(usage, "invalid invocation (bad args, unknown function)"),
(obligationsMissing, "obligations missing (eligible but unproved)"),
(staleEvidence, "stale evidence (body changed since the proof was linked)"),
(proofCheckFailure, "proof-check failure (Lean kernel rejected a referenced theorem)"),
(solverFailure, "solver/checker failure (omega/bv_decide/lake could not run)"),
(internalError, "internal compiler error") ]
/-- The `EXIT CODES` help block, generated from `taxonomy` (no hand-kept copy). -/
def helpBlock : List String :=
"EXIT CODES:" :: taxonomy.map (fun (c, m) => s!" {c} {m}")
end ExitCode
-- Shared command-line flag parsing (ROADMAP Phase 4 #14b). One definition of what
-- a boolean flag and a valued flag mean, so every command parses flags the same
-- way instead of re-deriving `args.contains` / `dropWhile` inline.
namespace Cli
/-- True iff the boolean flag `name` is present. -/
def hasFlag (args : List String) (name : String) : Bool := args.contains name
/-- The value following `name` (e.g. `--out PATH`), or `none` if `name` is absent
or the next token is itself a flag — so `--out --json` does NOT capture
`--json` as the path. This guard is applied uniformly (several call sites
previously omitted it). -/
def flagValue (args : List String) (name : String) : Option String :=
match args.dropWhile (· != name) with
| _ :: v :: _ => if v.startsWith "-" then none else some v
| _ => none
end Cli
/-- Phase 6E #1: the grouped, context-free help page. Groups commands by use
per the roadmap taxonomy; the full flag matrix stays in `usage` below. -/
def helpText : String := String.intercalate "\n" [
"concrete — the Concrete compiler",
"",
"USAGE: concrete <command> [args] | concrete <file.con> [flags]",
"",
"DAILY:",
" build [file|project] compile (project mode reads Concrete.toml)",
" run [file|project] compile and run",
" test [--module <name>] run #[test] functions",
" fmt <file.con> format (--check | --write | --stdin)",
"",
"REPORTS & EVIDENCE:",
" <file> --report <kind> caps, unsafe, layout, proof-status, obligations, …",
" prove <file> <fn> prove/check an obligation (prove --help for more)",
" <file> --query <kind> semantic queries (why-capability, evidence, …)",
"",
"DEBUGGING:",
" <file> --trace-pipeline per-stage trace naming the first failing phase",
" <file> --emit-trace-json per-stage telemetry (counts, timing)",
" reduce <file> --predicate <p> minimize a failing program",
" debug-bundle <file> capture a reproducible failure bundle",
"",
"INTERNALS / COMPAT:",
" <file> --emit-core | --emit-ssa | --emit-llvm | --interp",
" diff, snapshot, audit, check, validate-bundle, --version",
"",
"Run `concrete` with no arguments for the full flag matrix.",
""]
def usage : String :=
"Usage: concrete <file.con> [-o output] [--emit-llvm] [--emit-core] [--emit-ssa] [--emit-trace-json] [--trace-pipeline] [--test] [--test --module <name>] [--interp] [--report caps|unsafe|layout|interface|alloc|mono|authority|proof|eligibility|proof-status|obligations|extraction|lean-stubs|check-proofs|proof-diagnostics|proof-deps|proof-bundle|traceability|diagnostics-json|effects|recursion|stack-depth|fingerprints|consistency|contracts|vcs|obligation-ledger|compiler-ledger|verify|audit|arithmetic] [--query KIND|KIND:FUNCTION|fn:FUNCTION] [--fmt (legacy; use `concrete fmt`)]\n concrete build [-o output] [--emit-llvm]\n concrete check\n concrete fmt <file.con> [--check | --write | --stdin]\n concrete audit <file.con>\n concrete prove <file.con> <module.function> [--json] [--out <path>] [--force] [--emit-link] [--emit-lean] [--emit-artifacts] [--out-dir <dir>] [--show-obligation <id>] [--replay] [--nearest-lemmas] [--check] [--workspace <dir>]\n concrete prove --help=agent | --capabilities | --schema\n concrete run [-- args...]\n concrete test [--module <name>]\n concrete diff <old.json> <new.json> [--json]\n concrete snapshot <file.con> [-o output.json]\n concrete debug-bundle <file.con> [-o dir]\n concrete reduce <file.con> --predicate <pred> [-o output] [--verbose]\n concrete --version"
/-- Capture compiler identity: version, git commit, lean toolchain. -/
def compilerIdentity : IO String := do
let version := "0.1.0"
let commit ← try
let r ← IO.Process.output { cmd := "git", args := #["rev-parse", "--short", "HEAD"] }
if r.exitCode == 0 then
let hash := r.stdout.trimAscii.toString
-- Check for tracked modifications and untracked files
let d ← IO.Process.output { cmd := "git", args := #["status", "--porcelain"] }
pure (if d.stdout.trimAscii.toString.isEmpty then hash else hash ++ "-dirty")
else pure "unknown"
catch _ => pure "unknown"
let toolchain ← try
let tc ← IO.FS.readFile ⟨"lean-toolchain"⟩
pure tc.trimAscii.toString
catch _ => pure "unknown"
return s!"concrete {version} ({commit}) [{toolchain}]"
def writeFile (path : String) (content : String) : IO Unit := do
IO.FS.writeFile ⟨path⟩ content
/-- Detect macOS SDK sysroot for clang linking. Returns `--sysroot=<path>` flag if found. -/
def getMacOSSysrootFlags : IO (Array String) := do
-- Only relevant on macOS
let os ← IO.Process.output { cmd := "uname", args := #["-s"] }
if os.stdout.trimAscii.toString != "Darwin" then return #[]
-- Use xcrun to find the SDK path
let result ← IO.Process.output { cmd := "xcrun", args := #["--show-sdk-path"] }
if result.exitCode == 0 then
let sdkPath := result.stdout.trimAscii.toString
if sdkPath.length > 0 then return #[s!"--sysroot={sdkPath}"]
return #[]
/-- Build clang arguments for linking LLVM IR to a native binary. -/
def clangArgs (llPath : String) (outputPath : String) (extraFlags : Array String := #[]) : IO (Array String) := do
let sysrootFlags ← getMacOSSysrootFlags
return #[llPath, "-o", outputPath, "-Wno-override-module", "-w", "-O2"] ++ sysrootFlags ++ extraFlags
def runCmd (cmd : String) (args : Array String) : IO UInt32 := do
let child ← IO.Process.spawn {
cmd := cmd
args := args
stdout := .piped
stderr := .piped
}
let exitCode ← child.wait
if exitCode != 0 then
let stderr ← child.stderr.readToEnd
IO.eprintln stderr
return exitCode
/-- Hard-error gate for runtime-safety obligations already classified as
`VIOLATION`. This is intentionally narrower than the contracts report:
`unproven` obligations remain report/policy facts, while `violation` means
the compiler proved the safe program is wrong. -/
def enforceProvenRuntimeViolations (modules : List Module) (sourceMap : SourceMap) : IO Bool := do
let ds := Report.provenViolationDiagnostics modules
if hasErrors ds then
IO.eprintln (renderDiagnostics ds (sourceMap := sourceMap))
return false
return true
/-- Validate LLVM IR via `llvm-as` (parse-only, no output).
Returns true if valid or if llvm-as is not found on PATH.
Returns false (and prints errors) if the IR is malformed. -/
def validateLLVMIR (llPath : String) : IO Bool := do
-- Check if llvm-as is available
let which ← IO.Process.output { cmd := "which", args := #["llvm-as"] }
if which.exitCode != 0 then
return true -- llvm-as not available; skip validation
let result ← IO.Process.output {
cmd := "llvm-as"
args := #[llPath, "-o", "/dev/null"]
}
if result.exitCode != 0 then
IO.eprintln s!"LLVM IR validation failed for {llPath}:"
IO.eprintln result.stderr
return false
return true
/-- Best-effort resident-set size in KB. Reads `/proc/self/statm` (Linux); returns
`none` on any platform without it (e.g. macOS) — the telemetry field is
platform-graceful, never a hard dependency. -/
def readRssKb : IO (Option Nat) := do
try
let contents ← IO.FS.readFile "/proc/self/statm"
match contents.splitOn " " with
| _ :: resident :: _ => match resident.toNat? with
| some pages => pure (some (pages * 4096 / 1024))
| none => pure none
| _ => pure none
catch _ => pure none
def traceTelemetry (inputPath : String) : IO UInt32 := do
let source ← readFile inputPath
let git ← compilerIdentity
let rss ← readRssKb
let srcMap := [(inputPath, source)]
-- Run the pipeline stage by stage so we can time each pass. Timing is a debug
-- aid, not a perf claim; the gate pins schema + monotonic sanity, not magnitudes.
let baseDir := let parts := inputPath.splitOn "/"
match parts.reverse with | _ :: rest => "/".intercalate rest.reverse | [] => "."
-- Run the pipeline stage by stage so each pass can be timed. Timing is a debug
-- aid, not a perf claim; the gate pins schema + monotonic sanity, not magnitudes.
let mut timing : List (String × Nat) := []
let mut t ← IO.monoMsNow
match Pipeline.parse source with
| .error ds => IO.eprintln (renderDiagnostics ds (sourceMap := srcMap)); return 1
| .ok parsed =>
let astNodes := Pipeline.astModuleNodes parsed.modules
timing := timing ++ [("parse", (← IO.monoMsNow) - t)]; t ← IO.monoMsNow
match ← Pipeline.resolveFiles baseDir parsed inputPath resolveAllModules with
| .error ds => IO.eprintln (renderDiagnostics ds (sourceMap := srcMap)); return 1
| .ok (resolved, _) =>
let summary := Pipeline.buildSummary resolved
timing := timing ++ [("resolve-files", (← IO.monoMsNow) - t)]; t ← IO.monoMsNow
match Pipeline.resolve resolved summary with
| .error ds => IO.eprintln (renderDiagnostics ds (sourceMap := srcMap)); return 1
| .ok rp =>
let resolvedProg := Pipeline.desugar rp
timing := timing ++ [("resolve", (← IO.monoMsNow) - t)]; t ← IO.monoMsNow
match Pipeline.check resolvedProg summary with
| .error ds => IO.eprintln (renderDiagnostics ds (sourceMap := srcMap)); return 1
| .ok () =>
timing := timing ++ [("check", (← IO.monoMsNow) - t)]; t ← IO.monoMsNow
match Pipeline.elaborate resolvedProg summary with
| .error ds => IO.eprintln (renderDiagnostics ds (sourceMap := srcMap)); return 1
| .ok elabProg =>
timing := timing ++ [("elaborate", (← IO.monoMsNow) - t)]; t ← IO.monoMsNow
match Pipeline.coreCheck elabProg with
| .error ds => IO.eprintln (renderDiagnostics ds (sourceMap := srcMap)); return 1
| .ok validCore =>
timing := timing ++ [("coreCheck", (← IO.monoMsNow) - t)]; t ← IO.monoMsNow
match Pipeline.monomorphize validCore with
| .error ds => IO.eprintln (renderDiagnostics ds (sourceMap := srcMap)); return 1
| .ok mono =>
timing := timing ++ [("monomorphize", (← IO.monoMsNow) - t)]; t ← IO.monoMsNow
match Pipeline.lower mono with
| .error ds => IO.eprintln (renderDiagnostics ds (sourceMap := srcMap)); return 1
| .ok ssa =>
timing := timing ++ [("lower", (← IO.monoMsNow) - t)]
IO.println (Pipeline.telemetryJson git astNodes validCore mono ssa 0 timing rss)
return 0
/-- Phase 6C #3: per-stage pipeline trace as JSON. Runs the pipeline stage by
stage, recording which stages passed and — for a rejected program — the FIRST
stage that failed plus its diagnostic code. An accepted program reports every
stage `ok` plus the telemetry counts. Backs `concrete <file> --trace-pipeline`. -/
def tracePipeline (inputPath : String) : IO UInt32 := do
let source ← readFile inputPath
let git ← compilerIdentity
let firstCode : Diagnostics → String := fun ds => match ds.head? with | some d => d.code | none => ""
let emit := fun (okRev : List String) (fail : Option (String × String)) (counts : String) =>
IO.println (Pipeline.traceJson git inputPath okRev.reverse fail counts)
match Pipeline.parse source with
| .error ds => emit [] (some ("parse", firstCode ds)) "null"; return 0
| .ok parsed =>
let ok := ["parse"]
let baseDir := let parts := inputPath.splitOn "/"
match parts.reverse with | _ :: rest => "/".intercalate rest.reverse | [] => "."
match ← Pipeline.resolveFiles baseDir parsed inputPath resolveAllModules with
| .error ds => emit ok (some ("resolve-files", firstCode ds)) "null"; return 0
| .ok (resolved, _) =>
let ok := "resolve-files" :: ok
let summary := Pipeline.buildSummary resolved
match Pipeline.resolve resolved summary with
| .error ds => emit ok (some ("resolve", firstCode ds)) "null"; return 0
| .ok resolvedProg =>
let ok := "resolve" :: ok
let resolvedProg := Pipeline.desugar resolvedProg
match Pipeline.check resolvedProg summary with
| .error ds => emit ok (some ("check", firstCode ds)) "null"; return 0
| .ok () =>
let ok := "check" :: ok
match Pipeline.elaborate resolvedProg summary with
| .error ds => emit ok (some ("elaborate", firstCode ds)) "null"; return 0
| .ok elabProg =>
let ok := "elaborate" :: ok
match Pipeline.coreCheck elabProg with
| .error ds => emit ok (some ("coreCheck", firstCode ds)) "null"; return 0
| .ok validCore =>
let ok := "coreCheck" :: ok
match Pipeline.monomorphize validCore with
| .error ds => emit ok (some ("monomorphize", firstCode ds)) "null"; return 0
| .ok mono =>
let ok := "monomorphize" :: ok
match Pipeline.lower mono with
| .error ds => emit ok (some ("lower", firstCode ds)) "null"; return 0
| .ok ssa =>
let ok := "lower" :: ok
emit ok none (Pipeline.telemetryJson git (Pipeline.astModuleNodes parsed.modules) validCore mono ssa 0)
return 0
/-- Compile via SSA pipeline: Parse → Resolve → Check → Elab → CoreCanonicalize → CoreCheck → Mono → Lower → SSAVerify → SSACleanup → EmitSSA → clang -/
def compileSSA (inputPath : String) (outputPath : String) (emitLLVM : Bool) : IO UInt32 := do
let source ← readFile inputPath
match ← Pipeline.runFrontend inputPath source resolveAllModules with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := [(inputPath, source)]))
return 1
| .ok (parsed, _, validCore, srcMap) =>
if !(← enforceProvenRuntimeViolations parsed.modules srcMap) then
return 1
match Pipeline.monomorphize validCore with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := srcMap))
return 1
| .ok mono =>
match Pipeline.lower mono with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := srcMap))
return 1
| .ok ssa =>
-- An executable needs an entry point. Without one, EmitSSA emits no `@main`
-- wrapper and the failure would otherwise leak from clang/ld as an opaque
-- "Undefined symbols: _main" (bug 025). Reject it here as a diagnostic.
-- `--emit-llvm` is exempt: dumping IR for inspection is legitimate with no
-- entry point (and there is no separate library/embedded build profile).
if !emitLLVM && !(ssa.ssaModules.any fun m => m.functions.any (·.isEntryPoint)) then
IO.eprintln "error[link]: no `main` function found; an executable needs an entry point — define `fn main() -> Int` in the root module"
return 1
let llvmIR := Pipeline.emit ssa
let llPath := inputPath ++ ".ll"
writeFile llPath llvmIR
if emitLLVM then
IO.println llvmIR
return 0
-- Validate LLVM IR (if llvm-as available)
let llValid ← validateLLVMIR llPath
if !llValid then
IO.FS.removeFile ⟨llPath⟩
return 1
-- Compile with clang
let args ← clangArgs llPath outputPath
let exitCode ← runCmd "clang" args
if exitCode != 0 then
IO.eprintln "clang compilation failed"
return exitCode
-- Clean up .ll file
IO.FS.removeFile ⟨llPath⟩
IO.println s!"Compiled {inputPath} -> {outputPath}"
return 0
/-- Interpret a program via the source-level interpreter (no codegen). -/
def interpProgram (inputPath : String) : IO UInt32 := do
let source ← readFile inputPath
match ← Pipeline.runFrontend inputPath source resolveAllModules with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := [(inputPath, source)]))
return 1
| .ok (_, _, validCore, _) =>
match Interp.interpret validCore.coreModules with
| .error msg =>
IO.eprintln msg
return 1
| .ok (retVal, out) =>
-- Match compiled binary contract byte-for-byte: program output first (the
-- print_* buffer), then the return value on its own line — but ONLY when
-- `main` returns a value. A Unit `main` prints no value line, exactly like
-- the compiled binary (which used to diverge: interp printed a stray `0`).
IO.print out
match retVal with
| some n => IO.println s!"{n}"
| none => pure ()
return 0
/-- Compile and run tests: Parse → ... → EmitSSA (test mode) → clang → run -/
def compileTest (inputPath : String) (moduleFilter : Option String := none) : IO UInt32 := do
let source ← readFile inputPath
match ← Pipeline.runFrontend inputPath source resolveAllModules with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := [(inputPath, source)]))
return 1
| .ok (parsed, _, validCore, srcMap) =>
if !(← enforceProvenRuntimeViolations parsed.modules srcMap) then
return 1
match Pipeline.monomorphize validCore with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := srcMap))
return 1
| .ok mono =>
match Pipeline.lower mono with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := srcMap))
return 1
| .ok ssa =>
let llvmIR := Pipeline.emit ssa (testMode := true) (moduleFilter := moduleFilter)
let llPath := inputPath ++ ".test.ll"
let outPath := inputPath ++ ".test"
writeFile llPath llvmIR
-- Validate LLVM IR (if llvm-as available)
let llValid ← validateLLVMIR llPath
if !llValid then return 1
let args ← clangArgs llPath outPath
let exitCode ← runCmd "clang" args
if exitCode != 0 then
IO.eprintln "clang compilation failed"
IO.eprintln s!"LLVM IR left at: {llPath}"
return exitCode
-- Run the test binary (keep .ll and binary for debugging)
let child ← IO.Process.spawn {
cmd := outPath
stdout := .piped
stderr := .piped
}
let stdout ← child.stdout.readToEnd
let stderr ← child.stderr.readToEnd
let exitCode ← child.wait
IO.print stdout
if !stderr.isEmpty then IO.eprint stderr
if exitCode != 0 then
IO.eprintln s!"Test binary exited with code {exitCode}"
IO.eprintln s!"LLVM IR at: {llPath}"
IO.eprintln s!"Binary at: {outPath}"
else
IO.FS.removeFile ⟨llPath⟩
IO.FS.removeFile ⟨outPath⟩
return exitCode
/-- Emit Core or SSA IR for inspection. Runs full pipeline including new passes. -/
def compileAndEmit (inputPath : String) (mode : String) : IO UInt32 := do
let source ← readFile inputPath
match ← Pipeline.runFrontend inputPath source resolveAllModules with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := [(inputPath, source)]))
return 1
| .ok (parsed, _, validCore, srcMap) =>
if mode == "core" then
for cm in validCore.coreModules do
IO.println (ppCModule cm)
return 0
if !(← enforceProvenRuntimeViolations parsed.modules srcMap) then
return 1
match Pipeline.monomorphize validCore with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := srcMap))
return 1
| .ok mono =>
let lowerResult := if mode == "ssa-unverified"
then Pipeline.lowerUnverified mono
else Pipeline.lower mono
match lowerResult with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := srcMap))
return 1
| .ok ssa =>
for sm in ssa.ssaModules do
IO.println (ppSModule sm)
return 0
/-- Stable schema version for `concrete prove` machine-readable output. -/
def proveSchemaVersion : String := "1"
/-- Run pipeline to needed depth and produce a report. -/
def compileAndQuery (inputPath : String) (query : String) : IO UInt32 := do
let source ← readFile inputPath
let mainSrcMap : SourceMap := [(inputPath, source)]
match ← Pipeline.runFrontend inputPath source resolveAllModules with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := mainSrcMap))
return 1
| .ok (parsed, _, validCore, srcMap) =>
let locMap := Report.buildFnLocMap parsed.modules inputPath
let simpleLocMap := locMap.map fun e => (e.qualName, (e.file, e.fnSpan.line))
let registry ← loadRegistryWithLinks inputPath parsed.modules validCore.coreModules
let pc := extractProofCore validCore simpleLocMap registry
-- Traceability queries need the backend pipeline
let parts := query.splitOn ":"
if parts[0]! == "traceability" then
match Pipeline.monomorphize validCore with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := srcMap))
return 1
| .ok mono =>
match Pipeline.lower mono with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := srcMap))
return 1
| .ok ssa =>
let fnFilter := if parts.length == 2 then some parts[1]! else none
IO.println (Report.queryTraceability validCore.coreModules mono.coreModules ssa.ssaModules locMap fnFilter (registry := registry) (pc := pc))
return 0
else
match Report.queryFacts validCore.coreModules locMap query (registry := registry) (pc := pc) with
| .ok result =>
IO.println result
return 0
| .error msg =>
IO.eprintln s!"error: {msg}"
return 1
-- ============================================================
-- Concrete.toml project support
-- ============================================================
/-- Empty-content stand-in for a CModule, used to preserve a parent
wrapper (and thus the qualified-name prefix) without dragging in
sibling functions when scoping. -/
private def emptyWrapper (m : CModule) (subs : List CModule) : CModule :=
{ m with functions := [], structs := [], enums := []
, externFns := [], constants := []
, traitDefs := [], traitImpls := [], newtypes := []
, submodules := subs }
/-- Match a single subtree by bare name, preserving parent wrappers so
downstream iteration produces fully-qualified names like
`pkg.<sub>.<leaf>` instead of just `<leaf>`. -/
partial def scopeSubtreeByName
(m : CModule) (targetNames : List String) : Option CModule :=
if targetNames.contains m.name then some m
else
let scopedSubs := m.submodules.filterMap fun sm => scopeSubtreeByName sm targetNames
if scopedSubs.isEmpty then none
else some (emptyWrapper m scopedSubs)
/-- Find any nested CModule subtree whose `name` matches one of `targetNames`.
Bare-name fallback used when a path-derived module path isn't available
(e.g. when inputPath lives outside `<projectRoot>/src/`). Note: this
fallback merges duplicate basenames across subtrees; prefer
`findMatchingSubtreesByPath` whenever a project root is known. -/
def findMatchingSubtrees (mods : List CModule) (targetNames : List String) : List CModule :=
mods.filterMap fun m => scopeSubtreeByName m targetNames
/-- Match a single subtree by qualified path suffix, preserving parent
wrappers so qualified names retain their full prefix. -/
partial def scopeSubtreeByPath
(m : CModule) (targetPath : List String) (currentPath : List String)
: Option CModule :=
let p := currentPath ++ [m.name]
let isMatch :=
if targetPath.length > p.length then false
else (p.drop (p.length - targetPath.length)) == targetPath
if isMatch then some m
else
let scopedSubs := m.submodules.filterMap fun sm => scopeSubtreeByPath sm targetPath p
if scopedSubs.isEmpty then none
else some (emptyWrapper m scopedSubs)
/-- Find subtrees whose qualified path (root → leaf) ends with `targetPath`.
Disambiguates duplicate basenames in different subtrees: with
`targetPath := ["a", "foo"]`, `pkg.a.foo` matches but `pkg.b.foo`
does not. Preserves the qualified-name prefix via empty parent
wrappers (so iteration yields `pkg.a.foo.<fn>`, not `foo.<fn>`). -/
def findMatchingSubtreesByPath
(mods : List CModule) (targetPath : List String) : List CModule :=
mods.filterMap fun m => scopeSubtreeByPath m targetPath []
/-- Convert a source file path to its package-relative module path
segments, given the project root. Returns `none` when the file is
not under `<projectRoot>/src/`. The package entries `src/main.con`
and `src/lib.con` map to `[]` (use the parsed top-level name to
locate the package's root module). `src/foo/mod.con` maps to
`["foo"]` (the file declares the parent directory's module). -/
def filePathToModulePath (projectRoot inputPath : String) : Option (List String) :=
let srcPrefix := projectRoot ++ "/src/"
if !inputPath.startsWith srcPrefix then none
else
let chars := inputPath.toList
let rel := String.ofList (chars.drop srcPrefix.length)
if !rel.endsWith ".con" then none
else
let stripped := String.ofList (rel.toList.take (rel.length - 4))
let parts := stripped.splitOn "/"
let parts := if parts.length > 1 && parts.getLast? == some "mod"
then parts.dropLast else parts
some parts
/-- Scope `userModules` (a project's full user-package set) to the modules
declared in `inputPath`. Uses path-derived qualified module paths to
disambiguate duplicate basenames across subtrees; falls back to bare
parsed-name matching when the file is outside `<projectRoot>/src/`. -/
def scopeUserModulesToFile (userModules : List CModule) (inputPath projectRoot : String)
: IO (List CModule) := do
let source ← try readFile inputPath catch _ => pure ""
if source.isEmpty then return userModules
match Pipeline.parse source with
| .error _ => return userModules
| .ok parsedFile =>
let parsedNames := parsedFile.modules.map (·.name)
-- Path-derived match (preferred — handles duplicate basenames).
let pathMatched : List CModule :=
match filePathToModulePath projectRoot inputPath with
| none => []
| some [] => [] -- File isn't under src/; nothing to do.
-- src/main.con and src/lib.con are package entries: the file's
-- parsed top-level module names ARE the package's top-level
-- modules, so bare-name lookup is correct here.
| some ["main"] | some ["lib"] => findMatchingSubtrees userModules parsedNames
| some path => findMatchingSubtreesByPath userModules path
if !pathMatched.isEmpty then return pathMatched
-- Fallback: bare-name match. Used when inputPath isn't under
-- `<projectRoot>/src/` (e.g. exotic layouts or symlinked files).
let nameMatched := findMatchingSubtrees userModules parsedNames
if nameMatched.isEmpty then return userModules else return nameMatched
/-- Discharge call-site contract obligations with `bv_decide`. Each candidate is
`(index, leanBoolGoal)`; returns the indices that kernel-check. Runs one
batched `lake env lean` (all goals), falling back to per-goal runs only if
the batch fails. No external SMT — `bv_decide` is a kernel decision procedure. -/
def bvDischargeCallSites (candidates : List (Nat × String)) : IO (List Nat) := do
if candidates.isEmpty then return []
let mkSrc (cs : List (Nat × String)) : String :=
"import Std.Tactic.BVDecide\n\n"
++ String.join (cs.map (fun (i, g) => s!"theorem cobl_{i} : {g} = true := by bv_decide\n"))
let runLean (src : String) : IO UInt32 := do
let tmpDir ← IO.Process.output { cmd := "mktemp", args := #["-d"] }
let dir := tmpDir.stdout.trimAscii.toString
IO.FS.writeFile ⟨dir ++ "/cobl.lean"⟩ src
let r ← IO.Process.output { cmd := "lake", args := #["env", "lean", dir ++ "/cobl.lean"],
env := #[("LAKE_TERM_ANSI", "0")] }
let _ ← IO.Process.output { cmd := "rm", args := #["-rf", dir] }
return r.exitCode
if (← runLean (mkSrc candidates)) == 0 then
return candidates.map (·.1)
else
let mut proved : List Nat := []
for c in candidates do
if (← runLean (mkSrc [c])) == 0 then proved := proved ++ [c.1]
return proved
/-- Discharge nonlinear integer-overflow goals with `bv_decide`. Each candidate
is `(key, propGoal)` where the goal is a quantified BitVec proposition
(`∀ (v : BitVec w), … → BitVec.ule e hi`); returns the keys that kernel-check.
`intros; bv_decide` introduces the operands and bound hypotheses, then
bitblasts — an LRAT-checked kernel decision, no external SMT. Batched,
falling back per-goal. -/
def bvDischargeOverflow (candidates : List (String × String)) : IO (List String) := do
if candidates.isEmpty then return []
let indexed := (List.range candidates.length).zip candidates
let mkSrc (cs : List (Nat × (String × String))) : String :=
"import Std.Tactic.BVDecide\n\n"
++ String.join (cs.map (fun (i, (_, g)) => s!"theorem ovf_{i} : {g} := by intros; bv_decide\n"))
let runLean (src : String) : IO UInt32 := do
let tmpDir ← IO.Process.output { cmd := "mktemp", args := #["-d"] }
let dir := tmpDir.stdout.trimAscii.toString
IO.FS.writeFile ⟨dir ++ "/ovf.lean"⟩ src
let r ← IO.Process.output { cmd := "lake", args := #["env", "lean", dir ++ "/ovf.lean"],
env := #[("LAKE_TERM_ANSI", "0")] }
let _ ← IO.Process.output { cmd := "rm", args := #["-rf", dir] }
return r.exitCode
if (← runLean (mkSrc indexed)) == 0 then
return candidates.map (·.1)
else
let mut proved : List String := []
for c in indexed do
if (← runLean (mkSrc [c])) == 0 then proved := proved ++ [c.2.1]
return proved
/-- Discharge loop init/variant VCs with `omega`. Each candidate is
`(key, leanGoal)`; returns the keys that kernel-check. These VCs are linear
integer facts over `Int` (the same domain as the preservation proof), so the
decision procedure is `omega`, not `bv_decide` (bitvector-only). Batched,
falling back per-goal. No external SMT — `omega` is a kernel decision
procedure with a checked certificate. -/
def kernelDischargeLoopVCs (candidates : List (String × String)) : IO (List String) := do
if candidates.isEmpty then return []
let indexed := (List.range candidates.length).zip candidates
let mkSrc (cs : List (Nat × (String × String))) : String :=
String.join (cs.map (fun (i, (_, g)) => s!"theorem lvc_{i} : {g} := by intros; omega\n"))
let runLean (src : String) : IO UInt32 := do
let tmpDir ← IO.Process.output { cmd := "mktemp", args := #["-d"] }
let dir := tmpDir.stdout.trimAscii.toString
IO.FS.writeFile ⟨dir ++ "/lvc.lean"⟩ src
let r ← IO.Process.output { cmd := "lake", args := #["env", "lean", dir ++ "/lvc.lean"],
env := #[("LAKE_TERM_ANSI", "0")] }
let _ ← IO.Process.output { cmd := "rm", args := #["-rf", dir] }
return r.exitCode
if (← runLean (mkSrc indexed)) == 0 then
return candidates.map (·.1)
else
let mut proved : List String := []
for c in indexed do
if (← runLean (mkSrc [c])) == 0 then proved := proved ++ [c.2.1]
return proved
-- (Phase 3 #14) The former `computeVacuousQuals` / `computeAssumeQuals` /
-- `computeSolverTrustedQuals` side channels are gone: policy now reads these
-- facts from the one obligation ledger via `computePolicyQuals` (below), which
-- projects `ObligationCore.{vacuousFunctions,assumeFunctions,solverTrustedIds}`.
/-- Build the VC schedule and fold in the kernel-checked discharge results
(omega over the linear goals; `bv_decide` over the BitVec call-site and
overflow goals). The proved/`counterexample`/constant verdicts already
decided structurally by `collectVCs` are preserved; only `planned` VCs are
upgraded — and only to `proved_by_kernel_decision` (or `arithmetic_proved`
for loop preservation), never to an external-solver class. -/
def computeVCsDischarged (modules : List Concrete.Module) (locMap : Report.FnLocMap)
(registry : Concrete.ProofRegistry) : IO (List Report.VC) := do
let vcs := Report.collectVCs modules locMap registry
let omegaGoals := Report.callPrecondGoals modules ++ Report.assertGoals modules
++ Report.vacuityGoals modules ++ Report.loopVCGoals modules
++ Report.boundsGoals modules ++ Report.divGoals modules ++ Report.overflowGoals modules
let omegaProved ← kernelDischargeLoopVCs omegaGoals
let obs := Report.callSiteObligations modules
let cands := ((List.range obs.length).zip obs).filterMap fun (i, o) => o.leanGoal.map (fun g => (i, g))
let bvIdx ← bvDischargeCallSites cands
let bvCallKeys := bvIdx.filterMap fun i => obs[i]?.map (·.key)
let ovfBV := (Report.overflowBVGoals modules).filter (fun (k, _) => !omegaProved.contains k)
let bvOvfKeys ← bvDischargeOverflow ovfBV
return Report.dischargeVCs vcs omegaProved (bvCallKeys ++ bvOvfKeys)
/-- Read the value Z3 assigned to variable `v` from `(get-model)` output. Handles
both `... Int 100000)` and the negative `... Int (- 5))` shapes, across lines.
The declared name IS the source variable name, so no remapping is needed. -/
def smtModelValue (out v : String) : Option String :=
match ((out.splitOn s!"define-fun {v} () Int").drop 1).head? with
| none => none
| some after =>
let cs := after.toList.dropWhile (fun c => !c.isDigit && c != '-')
match cs with
| [] => none
| c :: rest =>
if c == '-' then
let num := (rest.dropWhile (· == ' ')).takeWhile Char.isDigit
if num.isEmpty then none else some (String.ofList ('-' :: num))
else
let num := cs.takeWhile Char.isDigit
if num.isEmpty then none else some (String.ofList num)
/-- Solver identity + version for provenance, e.g. "z3 4.16.0", or "z3 (unavailable)"
when Z3 is not on PATH. `z3 --version` prints "Z3 version X.Y.Z - 64 bit". -/
def z3VersionId : IO String := do
try
let o ← IO.Process.output { cmd := "z3", args := #["--version"] }
if o.exitCode != 0 then return "z3 (unavailable)"
-- extract the version token after "version"
let toks := o.stdout.trimAscii.toString.splitOn " "
match toks.dropWhile (· != "version") with
| _ :: v :: _ => return s!"z3 {v}"
| _ => return "z3"
catch _ => return "z3 (unavailable)"
/-- External-SMT adapter (Phase 2 #8/#10). One solver (Z3), pinned timeout. For each
`(vcKey, smtlibScript)` it writes the script, runs `z3 -T:<timeout>`, and reads
the first line: `unsat` → `solver_trusted` (solver-proved, solver in the TCB —
NOT a kernel-checked class), `sat` → `counterexample` (with the model parsed
back to source variables via `(get-model)`), `unknown`/`timeout` accordingly. If
Z3 is not on PATH the honest verdict is `solver_error` for every query — an
absent solver never yields a proof. Only ever called behind an explicit flag.
Returns `(vcKey, resultClass, counterexampleModel)`. -/
def smtDischarge (queries : List (String × String)) (timeoutSec : Nat)
(timeoutMs : Option Nat := none)
: IO (List (String × String × List (String × String))) := do
if queries.isEmpty then return []
-- a configured tiny millisecond soft-timeout (`-t:<ms>`) forces `unknown`; the
-- default is the per-run wall timeout (`-T:<sec>`).
let timeoutArg := match timeoutMs with
| some ms => "-t:" ++ toString ms
| none => "-T:" ++ toString timeoutSec
let haveZ3 ← (try
let o ← IO.Process.output { cmd := "bash", args := #["-c", "command -v z3"] }
pure (o.exitCode == 0)
catch _ => pure false)
if !haveZ3 then
return queries.map (fun (k, _) => (k, "solver_error", []))
let mut res : List (String × String × List (String × String)) := []
for (k, script) in queries do
let r ← (try
let mk ← IO.Process.output { cmd := "mktemp", args := #["-t", "concrete-vc-XXXXXX"] }
let path := mk.stdout.trimAscii.toString
IO.FS.writeFile ⟨path⟩ script
let out ← IO.Process.output { cmd := "z3", args := #[timeoutArg, path] }
let _ ← IO.Process.output { cmd := "rm", args := #["-f", path] }
let stdout := out.stdout
let line := ((stdout.trimAscii.toString.splitOn "\n").head?.getD "").trimAscii.toString
if line == "unsat" then pure ("solver_trusted", ([] : List (String × String)))
else if line == "sat" then
-- the declared vars are the source names; read each from the model.
let vars := (script.splitOn "\n").filterMap fun l =>
let t := l.trimAscii.toString
if t.startsWith "(declare-const " then ((t.drop "(declare-const ".length).toString.splitOn " ").head?
else none
let model := vars.filterMap fun vn => (smtModelValue stdout vn).map (fun x => (vn, x))
pure ("counterexample", model)
else if line == "unknown" then pure ("unknown", [])
else if line == "timeout" then pure ("timeout", [])
else pure ("solver_error", [])
catch _ => pure ("solver_error", ([] : List (String × String))))
res := res ++ [(k, r.1, r.2)]
return res
/-- Lean replay (Phase 2 #12). Given `(vcKey, leanTheoremSource)` pairs, write each
theorem to a file and run `lake env lean` on it. Returns the keys Lean
INDEPENDENTLY closed (exit 0) — those graduate from `solver_trusted` to
`proved_by_lean_replay`. Only the in-toolchain tactic in the source (`omega`)
is used; no Mathlib. A theorem omega cannot close simply fails to compile and
its key is not returned, so the VC honestly stays `solver_trusted`. -/
def leanReplayCheck (goals : List (String × String)) : IO (List String) := do
if goals.isEmpty then return []
let mut closed : List String := []
for (k, src) in goals do
let ok ← (try
let tmpDir ← IO.Process.output { cmd := "mktemp", args := #["-d"] }
let dir := tmpDir.stdout.trimAscii.toString
IO.FS.writeFile ⟨dir ++ "/vc_replay.lean"⟩ src
let r ← IO.Process.output { cmd := "lake", args := #["env", "lean", dir ++ "/vc_replay.lean"],
env := #[("LAKE_TERM_ANSI", "0")] }
let _ ← IO.Process.output { cmd := "rm", args := #["-rf", dir] }
pure (r.exitCode == 0)
catch _ => pure false)
if ok then closed := closed ++ [k]
return closed
/-- Phase 3 #14: policy inputs derived from the ONE obligation ledger. Builds the
discharged ledger (folding the external-SMT path when a solver-evidence stance
is set, so `solver_trusted` is present), then projects the vacuous / assume /
solver-trusted facts the release policy acts on — replacing the three
`compute*Quals` side channels. Returns `(vacuousQuals, assumeQuals,
solverTrustedQuals)`, dep-filtered exactly as before. -/
def computePolicyQuals (policy : Concrete.ProjectPolicy) (modules : List Concrete.Module)
(depNames : List String) (locMap : Report.FnLocMap) (registry : Concrete.ProofRegistry) :
IO (List String × List String × List String) := do
let dvcs ← computeVCsDischarged modules locMap registry
-- fold the external-SMT path into the ledger only when a stance is set (matches
-- the old computeSolverTrustedQuals gating; otherwise no solver runs).
let dvcs ← if policy.solverEvidence.isEmpty then pure dvcs else do
let smtGoals := Report.overflowSmtGoals modules
if smtGoals.isEmpty then pure dvcs else do
let replayGoals := Report.leanReplayGoals modules
let dvcs := Report.markSmtEligible dvcs smtGoals replayGoals
let solverId ← z3VersionId
let results ← smtDischarge smtGoals 5
let dvcs := Report.foldSmtResults dvcs results solverId
let trusted := dvcs.filterMap fun v => if v.status == "solver_trusted" then some v.id else none
let rg := replayGoals.filter (fun (k, _) => trusted.contains k)
let replayed ← leanReplayCheck rg
pure (Report.foldReplayResults dvcs replayed)
let ledger := Concrete.ObligationCore.ledgerOfVCs dvcs
let keep := fun (q : String) => !depNames.any (fun d => q.startsWith (d ++ "."))
let vac := (Concrete.ObligationCore.vacuousFunctions ledger).filter keep
let asm := (Concrete.ObligationCore.assumeFunctions ledger).filter keep
let st := Concrete.ObligationCore.solverTrustedIds ledger
return (vac, asm, st)
/-- Render the contracts report plus the call-site obligation section AS A VIEW
over the one discharged ObligationCore ledger (Phase 3 #15 / #18e).
Instead of re-running the per-family discharge (the old duplicate path that
`check_contracts_ledger_parity.sh` guards), this reads `computeVCsDischarged`
— the exact same ledger `--report obligation-ledger` and policy consume — and
slices the proved-key sets out of it: a key is omega-proved iff its discharged
VC carries engine `omega`, bv-proved iff engine `bv_decide` (`dischargeVCs`
sets the engine per adapter). Each render helper matches only its own family's
keys, so passing the shared sets is byte-identical to the former separate
discharge — now single-source, so the two surfaces cannot diverge. -/
def renderContracts (parsedModules : List Concrete.Module) (registry : Concrete.ProofRegistry)
(locMap : Report.FnLocMap) : IO String := do
let dvcs ← computeVCsDischarged parsedModules locMap registry
let omegaProved := dvcs.filterMap fun v => if v.engine == "omega" then some v.id else none
let bvProved := dvcs.filterMap fun v => if v.engine == "bv_decide" then some v.id else none
let obs := Report.callSiteObligations parsedModules
-- renderCallSites wants bv-proved call sites as obligation INDICES, not keys.
let bvCallIdx := (List.range obs.length).filter fun i =>
match obs[i]? with | some o => bvProved.contains o.key | none => false
let boundsObls := Report.boundsObligations parsedModules
let divObls := Report.divObligations parsedModules
let ovfObls := Report.overflowObligations parsedModules
-- Every helper below is handed the SAME omega/bv proved-key sets and filters its
-- own family's keys (loop / vacuity / assert / #pre / #bounds / #div / #ovf are
-- disjoint key spaces). overflow alone needs both (omega vs bv rendering).
return Report.contractsReport parsedModules registry omegaProved omegaProved
++ Report.renderCallSites obs bvCallIdx omegaProved
++ Report.renderAssertAssume parsedModules omegaProved
++ Report.renderBounds boundsObls omegaProved
++ Report.renderDiv divObls omegaProved
++ Report.renderOverflow ovfObls omegaProved bvProved
/-- Walk up from `path` for the directory holding a Lake workspace.
Kernel replay used to invoke `lake` with no `cwd`, so the workspace came from the
PROCESS working directory and the verdict depended on where the caller stood
(R-0004 slice 4). Resolving from the input makes the answer a property of what is
being checked. Returns `none` rather than guessing a default: a wrong workspace
would replay against the wrong library and report confident nonsense. -/
partial def findLakeWorkspace (path : String) : IO (Option System.FilePath) := do
let abs ← IO.FS.realPath (System.FilePath.mk path)
let rec up (dir : System.FilePath) (fuel : Nat) : IO (Option System.FilePath) := do
match fuel with
| 0 => return none
| fuel + 1 =>
if (← (dir / "lakefile.toml").pathExists) || (← (dir / "lakefile.lean").pathExists) then
return some dir
match dir.parent with
| some p => if p == dir then return none else up p fuel
| none => return none
-- Start at the file's directory; a file path has a parent, a directory is its
-- own starting point.
let start := if (← abs.isDir) then abs else (abs.parent.getD abs)
up start 64
/-- Run pipeline and check a profile constraint.
If the input file lives inside a `Concrete.toml` project, route
through project mode so std and other dependencies resolve. -/
def compileAndReport (inputPath : String) (reportType : String)
(proveTarget : Option String := none) (proveOut : Option String := none)
(proveForce : Bool := false) (proveEmitLink : Bool := false)
(proveShowObl : Option String := none) (proveReplay : Bool := false)
(proveJson : Bool := false) (proveNearestLemmas : Bool := false)
(proveEmitLean : Bool := false) (proveStdout : Bool := false)
(proveEmitArtifacts : Bool := false) (proveOutDir : Option String := none)
(proveCheck : Bool := false) (proveWorkspace : Option String := none)
(proveNearestId : Option String := none) (reportJson : Bool := false)
(smtRun : Bool := false) (smtEmit : Bool := false)
(smtReplay : Bool := false) (emitLeanReplay : Bool := false)
(smtTimeoutMs : Option Nat := none) : IO UInt32 := do
let source ← readFile inputPath
let mainSrcMap : SourceMap := [(inputPath, source)]
-- Interface report only needs parse + resolveFiles + summary
if reportType == "interface" then
match Pipeline.parse source with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := mainSrcMap))
return 1
| .ok parsed =>
match ← Pipeline.resolveFiles (dirOf inputPath) parsed inputPath resolveAllModules with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := mainSrcMap))
return 1
| .ok (resolved, _) =>
let summary := Pipeline.buildSummary resolved
IO.println (Report.interfaceReport summary.entries)
return 0
-- All other reports need the full frontend. If the file is inside a
-- Concrete.toml project, route through project mode so dependency imports
-- (e.g. std) resolve; mirrors compileAndCheck.
let inputDir := dirOf inputPath
-- Returns (parsed, fullValidCore, scopedValidCore, srcMap). In project
-- mode the two validCores differ: full covers the entire user package
-- (used for pc/registry validation, so sibling-file entries don't
-- appear "unknown"), scoped covers just the file the user invoked
-- (used to drive report output). In standalone mode they're identical.
let frontendResult : Except UInt32 (ParsedProgram × ValidatedCore × ValidatedCore × SourceMap) ←
match ← findProjectRoot inputDir with
| some root =>
match ← loadProject root with
| .error ec => pure (Except.error ec)
| .ok ctx =>
let { validCore, parsed, allSrcMap, depNames, .. } := ctx
let userModules := validCore.coreModules.filter fun m => !depNames.contains m.name
let fullValidCore : ValidatedCore := { validCore with coreModules := userModules }
let scopedModules ← scopeUserModulesToFile userModules inputPath root
let scopedValidCore : ValidatedCore := { validCore with coreModules := scopedModules }
pure (Except.ok (parsed, fullValidCore, scopedValidCore, allSrcMap))
| none =>
match ← Pipeline.runFrontend inputPath source resolveAllModules with
| .error ds =>
IO.eprintln (renderDiagnostics ds (sourceMap := mainSrcMap))
pure (Except.error 1)
| .ok (parsed, _, validCore, srcMap) =>
pure (Except.ok (parsed, validCore, validCore, srcMap))
match frontendResult with
| .error ec => return ec
| .ok (parsed, fullValidCore, scopedValidCore, srcMap) =>
let locMap := Report.buildFnLocMap parsed.modules inputPath
let simpleLocMap := locMap.map fun e => (e.qualName, (e.file, e.fnSpan.line))
-- The registry is the in-source proof links (#[proof_by]/#[spec]/...)
-- synthesized from the FULL user package.
let registry := Report.synthesizeSourceLinks parsed.modules fullValidCore.coreModules
-- pc and registry validation run on the FULL user package: a
-- registry entry naming a function defined in a sibling file must
-- still validate when the user is querying just one file.
let pc := extractProofCore fullValidCore simpleLocMap registry
-- Report output still iterates only the scoped modules.
let validCore := scopedValidCore
-- Validate registry against ProofCore and surface warnings/errors
let regIssues := Concrete.validateRegistry pc registry
for issue in regIssues do
IO.eprintln (Concrete.renderRegistryIssue issue)
let hasRegistryErrors := regIssues.any (·.isError)
-- `concrete prove <function>`: read-only per-function proof scaffold.
-- Writes nothing unless --out is given (and then refuses to clobber).
if let some target := proveTarget then
match Report.proveResolve pc target with
| .error msg => IO.eprintln msg; return 1
| .ok qual =>
-- --emit-link: print the in-source proof-link block (text or JSON).
if proveEmitLink then
IO.println (if proveJson then Report.emitProofLinkJson registry qual inputPath
else Report.emitProofLink registry qual)
return 0
let provedVCs ← kernelDischargeLoopVCs (Report.loopVCGoals parsed.modules)
-- --nearest-lemmas: proof-recipe hints per obligation kind + features.
if proveNearestLemmas then
IO.println (Report.nearestLemmas pc parsed.modules qual provedVCs proveJson proveNearestId)
return 0
-- --emit-lean: compilable single-function Lean proof stub (ends in `sorry`).
if proveEmitLean then
let stub := Report.emitLeanStub pc registry parsed.modules qual provedVCs
match proveOut with
| some path =>
if proveStdout then IO.println stub; return 0
if (← System.FilePath.pathExists path) && !proveForce then
IO.eprintln s!"refusing to overwrite existing '{path}' (pass --force to clobber)."
return 1
if let some parent := (System.FilePath.mk path).parent then
IO.FS.createDirAll parent
IO.FS.writeFile path stub
IO.println s!"wrote Lean proof stub for {qual} to {path}"
return 0
| none => IO.println stub; return 0
-- --emit-artifacts: write a reproducible bundle per failed obligation.
if proveEmitArtifacts then
let proveStatus := (pc.obligations.find? (·.functionId.qualName == qual)).map (·.status.canonical) |>.getD "missing"
let obs := Report.callSiteObligations parsed.modules
let myCands := ((List.range obs.length).zip obs).filterMap fun (i, o) =>
if o.caller == qual then o.leanGoal.map (fun g => (i, g)) else none
let bvProved ← bvDischargeCallSites myCands
let failingCalls := myCands.filter (fun (i, _) => !bvProved.contains i)
let arts := Report.proveArtifacts pc registry parsed.modules qual inputPath provedVCs failingCalls proveStatus
if arts.isEmpty then
IO.println s!"no failed obligations for {qual} (nothing to emit)."