summaryrefslogtreecommitdiff
path: root/source/Checking/FinalPrelude.hs
blob: 5951accf46a22c7b58899839fca57e9d3ad2763b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}

-- | Authority-confined construction of the inert final-prelude candidate.
module Checking.FinalPrelude
    ( FinalPreludeCandidate
    , finalPreludeParsed
    , finalPreludeSyntax
    , finalPreludeSemantic
    , finalPreludePrefix
    , finalPreludeObjects
    , PreludePublicRole(..)
    , expectedFinalPreludePublicRoles
    , FinalPreludeRoleTarget(..)
    , finalPreludePublicRole
    , FinalPreludeValidationError(..)
    , FinalPreludeFailure(..)
    , FinalPreludeBuildResult(..)
    , buildFinalPreludeCandidate
    , buildParsedFinalPreludeCandidate
    ) where

import Base hiding (Empty)
import Checking.Authority qualified as Authority
import Checking.Core
import Checking.Declaration qualified as Declaration
import Checking.Exact qualified as Exact
import Checking.Exact.Proof qualified as ExactProof
import Checking.Foundation
import Checking.Identity
import Checking.Semantic
import Checking.Semantic qualified as Semantic
import Felix.Module
import Felix.Parse
import Felix.Prelude qualified as Prelude
import Felix.Source (ImportRef)
import Report.Location
import Syntax.Abstract qualified as Raw
import Syntax.Interface
import Syntax.Lexicon qualified as Lexicon

import Control.Monad (unless)
import Data.Bifunctor (first)
import Data.List qualified as List
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set


data FinalPreludeCandidate = FinalPreludeCandidate
    !Prelude.ReservedParsedPrelude
    !ModuleSyntaxInterface
    !SemanticInterface
    !Declaration.PendingModulePrefix
    !CheckedObjectClosure
    !(Map.Map PreludePublicRole FinalPreludeRoleTarget)

finalPreludeParsed
    :: FinalPreludeCandidate
    -> Prelude.ReservedParsedPrelude
finalPreludeParsed
        (FinalPreludeCandidate parsed _syntax _semantic _prefix _objects
            _roles) =
    parsed

finalPreludeSyntax
    :: FinalPreludeCandidate
    -> ModuleSyntaxInterface
finalPreludeSyntax
        (FinalPreludeCandidate _parsed syntax _semantic _prefix _objects
            _roles) =
    syntax

finalPreludeSemantic
    :: FinalPreludeCandidate
    -> SemanticInterface
finalPreludeSemantic
        (FinalPreludeCandidate _parsed _syntax semantic _prefix _objects
            _roles) =
    semantic

finalPreludePrefix
    :: FinalPreludeCandidate
    -> Declaration.PendingModulePrefix
finalPreludePrefix
        (FinalPreludeCandidate _parsed _syntax _semantic prefix _objects
            _roles) =
    prefix

finalPreludeObjects
    :: FinalPreludeCandidate
    -> CheckedObjectClosure
finalPreludeObjects
        (FinalPreludeCandidate _parsed _syntax _semantic _prefix objects
            _roles) =
    objects

data FinalPreludeRoleTarget
    = FinalPreludeObjectRole !ObjectId
    | FinalPreludeTheoremRole !TheoremRef
    deriving stock (Show, Eq, Ord)

-- | Stable public roles exported by the packaged final prelude.
data PreludePublicRole
    = PreludeInfinityTheorem
    | PreludeOmegaObject
    | PreludeOmegaDefiningEquation
    | PreludeNaturalsAlias
    | PreludeNaturalsInductiveTheorem
    | PreludeNaturalsMinimalTheorem
    deriving stock (Show, Eq, Ord, Enum, Bounded)

expectedFinalPreludePublicRoles :: Set PreludePublicRole
expectedFinalPreludePublicRoles =
    Set.fromList [minBound .. maxBound]

finalPreludePublicRole
    :: FinalPreludeCandidate
    -> PreludePublicRole
    -> Maybe FinalPreludeRoleTarget
finalPreludePublicRole
        (FinalPreludeCandidate _parsed _syntax _semantic _prefix _objects
            roles) role =
    Map.lookup role roles

data FinalPreludeValidationError
    = FinalPreludePackagedInputMismatch
    | FinalPreludeSemanticEnvironmentMismatch
    | FinalPreludeDeclarationAssociationMismatch
    | FinalPreludeUnexpectedObject !ObjectId
    | FinalPreludeDeclarationMissing !Text
    | FinalPreludeDeclarationDuplicate !Text
    | FinalPreludeDeclarationShapeMismatch !Text
    | FinalPreludeDefinitionContentMismatch !Text
    | FinalPreludeFactContentMismatch !Text
    | FinalPreludeValidationInventoryMismatch !DeclarationSlot
    | FinalPreludeAuthorityMismatch !DeclarationSlot
    | FinalPreludeBaseStructureMismatch
    | FinalPreludePublicRoleMismatch !PreludePublicRole
    deriving stock (Show, Eq)

