summaryrefslogtreecommitdiff
path: root/source/Checking/Exact/Inductive.hs
blob: 6764ec8e589eea918cf7c549706ab70beb833fbd (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
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- | Exact preparation and atomic publication of direct set inductives.
module Checking.Exact.Inductive
    ( PreparedExactInductive
    , preparedExactInductiveCarrierId
    , preparedExactInductiveCarrierType
    , preparedExactInductiveCarrierBody
    , preparedExactInductiveGuardTargets
    , preparedExactInductiveFacts
    , prepareExactInductive
    , CheckedExactInductiveAuthorization
    , lowerPreparedExactInductive
    , authorizeCheckedExactInductive
    , ExactInductiveError(..)
    , exactInductiveErrorLocation
    , renderExactInductiveError
    ) where

import Base hiding (Empty)
import Checking.Authority
import Checking.Core
import Checking.Declaration qualified as Declaration
import Checking.Exact.Global qualified as ExactGlobal
import Checking.Exact.Vocabulary
import Checking.Foundation
import Checking.Identity
import Checking.Semantic
import Checking.Typed.Inductive qualified as Typed
import Felix.Cache.Codec
import Meaning qualified
import Report.Location
import Syntax.Abstract qualified as Raw
import Syntax.Interface
import Syntax.Internal qualified as Internal

import Control.Monad (unless, when)
import Control.Monad.Except (ExceptT)
import Control.Monad.Except qualified as Except
import Data.Bifunctor (first)
import Data.ByteString (ByteString)
import Data.List qualified as List
import Data.List.NonEmpty qualified as NonEmpty
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Text qualified as Text
import Data.Vector qualified as Vector


data PreparedExactInductive = PreparedExactInductive
    !Location
    !SemanticGlobalKey
    !ObjectId
    !(Maybe AssertedObject)
    !SemanticName
    !DeclarationSyntaxId
    !(Typed.PreparedTypedInductive ObjectId)
    ![SemanticFactOccurrenceFingerprint]

data CheckedExactInductiveAuthorization =
    CheckedExactInductiveAuthorization
        !ObjectId
        !(Typed.PreparedTypedInductive ObjectId)
        ![SemanticFactOccurrenceFingerprint]

preparedExactInductiveCarrierId
    :: PreparedExactInductive
    -> ObjectId
preparedExactInductiveCarrierId
        (PreparedExactInductive
            _location _key identity _asserted _alias _syntax _typed _guards) =
    identity

preparedExactInductiveCarrierType
    :: PreparedExactInductive
    -> CoreType
preparedExactInductiveCarrierType
        (PreparedExactInductive
            _location _key _identity _asserted _alias _syntax typed _guards) =
    Typed.typedInductiveCarrierType typed

preparedExactInductiveCarrierBody
    :: PreparedExactInductive
    -> FrozenCheckedCore ObjectId
preparedExactInductiveCarrierBody
        (PreparedExactInductive
            _location _key _identity _asserted _alias _syntax typed _guards) =
    Typed.typedInductiveCarrierBody typed

preparedExactInductiveGuardTargets
    :: PreparedExactInductive
    -> Vector.Vector (FrozenCheckedCore ObjectId)
preparedExactInductiveGuardTargets
        (PreparedExactInductive
            _location _key _identity _asserted _alias _syntax typed _guards) =
    Typed.typedInductiveGuardTargets typed

preparedExactInductiveFacts
    :: PreparedExactInductive
    -> NonEmpty (Typed.PreparedTypedInductiveFact ObjectId)
preparedExactInductiveFacts
        (PreparedExactInductive
            _location _key _identity _asserted _alias _syntax typed _guards) =
    Typed.typedInductiveFacts typed

data ExactInductiveError
    = ExactInductiveUnsupportedBlock !Location
    | ExactInductiveOccurrenceMissing !Location
    | ExactInductiveOccurrenceAmbiguous !Location
    | ExactInductiveHeadMismatch !Location
    | ExactInductiveGlossFailed !Location !Meaning.GlossError
    | ExactInductiveDuplicateParameter !Location !Internal.VarSymbol
    | ExactInductiveDomainFreeVariable !Location !Internal.VarSymbol
    | ExactInductiveDomainMentionsCarrier !Location
    | ExactInductiveResultShape !Location
    | ExactInductiveResultMentionsCarrier !Location
    | ExactInductiveRecursiveTermMentionsCarrier !Location
    | ExactInductiveNestedRecursion !Location
    | ExactInductiveFixedSemanticCollision !Location !SemanticGlobalKey
    | ExactInductiveGlobalAlreadyVisible !Location !SemanticGlobalKey
    | ExactInductiveGlobalNotVisible !Location !Internal.Symbol
    | ExactInductiveGlobalAmbiguous !Location !Internal.Symbol
    | ExactInductiveUnsupportedSymbol !Location !Internal.Symbol
    | ExactInductiveGlobalContentInvalid !Location !CoreCheckError
    | ExactInductivePreparationFailed
        !Location
        !Typed.TypedInductiveError
    | ExactInductiveGuardMissing !Location
    | ExactInductiveGuardAmbiguous !Location
    deriving stock (Show, Eq)

exactInductiveErrorLocation :: ExactInductiveError -> Location
exactInductiveErrorLocation = \case
    ExactInductiveUnsupportedBlock location -> location
    ExactInductiveOccurrenceMissing location -> location
    ExactInductiveOccurrenceAmbiguous location -> location
    ExactInductiveHeadMismatch location -> location
    ExactInductiveGlossFailed location _failure -> location
    ExactInductiveDuplicateParameter location _parameter -> location
    ExactInductiveDomainFreeVariable location _variable -> location
    ExactInductiveDomainMentionsCarrier location -> location
    ExactInductiveResultShape location -> location
    ExactInductiveResultMentionsCarrier location -> location
    ExactInductiveRecursiveTermMentionsCarrier location -> location
    ExactInductiveNestedRecursion location -> location
    ExactInductiveFixedSemanticCollision location _key -> location
    ExactInductiveGlobalAlreadyVisible location _key -> location
    ExactInductiveGlobalNotVisible location _symbol -> location
    ExactInductiveGlobalAmbiguous location _symbol -> location
    ExactInductiveUnsupportedSymbol location _symbol -> location
    ExactInductiveGlobalContentInvalid location _failure -> location
    ExactInductivePreparationFailed location _failure -> location
    ExactInductiveGuardMissing location -> location
    ExactInductiveGuardAmbiguous location -> location

renderExactInductiveError :: ExactInductiveError -> Text
renderExactInductiveError failure =
    locationToText (exactInductiveErrorLocation failure)
        <> ": "
        <> case failure of
            ExactInductiveUnsupportedBlock{} ->
                "this inductive source form is not supported by the typed checker"
            ExactInductiveOccurrenceMissing{} ->
                "the inductive declaration has no associated syntax occurrence"
            ExactInductiveOccurrenceAmbiguous{} ->
                "the inductive declaration has more than one semantic head"
            ExactInductiveHeadMismatch{} ->
                "the inductive head does not match its syntax occurrence"
            ExactInductiveGlossFailed _location glossFailure ->
                "inductive elaboration failed: " <> shown glossFailure
            ExactInductiveDuplicateParameter _location parameter ->
                "the inductive parameter is repeated: " <> shown parameter
            ExactInductiveDomainFreeVariable _location variable ->
                "the inductive domain contains an unbound variable: "
                    <> shown variable
            ExactInductiveDomainMentionsCarrier{} ->
                "the inductive domain must be independent of its carrier"
            ExactInductiveResultShape{} ->
                "an inductive result must have the form t \\in F(args)"
            ExactInductiveResultMentionsCarrier{} ->
                "an inductive result term must not mention its carrier"
            ExactInductiveRecursiveTermMentionsCarrier{} ->
                "a recursive occurrence must be in the carrier of a membership premise"
            ExactInductiveNestedRecursion{} ->
                "nested inductive recursion is not supported by the typed checker"
            ExactInductiveFixedSemanticCollision _location key ->
                "the inductive carrier collides with fixed semantics for "
                    <> shown key
            ExactInductiveGlobalAlreadyVisible _location key ->
                "the inductive carrier is already visible: " <> shown key
            ExactInductiveGlobalNotVisible _location symbol ->
                "an inductive source symbol is not visible: " <> shown symbol
            ExactInductiveGlobalAmbiguous _location symbol ->
                "an inductive source symbol has more than one meaning: "
                    <> shown symbol
            ExactInductiveUnsupportedSymbol _location symbol ->
                "this inductive source symbol is not supported: "
                    <> shown symbol
            ExactInductiveGlobalContentInvalid _location coreFailure ->
                "an inductive global has invalid checked content: "
                    <> shown coreFailure
            ExactInductivePreparationFailed _location typedFailure ->
                "typed inductive preparation failed: " <> shown typedFailure
            ExactInductiveGuardMissing{} ->
                "an inductive domain guard has no visible authorized fact"
            ExactInductiveGuardAmbiguous{} ->
                "an inductive domain guard matches more than one visible fact"
  where
    shown :: Show value => value -> Text
    shown = Text.pack . show

type Prepare =
    ExceptT
        ExactInductiveError
        (Declaration.LoweringDriver)

prepareExactInductive
    :: CheckedFoundation
    -> Raw.Block
    -> [CanonicalLexicalEntry]
    -> Declaration.LoweringDriver
        (Either ExactInductiveError PreparedExactInductive)
prepareExactInductive foundation block entries =
    Except.runExceptT do
        (location, marker, rawInductive) <-
            case block of
                Raw.BlockInductive blockLocation _title blockMarker inductive ->
                    pure (blockLocation, blockMarker, inductive)
                _ ->
                    Except.throwError
                        (ExactInductiveUnsupportedBlock (locate block))
        key <- validateOccurrence location rawInductive entries
        when
            (isJust (fixedSemanticMeaning key))
            (Except.throwError
                (ExactInductiveFixedSemanticCollision location key))
        visible <-
            Except.lift
                (Declaration.resolveVisibleGlobalLowering key)
        when (isJust visible)
            (Except.throwError
                (ExactInductiveGlobalAlreadyVisible location key))
        internal <-
            case Meaning.meaning [block] of
                Right
                    [Internal.BlockInductive
                        _internalLocation _internalMarker inductive] ->
                            pure inductive
                Left failure ->
                    Except.throwError
                        (ExactInductiveGlossFailed location failure)
                Right _ ->
                    Except.throwError
                        (ExactInductiveUnsupportedBlock location)
        direct <-
            Except.liftEither
                (normalizeDirectInductive internal)
        (sourceGlobals, globalTypes) <-
            resolveSourceGlobals location internal direct
        typed <-
            Except.liftEither
                (first
                    (ExactInductivePreparationFailed location)
                    (Typed.prepareTypedInductive
                        (requireGlobalType globalTypes)
                        foundation
                        (`Map.lookup` sourceGlobals)
                        marker
                        direct))
        guards <-
            traverse
                (resolveGuard location)
                (Vector.toList
                    (Typed.typedInductiveGuardTargets typed))
        theory <- Except.lift Declaration.currentTheoryLowering
        let carrierType = Typed.typedInductiveCarrierType typed
            carrierBody = Typed.typedInductiveCarrierBody typed
            carrierTerm = frozenCoreTerm carrierBody
            identity =
                transparentObjectId theory carrierType carrierTerm
            content =
                TransparentObjectContent theory carrierType carrierTerm
            alias = case marker of
                Raw.Marker name -> semanticName name
        available <-
            Except.lift
                (Declaration.objectAvailableLowering identity)
        let asserted
                | available = Nothing
                | otherwise = Just (assertedObject identity content)
            syntax =
                declarationSyntaxId
                    (encodePreparedInductive key alias typed)
        pure
            (PreparedExactInductive
                location
                key
                identity
                asserted
                alias
                syntax
                typed
                guards)
  where
    requireGlobalType types identity =
        fromMaybe
            (impossible
                "prepared inductive global has no checked type")
            (Map.lookup identity types)

validateOccurrence
    :: Location
    -> Raw.Inductive
    -> [CanonicalLexicalEntry]
    -> Prepare SemanticGlobalKey
validateOccurrence location rawInductive entries = do
    entry <-
        case entries of
            [] ->
                Except.throwError
                    (ExactInductiveOccurrenceMissing location)
            [single] -> pure single
            _ ->
                Except.throwError
                    (ExactInductiveOccurrenceAmbiguous location)
    key <-
        maybe
            (Except.throwError
                (ExactInductiveHeadMismatch location))
            pure
            (semanticGlobalKeyFromLexicalEntry entry)
    let Raw.SymbolPattern headSymbol _parameters =
            Raw.inductiveSymbolPattern rawInductive
        expected =
            SemanticExpressionFunction
                (Raw.mixfixPattern headSymbol)
    unless (key == expected)
        (Except.throwError
            (ExactInductiveHeadMismatch location))
    pure key

normalizeDirectInductive
    :: Internal.Inductive
    -> Either ExactInductiveError Typed.DirectInductive
normalizeDirectInductive inductive = do
    case firstDuplicate (Internal.inductiveParams inductive) of
        Just duplicate ->
            Left
                (ExactInductiveDuplicateParameter
                    (locate duplicate)
                    duplicate)
        Nothing -> pure ()
    let parameters = Internal.inductiveParams inductive
        parameterSet = Set.fromList parameters
        domain = Internal.inductiveDomain inductive
        carrier = Internal.inductiveSymbol inductive
        domainVariables =
            orderedUnique
                (toList domain)
    case find (`Set.notMember` parameterSet) domainVariables of
        Just variable ->
            Left
                (ExactInductiveDomainFreeVariable
                    (locate variable)
                    variable)
        Nothing -> pure ()
    when
        (Internal.SymbolMixfix carrier
            `Set.member` Internal.mentionedSymbols domain)
        (Left
            (ExactInductiveDomainMentionsCarrier
                (termLocation domain)))
    clauses <-
        traverse
            (normalizeClause carrier parameters)
            (Internal.inductiveIntros inductive)
    pure
        (Typed.DirectInductive
            parameters
            domain
            clauses)

normalizeClause
    :: Internal.FunctionSymbol
    -> [Internal.VarSymbol]
    -> Internal.IntroRule
    -> Either ExactInductiveError Typed.DirectInductiveClause
normalizeClause carrier parameters rule = do
    conditions <-
        traverse
            (normalizeCondition carrier parameters)
            (Internal.introConditions rule)
    result <-
        normalizeResult
            carrier
            parameters
            (Internal.introResult rule)
    let parameterSet = Set.fromList parameters
        variables =
            List.filter (`Set.notMember` parameterSet)
                (orderedUnique
                    ( concatMap toList
                        (Internal.introConditions rule)
                      <> toList result
                    ))
    pure
        (Typed.DirectInductiveClause
            variables
            conditions
            result)

normalizeResult
    :: Internal.FunctionSymbol
    -> [Internal.VarSymbol]
    -> Internal.Formula
    -> Either ExactInductiveError Internal.Term
normalizeResult carrier parameters = \case
    Internal.IsElementOf _location result target
        | not (matchesCarrier carrier parameters target) ->
            Left (ExactInductiveResultShape (termLocation target))
        | Internal.SymbolMixfix carrier
                `Set.member` Internal.mentionedSymbols result ->
            Left
                (ExactInductiveResultMentionsCarrier
                    (termLocation result))
        | otherwise ->
            Right result
    formula ->
        Left (ExactInductiveResultShape (termLocation formula))

normalizeCondition
    :: Internal.FunctionSymbol
    -> [Internal.VarSymbol]
    -> Internal.Formula
    -> Either ExactInductiveError Typed.DirectInductiveCondition
normalizeCondition carrier parameters formula
    | not
        (Internal.SymbolMixfix carrier
            `Set.member` Internal.mentionedSymbols formula) =
        Right (Typed.DirectSideCondition formula)
    | otherwise =
        case formula of
            Internal.IsElementOf _location recursiveTerm recursiveCarrier
                | Internal.SymbolMixfix carrier
                        `Set.member`
                            Internal.mentionedSymbols recursiveTerm ->
                    Left
                        (ExactInductiveRecursiveTermMentionsCarrier
                            (termLocation recursiveTerm))
                | matchesCarrier carrier parameters recursiveCarrier ->
                    Right
                        (Typed.DirectRecursiveCondition recursiveTerm)
                | otherwise ->
                    Left
                        (ExactInductiveNestedRecursion
                            (termLocation recursiveCarrier))
            _ ->
                Left
                    (ExactInductiveNestedRecursion
                        (termLocation formula))

matchesCarrier
    :: Internal.FunctionSymbol
    -> [Internal.VarSymbol]
    -> Internal.Term
    -> Bool
matchesCarrier carrier parameters = \case
    Internal.TermSymbol _location (Internal.SymbolMixfix actual) arguments ->
        actual == carrier
            && length arguments == length parameters
            && and
                (zipWith
                    (\argument parameter ->
                        argument == Internal.TermVar parameter)
                    arguments
                    parameters)
    _ -> False

resolveSourceGlobals
    :: Location
    -> Internal.Inductive
    -> Typed.DirectInductive
    -> Prepare
        ( Map.Map
            Internal.Symbol
            (Typed.SourceGlobal ObjectId)
        , Map.Map ObjectId CoreType
        )
resolveSourceGlobals location internal direct =
    Except.lift
        (ExactGlobal.resolveExactSourceGlobals symbols)
        >>= Except.liftEither
            . first (exactGlobalError location)
  where
    carrier = Internal.SymbolMixfix (Internal.inductiveSymbol internal)
    symbols =
        Set.delete carrier (directSymbols direct)

exactGlobalError
    :: Location
    -> ExactGlobal.ExactGlobalResolutionError
    -> ExactInductiveError
exactGlobalError location = \case
    ExactGlobal.ExactGlobalNotVisible symbol ->
        ExactInductiveGlobalNotVisible location symbol
    ExactGlobal.ExactGlobalAmbiguous symbol ->
        ExactInductiveGlobalAmbiguous location symbol
    ExactGlobal.ExactGlobalUnsupported symbol ->
        ExactInductiveUnsupportedSymbol location symbol
    ExactGlobal.ExactGlobalContextualUnsupported symbol ->
        ExactInductiveUnsupportedSymbol location symbol
    ExactGlobal.ExactGlobalContentInvalid failure ->
        ExactInductiveGlobalContentInvalid location failure

resolveGuard
    :: Location
    -> FrozenCheckedCore ObjectId
    -> Prepare SemanticFactOccurrenceFingerprint
resolveGuard location target = do
    matches <-
        Except.lift
            (Declaration.resolveVisibleFactTargetsLowering target)
    case matches of
        [] ->
            Except.throwError (ExactInductiveGuardMissing location)
        [fingerprint] ->
            pure fingerprint
        _ ->
            Except.throwError (ExactInductiveGuardAmbiguous location)

directSymbols :: Typed.DirectInductive -> Set.Set Internal.Symbol
directSymbols direct =
    Internal.mentionedSymbols (Typed.directInductiveDomain direct)
        <> foldMap clauseSymbols
            (Typed.directInductiveClauses direct)
  where
    clauseSymbols clause =
        foldMap conditionSymbols
                (Typed.directClauseConditions clause)
            <> Internal.mentionedSymbols
                (Typed.directClauseResult clause)
    conditionSymbols = \case
        Typed.DirectSideCondition formula ->
            Internal.mentionedSymbols formula
        Typed.DirectRecursiveCondition term ->
            Internal.mentionedSymbols term

lowerPreparedExactInductive
    :: PreparedExactInductive
    -> Declaration.LoweringDriver
        (Either
            Declaration.DeclarationError
            (Declaration.CheckedDeclaration
                CheckedExactInductiveAuthorization))
lowerPreparedExactInductive
        (PreparedExactInductive
            _location key identity asserted alias syntax typed guards) =
    do
        let facts = Typed.typedInductiveFacts typed
            objects = maybeToList asserted
        definition <-
            Declaration.prepareDefinitionEquationSpecLowering
                objects identity alias
        preparedCandidates <-
            traverse
                (\fact ->
                    fmap
                        (fmap
                            (\spec ->
                                Declaration.checkedCandidate spec
                                    (Declaration.checkedKernelPlanning
                                        (GuardedFoundationRules
                                            (guardedRuleSet
                                                (Typed.typedInductiveFactRules
                                                    fact)))
                                        guards)))
                        (Declaration.prepareCandidateSpecLowering
                            objects
                            (embedClosedCore []
                                (Typed.typedInductiveFactTarget fact))
                            SearchEligible
                            [markerAlias
                                (Typed.typedInductiveFactMarker fact)]))
                facts
        pure do
            definitionSpec <- definition
            factCandidates <- sequence preparedCandidates
            pure
                (Declaration.checkedCompiledDeclaration
                    syntax
                    objects
                    []
                    [semanticGlobalBinding key (GlobalReference identity)]
                    []
                    [ Declaration.checkedCandidate definitionSpec
                        (Declaration.checkedDefinitionEquationPlanning identity)
                        :| toList factCandidates
                    ]
                    (CheckedExactInductiveAuthorization
                        identity typed guards))
  where
    markerAlias (Raw.Marker name) =
        semanticName name

authorizeCheckedExactInductive
    :: CheckedExactInductiveAuthorization
    -> [NonEmpty Declaration.ReservedCandidate]
    -> Declaration.Declaration ()
authorizeCheckedExactInductive
        (CheckedExactInductiveAuthorization identity typed guards) = \case
    [definitionCandidate :| candidates] -> do
        Declaration.authorizeDefinitionEquationCandidate
            identity definitionCandidate
        let facts = Typed.typedInductiveFacts typed
        case NonEmpty.nonEmpty candidates of
            Just factCandidates
                | NonEmpty.length factCandidates == NonEmpty.length facts ->
                    sequence_
                        (NonEmpty.zipWith
                            authorizeFact
                            factCandidates
                            facts)
            _ ->
                Declaration.failDeclaration
                    (Declaration.CheckedAuthorizationCandidateShapeMismatch
                        (1 + NonEmpty.length facts)
                        (1 + length candidates))
    stages ->
        Declaration.failDeclaration
            (Declaration.CheckedAuthorizationCandidateShapeMismatch
                1 (length stages))
  where
    authorizeFact candidate fact =
        Declaration.authorizeKernelConstructionCandidate
            (GuardedFoundationRules
                (guardedRuleSet
                    (Typed.typedInductiveFactRules fact)))
            candidate do
                traverse_ Declaration.useAuthorizedFact guards
                pure (Typed.typedInductiveFactDerivation fact)

encodePreparedInductive
    :: SemanticGlobalKey
    -> SemanticName
    -> Typed.PreparedTypedInductive ObjectId
    -> ByteString
encodePreparedInductive key alias typed =
    encodeCache do
        putCacheTag 0x04
        putSemanticGlobalKeyCache key
        putCoreTypeCache
            (Typed.typedInductiveCarrierType typed)
        putCanonicalTermCache putObjectIdCache
            (frozenCoreTerm
                (Typed.typedInductiveCarrierBody typed))
        putCacheText (semanticNameText alias)
        putCacheList putFact
            (toList (Typed.typedInductiveFacts typed))
  where
    putFact fact = do
        let Raw.Marker marker =
                Typed.typedInductiveFactMarker fact
        putCacheText marker
        putCanonicalTermCache putObjectIdCache
            (frozenCoreTerm
                (Typed.typedInductiveFactTarget fact))
        putCacheList
            (putCacheBytes . encodeKernelRuleTag)
            (toList (Typed.typedInductiveFactRules fact))

firstDuplicate :: Ord value => [value] -> Maybe value
firstDuplicate =
    go Set.empty
  where
    go _seen [] = Nothing
    go seen (value : remaining)
        | value `Set.member` seen = Just value
        | otherwise =
            go (Set.insert value seen) remaining

orderedUnique :: Ord value => [value] -> [value]
orderedUnique =
    reverse . snd . foldl' step (Set.empty, [])
  where
    step (seen, values) value
        | value `Set.member` seen = (seen, values)
        | otherwise =
            (Set.insert value seen, value : values)

termLocation :: Internal.Expr -> Location
termLocation = Internal.exprLocation