summaryrefslogtreecommitdiff
path: root/source/Felix/Syntax/Interface.hs
blob: 18207059c1fafa40dbbddc3f0e5cbd7d2f0cbad4 (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
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE NoImplicitPrelude #-}

module Felix.Syntax.Interface
    ( MixfixLevel
    , mixfixLevel
    , mixfixLevelValue
    , MixfixLevelError(..)
    , Fixity(..)
    , sourcePragmaFixity
    , CanonicalLexicalEntry(..)
    , canonicalLexicalSurfacePatterns
    , eligibleExpressionPattern
    , CanonicalSyntaxDelta
    , canonicalSyntaxDelta
    , canonicalSyntaxDeltaEntries
    , canonicalSyntaxDeltaSize
    , CanonicalSyntaxCollision
    , canonicalCollisionPattern
    , canonicalCollisionEntries
    , CanonicalSyntaxDeltaId
    , canonicalSyntaxDeltaId
    , canonicalSyntaxDeltaIdDigest
    , BaseSyntaxInterfaceId
    , baseSyntaxInterfaceId
    , baseSyntaxInterfaceIdDigest
    , baseSyntaxManifest
    , fixedBaseSyntaxEntries
    , SyntaxInterfaceId
    , syntaxInterfaceIdDigest
    , ModuleSyntaxInterface
    , moduleSyntaxInterface
    , moduleSyntaxBase
    , moduleSyntaxDirectInputs
    , moduleSyntaxLocalDelta
    , moduleSyntaxAssertedId
    , SyntaxInterfaceError(..)
    , validateModuleSyntaxInterface
    , putCanonicalLexicalEntryCache
    , getCanonicalLexicalEntryCache
    , putPatternCache
    , getPatternCache
    , putTokenCache
    , getTokenCache
    , putCanonicalSyntaxDeltaCache
    , getCanonicalSyntaxDeltaCache
    , putModuleSyntaxInterfaceCache
    , getModuleSyntaxInterfaceCache
    , putBaseSyntaxInterfaceIdCache
    , getBaseSyntaxInterfaceIdCache
    , putSyntaxInterfaceIdCache
    , getSyntaxInterfaceIdCache
    ) where

import Base

import Felix.Cache.Codec
import Felix.Syntax.Abstract
import Felix.Syntax.Lexicon
import Felix.Syntax.Pragma

import Control.DeepSeq (NFData)
import Control.Monad (unless)
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.Word (Word8)
import Numeric.Natural (Natural)


newtype MixfixLevel = MixfixLevel Word8
    deriving stock (Show, Eq, Ord, Generic)
    deriving newtype (Hashable, NFData)

data MixfixLevelError
    = MixfixLevelOutOfRange !Word8
    deriving stock (Show, Eq)

mixfixLevel :: Word8 -> Either MixfixLevelError MixfixLevel
mixfixLevel supplied
    | supplied <= 9 =
        Right (MixfixLevel supplied)
    | otherwise =
        Left (MixfixLevelOutOfRange supplied)

mixfixLevelValue :: MixfixLevel -> Word8
mixfixLevelValue (MixfixLevel level) =
    level

data Fixity = Fixity
    { fixityAssociativity :: !Associativity
    , fixityLevel :: !MixfixLevel
    } deriving stock (Show, Eq, Ord, Generic)
      deriving anyclass (NFData)

sourcePragmaFixity :: SyntaxPragma -> Fixity
sourcePragmaFixity pragma =
    Fixity
        (syntaxPragmaAssociativity pragma)
        (MixfixLevel
            (sourceMixfixLevelValue
                (syntaxPragmaLevel pragma)))

-- | Complete origin-free lexical semantics produced by scanning.
data CanonicalLexicalEntry
    = CanonicalLeftAdjective !Pattern !Marker
    | CanonicalRightAdjective !Pattern !Marker
    | CanonicalFunctionPhrase !Pattern !Pattern !Marker
    | CanonicalNoun !Pattern !Pattern !Marker
    | CanonicalStructureNoun !Pattern !Pattern !Marker
    | CanonicalVerb !Pattern !Pattern !Marker
    | CanonicalRelation !Token !ParameterArity !Marker
    | CanonicalExpressionFunction !Pattern !Marker !Fixity
    | CanonicalPrefixPredicate !Text !Natural !Marker
    | CanonicalStructureOperation !Text
    deriving stock (Show, Eq, Ord, Generic)
    deriving anyclass (NFData)

-- | Every surface pattern through which the concrete parser can select an
-- entry. Equal singular and plural surfaces are returned only once.
canonicalLexicalSurfacePatterns
    :: CanonicalLexicalEntry
    -> NonEmpty Pattern
canonicalLexicalSurfacePatterns =
    deduplicatePatterns . \case
    CanonicalLeftAdjective pat _marker ->
        [pat]
    CanonicalRightAdjective pat _marker ->
        [pat]
    CanonicalFunctionPhrase singular _plural _marker ->
        [singular]
    CanonicalNoun singular plural _marker ->
        [singular, plural]
    CanonicalStructureNoun singular _plural _marker ->
        [singular]
    CanonicalVerb singular plural _marker ->
        [singular, plural]
    CanonicalRelation token arity marker ->
        [ relationSymbolPattern
            (RelationSymbol token arity marker)
        ]
    CanonicalExpressionFunction pat _marker _fixity ->
        [pat]
    CanonicalPrefixPredicate command _arity _marker ->
        [ prefixPredicatePattern
            (PrefixPredicate command 0)
        ]
    CanonicalStructureOperation command ->
        [structSymbolPattern (StructSymbol command)]
  where
    deduplicatePatterns patterns =
        case NonEmpty.nonEmpty
                (Set.toList (Set.fromList patterns)) of
            Just nonempty ->
                nonempty
            Nothing ->
                impossible
                    "canonical lexical entry has no parser surface"

eligibleExpressionPattern :: Pattern -> Bool
eligibleExpressionPattern pat =
    case patternToHoley pat of
        Nothing : rest ->
            case reverse rest of
                Nothing : middleReversed ->
                    let middle =
                            reverse middleReversed
                    in
                        countHoles middle == 0
                            && any isJust middle
                _ ->
                    False
        _ ->
            False
  where
    countHoles =
        length . List.filter isNothing

newtype CanonicalSyntaxDelta =
    CanonicalSyntaxDelta
        [CanonicalLexicalEntry]
    deriving stock (Show, Eq, Generic)
    deriving anyclass (NFData)

data CanonicalSyntaxCollision = CanonicalSyntaxCollision
    { canonicalCollisionPattern :: !Pattern
    , canonicalCollisionEntries
        :: !(NonEmpty CanonicalLexicalEntry)
    } deriving stock (Show, Eq)

canonicalSyntaxDelta
    :: [CanonicalLexicalEntry]
    -> Either CanonicalSyntaxCollision CanonicalSyntaxDelta
canonicalSyntaxDelta supplied =
    case orderedCollisions of
        [] ->
            Right (CanonicalSyntaxDelta orderedEntries)
        (_encodedPattern, pat, entries) : _ ->
            Left
                (CanonicalSyntaxCollision
                    pat
                    (case NonEmpty.nonEmpty
                        (canonicalEntryOrder
                            (Set.toList entries)) of
                        Just collisionEntries ->
                            collisionEntries
                        Nothing ->
                            impossible
                                "canonical syntax collision has no entries"))
  where
    orderedEntries =
        canonicalEntryOrder
            (Set.toList (Set.fromList supplied))

    grouped =
        foldl'
            (\entries entry ->
                foldl'
                    (\indexed pat ->
                        Map.insertWith
                            Set.union
                            pat
                            (Set.singleton entry)
                            indexed)
                    entries
                    (canonicalLexicalSurfacePatterns entry))
            mempty
            orderedEntries

    orderedCollisions =
        List.sortOn
            (\(encodedPattern, _pattern, _entries) ->
                encodedPattern)
            [ ( encodeCache (putPatternCache pat)
              , pat
              , entries
              )
            | (pat, entries) <- Map.toList grouped
            , Set.size entries > 1
            ]

canonicalSyntaxDeltaEntries
    :: CanonicalSyntaxDelta
    -> [CanonicalLexicalEntry]
canonicalSyntaxDeltaEntries
        (CanonicalSyntaxDelta entries) =
    entries

canonicalSyntaxDeltaSize :: CanonicalSyntaxDelta -> Int
canonicalSyntaxDeltaSize
        (CanonicalSyntaxDelta entries) =
    length entries

canonicalEntryOrder
    :: [CanonicalLexicalEntry]
    -> [CanonicalLexicalEntry]
canonicalEntryOrder =
    List.sortOn
        (encodeCache . putCanonicalLexicalEntryCache)

newtype CanonicalSyntaxDeltaId =
    CanonicalSyntaxDeltaId CacheDigest
    deriving stock (Show, Eq, Ord, Generic)
    deriving newtype (Hashable, NFData)

canonicalSyntaxDeltaId
    :: CanonicalSyntaxDelta
    -> CanonicalSyntaxDeltaId
canonicalSyntaxDeltaId delta =
    CanonicalSyntaxDeltaId
        (hashCacheFields
            "felix-syntax-delta-v1"
            [encodeCache
                (putCanonicalSyntaxDeltaCache delta)])

canonicalSyntaxDeltaIdDigest
    :: CanonicalSyntaxDeltaId
    -> CacheDigest
canonicalSyntaxDeltaIdDigest
        (CanonicalSyntaxDeltaId digest) =
    digest

newtype BaseSyntaxInterfaceId =
    BaseSyntaxInterfaceId CacheDigest
    deriving stock (Show, Eq, Ord, Generic)
    deriving newtype (Hashable, NFData)

baseSyntaxInterfaceId :: BaseSyntaxInterfaceId
baseSyntaxInterfaceId =
    BaseSyntaxInterfaceId
        (hashCacheFields
            "felix-base-syntax-interface-v1"
            [encodeCache
                (putCacheList
                    putManifestRow
                    baseSyntaxManifest)])
  where
    putManifestRow =
        putCacheList putCanonicalLexicalEntryCache
            . canonicalEntryOrder

baseSyntaxInterfaceIdDigest
    :: BaseSyntaxInterfaceId
    -> CacheDigest
baseSyntaxInterfaceIdDigest
        (BaseSyntaxInterfaceId digest) =
    digest

baseSyntaxManifest :: [[CanonicalLexicalEntry]]
baseSyntaxManifest =
    case traverse makeRow
            (zip [0 :: Word8 ..] builtinMixfixLevels) of
        Right rows
            | length rows == 10 ->
                rows
        _ ->
            impossible
                "the fixed mixfix manifest does not have ten valid rows"
  where
    makeRow (row, entries) = do
        level <- mixfixLevel row
        pure
            [ CanonicalExpressionFunction
                pat
                marker
                (Fixity associativity level)
            | MixfixItem pat marker associativity <-
                entries
            ]

-- | Every fixed lexical entry consulted by the concrete parser. The base
-- syntax identity above commits to the ten expression rows; the remaining
-- fixed categories are compiler input covered by the cache epoch.
fixedBaseSyntaxEntries :: [CanonicalLexicalEntry]
fixedBaseSyntaxEntries =
    case canonicalSyntaxDelta rawEntries of
        Right delta ->
            canonicalSyntaxDeltaEntries delta
        Left collision ->
            impossible
                ("fixed base syntax contains a collision: "
                    <> show collision)
  where
    rawEntries =
        concat baseSyntaxManifest
            <> (canonicalAdjective CanonicalLeftAdjective
                    <$> lexiconAdjLs builtins)
            <> (canonicalAdjective CanonicalRightAdjective
                    <$> lexiconAdjRs builtins)
            <> (canonicalSgPl CanonicalFunctionPhrase
                    <$> lexiconFuns builtins)
            <> (canonicalSgPl CanonicalNoun
                    <$> lexiconNouns builtins)
            <> (canonicalSgPl CanonicalStructureNoun
                    <$> lexiconStructNouns builtins)
            <> (canonicalSgPl CanonicalVerb
                    <$> lexiconVerbs builtins)
            <> (canonicalRelation
                    <$> lexiconRelationSymbols builtins)
            <> (canonicalPrefix
                    <$> lexiconPrefixPredicates builtins)
            <> (canonicalStructure
                    <$> lexiconStructFun builtins)

    canonicalAdjective constructor item =
        constructor
            (lexicalItemPattern item)
            (lexicalItemMarker item)

    canonicalSgPl constructor item =
        let patterns =
                lexicalItemSgPlPattern item
        in
            constructor
                (sg patterns)
                (pl patterns)
                (lexicalItemSgPlMarker item)

    canonicalRelation relation =
        CanonicalRelation
            (relationSymbolToken relation)
            (relationSymbolParameterArity relation)
            (relationSymbolMarker relation)

    canonicalPrefix
            (PrefixPredicate command arity, marker) =
        CanonicalPrefixPredicate
            command
            (fromIntegral arity)
            marker

    canonicalStructure (StructSymbol command) =
        CanonicalStructureOperation command

newtype SyntaxInterfaceId =
    SyntaxInterfaceId CacheDigest
    deriving stock (Show, Eq, Ord, Generic)
    deriving newtype (Hashable, NFData)

syntaxInterfaceIdDigest :: SyntaxInterfaceId -> CacheDigest
syntaxInterfaceIdDigest (SyntaxInterfaceId digest) =
    digest

data ModuleSyntaxInterface = ModuleSyntaxInterface
    !BaseSyntaxInterfaceId
    ![SyntaxInterfaceId]
    !CanonicalSyntaxDelta
    !SyntaxInterfaceId
    deriving stock (Show, Eq, Generic)
    deriving anyclass (NFData)

moduleSyntaxBase
    :: ModuleSyntaxInterface
    -> BaseSyntaxInterfaceId
moduleSyntaxBase
        (ModuleSyntaxInterface base _direct _delta _asserted) =
    base

moduleSyntaxDirectInputs
    :: ModuleSyntaxInterface
    -> [SyntaxInterfaceId]
moduleSyntaxDirectInputs
        (ModuleSyntaxInterface _base direct _delta _asserted) =
    direct

moduleSyntaxLocalDelta
    :: ModuleSyntaxInterface
    -> CanonicalSyntaxDelta
moduleSyntaxLocalDelta
        (ModuleSyntaxInterface _base _direct delta _asserted) =
    delta

moduleSyntaxAssertedId
    :: ModuleSyntaxInterface
    -> SyntaxInterfaceId
moduleSyntaxAssertedId
        (ModuleSyntaxInterface _base _direct _delta asserted) =
    asserted

data SyntaxInterfaceError
    = DuplicateDirectSyntaxInterface !SyntaxInterfaceId
    | UnexpectedBaseSyntaxInterface
        !BaseSyntaxInterfaceId
        !BaseSyntaxInterfaceId
    | SyntaxInterfaceIdMismatch
        !SyntaxInterfaceId
        !SyntaxInterfaceId
    deriving stock (Show, Eq)

moduleSyntaxInterface
    :: [SyntaxInterfaceId]
    -> CanonicalSyntaxDelta
    -> Either SyntaxInterfaceError ModuleSyntaxInterface
moduleSyntaxInterface direct delta =
    validateModuleSyntaxInterface
        baseSyntaxInterfaceId
        direct
        delta
        (computeSyntaxInterfaceId
            baseSyntaxInterfaceId
            direct
            delta)

validateModuleSyntaxInterface
    :: BaseSyntaxInterfaceId
    -> [SyntaxInterfaceId]
    -> CanonicalSyntaxDelta
    -> SyntaxInterfaceId
    -> Either SyntaxInterfaceError ModuleSyntaxInterface
validateModuleSyntaxInterface base direct delta asserted = do
    unless
        (base == baseSyntaxInterfaceId)
        (Left
            (UnexpectedBaseSyntaxInterface
                base
                baseSyntaxInterfaceId))
    case firstDuplicate direct of
        Just duplicate ->
            Left
                (DuplicateDirectSyntaxInterface duplicate)
        Nothing ->
            pure ()
    let computed =
            computeSyntaxInterfaceId base direct delta
    unless
        (asserted == computed)
        (Left
            (SyntaxInterfaceIdMismatch
                asserted
                computed))
    Right
        (ModuleSyntaxInterface
            base
            direct
            delta
            asserted)

computeSyntaxInterfaceId
    :: BaseSyntaxInterfaceId
    -> [SyntaxInterfaceId]
    -> CanonicalSyntaxDelta
    -> SyntaxInterfaceId
computeSyntaxInterfaceId base direct delta =
    SyntaxInterfaceId
        (hashCacheFields
            "felix-syntax-interface-v1"
            [ cacheDigestBytes
                (baseSyntaxInterfaceIdDigest base)
            , encodeCache
                (putCacheList
                    putSyntaxInterfaceIdCache
                    direct)
            , cacheDigestBytes
                (canonicalSyntaxDeltaIdDigest
                    (canonicalSyntaxDeltaId delta))
            ])

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

putCanonicalLexicalEntryCache
    :: CanonicalLexicalEntry
    -> CachePut
putCanonicalLexicalEntryCache = \case
    CanonicalLeftAdjective pat marker -> do
        putCacheTag 0x00
        putPatternCache pat
        putMarkerCache marker
    CanonicalRightAdjective pat marker -> do
        putCacheTag 0x01
        putPatternCache pat
        putMarkerCache marker
    CanonicalFunctionPhrase singular plural marker -> do
        putCacheTag 0x02
        putPatternCache singular
        putPatternCache plural
        putMarkerCache marker
    CanonicalNoun singular plural marker -> do
        putCacheTag 0x03
        putPatternCache singular
        putPatternCache plural
        putMarkerCache marker
    CanonicalStructureNoun singular plural marker -> do
        putCacheTag 0x04
        putPatternCache singular
        putPatternCache plural
        putMarkerCache marker
    CanonicalVerb singular plural marker -> do
        putCacheTag 0x05
        putPatternCache singular
        putPatternCache plural
        putMarkerCache marker
    CanonicalRelation token arity marker -> do
        putCacheTag 0x06
        putTokenCache token
        putCacheNatural (parameterArityValue arity)
        putMarkerCache marker
    CanonicalExpressionFunction pat marker fixity -> do
        putCacheTag 0x07
        putPatternCache pat
        putMarkerCache marker
        putFixityCache fixity
    CanonicalPrefixPredicate command arity marker -> do
        putCacheTag 0x08
        putCacheText command
        putCacheNatural arity
        putMarkerCache marker
    CanonicalStructureOperation command -> do
        putCacheTag 0x09
        putCacheText command

getCanonicalLexicalEntryCache
    :: CacheGet CanonicalLexicalEntry
getCanonicalLexicalEntryCache =
    getCacheTag >>= \case
        0x00 ->
            CanonicalLeftAdjective
                <$> getPatternCache
                <*> getMarkerCache
        0x01 ->
            CanonicalRightAdjective
                <$> getPatternCache
                <*> getMarkerCache
        0x02 ->
            CanonicalFunctionPhrase
                <$> getPatternCache
                <*> getPatternCache
                <*> getMarkerCache
        0x03 ->
            CanonicalNoun
                <$> getPatternCache
                <*> getPatternCache
                <*> getMarkerCache
        0x04 ->
            CanonicalStructureNoun
                <$> getPatternCache
                <*> getPatternCache
                <*> getMarkerCache
        0x05 ->
            CanonicalVerb
                <$> getPatternCache
                <*> getPatternCache
                <*> getMarkerCache
        0x06 ->
            CanonicalRelation
                <$> getTokenCache
                <*> (ParameterArity <$> getCacheNatural)
                <*> getMarkerCache
        0x07 ->
            CanonicalExpressionFunction
                <$> getPatternCache
                <*> getMarkerCache
                <*> getFixityCache
        0x08 ->
            CanonicalPrefixPredicate
                <$> getCacheText
                <*> getCacheNatural
                <*> getMarkerCache
        0x09 ->
            CanonicalStructureOperation
                <$> getCacheText
        tag ->
            fail
                ("unknown canonical lexical entry tag "
                    <> show tag)

putCanonicalSyntaxDeltaCache
    :: CanonicalSyntaxDelta
    -> CachePut
putCanonicalSyntaxDeltaCache
        (CanonicalSyntaxDelta entries) =
    putCacheList putCanonicalLexicalEntryCache entries

getCanonicalSyntaxDeltaCache
    :: CacheGet CanonicalSyntaxDelta
getCanonicalSyntaxDeltaCache = do
    supplied <- getCacheList getCanonicalLexicalEntryCache
    case canonicalSyntaxDelta supplied of
        Left collision ->
            fail
                ("colliding cached canonical syntax entries: "
                    <> show collision)
        Right delta
            | canonicalSyntaxDeltaEntries delta == supplied ->
                pure delta
            | otherwise ->
                fail
                    "cached canonical syntax entries are not in canonical order"

putModuleSyntaxInterfaceCache
    :: ModuleSyntaxInterface
    -> CachePut
putModuleSyntaxInterfaceCache
        (ModuleSyntaxInterface base direct delta asserted) = do
    putBaseSyntaxInterfaceIdCache base
    putCacheList putSyntaxInterfaceIdCache direct
    putCanonicalSyntaxDeltaCache delta
    putSyntaxInterfaceIdCache asserted

getModuleSyntaxInterfaceCache
    :: CacheGet ModuleSyntaxInterface
getModuleSyntaxInterfaceCache = do
    base <- getBaseSyntaxInterfaceIdCache
    direct <- getCacheList getSyntaxInterfaceIdCache
    delta <- getCanonicalSyntaxDeltaCache
    asserted <- getSyntaxInterfaceIdCache
    case
        validateModuleSyntaxInterface
            base
            direct
            delta
            asserted of
        Left err ->
            fail
                ("invalid module syntax interface: "
                    <> show err)
        Right interface ->
            pure interface

putBaseSyntaxInterfaceIdCache
    :: BaseSyntaxInterfaceId
    -> CachePut
putBaseSyntaxInterfaceIdCache
        (BaseSyntaxInterfaceId digest) =
    putCacheDigest digest

getBaseSyntaxInterfaceIdCache
    :: CacheGet BaseSyntaxInterfaceId
getBaseSyntaxInterfaceIdCache =
    BaseSyntaxInterfaceId <$> getCacheDigest

putSyntaxInterfaceIdCache
    :: SyntaxInterfaceId
    -> CachePut
putSyntaxInterfaceIdCache
        (SyntaxInterfaceId digest) =
    putCacheDigest digest

getSyntaxInterfaceIdCache
    :: CacheGet SyntaxInterfaceId
getSyntaxInterfaceIdCache =
    SyntaxInterfaceId <$> getCacheDigest

putFixityCache :: Fixity -> CachePut
putFixityCache (Fixity associativity level) = do
    putAssociativityCache associativity
    putCacheTag (mixfixLevelValue level)

getFixityCache :: CacheGet Fixity
getFixityCache = do
    associativity <- getAssociativityCache
    suppliedLevel <- getCacheTag
    case mixfixLevel suppliedLevel of
        Left err ->
            fail ("invalid cached mixfix level: " <> show err)
        Right level ->
            pure (Fixity associativity level)

putAssociativityCache :: Associativity -> CachePut
putAssociativityCache =
    putCacheTag . \case
        LeftAssoc ->
            0x00
        RightAssoc ->
            0x01
        NonAssoc ->
            0x02

getAssociativityCache :: CacheGet Associativity
getAssociativityCache =
    getCacheTag >>= \case
        0x00 ->
            pure LeftAssoc
        0x01 ->
            pure RightAssoc
        0x02 ->
            pure NonAssoc
        tag ->
            fail
                ("unknown associativity tag " <> show tag)

putMarkerCache :: Marker -> CachePut
putMarkerCache (Marker marker) =
    putCacheText marker

getMarkerCache :: CacheGet Marker
getMarkerCache =
    Marker <$> getCacheText

putPatternCache :: Pattern -> CachePut
putPatternCache = \case
    End ->
        putCacheTag 0x00
    HoleCons rest -> do
        putCacheTag 0x01
        putPatternCache rest
    TokenCons token rest -> do
        putCacheTag 0x02
        putTokenCache token
        putPatternCache rest

getPatternCache :: CacheGet Pattern
getPatternCache =
    getCacheTag >>= \case
        0x00 ->
            pure End
        0x01 ->
            HoleCons <$> getPatternCache
        0x02 ->
            TokenCons
                <$> getTokenCache
                <*> getPatternCache
        tag ->
            fail
                ("unknown lexical pattern tag " <> show tag)

putTokenCache :: Token -> CachePut
putTokenCache = \case
    Word text -> do
        putCacheTag 0x00
        putCacheText text
    Variable text -> do
        putCacheTag 0x01
        putCacheText text
    Symbol text -> do
        putCacheTag 0x02
        putCacheText text
    Integer integer -> do
        putCacheTag 0x03
        putCacheInteger (toInteger integer)
    Command text -> do
        putCacheTag 0x04
        putCacheText text
    Label text -> do
        putCacheTag 0x05
        putCacheText text
    Ref references -> do
        putCacheTag 0x06
        putCacheList putCacheText (toList references)
    BeginEnv text -> do
        putCacheTag 0x07
        putCacheText text
    EndEnv text -> do
        putCacheTag 0x08
        putCacheText text
    ParenL ->
        putCacheTag 0x09
    ParenR ->
        putCacheTag 0x0a
    BracketL ->
        putCacheTag 0x0b
    BracketR ->
        putCacheTag 0x0c
    VisibleBraceL ->
        putCacheTag 0x0d
    VisibleBraceR ->
        putCacheTag 0x0e
    InvisibleBraceL ->
        putCacheTag 0x0f
    InvisibleBraceR ->
        putCacheTag 0x10

getTokenCache :: CacheGet Token
getTokenCache =
    getCacheTag >>= \case
        0x00 ->
            Word <$> getCacheText
        0x01 ->
            Variable <$> getCacheText
        0x02 ->
            Symbol <$> getCacheText
        0x03 ->
            Integer <$> getCacheInt
        0x04 ->
            Command <$> getCacheText
        0x05 ->
            Label <$> getCacheText
        0x06 -> do
            references <- getCacheList getCacheText
            case NonEmpty.nonEmpty references of
                Nothing ->
                    fail "cached reference token has no marker"
                Just nonempty ->
                    pure (Ref nonempty)
        0x07 ->
            BeginEnv <$> getCacheText
        0x08 ->
            EndEnv <$> getCacheText
        0x09 ->
            pure ParenL
        0x0a ->
            pure ParenR
        0x0b ->
            pure BracketL
        0x0c ->
            pure BracketR
        0x0d ->
            pure VisibleBraceL
        0x0e ->
            pure VisibleBraceR
        0x0f ->
            pure InvisibleBraceL
        0x10 ->
            pure InvisibleBraceR
        tag ->
            fail ("unknown lexical token tag " <> show tag)

getCacheInt :: CacheGet Int
getCacheInt = do
    integer <- getCacheInteger
    if integer < toInteger (minBound :: Int)
        || integer > toInteger (maxBound :: Int)
        then
            fail "cached integer token exceeds Int"
        else
            pure (fromInteger integer)