data FinalPreludeFailure
    = FinalPreludeWrongOwner !ModuleName
    | FinalPreludeHasImports ![ImportRef]
    | FinalPreludeHasSyntaxImports ![SyntaxInterfaceId]
    | FinalPreludeUnsupportedBlock !Location
    | FinalPreludeUnmatchedProof !Location
    | FinalPreludeExactDeclarationFailed !Exact.ExactCompileError
    | FinalPreludeExactProofFailed !ExactProof.ExactProofError
    | FinalPreludeOmittedProof !Location
    | FinalPreludeDeclarationFailed !Declaration.DeclarationError
    | FinalPreludeSealFailed !SemanticInterfaceError
    | FinalPreludeValidationFailed !FinalPreludeValidationError
    deriving stock (Show, Eq)

data FinalPreludeBuildResult
    = FinalPreludeSourceLoadFailed !Prelude.PreludeLoadError
    | FinalPreludeSourceParseFailed !Prelude.PreludeParseError
    | FinalPreludeBuilt !FinalPreludeCandidate
    | FinalPreludeBuildFailed
        !FinalPreludeFailure
        !Declaration.PendingModulePrefix
    | FinalPreludeBuildOpenFailed !Declaration.DriverOpenError

data PlannedPreludeDeclaration
    = PlannedPreludeBinding
        !(Declaration.PlannedDeclaration (Maybe ObjectId))
    | PlannedPreludeFoundation
        !(Declaration.PlannedDeclaration
            ExactProof.CheckedFinalPreludeFoundationAuthorization)
    | PlannedPreludeProof
        !(Declaration.PlannedDeclaration
            ExactProof.CheckedExactProofAuthorization)
    | PlannedPreludeBase
        !(Declaration.PlannedDeclaration ())

data PreludePlanningFailure
    = PreludePlanningAction !FinalPreludeFailure
    | PreludePlanningDeclaration !Declaration.DeclarationError

data PreludeModulePlan = PreludeModulePlan
    ![PlannedPreludeDeclaration]
    !(Maybe PreludePlanningFailure)

buildFinalPreludeCandidate
    :: CheckedFoundation
    -> Declaration.VampireResolver
    -> IO FinalPreludeBuildResult
buildFinalPreludeCandidate foundation resolver =
    Prelude.loadReservedPreludeSourceInput >>= \case
        Left failure ->
            pure (FinalPreludeSourceLoadFailed failure)
        Right source ->
            Prelude.parseReservedPreludeSource source >>= \case
                Left failure ->
                    pure (FinalPreludeSourceParseFailed failure)
                Right parsed ->
                    buildParsedFinalPreludeCandidate
                        foundation parsed resolver

-- The production acquisition path establishes packaged provenance before
-- passing its already parsed source here.  The explicit parsed seam avoids a
-- second load and parse on a cache miss.
buildParsedFinalPreludeCandidate
    :: CheckedFoundation
    -> Prelude.ReservedParsedPrelude
    -> Declaration.VampireResolver
    -> IO FinalPreludeBuildResult
