-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathDecode.hs
More file actions
1644 lines (1320 loc) · 50.7 KB
/
Decode.hs
File metadata and controls
1644 lines (1320 loc) · 50.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
{-| Please read the "Dhall.Tutorial" module, which contains a tutorial explaining
how to use the language, the compiler, and this library
-}
module Dhall.Marshal.Decode
( -- * General
Decoder (..)
, FromDhall(..)
, Interpret
, auto
-- * Building decoders
-- ** Simple decoders
, bool
, unit
, void
-- ** Numbers
, natural
, word
, word8
, word16
, word32
, word64
, integer
, int
, int8
, int16
, int32
, int64
, scientific
, double
-- ** Textual
, string
, lazyText
, strictText
-- ** Time
, timeOfDay
, day
, timeZone
, localTime
, zonedTime
, utcTime
, dayOfWeek
-- ** Containers
, maybe
, pair
, sequence
, list
, vector
, setFromDistinctList
, setIgnoringDuplicates
, hashSetFromDistinctList
, hashSetIgnoringDuplicates
, Dhall.Marshal.Decode.map
, hashMap
, pairFromMapEntry
-- ** Functions
, function
, functionWith
-- ** Records
, RecordDecoder(..)
, record
, field
-- ** Unions
, UnionDecoder(..)
, union
, constructor
-- * Generic decoding
, GenericFromDhall(..)
, GenericFromDhallUnion(..)
, genericAuto
, genericAutoWith
, genericAutoWithInputNormalizer
-- * Decoding errors
, DhallErrors(..)
, showDhallErrors
, InvalidDecoder(..)
-- ** Extraction errors
, ExtractErrors
, ExtractError(..)
, Extractor
, typeError
, extractError
, MonadicExtractor
, toMonadic
, fromMonadic
-- ** Typing errors
, ExpectedTypeErrors
, ExpectedTypeError(..)
, Expector
-- * Miscellaneous
, InputNormalizer(..)
, defaultInputNormalizer
, InterpretOptions(..)
, SingletonConstructors(..)
, defaultInterpretOptions
, Result
-- * Re-exports
, Natural
, Seq
, Text
, Vector
, Generic
) where
import Control.Applicative (empty, liftA2)
import Control.Exception (Exception)
import Control.Monad (guard)
import Control.Monad.Trans.State.Strict
import Data.Coerce (coerce)
import Data.Either.Validation
( Validation (..)
, eitherToValidation
, validationToEither
)
import Data.Functor.Contravariant
( Equivalence (..)
, Op (..)
, Predicate (..)
)
import Data.Hashable (Hashable)
import Data.List.NonEmpty (NonEmpty (..))
import Data.Typeable (Proxy (..), Typeable)
import Dhall.Parser (Src (..))
import Dhall.Syntax
( Chunks (..)
, DhallDouble (..)
, Expr (..)
, FieldSelection (..)
, FunctionBinding (..)
, Var (..)
)
import GHC.Generics
import Prelude hiding (maybe, sequence)
import Prettyprinter (Pretty)
import qualified Control.Applicative
import qualified Data.Foldable
import qualified Data.Functor.Compose
import qualified Data.Functor.Product
import qualified Data.HashMap.Strict as HashMap
import qualified Data.HashSet
import qualified Data.List as List
import qualified Data.List.NonEmpty
import qualified Data.Map
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Sequence
import qualified Data.Set
import qualified Data.Text
import qualified Data.Text.Lazy
import qualified Data.Time as Time
import qualified Data.Vector
import qualified Dhall.Core as Core
import qualified Dhall.Map
import qualified Dhall.Util
import Dhall.Marshal.Encode
import Dhall.Marshal.Internal
-- $setup
-- >>> import Dhall (input)
{-| A @(Decoder a)@ represents a way to marshal a value of type @\'a\'@ from Dhall
into Haskell.
You can produce `Decoder`s either explicitly:
> example :: Decoder (Vector Text)
> example = vector text
... or implicitly using `auto`:
> example :: Decoder (Vector Text)
> example = auto
You can consume `Decoder`s using the `Dhall.input` function:
> input :: Decoder a -> Text -> IO a
-}
data Decoder a = Decoder
{ extract :: Expr Src Void -> Extractor Src Void a
-- ^ Extracts Haskell value from the Dhall expression
, expected :: Expector (Expr Src Void)
-- ^ Dhall type of the Haskell value
}
deriving (Functor)
{-| Any value that implements `FromDhall` can be automatically decoded based on
the inferred return type of `Dhall.input`.
>>> input auto "[1, 2, 3]" :: IO (Vector Natural)
[1,2,3]
>>> input auto "toMap { a = False, b = True }" :: IO (Map Text Bool)
fromList [("a",False),("b",True)]
This class auto-generates a default implementation for types that
implement `Generic`. This does not auto-generate an instance for recursive
types.
The default instance can be tweaked using 'genericAutoWith'/'genericAutoWithInputNormalizer'
and custom 'InterpretOptions', or using
[DerivingVia](https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#extension-DerivingVia)
and 'Dhall.Deriving.Codec' from "Dhall.Deriving".
-}
class FromDhall a where
autoWith :: InputNormalizer -> Decoder a
default autoWith
:: (Generic a, GenericFromDhall a (Rep a)) => InputNormalizer -> Decoder a
autoWith _ = genericAuto
-- | A compatibility alias for `FromDhall`.
type Interpret = FromDhall
{-# DEPRECATED Interpret "Use FromDhall instead" #-}
{-| Use the default input normalizer for interpreting an input.
> auto = autoWith defaultInputNormalizer
-}
auto :: FromDhall a => Decoder a
auto = autoWith defaultInputNormalizer
instance FromDhall Void where
autoWith _ = void
instance FromDhall () where
autoWith _ = unit
instance FromDhall Bool where
autoWith _ = bool
instance FromDhall Natural where
autoWith _ = natural
instance FromDhall Word where
autoWith _ = word
instance FromDhall Word8 where
autoWith _ = word8
instance FromDhall Word16 where
autoWith _ = word16
instance FromDhall Word32 where
autoWith _ = word32
instance FromDhall Word64 where
autoWith _ = word64
instance FromDhall Integer where
autoWith _ = integer
instance FromDhall Int where
autoWith _ = int
instance FromDhall Int8 where
autoWith _ = int8
instance FromDhall Int16 where
autoWith _ = int16
instance FromDhall Int32 where
autoWith _ = int32
instance FromDhall Int64 where
autoWith _ = int64
instance FromDhall Scientific where
autoWith _ = scientific
instance FromDhall Double where
autoWith _ = double
instance {-# OVERLAPS #-} FromDhall [Char] where
autoWith _ = string
instance FromDhall Data.Text.Lazy.Text where
autoWith _ = lazyText
instance FromDhall Text where
autoWith _ = strictText
instance FromDhall a => FromDhall (Maybe a) where
autoWith opts = maybe (autoWith opts)
instance FromDhall a => FromDhall (Seq a) where
autoWith opts = sequence (autoWith opts)
instance FromDhall a => FromDhall [a] where
autoWith opts = list (autoWith opts)
instance FromDhall a => FromDhall (Vector a) where
autoWith opts = vector (autoWith opts)
instance FromDhall Time.TimeOfDay where
autoWith _ = timeOfDay
instance FromDhall Time.Day where
autoWith _ = day
instance FromDhall Time.TimeZone where
autoWith _ = timeZone
instance FromDhall Time.LocalTime where
autoWith _ = localTime
instance FromDhall Time.ZonedTime where
autoWith _ = zonedTime
instance FromDhall Time.UTCTime where
autoWith _ = utcTime
instance FromDhall Time.DayOfWeek where
autoWith _ = dayOfWeek
{-| Note that this instance will throw errors in the presence of duplicates in
the list. To ignore duplicates, use `setIgnoringDuplicates`.
-}
instance (FromDhall a, Ord a, Show a) => FromDhall (Data.Set.Set a) where
autoWith opts = setFromDistinctList (autoWith opts)
{-| Note that this instance will throw errors in the presence of duplicates in
the list. To ignore duplicates, use `hashSetIgnoringDuplicates`.
-}
instance (FromDhall a, Hashable a, Ord a, Show a) => FromDhall (Data.HashSet.HashSet a) where
autoWith inputNormalizer = hashSetFromDistinctList (autoWith inputNormalizer)
instance (Ord k, FromDhall k, FromDhall v) => FromDhall (Map k v) where
autoWith inputNormalizer = Dhall.Marshal.Decode.map (autoWith inputNormalizer) (autoWith inputNormalizer)
instance (Eq k, Hashable k, FromDhall k, FromDhall v) => FromDhall (HashMap k v) where
autoWith inputNormalizer = Dhall.Marshal.Decode.hashMap (autoWith inputNormalizer) (autoWith inputNormalizer)
instance (ToDhall a, FromDhall b) => FromDhall (a -> b) where
autoWith inputNormalizer =
functionWith inputNormalizer (injectWith inputNormalizer) (autoWith inputNormalizer)
instance (FromDhall a, FromDhall b) => FromDhall (a, b)
instance FromDhall (f (Result f)) => FromDhall (Result f) where
autoWith inputNormalizer = Decoder {..}
where
extract (App _ expr) =
fmap Result (Dhall.Marshal.Decode.extract (autoWith inputNormalizer) expr)
extract expr = typeError expected expr
expected = pure "result"
deriving newtype instance (ToDhall x) => FromDhall (Predicate x)
deriving newtype instance (ToDhall x) => FromDhall (Equivalence x)
deriving newtype instance (FromDhall b, ToDhall x) => FromDhall (Op b x)
-- | You can use this instance to marshal recursive types from Dhall to Haskell.
--
-- Here is an example use of this instance:
--
-- > {-# LANGUAGE DeriveAnyClass #-}
-- > {-# LANGUAGE DeriveFoldable #-}
-- > {-# LANGUAGE DeriveFunctor #-}
-- > {-# LANGUAGE DeriveTraversable #-}
-- > {-# LANGUAGE DeriveGeneric #-}
-- > {-# LANGUAGE KindSignatures #-}
-- > {-# LANGUAGE QuasiQuotes #-}
-- > {-# LANGUAGE StandaloneDeriving #-}
-- > {-# LANGUAGE TypeFamilies #-}
-- > {-# LANGUAGE TemplateHaskell #-}
-- >
-- > import Data.Fix (Fix(..))
-- > import Data.Text (Text)
-- > import Dhall (FromDhall)
-- > import GHC.Generics (Generic)
-- > import Numeric.Natural (Natural)
-- >
-- > import qualified Data.Fix as Fix
-- > import qualified Data.Functor.Foldable as Foldable
-- > import qualified Data.Functor.Foldable.TH as TH
-- > import qualified Dhall
-- > import qualified NeatInterpolation
-- >
-- > data Expr
-- > = Lit Natural
-- > | Add Expr Expr
-- > | Mul Expr Expr
-- > deriving (Show)
-- >
-- > TH.makeBaseFunctor ''Expr
-- >
-- > deriving instance Generic (ExprF a)
-- > deriving instance FromDhall a => FromDhall (ExprF a)
-- >
-- > example :: Text
-- > example = [NeatInterpolation.text|
-- > \(Expr : Type)
-- > -> let ExprF =
-- > < LitF :
-- > Natural
-- > | AddF :
-- > { _1 : Expr, _2 : Expr }
-- > | MulF :
-- > { _1 : Expr, _2 : Expr }
-- > >
-- >
-- > in \(Fix : ExprF -> Expr)
-- > -> let Lit = \(x : Natural) -> Fix (ExprF.LitF x)
-- >
-- > let Add =
-- > \(x : Expr)
-- > -> \(y : Expr)
-- > -> Fix (ExprF.AddF { _1 = x, _2 = y })
-- >
-- > let Mul =
-- > \(x : Expr)
-- > -> \(y : Expr)
-- > -> Fix (ExprF.MulF { _1 = x, _2 = y })
-- >
-- > in Add (Mul (Lit 3) (Lit 7)) (Add (Lit 1) (Lit 2))
-- > |]
-- >
-- > convert :: Fix ExprF -> Expr
-- > convert = Fix.foldFix Foldable.embed
-- >
-- > main :: IO ()
-- > main = do
-- > x <- Dhall.input Dhall.auto example :: IO (Fix ExprF)
-- >
-- > print (convert x :: Expr)
instance (Functor f, FromDhall (f (Result f))) => FromDhall (Fix f) where
autoWith inputNormalizer = Decoder {..}
where
extract expr0 = extract0 expr0
where
die = typeError expected expr0
extract0 (Lam _ (FunctionBinding { functionBindingVariable = x }) expr) =
extract1 (rename x "result" expr)
extract0 _ = die
extract1 (Lam _ (FunctionBinding { functionBindingVariable = y }) expr) =
extract2 (rename y "Make" expr)
extract1 _ = die
extract2 expr = fmap resultToFix (Dhall.Marshal.Decode.extract (autoWith inputNormalizer) expr)
rename a b expr
| a /= b = Core.subst (V a 0) (Var (V b 0)) (Core.shift 1 (V b 0) expr)
| otherwise = expr
expected = (\x -> Pi mempty "result" (Const Core.Type) (Pi mempty "Make" (Pi mempty "_" x "result") "result"))
<$> Dhall.Marshal.Decode.expected (autoWith inputNormalizer :: Decoder (f (Result f)))
resultToFix :: Functor f => Result f -> Fix f
resultToFix (Result x) = Fix (fmap resultToFix x)
{-| This is the underlying class that powers the `FromDhall` class's support
for automatically deriving a generic implementation.
-}
class GenericFromDhall t f where
genericAutoWithNormalizer :: Proxy t -> InputNormalizer -> InterpretOptions -> State Int (Decoder (f a))
instance GenericFromDhall t f => GenericFromDhall t (M1 D d f) where
genericAutoWithNormalizer p inputNormalizer options = do
res <- genericAutoWithNormalizer p inputNormalizer options
pure (fmap M1 res)
instance GenericFromDhall t V1 where
genericAutoWithNormalizer _ _ _ = pure Decoder {..}
where
extract expr = typeError expected expr
expected = pure $ Union mempty
instance GenericFromDhallUnion t (f :+: g) => GenericFromDhall t (f :+: g) where
genericAutoWithNormalizer p inputNormalizer options =
pure (union (genericUnionAutoWithNormalizer p inputNormalizer options))
instance GenericFromDhall t f => GenericFromDhall t (M1 C c f) where
genericAutoWithNormalizer p inputNormalizer options = do
res <- genericAutoWithNormalizer p inputNormalizer options
pure (fmap M1 res)
instance GenericFromDhall t U1 where
genericAutoWithNormalizer _ _ _ = pure (Decoder {..})
where
extract _ = pure U1
expected = pure expected'
expected' = Record (Dhall.Map.fromList [])
instance (GenericFromDhall t (f :*: g), GenericFromDhall t (h :*: i)) => GenericFromDhall t ((f :*: g) :*: (h :*: i)) where
genericAutoWithNormalizer p inputNormalizer options = do
Decoder extractL expectedL <- genericAutoWithNormalizer p inputNormalizer options
Decoder extractR expectedR <- genericAutoWithNormalizer p inputNormalizer options
let ktsL = unsafeExpectRecord "genericAutoWithNormalizer (:*:)" <$> expectedL
let ktsR = unsafeExpectRecord "genericAutoWithNormalizer (:*:)" <$> expectedR
let expected = Record <$> (Dhall.Map.union <$> ktsL <*> ktsR)
let extract expression =
liftA2 (:*:) (extractL expression) (extractR expression)
return (Decoder {..})
instance (GenericFromDhall t (f :*: g), Selector s, FromDhall a) => GenericFromDhall t ((f :*: g) :*: M1 S s (K1 i a)) where
genericAutoWithNormalizer p inputNormalizer options@InterpretOptions{..} = do
let nR :: M1 S s (K1 i a) r
nR = undefined
nameR <- fmap fieldModifier (getSelName nR)
Decoder extractL expectedL <- genericAutoWithNormalizer p inputNormalizer options
let Decoder extractR expectedR = autoWith inputNormalizer
let ktsL = unsafeExpectRecord "genericAutoWithNormalizer (:*:)" <$> expectedL
let expected = Record <$> (Dhall.Map.insert nameR . Core.makeRecordField <$> expectedR <*> ktsL)
let extract expression = do
let die = typeError expected expression
case expression of
RecordLit kvs ->
case Core.recordFieldValue <$> Dhall.Map.lookup nameR kvs of
Just expressionR ->
liftA2 (:*:)
(extractL expression)
(fmap (M1 . K1) (extractR expressionR))
_ -> die
_ -> die
return (Decoder {..})
instance (Selector s, FromDhall a, GenericFromDhall t (f :*: g)) => GenericFromDhall t (M1 S s (K1 i a) :*: (f :*: g)) where
genericAutoWithNormalizer p inputNormalizer options@InterpretOptions{..} = do
let nL :: M1 S s (K1 i a) r
nL = undefined
nameL <- fmap fieldModifier (getSelName nL)
let Decoder extractL expectedL = autoWith inputNormalizer
Decoder extractR expectedR <- genericAutoWithNormalizer p inputNormalizer options
let ktsR = unsafeExpectRecord "genericAutoWithNormalizer (:*:)" <$> expectedR
let expected = Record <$> (Dhall.Map.insert nameL . Core.makeRecordField <$> expectedL <*> ktsR)
let extract expression = do
let die = typeError expected expression
case expression of
RecordLit kvs ->
case Core.recordFieldValue <$> Dhall.Map.lookup nameL kvs of
Just expressionL ->
liftA2 (:*:)
(fmap (M1 . K1) (extractL expressionL))
(extractR expression)
_ -> die
_ -> die
return (Decoder {..})
instance {-# OVERLAPPING #-} GenericFromDhall a1 (M1 S s1 (K1 i1 a1) :*: M1 S s2 (K1 i2 a2)) where
genericAutoWithNormalizer _ _ _ = pure $ Decoder
{ extract = \_ -> Failure $ DhallErrors $ pure $ ExpectedTypeError RecursiveTypeError
, expected = Failure $ DhallErrors $ pure RecursiveTypeError
}
instance {-# OVERLAPPING #-} GenericFromDhall a2 (M1 S s1 (K1 i1 a1) :*: M1 S s2 (K1 i2 a2)) where
genericAutoWithNormalizer _ _ _ = pure $ Decoder
{ extract = \_ -> Failure $ DhallErrors $ pure $ ExpectedTypeError RecursiveTypeError
, expected = Failure $ DhallErrors $ pure RecursiveTypeError
}
instance {-# OVERLAPPABLE #-} (Selector s1, Selector s2, FromDhall a1, FromDhall a2) => GenericFromDhall t (M1 S s1 (K1 i1 a1) :*: M1 S s2 (K1 i2 a2)) where
genericAutoWithNormalizer _ inputNormalizer InterpretOptions{..} = do
let nL :: M1 S s1 (K1 i1 a1) r
nL = undefined
let nR :: M1 S s2 (K1 i2 a2) r
nR = undefined
nameL <- fmap fieldModifier (getSelName nL)
nameR <- fmap fieldModifier (getSelName nR)
let Decoder extractL expectedL = autoWith inputNormalizer
let Decoder extractR expectedR = autoWith inputNormalizer
let expected = do
l <- Core.makeRecordField <$> expectedL
r <- Core.makeRecordField <$> expectedR
pure $ Record
(Dhall.Map.fromList
[ (nameL, l)
, (nameR, r)
]
)
let extract expression = do
let die = typeError expected expression
case expression of
RecordLit kvs ->
case liftA2 (,) (Dhall.Map.lookup nameL kvs) (Dhall.Map.lookup nameR kvs) of
Just (expressionL, expressionR) ->
liftA2 (:*:)
(fmap (M1 . K1) (extractL $ Core.recordFieldValue expressionL))
(fmap (M1 . K1) (extractR $ Core.recordFieldValue expressionR))
Nothing -> die
_ -> die
return (Decoder {..})
instance {-# OVERLAPPING #-} GenericFromDhall a (M1 S s (K1 i a)) where
genericAutoWithNormalizer _ _ _ = pure $ Decoder
{ extract = \_ -> Failure $ DhallErrors $ pure $ ExpectedTypeError RecursiveTypeError
, expected = Failure $ DhallErrors $ pure RecursiveTypeError
}
instance {-# OVERLAPPABLE #-} (Selector s, FromDhall a) => GenericFromDhall t (M1 S s (K1 i a)) where
genericAutoWithNormalizer _ inputNormalizer InterpretOptions{..} = do
let n :: M1 S s (K1 i a) r
n = undefined
name <- fmap fieldModifier (getSelName n)
let Decoder { extract = extract', expected = expected'} = autoWith inputNormalizer
let expected =
case singletonConstructors of
Bare ->
expected'
Smart | selName n == "" ->
expected'
_ ->
Record . Dhall.Map.singleton name . Core.makeRecordField <$> expected'
let extract0 expression = fmap (M1 . K1) (extract' expression)
let extract1 expression = do
let die = typeError expected expression
case expression of
RecordLit kvs ->
case Core.recordFieldValue <$> Dhall.Map.lookup name kvs of
Just subExpression ->
fmap (M1 . K1) (extract' subExpression)
Nothing ->
die
_ -> die
let extract =
case singletonConstructors of
Bare -> extract0
Smart | selName n == "" -> extract0
_ -> extract1
return (Decoder {..})
{-| `genericAuto` is the default implementation for `auto` if you derive
`FromDhall`. The difference is that you can use `genericAuto` without
having to explicitly provide a `FromDhall` instance for a type as long as
the type derives `Generic`.
-}
genericAuto :: (Generic a, GenericFromDhall a (Rep a)) => Decoder a
genericAuto = genericAutoWith defaultInterpretOptions
{-| `genericAutoWith` is a configurable version of `genericAuto`.
-}
genericAutoWith :: (Generic a, GenericFromDhall a (Rep a)) => InterpretOptions -> Decoder a
genericAutoWith options = genericAutoWithInputNormalizer options defaultInputNormalizer
{-| `genericAutoWithInputNormalizer` is like `genericAutoWith`, but instead of
using the `defaultInputNormalizer` it expects an custom `InputNormalizer`.
-}
genericAutoWithInputNormalizer :: (Generic a, GenericFromDhall a (Rep a)) => InterpretOptions -> InputNormalizer -> Decoder a
genericAutoWithInputNormalizer options inputNormalizer = withProxy (\p -> fmap to (evalState (genericAutoWithNormalizer p inputNormalizer options) 1))
where
withProxy :: (Proxy a -> Decoder a) -> Decoder a
withProxy f = f Proxy
extractUnionConstructor
:: Expr s a -> Maybe (Text, Expr s a, Dhall.Map.Map Text (Maybe (Expr s a)))
extractUnionConstructor (App (Field (Union kts) (Core.fieldSelectionLabel -> fld)) e) =
return (fld, e, Dhall.Map.delete fld kts)
extractUnionConstructor (Field (Union kts) (Core.fieldSelectionLabel -> fld)) =
return (fld, RecordLit mempty, Dhall.Map.delete fld kts)
extractUnionConstructor _ =
empty
{-| This is the underlying class that powers the `FromDhall` class's support
for automatically deriving a generic implementation for a union type.
-}
class GenericFromDhallUnion t f where
genericUnionAutoWithNormalizer :: Proxy t -> InputNormalizer -> InterpretOptions -> UnionDecoder (f a)
instance (GenericFromDhallUnion t f1, GenericFromDhallUnion t f2) => GenericFromDhallUnion t (f1 :+: f2) where
genericUnionAutoWithNormalizer p inputNormalizer options =
(<>)
(L1 <$> genericUnionAutoWithNormalizer p inputNormalizer options)
(R1 <$> genericUnionAutoWithNormalizer p inputNormalizer options)
instance (Constructor c1, GenericFromDhall t f1) => GenericFromDhallUnion t (M1 C c1 f1) where
genericUnionAutoWithNormalizer p inputNormalizer options@(InterpretOptions {..}) =
constructor name (evalState (genericAutoWithNormalizer p inputNormalizer options) 1)
where
n :: M1 C c1 f1 a
n = undefined
name = constructorModifier (Data.Text.pack (conName n))
{-| Decode a `Prelude.Bool`.
>>> input bool "True"
True
-}
bool :: Decoder Bool
bool = Decoder {..}
where
extract (BoolLit b) = pure b
extract expr = typeError expected expr
expected = pure Bool
{-| Decode a `Prelude.Natural`.
>>> input natural "42"
42
-}
natural :: Decoder Natural
natural = Decoder {..}
where
extract (NaturalLit n) = pure n
extract expr = typeError expected expr
expected = pure Natural
{-| Decode an `Prelude.Integer`.
>>> input integer "+42"
42
-}
integer :: Decoder Integer
integer = Decoder {..}
where
extract (IntegerLit n) = pure n
extract expr = typeError expected expr
expected = pure Integer
wordHelper :: forall a . (Bounded a, Integral a) => Text -> Decoder a
wordHelper name = Decoder {..}
where
extract (NaturalLit n)
| toInteger n <= toInteger (maxBound @a) =
pure (fromIntegral n)
| otherwise =
extractError ("Decoded " <> name <> " is out of bounds: " <> Data.Text.pack (show n))
extract expr =
typeError expected expr
expected = pure Natural
{-| Decode a `Word` from a Dhall @Natural@.
>>> input word "42"
42
-}
word :: Decoder Word
word = wordHelper "Word"
{-| Decode a `Word8` from a Dhall @Natural@.
>>> input word8 "42"
42
-}
word8 :: Decoder Word8
word8 = wordHelper "Word8"
{-| Decode a `Word16` from a Dhall @Natural@.
>>> input word16 "42"
42
-}
word16 :: Decoder Word16
word16 = wordHelper "Word16"
{-| Decode a `Word32` from a Dhall @Natural@.
>>> input word32 "42"
42
-}
word32 :: Decoder Word32
word32 = wordHelper "Word32"
{-| Decode a `Word64` from a Dhall @Natural@.
>>> input word64 "42"
42
-}
word64 :: Decoder Word64
word64 = wordHelper "Word64"
intHelper :: forall a . (Bounded a, Integral a) => Text -> Decoder a
intHelper name = Decoder {..}
where
extract (IntegerLit n)
| toInteger (minBound @a) <= n && n <= toInteger (maxBound @a) =
pure (fromIntegral n)
| otherwise =
extractError ("Decoded " <> name <> " is out of bounds: " <> Data.Text.pack (show n))
extract expr =
typeError expected expr
expected = pure Integer
{-| Decode an `Int` from a Dhall @Integer@.
>>> input int "-42"
-42
-}
int :: Decoder Int
int = intHelper "Int"
{-| Decode an `Int8` from a Dhall @Integer@.
>>> input int8 "-42"
-42
-}
int8 :: Decoder Int8
int8 = intHelper "Int8"
{-| Decode an `Int16` from a Dhall @Integer@.
>>> input int16 "-42"
-42
-}
int16 :: Decoder Int16
int16 = intHelper "Int16"
{-| Decode an `Int32` from a Dhall @Integer@.
>>> input int32 "-42"
-42
-}
int32 :: Decoder Int32
int32 = intHelper "Int32"
{-| Decode an `Int64` from a Dhall @Integer@.
>>> input int64 "-42"
-42
-}
int64 :: Decoder Int64
int64 = intHelper "Int64"
{-| Decode a `Scientific`.
>>> input scientific "1e100"
1.0e100
-}
scientific :: Decoder Scientific
scientific = fmap Data.Scientific.fromFloatDigits double
{-| Decode a `Prelude.Double`.
>>> input double "42.0"
42.0
-}
double :: Decoder Double
double = Decoder {..}
where
extract (DoubleLit (DhallDouble n)) = pure n
extract expr = typeError expected expr
expected = pure Double
{-| Decode lazy `Data.Text.Text`.
>>> input lazyText "\"Test\""
"Test"
-}
lazyText :: Decoder Data.Text.Lazy.Text
lazyText = fmap Data.Text.Lazy.fromStrict strictText
{-| Decode strict `Data.Text.Text`.
>>> input strictText "\"Test\""
"Test"
-}
strictText :: Decoder Text
strictText = Decoder {..}
where
extract (TextLit (Chunks [] t)) = pure t
extract expr = typeError expected expr
expected = pure Text
{-| Decode `Time.TimeOfDay`
>>> input timeOfDay "00:00:00"
00:00:00
-}
timeOfDay :: Decoder Time.TimeOfDay
timeOfDay = Decoder {..}
where
extract (TimeLiteral t _) = pure t
extract expr = typeError expected expr
expected = pure Time
{-| Decode `Time.Day`
>>> input day "2000-01-01"
2000-01-01
-}
day :: Decoder Time.Day
day = Decoder {..}
where
extract (DateLiteral d) = pure d
extract expr = typeError expected expr
expected = pure Date
{-| Decode `Time.TimeZone`
>>> input timeZone "+00:00"
+0000
-}
timeZone :: Decoder Time.TimeZone
timeZone = Decoder {..}
where
extract (TimeZoneLiteral z) = pure z
extract expr = typeError expected expr
expected = pure TimeZone
{-| Decode `Time.LocalTime`
>>> input localTime "2020-01-01T12:34:56"
2020-01-01 12:34:56
-}
localTime :: Decoder Time.LocalTime
localTime = record $
Time.LocalTime
<$> field "date" day
<*> field "time" timeOfDay
{-| Decode `Time.ZonedTime`
>>> input zonedTime "2020-01-01T12:34:56+02:00"
2020-01-01 12:34:56 +0200
-}
zonedTime :: Decoder Time.ZonedTime
zonedTime = record $
adapt
<$> field "date" day
<*> field "time" timeOfDay
<*> field "timeZone" timeZone
where
adapt date time = Time.ZonedTime (Time.LocalTime date time)
{-| Decode `Time.UTCTime`