buildParsedFinalPreludeCandidate foundation parsed resolver =
    case validatePackagedPreludeInput parsed syntax of
        Left failure -> do
            case emptyPrefix of
                Left prefixFailure ->
                    pure
                        (FinalPreludeBuildOpenFailed
                            (Declaration.DriverInitialPrefixError
                                prefixFailure))
                Right prefix ->
                    pure (FinalPreludeBuildFailed failure prefix)
        Right () -> do
            outcome <-
                Declaration.runModuleDriver
                    foundation
                    preludeModuleName
                    []
                    resolver
                    -- The confined builder never consults stored validation.
                    Declaration.FreshValidation
                    do
                        PreludeModulePlan declarations terminal <-
                            Declaration.runProspectiveLoweringDriver
                                (planBlocks [] 0 blocks)
                        traverse_ admitPreludeDeclaration declarations
                        traverse_ failPreludePlanning terminal
            pure case outcome of
                Left failure ->
                    FinalPreludeBuildOpenFailed failure
                Right (Declaration.DriverFailed failure prefix) ->
                    FinalPreludeBuildFailed
                        (case failure of
                            Declaration.DriverDeclarationFailed err ->
                                FinalPreludeDeclarationFailed err
                            Declaration.DriverActionFailed err ->
                                err)
                        prefix
                Right (Declaration.DriverSealFailed failure prefix) ->
                    FinalPreludeBuildFailed
                        (FinalPreludeSealFailed failure)
                        prefix
                Right (Declaration.DriverSucceeded
                        () semantic prefix objects) ->
                    case validateFinalPrelude
                            foundation parsed semantic prefix objects of
                        Left failure ->
                            FinalPreludeBuildFailed
                                (FinalPreludeValidationFailed failure)
                                prefix
                        Right roles ->
                            FinalPreludeBuilt
                                (FinalPreludeCandidate
                                    parsed syntax semantic prefix objects roles)
  where
    identified = Prelude.reservedParsedPreludeModule parsed
    blocks = identifiedParsedModuleBlocks identified
    occurrences = identifiedParsedModuleSyntaxOccurrences identified
    syntax = identifiedParsedModuleSyntaxInterface identified

    emptyPrefix =
        Declaration.emptyPendingModulePrefix
            <$> initialPrefixContextId
                (theoryId foundation)
                preludeModuleName
                []

    planBlocks completed _blockIndex [] = do
        planBaseStructure >>= \case
            Left failure ->
                pure
                    (PreludeModulePlan
                        (reverse completed)
                        (Just failure))
            Right base ->
                pure
                    (PreludeModulePlan
                        (reverse (base : completed))
                        Nothing)
    planBlocks completed blockIndex (block : remaining) =
        case block of
            Raw.BlockClaim{} ->
                case remaining of
                    Raw.BlockProof _location proof _end : rest -> do
                        continue completed (blockIndex + 2) rest
                            =<< planOrdinaryProof block (Just proof)
                    _ -> do
                        continue completed (blockIndex + 1) remaining
                            =<< planImplicitClaim block
            Raw.BlockProof location _proof _end ->
                pure
                    (PreludeModulePlan
                        (reverse completed)
                        (Just
                            (PreludePlanningAction
                                (FinalPreludeUnmatchedProof location))))
            Raw.BlockAbbr{} -> do
                continue completed (blockIndex + 1) remaining
                    =<< planBinding blockIndex block
            Raw.BlockDefn{} -> do
                continue completed (blockIndex + 1) remaining
                    =<< planBinding blockIndex block
            _ ->
                pure
                    (PreludeModulePlan
                        (reverse completed)
                        (Just
                            (PreludePlanningAction
                                (FinalPreludeUnsupportedBlock
                                    (locate block)))))
      where
        continue accumulated nextIndex rest = \case
            Left failure ->
                pure
                    (PreludeModulePlan
                        (reverse accumulated)
                        (Just failure))
            Right declaration ->
                planBlocks (declaration : accumulated) nextIndex rest

    planBaseStructure = do
        slot <- Declaration.nextDeclarationSlotLowering
        theory <- Declaration.currentTheoryLowering
        let seed =
                opaqueDeclarationSeed
                    (declarationSlotModule slot)
                    (declarationSlotOrdinal slot)
                    StructureDeclaration
                    (generatedObjectSlot 0)
            coreType = TyArrow TySet TySet
            content = OpaqueObjectContent theory seed coreType
            identity = opaqueObjectId theory seed coreType
            asserted = assertedObject identity content
            structurePhrase =
                semanticStructurePhrase Lexicon._Onesorted
            operation =
                semanticStructureOperation Raw.CarrierSymbol identity
        descriptor <-
            either
                (pure
                    . Left
                    . PreludePlanningDeclaration
                    . Declaration.DeclarationEnvironmentFailed)
                (pure . Right)
                (semanticStructureDescriptor
                    structurePhrase Nothing [] [operation])
        case descriptor of
            Left failure -> pure (Left failure)
            Right checkedDescriptor ->
                planPreludeChecked PlannedPreludeBase
                    (Declaration.checkedCompiledDeclaration
                        (declarationSyntaxId
                            "felix-final-prelude-base-structure-v1")
                        [asserted] [] [] [checkedDescriptor] [] ())

    planBinding blockIndex block = do
        prepared <-
            Exact.prepareExactDeclaration
                block
                [ parsedSyntaxOccurrenceEntry occurrence
                | occurrence <- occurrences
                , parsedSyntaxOccurrenceBlockIndex occurrence == blockIndex
                ]
        case prepared of
            Left failure ->
                pure
                    (Left
                        (PreludePlanningAction
                            (FinalPreludeExactDeclarationFailed failure)))
            Right declaration -> do
                Exact.lowerPreparedExactBinding declaration >>= \case
                    Left failure -> planningDeclarationFailure failure
                    Right checked ->
                        planPreludeChecked PlannedPreludeBinding checked

    planImplicitClaim block = do
        foundationClaim <-
            ExactProof.prepareFinalPreludeFoundationClaim
                foundation block Nothing
        case foundationClaim of
            Right claim -> do
                ExactProof.lowerPreparedFinalPreludeFoundationClaim claim
                    >>= \case
                        Left failure -> planningDeclarationFailure failure
                        Right checked ->
                            planPreludeChecked PlannedPreludeFoundation checked
            Left ExactProof.ExactProofFoundationLeafTargetMismatch{} ->
                planOrdinaryProof block Nothing
            Left ExactProof.ExactProofFoundationLeafRequiresImplicitAuto{} ->
                planOrdinaryProof block Nothing
            Left failure ->
                pure
                    (Left
                        (PreludePlanningAction
                            (FinalPreludeExactProofFailed failure)))

    planOrdinaryProof block explicitProof = do
        prepared <-
            ExactProof.prepareExactProof block explicitProof
        case prepared of
            Left failure ->
                pure
                    (Left
                        (PreludePlanningAction
                            (FinalPreludeExactProofFailed failure)))
            Right proof
                | Just location <-
                    ExactProof.preparedExactProofFirstOmission proof ->
                    pure
                        (Left
                            (PreludePlanningAction
                                (FinalPreludeOmittedProof location)))
                | otherwise ->
                    ExactProof.lowerPreparedExactProof proof >>= \case
                        Left failure -> planningDeclarationFailure failure
                        Right checked ->
                            planPreludeChecked PlannedPreludeProof checked

    planPreludeChecked
        :: forall body.
           (Declaration.PlannedDeclaration body
                -> PlannedPreludeDeclaration)
        -> Declaration.CheckedDeclaration body
        -> Declaration.LoweringDriver
            (Either PreludePlanningFailure PlannedPreludeDeclaration)
    planPreludeChecked constructor checked =
        Declaration.planCheckedDeclaration checked >>= \case
            Left failure -> planningDeclarationFailure failure
            Right planned -> pure (Right (constructor planned))

    planningDeclarationFailure =
        pure . Left . PreludePlanningDeclaration

    admitPreludeDeclaration = \case
        PlannedPreludeBinding planned ->
            void
                (Declaration.admitPlannedCheckedDeclaration
                    planned Exact.authorizeCheckedExactBinding)
        PlannedPreludeFoundation planned ->
            void
                (Declaration.admitPlannedCheckedDeclaration planned
                    ExactProof.authorizeCheckedFinalPreludeFoundationClaim)
        PlannedPreludeProof planned ->
            void
                (Declaration.admitPlannedCheckedDeclaration
                    planned ExactProof.authorizeCheckedExactProof)
        PlannedPreludeBase planned ->
            void
                (Declaration.admitPlannedCheckedDeclaration planned
                    (\() stages ->
                        unless
                            (null stages)
                            (Declaration.failDeclaration
                                (Declaration.CheckedAuthorizationCandidateShapeMismatch
                                    0 (length stages)))))

    failPreludePlanning = \case
        PreludePlanningAction failure ->
            Declaration.failModuleDriver failure
        PreludePlanningDeclaration failure ->
            Declaration.failDeclarationDriver failure

data PreludeDeclaration = PreludeDeclaration
    !Raw.Block
    !Declaration.CommittedDeclarationBatch

data PreludeDefinitionKind
    = PreludeDefinition
    | PreludeAbbreviation

data PreludeDefinitionView = PreludeDefinitionView
    !ObjectId
    !SemanticGlobalTarget

validateFinalPrelude
    :: CheckedFoundation
    -> Prelude.ReservedParsedPrelude
    -> SemanticInterface
    -> Declaration.PendingModulePrefix
    -> CheckedObjectClosure
    -> Either
        FinalPreludeValidationError
        (Map.Map PreludePublicRole FinalPreludeRoleTarget)
validateFinalPrelude foundation parsed semantic prefix objects = do
    (declarations, baseStructure) <-
        associatePreludeDeclarations parsed prefix
    validateConfinedAuthority
        foundation semantic objects declarations baseStructure
    resolveAndValidatePublicRoles foundation objects declarations

resolveAndValidatePublicRoles
    :: CheckedFoundation
    -> CheckedObjectClosure
    -> [PreludeDeclaration]
    -> Either
        FinalPreludeValidationError
        (Map.Map PreludePublicRole FinalPreludeRoleTarget)
resolveAndValidatePublicRoles foundation objects declarations = do
    successor <-
        expectDefinition
            foundation objects declarations
            "prelude_successor"
            PreludeDefinition
            (TyArrow TySet TySet)
            expectedSuccessorBody
    let successorId = definitionViewObject successor

    inductive <-
        expectDefinition
            foundation objects declarations
            "prelude_inductive"
            PreludeDefinition
            (TyArrow TySet TyProp)
            (expectedInductiveBody successorId)
    let inductiveId = definitionViewObject inductive

    u0 <-
        expectDefinition
            foundation objects declarations
            "prelude_u0"
            PreludeDefinition
            TySet
            (applyIntrinsic UnivOf (CIntrinsic Empty))
    let u0Id = definitionViewObject u0

    let omegaBody = expectedOmegaBody u0Id inductiveId
    omega <-
        expectDefinition
            foundation objects declarations
            "prelude_omega"
            PreludeDefinition
            TySet
            omegaBody
    let omegaId = definitionViewObject omega

    naturals <-
        expectDefinition
            foundation objects declarations
            "prelude_naturals"
            PreludeAbbreviation
            TySet
            (CGlobal omegaId)
    case definitionViewTarget naturals of
        TransparentExpansion{} -> pure ()
        _ ->
            Left
                (FinalPreludeDefinitionContentMismatch
                    "prelude_naturals")

    (infinity, infinityTarget) <-
        expectClaim declarations "prelude_infinity"
    validateInfinityTarget objects inductiveId infinityTarget
    omegaEquation <-
        fst
            <$> expectFactTarget
                declarations
                "prelude_omega"
                (CEq TySet (CGlobal omegaId) omegaBody)
    let inductiveOmega =
            CApp (CGlobal inductiveId) (CGlobal omegaId)
        minimalOmega = expectedMinimality inductiveId omegaId
    naturalsInductive <-
        fst
            <$> expectClaimTarget
                declarations
                "prelude_naturals_inductive"
                inductiveOmega
    naturalsMinimal <-
        fst
            <$> expectClaimTarget
                declarations
                "prelude_naturals_minimal"
                minimalOmega

    let roles = Map.fromList
            [ ( PreludeInfinityTheorem
              , FinalPreludeTheoremRole infinity
              )
            , ( PreludeOmegaObject
              , FinalPreludeObjectRole omegaId
              )
            , ( PreludeOmegaDefiningEquation
              , FinalPreludeTheoremRole omegaEquation
              )
            , ( PreludeNaturalsAlias
              , FinalPreludeObjectRole omegaId
              )
            , ( PreludeNaturalsInductiveTheorem
              , FinalPreludeTheoremRole naturalsInductive
              )
            , ( PreludeNaturalsMinimalTheorem
              , FinalPreludeTheoremRole naturalsMinimal
              )
            ]
    unless
        (Map.keysSet roles == expectedFinalPreludePublicRoles)
        (Left
            (FinalPreludePublicRoleMismatch
                PreludeInfinityTheorem))
    pure roles

validatePackagedPreludeInput
    :: Prelude.ReservedParsedPrelude
    -> ModuleSyntaxInterface
    -> Either FinalPreludeFailure ()
validatePackagedPreludeInput parsed syntax
    | freshModuleInputOwner input /= preludeModuleName =
        Left (FinalPreludeWrongOwner (freshModuleInputOwner input))
    | not (null (freshModuleInputImports input)) =
        Left (FinalPreludeHasImports (freshModuleInputImports input))
    | not (null (moduleSyntaxDirectInputs syntax)) =
        Left
            (FinalPreludeHasSyntaxImports
                (moduleSyntaxDirectInputs syntax))
    | otherwise = do
        unless
            ( freshModuleInputBinding input == FreshReservedSource
              && freshModuleInputLocationPath input
                    == Prelude.preludeDiagnosticLabel
              && freshModuleInputSyntaxInterface input == syntax
              && identifiedParsedModuleSyntaxInterface identified == syntax
            )
            (Left
                (FinalPreludeValidationFailed
                    FinalPreludePackagedInputMismatch))
  where
    input = Prelude.reservedParsedPreludeInput parsed
    identified = Prelude.reservedParsedPreludeModule parsed

associatePreludeDeclarations
    :: Prelude.ReservedParsedPrelude
    -> Declaration.PendingModulePrefix
    -> Either
        FinalPreludeValidationError
        ([PreludeDeclaration], Declaration.CommittedDeclarationBatch)
associatePreludeDeclarations parsed prefix = do
    case List.splitAt (length sourceDeclarations) batches of
        (sourceBatches, [baseStructure])
            | length sourceBatches == length sourceDeclarations ->
                pure
                    ( zipWith PreludeDeclaration
                        sourceDeclarations sourceBatches
                    , baseStructure
                    )
        _ -> Left FinalPreludeDeclarationAssociationMismatch
  where
    sourceDeclarations =
        [ block
        | block <-
            identifiedParsedModuleBlocks
                (Prelude.reservedParsedPreludeModule parsed)
        , case block of
            Raw.BlockProof{} -> False
            _ -> True
        ]
    batches = Declaration.pendingModulePrefixBatches prefix

validateConfinedAuthority
    :: CheckedFoundation
    -> SemanticInterface
    -> CheckedObjectClosure
    -> [PreludeDeclaration]
    -> Declaration.CommittedDeclarationBatch
    -> Either FinalPreludeValidationError ()
validateConfinedAuthority
        foundation semantic objects declarations baseStructure = do
    unless
        ( semanticInterfaceOwner semantic == preludeModuleName
          && null (semanticInterfaceDirectInputs semantic)
        )
        (Left FinalPreludeSemanticEnvironmentMismatch)
    traverse_ requireTransparent
        [ identity
        | declaration <- declarations
        , identity <-
            declarationDeltaObjects
                (Declaration.committedBatchDelta
                    (declarationBatch declaration))
        ]
    traverse_ (validateDeclarationAuthority foundation objects) declarations
    validateBaseStructure foundation objects baseStructure
  where
    requireTransparent identity =
        case lookupCheckedObjectContent identity objects of
            Just TransparentObjectContent{} -> pure ()
            _ -> Left (FinalPreludeUnexpectedObject identity)

validateBaseStructure
    :: CheckedFoundation
    -> CheckedObjectClosure
    -> Declaration.CommittedDeclarationBatch
    -> Either FinalPreludeValidationError ()
validateBaseStructure foundation objects batch = do
    let slot = Declaration.committedBatchSlot batch
        delta = Declaration.committedBatchDelta batch
        environment = declarationDeltaEnvironment delta
        structurePhrase = semanticStructurePhrase Lexicon._Onesorted
        expectedSeed =
            opaqueDeclarationSeed
                (declarationSlotModule slot)
                (declarationSlotOrdinal slot)
                StructureDeclaration
                (generatedObjectSlot 0)
        expectedType = TyArrow TySet TySet
        expectedObject = opaqueObjectId (theoryId foundation) expectedSeed expectedType
        expectedContent =
            OpaqueObjectContent
                (theoryId foundation)
                expectedSeed
                expectedType
    descriptor <-
        case semanticEnvironmentStructures environment of
            [single] -> Right single
            _ -> Left FinalPreludeBaseStructureMismatch
    expectedDescriptor <-
        first (const FinalPreludeBaseStructureMismatch)
            (semanticStructureDescriptor
                structurePhrase
                Nothing
                []
                [semanticStructureOperation Raw.CarrierSymbol expectedObject])
    unless
        ( declarationSlotModule slot == preludeModuleName
          && descriptor == expectedDescriptor
          && null (semanticEnvironmentBindings environment)
          && declarationDeltaObjects delta == [expectedObject]
          && null (declarationDeltaFacts delta)
          && null (declarationDeltaAliases delta)
          && null (declarationDeltaPropositions delta)
          && Declaration.committedBatchObjects batch
                == [assertedObject expectedObject expectedContent]
          && null (Declaration.committedBatchPropositions batch)
          && null (Declaration.committedBatchProofValidations batch)
          && maybe
                False
                (null . declarationValidationRecordCertificates)
                (Declaration.committedBatchDeclarationValidation batch)
          && lookupCheckedObjectContent expectedObject objects
                == Just expectedContent
        )
        (Left FinalPreludeBaseStructureMismatch)

validateDeclarationAuthority
    :: CheckedFoundation
    -> CheckedObjectClosure
    -> PreludeDeclaration
    -> Either FinalPreludeValidationError ()
validateDeclarationAuthority foundation objects declaration = do
    unless
        (fmap Authority.validationTarget certificates
            == fmap semanticFactAuthority facts)
        (Left (FinalPreludeValidationInventoryMismatch slot))
    traverse_ validateOne (zip facts certificates)
  where
    batch = declarationBatch declaration
    delta = Declaration.committedBatchDelta batch
    slot = Declaration.committedBatchSlot batch
    facts = declarationDeltaFacts delta
    certificates =
        ( Semantic.proofValidationRecordCertificate
            <$> Declaration.committedBatchProofValidations batch
        )
        <> maybe
            []
            Semantic.declarationValidationRecordCertificates
            (Declaration.committedBatchDeclarationValidation batch)

    validateOne (occurrence, certificate) = do
        unless
            (Authority.factAuthoritySafety
                (semanticFactAuthority occurrence)
                    == Authority.cleanAuthoritySafety)
            (Left (FinalPreludeAuthorityMismatch slot))
        proposition <-
            maybe
                (Left (FinalPreludeValidationInventoryMismatch slot))
                Right
                (List.find
                    ((== semanticFactProposition occurrence)
                        . checkedPropositionId)
                    (Declaration.committedBatchPropositions batch))
        let target = frozenCoreTerm (checkedPropositionTerm proposition)
        case Authority.validationDirectAuthorization certificate of
            Authority.CheckedKernelConstruction
                    (Authority.FoundationLeaf tag) -> do
                let expected =
                        frozenCoreTerm
                            (mapFrozenGlobals absurd
                                (foundationAxiomFrozen foundation tag))
                unless (target == expected)
                    (Left (FinalPreludeAuthorityMismatch slot))
            Authority.CheckedKernelConstruction
                    (Authority.CheckedDefinitionEquation identity) ->
                case lookupCheckedObjectContent identity objects of
                    Just (TransparentObjectContent _theory coreType body) ->
                        unless
                            (target == CEq coreType (CGlobal identity) body)
                            (Left (FinalPreludeAuthorityMismatch slot))
                    _ ->
                        Left (FinalPreludeAuthorityMismatch slot)
            Authority.CheckedSourceProof requests ->
                unless
                    ( not (null requests)
                      && case declarationBlock declaration of
                            Raw.BlockClaim{} -> True
                            _ -> False
                    )
                    (Left (FinalPreludeAuthorityMismatch slot))
            _ ->
                Left (FinalPreludeAuthorityMismatch slot)

expectDefinition
    :: CheckedFoundation
    -> CheckedObjectClosure
    -> [PreludeDeclaration]
    -> Text
    -> PreludeDefinitionKind
    -> CoreType
    -> CanonicalTerm ObjectId
    -> Either FinalPreludeValidationError PreludeDefinitionView
expectDefinition foundation objects declarations marker kind coreType body = do
    declaration <- findDeclaration marker declarations
    let delta =
            Declaration.committedBatchDelta
                (declarationBatch declaration)
    unless
        (case (kind, declarationBlock declaration) of
            (PreludeDefinition, Raw.BlockDefn{}) -> True
            (PreludeAbbreviation, Raw.BlockAbbr{}) -> True
            _ -> False)
        (Left (FinalPreludeDeclarationShapeMismatch marker))
    binding <-
        case semanticEnvironmentBindings
                (declarationDeltaEnvironment delta) of
            [single] -> Right single
            _ -> Left (FinalPreludeDeclarationShapeMismatch marker)
    let target = semanticGlobalBindingTarget binding
        identity = semanticGlobalTargetObject target
    unless
        (case (kind, target) of
            (PreludeDefinition, GlobalReference{}) -> True
            (PreludeAbbreviation, TransparentExpansion{}) -> True
            _ -> False)
        (Left (FinalPreludeDefinitionContentMismatch marker))
    content <-
        maybe
            (Left (FinalPreludeDefinitionContentMismatch marker))
            Right
            (lookupCheckedObjectContent identity objects)
    let expected =
            TransparentObjectContent
                (theoryId foundation)
                coreType
                body
    unless (content == expected)
        (Left (FinalPreludeDefinitionContentMismatch marker))
    pure (PreludeDefinitionView identity target)

expectClaim
    :: [PreludeDeclaration]
    -> Text
    -> Either
        FinalPreludeValidationError
        (TheoremRef, CanonicalTerm ObjectId)
expectClaim declarations marker = do
    declaration <- findDeclaration marker declarations
    unless
        (case declarationBlock declaration of
            Raw.BlockClaim{} -> True
            _ -> False)
        (Left (FinalPreludeDeclarationShapeMismatch marker))
    expectFact declarations marker

expectClaimTarget
    :: [PreludeDeclaration]
    -> Text
    -> CanonicalTerm ObjectId
    -> Either
        FinalPreludeValidationError
        (TheoremRef, CanonicalTerm ObjectId)
expectClaimTarget declarations marker expected = do
    result@(_theorem, actual) <- expectClaim declarations marker
    unless
        (actual == expected)
        (Left (FinalPreludeFactContentMismatch marker))
    pure result

expectFact
    :: [PreludeDeclaration]
    -> Text
    -> Either
        FinalPreludeValidationError
        (TheoremRef, CanonicalTerm ObjectId)
expectFact declarations marker = do
    declaration <- findDeclaration marker declarations
    let batch = declarationBatch declaration
        delta = Declaration.committedBatchDelta batch
        expectedAlias = semanticName marker
    occurrence <- case declarationDeltaFacts delta of
        [single] -> Right single
        _ -> Left (FinalPreludeFactContentMismatch marker)
    unless
        (declarationDeltaAliases delta
            == [semanticAlias expectedAlias
                    (semanticFactFingerprint occurrence)])
        (Left (FinalPreludeFactContentMismatch marker))
    proposition <-
        maybe
            (Left (FinalPreludeFactContentMismatch marker))
            Right
            (List.find
                ((== semanticFactProposition occurrence)
                    . checkedPropositionId)
                (Declaration.committedBatchPropositions batch))
    pure
        ( Authority.factAuthorityTheorem
            (semanticFactAuthority occurrence)
        , frozenCoreTerm (checkedPropositionTerm proposition)
        )

expectFactTarget
    :: [PreludeDeclaration]
    -> Text
    -> CanonicalTerm ObjectId
    -> Either
        FinalPreludeValidationError
        (TheoremRef, CanonicalTerm ObjectId)
expectFactTarget declarations marker expected = do
    result@(_theorem, actual) <- expectFact declarations marker
    unless
        (actual == expected)
        (Left (FinalPreludeFactContentMismatch marker))
    pure result

validateInfinityTarget
    :: CheckedObjectClosure
    -> ObjectId
    -> CanonicalTerm ObjectId
    -> Either FinalPreludeValidationError ()
validateInfinityTarget objects inductive = \case
    CApp (CGlobal predicate) (CGlobal witness)
        | predicate == inductive ->
            case lookupCheckedObjectContent witness objects of
                Just TransparentObjectContent{} -> pure ()
                _ ->
                    Left
                        (FinalPreludeFactContentMismatch
                            "prelude_infinity")
    _ ->
        Left
            (FinalPreludeFactContentMismatch
                "prelude_infinity")

findDeclaration
    :: Text
    -> [PreludeDeclaration]
    -> Either FinalPreludeValidationError PreludeDeclaration
findDeclaration marker declarations =
    case List.filter ((== marker) . declarationMarker) declarations of
        [] -> Left (FinalPreludeDeclarationMissing marker)
        [single] -> Right single
        _ -> Left (FinalPreludeDeclarationDuplicate marker)

declarationBlock :: PreludeDeclaration -> Raw.Block
declarationBlock (PreludeDeclaration block _batch) =
    block

declarationBatch
    :: PreludeDeclaration
    -> Declaration.CommittedDeclarationBatch
declarationBatch (PreludeDeclaration _block batch) =
    batch

declarationMarker :: PreludeDeclaration -> Text
declarationMarker =
    fromMaybe "<unmarked>" . blockMarkerText . declarationBlock

definitionViewObject :: PreludeDefinitionView -> ObjectId
definitionViewObject (PreludeDefinitionView identity _target) =
    identity

definitionViewTarget
    :: PreludeDefinitionView
    -> SemanticGlobalTarget
definitionViewTarget (PreludeDefinitionView _identity target) =
    target

blockMarkerText :: Raw.Block -> Maybe Text
blockMarkerText = fmap (\(Raw.Marker marker) -> marker) . \case
    Raw.BlockAxiom _location _title marker _axiom -> Just marker
    Raw.BlockClaim _kind _location _title marker _claim -> Just marker
    Raw.BlockDefn _location _title marker _definition -> Just marker
    Raw.BlockAbbr _location _title marker _abbreviation -> Just marker
    Raw.BlockData _location _title marker _datatype -> Just marker
    Raw.BlockInductive _location _title marker _inductive -> Just marker
    Raw.BlockSig _location _title marker _assumptions _signature -> Just marker
    Raw.BlockStruct _location _title marker _structure -> Just marker
    Raw.BlockProof{} -> Nothing

expectedSuccessorBody :: CanonicalTerm ObjectId
expectedSuccessorBody =
    CLam TySet
        (canonicalSetInsert (CBound 0) (CBound 0))

expectedInductiveBody :: ObjectId -> CanonicalTerm ObjectId
expectedInductiveBody successor =
    CLam TySet
        (logicalAnd
            (memberTerm (CIntrinsic Empty) (CBound 0))
            (CForall TySet
                (CImp
                    (memberTerm (CBound 0) (CBound 1))
                    (memberTerm
                        (CApp (CGlobal successor) (CBound 0))
                        (CBound 1)))))

expectedOmegaBody
    :: ObjectId
    -> ObjectId
    -> CanonicalTerm ObjectId
expectedOmegaBody u0 inductive =
    CApp
        (CApp (CIntrinsic Sep) (CGlobal u0))
        (CLam TySet
            (CForall TySet
                (CImp
                    (CApp (CGlobal inductive) (CBound 0))
                    (memberTerm (CBound 1) (CBound 0)))))

expectedMinimality
    :: ObjectId
    -> ObjectId
    -> CanonicalTerm ObjectId
expectedMinimality inductive omega =
    CForall TySet
        (CImp
            (CApp (CGlobal inductive) (CBound 0))
            (CForall TySet
                (CImp
                    (memberTerm (CBound 0) (CGlobal omega))
                    (memberTerm (CBound 0) (CBound 1)))))

applyIntrinsic
    :: CoreIntrinsicTag
    -> CanonicalTerm global
    -> CanonicalTerm global
applyIntrinsic intrinsic argument =
    CApp (CIntrinsic intrinsic) argument

applyIntrinsic2
    :: CoreIntrinsicTag
    -> CanonicalTerm global
    -> CanonicalTerm global
    -> CanonicalTerm global
applyIntrinsic2 intrinsic firstArgument secondArgument =
    CApp
        (CApp (CIntrinsic intrinsic) firstArgument)
        secondArgument

memberTerm
    :: CanonicalTerm global
    -> CanonicalTerm global
    -> CanonicalTerm global
memberTerm =
    applyIntrinsic2 Member

logicalAnd
    :: CanonicalTerm global
    -> CanonicalTerm global
    -> CanonicalTerm global
logicalAnd left right =
    CImp
        (CImp left (CImp right CFalsum))
        CFalsum