@@ -5,19 +5,16 @@
55{-# LANGUAGE FlexibleInstances #-}
66{-# LANGUAGE GADTs #-}
77{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE NamedFieldPuns #-}
8+{-# LANGUAGE NoImplicitPrelude #-}
99{-# LANGUAGE OverloadedStrings #-}
10+{-# LANGUAGE PolyKinds #-}
1011{-# LANGUAGE RecordWildCards #-}
1112{-# LANGUAGE ScopedTypeVariables #-}
1213{-# LANGUAGE TypeOperators #-}
13−{-# LANGUAGE TypeSynonymInstances #-}
14+{-# LANGUAGE TupleSections #-}
1415{-# LANGUAGE UndecidableInstances #-}
1516{-# LANGUAGE ViewPatterns #-}
1617
17−#if __GLASGOW_HASKELL__ >= 706
18−{-# LANGUAGE PolyKinds #-}
19−#endif
20−
2118#include "incoherent-compat.h"
2219#include "overlapping-compat.h"
2320
@@ -45,6 +42,9 @@ module Data.Aeson.Types.FromJSON
4542 , coerceFromJSONKeyFunction
4643 , mapFromJSONKeyFunction
4744
45+ , GFromJSONKey()
46+ , genericFromJSONKey
47+
4848 -- * List functions
4949 , listParser
5050
@@ -52,20 +52,22 @@ module Data.Aeson.Types.FromJSON
5252 , withObject
5353 , withText
5454 , withArray
55− , withNumber
5655 , withScientific
5756 , withBool
57+ , withEmbeddedJSON
5858
5959 -- * Functions
6060 , fromJSON
6161 , ifromJSON
6262 , typeMismatch
63+ , unexpected
6364 , parseField
6465 , parseFieldMaybe
6566 , parseFieldMaybe'
6667 , explicitParseField
6768 , explicitParseFieldMaybe
6869 , explicitParseFieldMaybe'
70+ , parseIndexedJSON
6971 -- ** Operators
7072 , (.:)
7173 , (.:?)
@@ -76,17 +78,16 @@ module Data.Aeson.Types.FromJSON
7678 , parseOptionalFieldWith
7779 ) where
7880
79−import Prelude ()
8081import Prelude.Compat
8182
82−import Control.Applicative ((<|>), Const(..))
83−import Control.Monad ((<=<), zipWithM)
83+import Control.Applicative ((<|>), Const(..), liftA2)
84+import Control.Monad (zipWithM)
8485import Data.Aeson.Internal.Functions (mapKey)
86+import Data.Aeson.Parser.Internal (eitherDecodeWith, jsonEOF)
8587import Data.Aeson.Types.Generic
8688import Data.Aeson.Types.Internal
87−import Data.Attoparsec.Number (Number(..))
8889import Data.Bits (unsafeShiftR)
89−import Data.Fixed (Fixed, HasResolution)
90+import Data.Fixed (Fixed, HasResolution (resolution), Nano)
9091import Data.Functor.Compose (Compose(..))
9192import Data.Functor.Identity (Identity(..))
9293import Data.Functor.Product (Product(..))
@@ -95,26 +96,31 @@ import Data.Hashable (Hashable(..))
9596import Data.Int (Int16, Int32, Int64, Int8)
9697import Data.List.NonEmpty (NonEmpty(..))
9798import Data.Maybe (fromMaybe)
98−import Data.Monoid ((<>))
99+import Data.Semigroup ((<>))
99100import Data.Proxy (Proxy(..))
100101import Data.Ratio ((%), Ratio)
101−import Data.Scientific (Scientific)
102+import Data.Scientific (Scientific, base10Exponent)
102103import Data.Tagged (Tagged(..))
103104import Data.Text (Text, pack, unpack)
104105import Data.Time (Day, DiffTime, LocalTime, NominalDiffTime, TimeOfDay, UTCTime, ZonedTime)
105−import Data.Time.Format (parseTime)
106−import Data.Time.Locale.Compat (defaultTimeLocale)
106+import Data.Time.Calendar.Compat (CalendarDiffDays (..), DayOfWeek (..))
107+import Data.Time.LocalTime.Compat (CalendarDiffTime (..))
108+import Data.Time.Clock.System.Compat (SystemTime (..))
109+import Data.Time.Format.Compat (parseTimeM, defaultTimeLocale)
107110import Data.Traversable as Tr (sequence)
108111import Data.Vector (Vector)
109112import Data.Version (Version, parseVersion)
113+import Data.Void (Void)
110114import Data.Word (Word16, Word32, Word64, Word8)
111115import Foreign.Storable (Storable)
116+import Foreign.C.Types (CTime (..))
112117import GHC.Generics
113118import Numeric.Natural (Natural)
114119import Text.ParserCombinators.ReadP (readP_to_S)
115120import Unsafe.Coerce (unsafeCoerce)
116121import qualified Data.Aeson.Parser.Time as Time
117122import qualified Data.Attoparsec.ByteString.Char8 as A (endOfInput, parseOnly, scientific)
123+import qualified Data.ByteString.Lazy as L
118124import qualified Data.DList as DList
119125import qualified Data.HashMap.Strict as H
120126import qualified Data.HashSet as HashSet
@@ -137,18 +143,20 @@ import qualified Data.Vector.Primitive as VP
137143import qualified Data.Vector.Storable as VS
138144import qualified Data.Vector.Unboxed as VU
139145
140−#ifndef HAS_COERCIBLE
141−#define HAS_COERCIBLE (__GLASGOW_HASKELL__ >= 707)
146+import qualified GHC.Exts as Exts
147+import qualified Data.Primitive.Array as PM
148+import qualified Data.Primitive.SmallArray as PM
149+import qualified Data.Primitive.Types as PM
150+
151+#if MIN_VERSION_primitive(0,6,4)
152+#if !MIN_VERSION_primitive(0,7,0)
153+import qualified Data.Primitive.UnliftedArray as PM
142154#endif
155+import qualified Data.Primitive.PrimArray as PM
156+#endif
157+
143158
144−#if HAS_COERCIBLE
145159import Data.Coerce (Coercible, coerce)
146−coerce' :: Coercible a b => a -> b
147−coerce' = coerce
148−#else
149−coerce' :: a -> b
150−coerce' = unsafeCoerce
151−#endif
152160
153161parseIndexedJSON :: (Value -> Parser a) -> Int -> Value -> Parser a
154162parseIndexedJSON p idx value = p value <?> Index idx
@@ -157,7 +165,7 @@ parseIndexedJSON p idx value = p value <?> Index idx
157165parseIndexedJSONPair :: (Value -> Parser a) -> (Value -> Parser b) -> Int -> Value -> Parser (a, b)
158166parseIndexedJSONPair keyParser valParser idx value = p value <?> Index idx
159167 where
160− p = withArray "(k,v)" $ \ab ->
168+ p = withArray "(k, v)" $ \ab ->
161169 let n = V.length ab
162170 in if n == 2
163171 then (,) <$> parseJSONElemAtIndex keyParser 0 ab
@@ -169,43 +177,34 @@ parseIndexedJSONPair keyParser valParser idx value = p value <?> Index idx
169177parseJSONElemAtIndex :: (Value -> Parser a) -> Int -> V.Vector Value -> Parser a
170178parseJSONElemAtIndex p idx ary = p (V.unsafeIndex ary idx) <?> Index idx
171179
172−scientificToNumber :: Scientific -> Number
173−scientificToNumber s
174− | e < 0 = D $ Scientific.toRealFloat s
175− | otherwise = I $ c * 10 ^ e
176− where
177− e = Scientific.base10Exponent s
178− c = Scientific.coefficient s
179−{-# INLINE scientificToNumber #-}
180−
181180parseRealFloat :: RealFloat a => String -> Value -> Parser a
182−parseRealFloat _ (Number s) = pure $ Scientific.toRealFloat s
183−parseRealFloat _ Null = pure (0/0)
184−parseRealFloat expected v = typeMismatch expected v
181+parseRealFloat _ (Number s) = pure $ Scientific.toRealFloat s
182+parseRealFloat _ Null = pure (0/0)
183+parseRealFloat name v = prependContext name (unexpected v)
185184{-# INLINE parseRealFloat #-}
186185
187−parseIntegralFromScientific :: forall a. Integral a => String -> Scientific -> Parser a
188−parseIntegralFromScientific expected s =
186+parseIntegralFromScientific :: forall a. Integral a => Scientific -> Parser a
187+parseIntegralFromScientific s =
189188 case Scientific.floatingOrInteger s :: Either Double a of
190189 Right x -> pure x
191− Left _ -> fail $ "expected " ++ expected ++ ", encountered floating number " ++ show s
190+ Left _ -> fail $ "unexpected floating number " ++ show s
192191{-# INLINE parseIntegralFromScientific #-}
193192
194193parseIntegral :: Integral a => String -> Value -> Parser a
195−parseIntegral expected =
196− withScientific expected $ parseIntegralFromScientific expected
194+parseIntegral name =
195+ prependContext name . withBoundedScientific' parseIntegralFromScientific
197196{-# INLINE parseIntegral #-}
198197
199−parseBoundedIntegralFromScientific :: (Bounded a, Integral a) => String -> Scientific -> Parser a
200−parseBoundedIntegralFromScientific expected s = maybe
201− (fail $ expected ++ " is either floating or will cause over or underflow: " ++ show s)
198+parseBoundedIntegralFromScientific :: (Bounded a, Integral a) => Scientific -> Parser a
199+parseBoundedIntegralFromScientific s = maybe
200+ (fail $ "value is either floating or will cause over or underflow " ++ show s)
202201 pure
203202 (Scientific.toBoundedInteger s)
204203{-# INLINE parseBoundedIntegralFromScientific #-}
205204
206205parseBoundedIntegral :: (Bounded a, Integral a) => String -> Value -> Parser a
207−parseBoundedIntegral expected =
208− withScientific expected $ parseBoundedIntegralFromScientific expected
206+parseBoundedIntegral name =
207+ prependContext name . withScientific' parseBoundedIntegralFromScientific
209208{-# INLINE parseBoundedIntegral #-}
210209
211210parseScientificText :: Text -> Parser Scientific
@@ -215,13 +214,20 @@ parseScientificText
215214 . T.encodeUtf8
216215
217216parseIntegralText :: Integral a => String -> Text -> Parser a
218−parseIntegralText expected t =
219− parseScientificText t >>= parseIntegralFromScientific expected
217+parseIntegralText name t =
218+ prependContext name $
219+ parseScientificText t
220+ >>= rejectLargeExponent
221+ >>= parseIntegralFromScientific
222+ where
223+ rejectLargeExponent :: Scientific -> Parser Scientific
224+ rejectLargeExponent s = withBoundedScientific' pure (Number s)
220225{-# INLINE parseIntegralText #-}
221226
222227parseBoundedIntegralText :: (Bounded a, Integral a) => String -> Text -> Parser a
223−parseBoundedIntegralText expected t =
224− parseScientificText t >>= parseBoundedIntegralFromScientific expected
228+parseBoundedIntegralText name t =
229+ prependContext name $
230+ parseScientificText t >>= parseBoundedIntegralFromScientific
225231
226232parseOptionalFieldWith :: (Value -> Parser (Maybe a))
227233 -> Object -> Text -> Parser (Maybe a)
@@ -281,14 +287,21 @@ genericLiftParseJSON opts pj pjl = fmap to1 . gParseJSON opts (From1Args pj pjl)
281287--
282288-- The basic ways to signal a failed conversion are as follows:
283289--
284−-- * 'empty' and 'mzero' work, but are terse and uninformative;
290+-- * 'fail' yields a custom error message: it is the recommended way of
291+-- reporting a failure;
292+--
293+-- * 'Control.Applicative.empty' (or 'Control.Monad.mzero') is uninformative:
294+-- use it when the error is meant to be caught by some @('<|>')@;
285295--
286−-- * 'fail' yields a custom error message;
296+-- * 'typeMismatch' can be used to report a failure when the encountered value
297+-- is not of the expected JSON type; 'unexpected' is an appropriate alternative
298+-- when more than one type may be expected, or to keep the expected type
299+-- implicit.
287300--
288−-- * 'typeMismatch' produces an informative message for cases when the
289−-- value encountered is not of the expected type.
301+-- 'prependFailure' (or 'modifyFailure') add more information to a parser's
302+-- error messages.
290303--
291−-- An example type and instance using 'typeMismatch':
304+-- An example type and instance using 'typeMismatch' and 'prependFailure':
292305--
293306-- @
294307-- \-- Allow ourselves to write 'Text' literals.
@@ -302,20 +315,22 @@ genericLiftParseJSON opts pj pjl = fmap to1 . gParseJSON opts (From1Args pj pjl)
302315-- '<*>' v '.:' \"y\"
303316--
304317-- \-- We do not expect a non-'Object' value here.
305−-- \-- We could use 'mzero' to fail, but 'typeMismatch'
318+-- \-- We could use 'Control.Applicative.empty' to fail, but 'typeMismatch'
306319-- \-- gives a much more informative error message.
307−-- 'parseJSON' invalid = 'typeMismatch' \"Coord\" invalid
320+-- 'parseJSON' invalid =
321+-- 'prependFailure' "parsing Coord failed, "
322+-- ('typeMismatch' \"Object\" invalid)
308323-- @
309324--
310325-- For this common case of only being concerned with a single
311−-- type of JSON value, the functions 'withObject', 'withNumber', etc.
326+-- type of JSON value, the functions 'withObject', 'withScientific', etc.
312327-- are provided. Their use is to be preferred when possible, since
313328-- they are more terse. Using 'withObject', we can rewrite the above instance
314329-- (assuming the same language extension and data type) as:
315330--
316331-- @
317332-- instance 'FromJSON' Coord where
318−-- 'parseJSON' = 'withObject' \"Coord\" $ \v -> Coord
333+-- 'parseJSON' = 'withObject' \"Coord\" $ \\v -> Coord
319334-- '<$>' v '.:' \"x\"
320335-- '<*>' v '.:' \"y\"
321336-- @
@@ -347,7 +362,7 @@ genericLiftParseJSON opts pj pjl = fmap to1 . gParseJSON opts (From1Args pj pjl)
347362-- @
348363--
349364-- The default implementation will be equivalent to
350−-- @parseJSON = 'genericParseJSON' 'defaultOptions'@; If you need different
365+-- @parseJSON = 'genericParseJSON' 'defaultOptions'@; if you need different
351366-- options, you can customize the generic decoding by defining:
352367--
353368-- @
@@ -365,13 +380,11 @@ class FromJSON a where
365380 parseJSON = genericParseJSON defaultOptions
366381
367382 parseJSONList :: Value -> Parser [a]
368− parseJSONList (Array a)
369− = zipWithM (parseIndexedJSON parseJSON) [0..]
383+ parseJSONList = withArray "[]" $ \a ->
384+ zipWithM (parseIndexedJSON parseJSON) [0..]
370385 . V.toList
371386 $ a
372387
373− parseJSONList v = typeMismatch "[a]" v
374−
375388-------------------------------------------------------------------------------
376389-- Classes and types for map keys
377390-------------------------------------------------------------------------------
@@ -383,6 +396,16 @@ class FromJSON a where
383396-- > newtype SomeId = SomeId { getSomeId :: Text }
384397-- > deriving (Eq,Ord,Hashable,FromJSONKey)
385398--
399+-- If you have a sum of nullary constructors, you may use the generic
400+-- implementation:
401+--
402+-- @
403+-- data Color = Red | Green | Blue
404+-- deriving Generic
405+--
406+-- instance 'FromJSONKey' Color where
407+-- 'fromJSONKey' = 'genericFromJSONKey' 'defaultJSONKeyOptions'
408+-- @
386409class FromJSONKey a where
387410 -- | Strategy for parsing the key of a map-like container.
388411 fromJSONKey :: FromJSONKeyFunction a
@@ -405,11 +428,7 @@ class FromJSONKey a where
405428-- At the moment this type is intentionally not exported. 'FromJSONKeyFunction'
406429-- can be inspected, but cannot be constructed.
407430data CoerceText a where
408−#if HAS_COERCIBLE
409431 CoerceText :: Coercible Text a => CoerceText a
410−#else
411− CoerceText :: CoerceText a
412−#endif
413432
414433-- | This type is related to 'ToJSONKeyFunction'. If 'FromJSONKeyValue' is used in the
415434-- 'FromJSONKey' instance, then 'ToJSONKeyValue' should be used in the 'ToJSONKey'
@@ -429,7 +448,7 @@ data FromJSONKeyFunction a
429448
430449-- | Only law abiding up to interpretation
431450instance Functor FromJSONKeyFunction where
432− fmap h (FromJSONKeyCoerce CoerceText) = FromJSONKeyText (h . coerce')
451+ fmap h (FromJSONKeyCoerce CoerceText) = FromJSONKeyText (h . coerce)
433452 fmap h (FromJSONKeyText f) = FromJSONKeyText (h . f)
434453 fmap h (FromJSONKeyTextParser f) = FromJSONKeyTextParser (fmap h . f)
435454 fmap h (FromJSONKeyValue f) = FromJSONKeyValue (fmap h . f)
@@ -443,9 +462,7 @@ instance Functor FromJSONKeyFunction where
443462--
444463-- On pre GHC 7.8 this is unconstrainted function.
445464fromJSONKeyCoerce ::
446−#if HAS_COERCIBLE
447465 Coercible Text a =>
448−#endif
449466 FromJSONKeyFunction a
450467fromJSONKeyCoerce = FromJSONKeyCoerce CoerceText
451468
@@ -453,60 +470,91 @@ fromJSONKeyCoerce = FromJSONKeyCoerce CoerceText
453470--
454471-- See note on 'fromJSONKeyCoerce'.
455472coerceFromJSONKeyFunction ::
456−#if HAS_COERCIBLE
457473 Coercible a b =>
458−#endif
459474 FromJSONKeyFunction a -> FromJSONKeyFunction b
460−#if HAS_COERCIBLE
461475coerceFromJSONKeyFunction = coerce
462−#else
463−coerceFromJSONKeyFunction (FromJSONKeyCoerce CoerceText) = FromJSONKeyCoerce CoerceText
464−coerceFromJSONKeyFunction (FromJSONKeyText f) = FromJSONKeyText (coerce' . f)
465−coerceFromJSONKeyFunction (FromJSONKeyTextParser f) = FromJSONKeyTextParser (fmap coerce' . f)
466−coerceFromJSONKeyFunction (FromJSONKeyValue f) = FromJSONKeyValue (fmap coerce' . f)
467−#endif
468476
469477{-# RULES
470478 "FromJSONKeyCoerce: fmap id" forall (x :: FromJSONKeyFunction a).
471479 fmap id x = x
472480 #-}
473−#if HAS_COERCIBLE
474481{-# RULES
475482 "FromJSONKeyCoerce: fmap coerce" forall x .
476483 fmap coerce x = coerceFromJSONKeyFunction x
477484 #-}
478−#endif
479485
480486-- | Same as 'fmap'. Provided for the consistency with 'ToJSONKeyFunction'.
481487mapFromJSONKeyFunction :: (a -> b) -> FromJSONKeyFunction a -> FromJSONKeyFunction b
482488mapFromJSONKeyFunction = fmap
483489
490+-- | 'fromJSONKey' for 'Generic' types.
491+-- These types must be sums of nullary constructors, whose names will be used
492+-- as keys for JSON objects.
493+--
494+-- See also 'genericToJSONKey'.
495+--
496+-- === __Example__
497+--
498+-- @
499+-- data Color = Red | Green | Blue
500+-- deriving 'Generic'
501+--
502+-- instance 'FromJSONKey' Color where
503+-- 'fromJSONKey' = 'genericFromJSONKey' 'defaultJSONKeyOptions'
504+-- @
505+genericFromJSONKey :: forall a. (Generic a, GFromJSONKey (Rep a))
506+ => JSONKeyOptions
507+ -> FromJSONKeyFunction a
508+genericFromJSONKey opts = FromJSONKeyTextParser $ \t ->
509+ case parseSumFromString (keyModifier opts) t of
510+ Nothing -> fail $
511+ "invalid key " ++ show t ++ ", expected one of " ++ show cnames
512+ Just k -> pure (to k)
513+ where
514+ cnames = unTagged2 (constructorTags (keyModifier opts) :: Tagged2 (Rep a) [String])
515+
516+class (ConstructorNames f, SumFromString f) => GFromJSONKey f where
517+instance (ConstructorNames f, SumFromString f) => GFromJSONKey f where
518+
484519-------------------------------------------------------------------------------
485520-- Functions needed for documentation
486521-------------------------------------------------------------------------------
487522
488523-- | Fail parsing due to a type mismatch, with a descriptive message.
489524--
490−-- Example usage:
525+-- The following wrappers should generally be prefered:
526+-- 'withObject', 'withArray', 'withText', 'withBool'.
491527--
492−-- @
493−-- instance FromJSON Coord where
494−-- parseJSON ('Object' v) = {- type matches, life is good -}
495−-- parseJSON wat = 'typeMismatch' \"Coord\" wat
496−-- @
497−typeMismatch :: String -- ^ The name of the type you are trying to parse.
528+-- ==== Error message example
529+--
530+-- > typeMismatch "Object" (String "oops")
531+-- > -- Error: "expected Object, but encountered String"
532+typeMismatch :: String -- ^ The name of the JSON type being parsed
533+ -- (@\"Object\"@, @\"Array\"@, @\"String\"@, @\"Number\"@,
534+ -- @\"Boolean\"@, or @\"Null\"@).
498535 -> Value -- ^ The actual value encountered.
499536 -> Parser a
500537typeMismatch expected actual =
501− fail $ "expected " ++ expected ++ ", encountered " ++ name
502− where
503− name = case actual of
504− Object _ -> "Object"
505− Array _ -> "Array"
506− String _ -> "String"
507− Number _ -> "Number"
508− Bool _ -> "Boolean"
509− Null -> "Null"
538+ fail $ "expected " ++ expected ++ ", but encountered " ++ typeOf actual
539+
540+-- | Fail parsing due to a type mismatch, when the expected types are implicit.
541+--
542+-- ==== Error message example
543+--
544+-- > unexpected (String "oops")
545+-- > -- Error: "unexpected String"
546+unexpected :: Value -> Parser a
547+unexpected actual = fail $ "unexpected " ++ typeOf actual
548+
549+-- | JSON type of a value, name of the head constructor.
550+typeOf :: Value -> String
551+typeOf v = case v of
552+ Object _ -> "Object"
553+ Array _ -> "Array"
554+ String _ -> "String"
555+ Number _ -> "Number"
556+ Bool _ -> "Boolean"
557+ Null -> "Null"
510558
511559-------------------------------------------------------------------------------
512560-- Lifings of FromJSON and ToJSON to unary and binary type constructors
@@ -587,9 +635,8 @@ class FromJSON2 f where
587635 -> (Value -> Parser b)
588636 -> (Value -> Parser [b])
589637 -> Value -> Parser [f a b]
590− liftParseJSONList2 fa ga fb gb v = case v of
591− Array vals -> fmap V.toList (V.mapM (liftParseJSON2 fa ga fb gb) vals)
592− _ -> typeMismatch "[a]" v
638+ liftParseJSONList2 fa ga fb gb = withArray "[]" $ \vals ->
639+ fmap V.toList (V.mapM (liftParseJSON2 fa ga fb gb) vals)
593640
594641-- | Lift the standard 'parseJSON' function through the type constructor.
595642parseJSON2 :: (FromJSON2 f, FromJSON a, FromJSON b) => Value -> Parser (f a b)
@@ -603,7 +650,7 @@ parseJSON2 = liftParseJSON2 parseJSON parseJSONList parseJSON parseJSONList
603650-- | Helper function to use with 'liftParseJSON'. See 'Data.Aeson.ToJSON.listEncoding'.
604651listParser :: (Value -> Parser a) -> Value -> Parser [a]
605652listParser f (Array xs) = fmap V.toList (V.mapM f xs)
606−listParser _ v = typeMismatch "[a]" v
653+listParser _ v = typeMismatch "Array" v
607654{-# INLINE listParser #-}
608655
609656-------------------------------------------------------------------------------
@@ -621,49 +668,139 @@ instance (FromJSON a) => FromJSON [a] where
621668-- Functions
622669-------------------------------------------------------------------------------
623670
624−-- | @'withObject' expected f value@ applies @f@ to the 'Object' when @value@
625−-- is an 'Object' and fails using @'typeMismatch' expected@ otherwise.
671+-- | Add context to a failure message, indicating the name of the structure
672+-- being parsed.
673+--
674+-- > prependContext "MyType" (fail "[error message]")
675+-- > -- Error: "parsing MyType failed, [error message]"
676+prependContext :: String -> Parser a -> Parser a
677+prependContext name = prependFailure ("parsing " ++ name ++ " failed, ")
678+
679+-- | @'withObject' name f value@ applies @f@ to the 'Object' when @value@
680+-- is an 'Data.Aeson.Object' and fails otherwise.
681+--
682+-- ==== Error message example
683+--
684+-- > withObject "MyType" f (String "oops")
685+-- > -- Error: "parsing MyType failed, expected Object, but encountered String"
626686withObject :: String -> (Object -> Parser a) -> Value -> Parser a
627−withObject _ f (Object obj) = f obj
628−withObject expected _ v = typeMismatch expected v
687+withObject _ f (Object obj) = f obj
688+withObject name _ v = prependContext name (typeMismatch "Object" v)
629689{-# INLINE withObject #-}
630690
631−-- | @'withText' expected f value@ applies @f@ to the 'Text' when @value@ is a
632−-- 'String' and fails using @'typeMismatch' expected@ otherwise.
691+-- | @'withText' name f value@ applies @f@ to the 'Text' when @value@ is a
692+-- 'Data.Aeson.String' and fails otherwise.
693+--
694+-- ==== Error message example
695+--
696+-- > withText "MyType" f Null
697+-- > -- Error: "parsing MyType failed, expected String, but encountered Null"
633698withText :: String -> (Text -> Parser a) -> Value -> Parser a
634−withText _ f (String txt) = f txt
635−withText expected _ v = typeMismatch expected v
699+withText _ f (String txt) = f txt
700+withText name _ v = prependContext name (typeMismatch "String" v)
636701{-# INLINE withText #-}
637702
638703-- | @'withArray' expected f value@ applies @f@ to the 'Array' when @value@ is
639−-- an 'Array' and fails using @'typeMismatch' expected@ otherwise.
704+-- an 'Data.Aeson.Array' and fails otherwise.
705+--
706+-- ==== Error message example
707+--
708+-- > withArray "MyType" f (String "oops")
709+-- > -- Error: "parsing MyType failed, expected Array, but encountered String"
640710withArray :: String -> (Array -> Parser a) -> Value -> Parser a
641−withArray _ f (Array arr) = f arr
642−withArray expected _ v = typeMismatch expected v
711+withArray _ f (Array arr) = f arr
712+withArray name _ v = prependContext name (typeMismatch "Array" v)
643713{-# INLINE withArray #-}
644714
645−-- | @'withNumber' expected f value@ applies @f@ to the 'Number' when @value@
646−-- is a 'Number' and fails using @'typeMismatch' expected@ otherwise.
647−withNumber :: String -> (Number -> Parser a) -> Value -> Parser a
648−withNumber expected f = withScientific expected (f . scientificToNumber)
649−{-# INLINE withNumber #-}
650−{-# DEPRECATED withNumber "Use withScientific instead" #-}
651−
652−-- | @'withScientific' expected f value@ applies @f@ to the 'Scientific' number
653−-- when @value@ is a 'Number' and fails using @'typeMismatch' expected@
715+-- | @'withScientific' name f value@ applies @f@ to the 'Scientific' number
716+-- when @value@ is a 'Data.Aeson.Number' and fails using 'typeMismatch'
654717-- otherwise.
718+--
719+-- /Warning/: If you are converting from a scientific to an unbounded
720+-- type such as 'Integer' you may want to add a restriction on the
721+-- size of the exponent (see 'withBoundedScientific') to prevent
722+-- malicious input from filling up the memory of the target system.
723+--
724+-- ==== Error message example
725+--
726+-- > withScientific "MyType" f (String "oops")
727+-- > -- Error: "parsing MyType failed, expected Number, but encountered String"
655728withScientific :: String -> (Scientific -> Parser a) -> Value -> Parser a
656−withScientific _ f (Number scientific) = f scientific
657−withScientific expected _ v = typeMismatch expected v
729+withScientific _ f (Number scientific) = f scientific
730+withScientific name _ v = prependContext name (typeMismatch "Number" v)
658731{-# INLINE withScientific #-}
659732
733+-- | A variant of 'withScientific' which doesn't use 'prependContext', so that
734+-- such context can be added separately in a way that also applies when the
735+-- continuation @f :: Scientific -> Parser a@ fails.
736+--
737+-- /Warning/: If you are converting from a scientific to an unbounded
738+-- type such as 'Integer' you may want to add a restriction on the
739+-- size of the exponent (see 'withBoundedScientific') to prevent
740+-- malicious input from filling up the memory of the target system.
741+--
742+-- ==== Error message examples
743+--
744+-- > withScientific' f (String "oops")
745+-- > -- Error: "unexpected String"
746+-- >
747+-- > prependContext "MyType" (withScientific' f (String "oops"))
748+-- > -- Error: "parsing MyType failed, unexpected String"
749+withScientific' :: (Scientific -> Parser a) -> Value -> Parser a
750+withScientific' f v = case v of
751+ Number n -> f n
752+ _ -> typeMismatch "Number" v
753+{-# INLINE withScientific' #-}
754+
755+-- | @'withBoundedScientific' name f value@ applies @f@ to the 'Scientific' number
756+-- when @value@ is a 'Number' with exponent less than or equal to 1024.
757+withBoundedScientific :: String -> (Scientific -> Parser a) -> Value -> Parser a
758+withBoundedScientific name f v = withBoundedScientific_ (prependContext name) f v
759+{-# INLINE withBoundedScientific #-}
760+
761+-- | A variant of 'withBoundedScientific' which doesn't use 'prependContext',
762+-- so that such context can be added separately in a way that also applies
763+-- when the continuation @f :: Scientific -> Parser a@ fails.
764+withBoundedScientific' :: (Scientific -> Parser a) -> Value -> Parser a
765+withBoundedScientific' f v = withBoundedScientific_ id f v
766+{-# INLINE withBoundedScientific' #-}
767+
768+-- | A variant of 'withBoundedScientific_' parameterized by a function to apply
769+-- to the 'Parser' in case of failure.
770+withBoundedScientific_ :: (Parser a -> Parser a) -> (Scientific -> Parser a) -> Value -> Parser a
771+withBoundedScientific_ whenFail f (Number scientific) =
772+ if exp10 > 1024
773+ then whenFail (fail msg)
774+ else f scientific
775+ where
776+ exp10 = base10Exponent scientific
777+ msg = "found a number with exponent " ++ show exp10 ++ ", but it must not be greater than 1024"
778+withBoundedScientific_ whenFail _ v =
779+ whenFail (typeMismatch "Number" v)
780+{-# INLINE withBoundedScientific_ #-}
781+
660782-- | @'withBool' expected f value@ applies @f@ to the 'Bool' when @value@ is a
661−-- 'Bool' and fails using @'typeMismatch' expected@ otherwise.
783+-- 'Boolean' and fails otherwise.
784+--
785+-- ==== Error message example
786+--
787+-- > withBool "MyType" f (String "oops")
788+-- > -- Error: "parsing MyType failed, expected Boolean, but encountered String"
662789withBool :: String -> (Bool -> Parser a) -> Value -> Parser a
663−withBool _ f (Bool arr) = f arr
664−withBool expected _ v = typeMismatch expected v
790+withBool _ f (Bool arr) = f arr
791+withBool name _ v = prependContext name (typeMismatch "Boolean" v)
665792{-# INLINE withBool #-}
666793
794+-- | Decode a nested JSON-encoded string.
795+withEmbeddedJSON :: String -> (Value -> Parser a) -> Value -> Parser a
796+withEmbeddedJSON _ innerParser (String txt) =
797+ either fail innerParser $ eitherDecode (L.fromStrict $ T.encodeUtf8 txt)
798+ where
799+ eitherDecode = eitherFormatError . eitherDecodeWith jsonEOF ifromJSON
800+ eitherFormatError = either (Left . uncurry formatError) Right
801+withEmbeddedJSON name _ v = prependContext name (typeMismatch "String" v)
802+{-# INLINE withEmbeddedJSON #-}
803+
667804-- | Convert a value from JSON, failing if the types do not match.
668805fromJSON :: (FromJSON a) => Value -> Result a
669806fromJSON = parse parseJSON
@@ -726,7 +863,7 @@ parseFieldMaybe' = (.:!)
726863-- E.g. @'explicitParseField' 'parseJSON1' :: ('FromJSON1' f, 'FromJSON' a) -> 'Object' -> 'Text' -> 'Parser' (f a)@
727864explicitParseField :: (Value -> Parser a) -> Object -> Text -> Parser a
728865explicitParseField p obj key = case H.lookup key obj of
729− Nothing -> fail $ "key " ++ show key ++ " not present"
866+ Nothing -> fail $ "key " ++ show key ++ " not found"
730867 Just v -> p v <?> Key key
731868{-# INLINE explicitParseField #-}
732869
@@ -766,11 +903,47 @@ pmval .!= val = fromMaybe val <$> pmval
766903-- Generic parseJSON
767904-------------------------------------------------------------------------------
768905
906+instance GFromJSON arity V1 where
907+ -- Whereof we cannot format, thereof we cannot parse:
908+ gParseJSON _ _ _ = fail "Attempted to parse empty type"
909+
910+
769911instance OVERLAPPABLE_ (GFromJSON arity a) => GFromJSON arity (M1 i c a) where
770912 -- Meta-information, which is not handled elsewhere, is just added to the
771913 -- parsed value:
772914 gParseJSON opts fargs = fmap M1 . gParseJSON opts fargs
773915
916+-- Information for error messages
917+
918+type TypeName = String
919+type ConName = String
920+
921+-- | Add the name of the type being parsed to a parser's error messages.
922+contextType :: TypeName -> Parser a -> Parser a
923+contextType = prependContext
924+
925+-- | Add the tagKey that will be looked up while building an ADT
926+-- | Produce the error equivalent to
927+-- | Left "Error in $: parsing T failed, expected an object with keys "tag" and
928+-- | "contents", where "tag" i-- |s associated to one of ["Foo", "Bar"],
929+-- | The parser returned error was: could not find key "tag"
930+contextTag :: Text -> [String] -> Parser a -> Parser a
931+contextTag tagKey cnames = prependFailure
932+ ("expected Object with key \"" ++ unpack tagKey ++ "\"" ++
933+ " containing one of " ++ show cnames ++ ", ")
934+
935+-- | Add the name of the constructor being parsed to a parser's error messages.
936+contextCons :: ConName -> TypeName -> Parser a -> Parser a
937+contextCons cname tname = prependContext (showCons cname tname)
938+
939+-- | Render a constructor as @\"MyType(MyConstructor)\"@.
940+showCons :: ConName -> TypeName -> String
941+showCons cname tname = tname ++ "(" ++ cname ++ ")"
942+
943+--------------------------------------------------------------------------------
944+
945+-- Parsing single fields
946+
774947instance (FromJSON a) => GFromJSON arity (K1 i a) where
775948 -- Constant values are decoded using their FromJSON instance:
776949 gParseJSON _opts _ = fmap K1 . parseJSON
@@ -785,339 +958,499 @@ instance (FromJSON1 f) => GFromJSON One (Rec1 f) where
785958 -- FromJSON1 instance:
786959 gParseJSON _opts (From1Args pj pjl) = fmap Rec1 . liftParseJSON pj pjl
787960
788−instance GFromJSON arity U1 where
789− -- Empty constructors are expected to be encoded as an empty array:
790− gParseJSON _opts _ v
791− | isEmptyArray v = pure U1
792− | otherwise = typeMismatch "unit constructor (U1)" v
961+instance (FromJSON1 f, GFromJSON One g) => GFromJSON One (f :.: g) where
962+ -- If an occurrence of the last type parameter is nested inside two
963+ -- composed types, it is decoded by using the outermost type's FromJSON1
964+ -- instance to generically decode the innermost type:
965+ gParseJSON opts fargs =
966+ let gpj = gParseJSON opts fargs in
967+ fmap Comp1 . liftParseJSON gpj (listParser gpj)
793968
969+--------------------------------------------------------------------------------
970+
971+instance (GFromJSON' arity a, Datatype d) => GFromJSON arity (D1 d a) where
972+ -- Meta-information, which is not handled elsewhere, is just added to the
973+ -- parsed value:
974+ gParseJSON opts fargs = fmap M1 . gParseJSON' (tname :* opts :* fargs)
975+ where
976+ tname = moduleName proxy ++ "." ++ datatypeName proxy
977+ proxy = undefined :: M1 _i d _f _p
978+
979+-- | 'GFromJSON', after unwrapping the 'D1' constructor, now carrying the data
980+-- type's name.
981+class GFromJSON' arity f where
982+ gParseJSON' :: TypeName :* Options :* FromArgs arity a
983+ -> Value
984+ -> Parser (f a)
985+
986+-- | Single constructor.
794987instance ( ConsFromJSON arity a
795988 , AllNullary (C1 c a) allNullary
796989 , ParseSum arity (C1 c a) allNullary
797− ) => GFromJSON arity (D1 d (C1 c a)) where
990+ , Constructor c
991+ ) => GFromJSON' arity (C1 c a) where
798992 -- The option 'tagSingleConstructors' determines whether to wrap
799993 -- a single-constructor type.
800− gParseJSON opts fargs
994+ gParseJSON' p@(_ :* opts :* _)
801995 | tagSingleConstructors opts
802− = fmap M1
803− . (unTagged :: Tagged allNullary (Parser (C1 c a p)) -> Parser (C1 c a p))
804− . parseSum opts fargs
805− | otherwise = fmap M1 . fmap M1 . consParseJSON opts fargs
806−
807−instance (ConsFromJSON arity a) => GFromJSON arity (C1 c a) where
808− -- Constructors need to be decoded differently depending on whether they're
809− -- a record or not. This distinction is made by consParseJSON:
810− gParseJSON opts fargs = fmap M1 . consParseJSON opts fargs
811−
812−instance ( FromProduct arity a, FromProduct arity b
813− , ProductSize a, ProductSize b
814− ) => GFromJSON arity (a :*: b) where
815− -- Products are expected to be encoded to an array. Here we check whether we
816− -- got an array of the same size as the product, then parse each of the
817− -- product's elements using parseProduct:
818− gParseJSON opts fargs = withArray "product (:*:)" $ \arr ->
819− let lenArray = V.length arr
820− lenProduct = (unTagged2 :: Tagged2 (a :*: b) Int -> Int)
821− productSize in
822− if lenArray == lenProduct
823− then parseProduct opts fargs arr 0 lenProduct
824− else fail $ "When expecting a product of " ++ show lenProduct ++
825− " values, encountered an Array of " ++ show lenArray ++
826− " elements instead"
827−
828−instance ( AllNullary (a :+: b) allNullary
829− , ParseSum arity (a :+: b) allNullary
830− ) => GFromJSON arity (a :+: b) where
996+ = (unTagged :: Tagged allNullary (Parser (C1 c a p)) -> Parser (C1 c a p))
997+ . parseSum p
998+ | otherwise = fmap M1 . consParseJSON (cname :* p)
999+ where
1000+ cname = conName (undefined :: M1 _i c _f _p)
1001+
1002+-- | Multiple constructors.
1003+instance ( AllNullary (a :+: b) allNullary
1004+ , ParseSum arity (a :+: b) allNullary
1005+ ) => GFromJSON' arity (a :+: b) where
8311006 -- If all constructors of a sum datatype are nullary and the
8321007 -- 'allNullaryToStringTag' option is set they are expected to be
8331008 -- encoded as strings. This distinction is made by 'parseSum':
834− gParseJSON opts fargs =
835− (unTagged :: Tagged allNullary (Parser ((a :+: b) d)) ->
836− Parser ((a :+: b) d))
837− . parseSum opts fargs
838−
839−instance (FromJSON1 f, GFromJSON One g) => GFromJSON One (f :.: g) where
840− -- If an occurrence of the last type parameter is nested inside two
841− -- composed types, it is decoded by using the outermost type's FromJSON1
842− -- instance to generically decode the innermost type:
843− gParseJSON opts fargs =
844− let gpj = gParseJSON opts fargs in
845− fmap Comp1 . liftParseJSON gpj (listParser gpj)
1009+ gParseJSON' p =
1010+ (unTagged :: Tagged allNullary (Parser ((a :+: b) _d)) ->
1011+ Parser ((a :+: b) _d))
1012+ . parseSum p
8461013
8471014--------------------------------------------------------------------------------
8481015
8491016class ParseSum arity f allNullary where
850− parseSum :: Options -> FromArgs arity a
851− -> Value -> Tagged allNullary (Parser (f a))
1017+ parseSum :: TypeName :* Options :* FromArgs arity a
1018+ -> Value
1019+ -> Tagged allNullary (Parser (f a))
8521020
853−instance ( SumFromString f
1021+instance ( ConstructorNames f
1022+ , SumFromString f
8541023 , FromPair arity f
8551024 , FromTaggedObject arity f
8561025 , FromUntaggedValue arity f
8571026 ) => ParseSum arity f True where
858− parseSum opts fargs
859− | allNullaryToStringTag opts = Tagged . parseAllNullarySum opts
860− | otherwise = Tagged . parseNonAllNullarySum opts fargs
1027+ parseSum p@(tname :* opts :* _)
1028+ | allNullaryToStringTag opts = Tagged . parseAllNullarySum tname opts
1029+ | otherwise = Tagged . parseNonAllNullarySum p
8611030
862−instance ( FromPair arity f
1031+instance ( ConstructorNames f
1032+ , FromPair arity f
8631033 , FromTaggedObject arity f
8641034 , FromUntaggedValue arity f
8651035 ) => ParseSum arity f False where
866− parseSum opts fargs = Tagged . parseNonAllNullarySum opts fargs
1036+ parseSum p = Tagged . parseNonAllNullarySum p
8671037
8681038--------------------------------------------------------------------------------
8691039
870−parseAllNullarySum :: SumFromString f => Options -> Value -> Parser (f a)
871−parseAllNullarySum opts = withText "Text" $ \key ->
872− maybe (notFound key) return $
873− parseSumFromString opts key
1040+parseAllNullarySum :: (SumFromString f, ConstructorNames f)
1041+ => TypeName -> Options -> Value -> Parser (f a)
1042+parseAllNullarySum tname opts =
1043+ withText tname $ \tag ->
1044+ maybe (badTag tag) return $
1045+ parseSumFromString modifier tag
1046+ where
1047+ badTag tag = failWithCTags tname modifier $ \cnames ->
1048+ "expected one of the tags " ++ show cnames ++
1049+ ", but found tag " ++ show tag
1050+ modifier = constructorTagModifier opts
1051+
1052+-- | Fail with an informative error message about a mismatched tag.
1053+-- The error message is parameterized by the list of expected tags,
1054+-- to be inferred from the result type of the parser.
1055+failWithCTags
1056+ :: forall f a t. ConstructorNames f
1057+ => TypeName -> (String -> t) -> ([t] -> String) -> Parser (f a)
1058+failWithCTags tname modifier f =
1059+ contextType tname . fail $ f cnames
1060+ where
1061+ cnames = unTagged2 (constructorTags modifier :: Tagged2 f [t])
8741062
8751063class SumFromString f where
876− parseSumFromString :: Options -> Text -> Maybe (f a)
1064+ parseSumFromString :: (String -> String) -> Text -> Maybe (f a)
8771065
8781066instance (SumFromString a, SumFromString b) => SumFromString (a :+: b) where
8791067 parseSumFromString opts key = (L1 <$> parseSumFromString opts key) <|>
8801068 (R1 <$> parseSumFromString opts key)
8811069
8821070instance (Constructor c) => SumFromString (C1 c U1) where
883− parseSumFromString opts key | key == name = Just $ M1 U1
884− | otherwise = Nothing
885− where
886− name = pack $ constructorTagModifier opts $
887− conName (undefined :: t c U1 p)
1071+ parseSumFromString modifier key
1072+ | key == name = Just $ M1 U1
1073+ | otherwise = Nothing
1074+ where
1075+ name = pack $ modifier $ conName (undefined :: M1 _i c _f _p)
8881076
889−--------------------------------------------------------------------------------
1077+-- For genericFromJSONKey
1078+instance SumFromString a => SumFromString (D1 d a) where
1079+ parseSumFromString modifier key = M1 <$> parseSumFromString modifier key
1080+
1081+-- | List of all constructor tags.
1082+constructorTags :: ConstructorNames a => (String -> t) -> Tagged2 a [t]
1083+constructorTags modifier =
1084+ fmap DList.toList (constructorNames' modifier)
1085+
1086+-- | List of all constructor names of an ADT, after a given conversion
1087+-- function. (Better inlining.)
1088+class ConstructorNames a where
1089+ constructorNames' :: (String -> t) -> Tagged2 a (DList.DList t)
1090+
1091+instance (ConstructorNames a, ConstructorNames b) => ConstructorNames (a :+: b) where
1092+ constructorNames' = liftA2 append constructorNames' constructorNames'
1093+ where
1094+ append
1095+ :: Tagged2 a (DList.DList t)
1096+ -> Tagged2 b (DList.DList t)
1097+ -> Tagged2 (a :+: b) (DList.DList t)
1098+ append (Tagged2 xs) (Tagged2 ys) = Tagged2 (DList.append xs ys)
1099+
1100+instance Constructor c => ConstructorNames (C1 c a) where
1101+ constructorNames' f = Tagged2 (pure (f cname))
1102+ where
1103+ cname = conName (undefined :: M1 _i c _f _p)
1104+
1105+-- For genericFromJSONKey
1106+instance ConstructorNames a => ConstructorNames (D1 d a) where
1107+ constructorNames' = retag . constructorNames'
1108+ where
1109+ retag :: Tagged2 a u -> Tagged2 (D1 d a) u
1110+ retag (Tagged2 x) = Tagged2 x
8901111
891−parseNonAllNullarySum :: ( FromPair arity f
1112+--------------------------------------------------------------------------------
1113+parseNonAllNullarySum :: forall f c arity.
1114+ ( FromPair arity f
8921115 , FromTaggedObject arity f
8931116 , FromUntaggedValue arity f
894− ) => Options -> FromArgs arity c
1117+ , ConstructorNames f
1118+ ) => TypeName :* Options :* FromArgs arity c
8951119 -> Value -> Parser (f c)
896−parseNonAllNullarySum opts fargs =
1120+parseNonAllNullarySum p@(tname :* opts :* _) =
8971121 case sumEncoding opts of
8981122 TaggedObject{..} ->
899− withObject "Object" $ \obj -> do
900− tag <- obj .: pack tagFieldName
901− fromMaybe (notFound tag) $
902− parseFromTaggedObject opts fargs contentsFieldName obj tag
1123+ withObject tname $ \obj -> do
1124+ tag <- contextType tname . contextTag tagKey cnames_ $ obj .: tagKey
1125+ fromMaybe (badTag tag <?> Key tagKey) $
1126+ parseFromTaggedObject (tag :* contentsFieldName :* p) obj
1127+ where
1128+ tagKey = pack tagFieldName
1129+ badTag tag = failWith_ $ \cnames ->
1130+ "expected tag field to be one of " ++ show cnames ++
1131+ ", but found tag " ++ show tag
1132+ cnames_ = unTagged2 (constructorTags (constructorTagModifier opts) :: Tagged2 f [String])
9031133
9041134 ObjectWithSingleField ->
905− withObject "Object" $ \obj ->
906− case H.toList obj of
907− [pair@(tag, _)] -> fromMaybe (notFound tag) $
908− parsePair opts fargs pair
909− _ -> fail "Object doesn't have a single field"
1135+ withObject tname $ \obj -> case H.toList obj of
1136+ [(tag, v)] -> maybe (badTag tag) (<?> Key tag) $
1137+ parsePair (tag :* p) v
1138+ _ -> contextType tname . fail $
1139+ "expected an Object with a single pair, but found " ++
1140+ show (H.size obj) ++ " pairs"
1141+ where
1142+ badTag tag = failWith_ $ \cnames ->
1143+ "expected an Object with a single pair where the tag is one of " ++
1144+ show cnames ++ ", but found tag " ++ show tag
9101145
9111146 TwoElemArray ->
912− withArray "Array" $ \arr ->
913− if V.length arr == 2
914− then case V.unsafeIndex arr 0 of
915− String tag -> fromMaybe (notFound tag) $
916− parsePair opts fargs (tag, V.unsafeIndex arr 1)
917− _ -> fail "First element is not a String"
918− else fail "Array doesn't have 2 elements"
1147+ withArray tname $ \arr -> case V.length arr of
1148+ 2 | String tag <- V.unsafeIndex arr 0 ->
1149+ maybe (badTag tag <?> Index 0) (<?> Index 1) $
1150+ parsePair (tag :* p) (V.unsafeIndex arr 1)
1151+ | otherwise ->
1152+ contextType tname $
1153+ fail "tag element is not a String" <?> Index 0
1154+ len -> contextType tname . fail $
1155+ "expected a 2-element Array, but encountered an Array of length " ++
1156+ show len
1157+ where
1158+ badTag tag = failWith_ $ \cnames ->
1159+ "expected tag of the 2-element Array to be one of " ++
1160+ show cnames ++ ", but found tag " ++ show tag
9191161
920− UntaggedValue -> parseUntaggedValue opts fargs
1162+ UntaggedValue -> parseUntaggedValue p
1163+ where
1164+ failWith_ = failWithCTags tname (constructorTagModifier opts)
9211165
9221166--------------------------------------------------------------------------------
9231167
9241168class FromTaggedObject arity f where
925− parseFromTaggedObject :: Options -> FromArgs arity a
926− -> String -> Object
927− -> Text -> Maybe (Parser (f a))
1169+ -- The first two components of the parameter tuple are: the constructor tag
1170+ -- to match against, and the contents field name.
1171+ parseFromTaggedObject
1172+ :: Text :* String :* TypeName :* Options :* FromArgs arity a
1173+ -> Object
1174+ -> Maybe (Parser (f a))
9281175
9291176instance ( FromTaggedObject arity a, FromTaggedObject arity b) =>
9301177 FromTaggedObject arity (a :+: b) where
931− parseFromTaggedObject opts fargs contentsFieldName obj tag =
932− (fmap L1 <$> parseFromTaggedObject opts fargs contentsFieldName obj tag) <|>
933− (fmap R1 <$> parseFromTaggedObject opts fargs contentsFieldName obj tag)
1178+ parseFromTaggedObject p obj =
1179+ (fmap L1 <$> parseFromTaggedObject p obj) <|>
1180+ (fmap R1 <$> parseFromTaggedObject p obj)
9341181
935−instance ( FromTaggedObject' arity f
1182+instance ( IsRecord f isRecord
1183+ , FromTaggedObject' arity f isRecord
9361184 , Constructor c
9371185 ) => FromTaggedObject arity (C1 c f) where
938− parseFromTaggedObject opts fargs contentsFieldName obj tag
939− | tag == name = Just $ M1 <$> parseFromTaggedObject'
940− opts fargs contentsFieldName obj
941− | otherwise = Nothing
942− where
943− name = pack $ constructorTagModifier opts $
944− conName (undefined :: t c f p)
1186+ parseFromTaggedObject (tag :* contentsFieldName :* p@(_ :* opts :* _))
1187+ | tag == tag'
1188+ = Just . fmap M1 .
1189+ (unTagged :: Tagged isRecord (Parser (f a)) -> Parser (f a)) .
1190+ parseFromTaggedObject' (contentsFieldName :* cname :* p)
1191+ | otherwise = const Nothing
1192+ where
1193+ tag' = pack $ constructorTagModifier opts cname
1194+ cname = conName (undefined :: M1 _i c _f _p)
9451195
9461196--------------------------------------------------------------------------------
9471197
948−class FromTaggedObject' arity f where
949− parseFromTaggedObject' :: Options -> FromArgs arity a -> String
950− -> Object -> Parser (f a)
951−
952−class FromTaggedObject'' arity f isRecord where
953− parseFromTaggedObject'' :: Options -> FromArgs arity a -> String
954− -> Object -> Tagged isRecord (Parser (f a))
955−
956−instance ( IsRecord f isRecord
957− , FromTaggedObject'' arity f isRecord
958− ) => FromTaggedObject' arity f where
959− parseFromTaggedObject' opts fargs contentsFieldName =
960− (unTagged :: Tagged isRecord (Parser (f a)) -> Parser (f a)) .
961− parseFromTaggedObject'' opts fargs contentsFieldName
962−
963−instance (FromRecord arity f) => FromTaggedObject'' arity f True where
964− parseFromTaggedObject'' opts fargs _ =
965− Tagged . parseRecord opts fargs Nothing
966−
967−instance (GFromJSON arity f) => FromTaggedObject'' arity f False where
968− parseFromTaggedObject'' opts fargs contentsFieldName = Tagged .
969− (gParseJSON opts fargs <=< (.: pack contentsFieldName))
1198+class FromTaggedObject' arity f isRecord where
1199+ -- The first component of the parameter tuple is the contents field name.
1200+ parseFromTaggedObject'
1201+ :: String :* ConName :* TypeName :* Options :* FromArgs arity a
1202+ -> Object -> Tagged isRecord (Parser (f a))
1203+
1204+instance (RecordFromJSON arity f, FieldNames f) => FromTaggedObject' arity f True where
1205+ -- Records are unpacked in the tagged object
1206+ parseFromTaggedObject' (_ :* p) = Tagged . recordParseJSON (True :* p)
1207+
1208+instance (ConsFromJSON arity f) => FromTaggedObject' arity f False where
1209+ -- Nonnullary nonrecords are encoded in the contents field
1210+ parseFromTaggedObject' p obj = Tagged $ do
1211+ contents <- contextCons cname tname (obj .: key)
1212+ consParseJSON p' contents <?> Key key
1213+ where
1214+ key = pack contentsFieldName
1215+ contentsFieldName :* p'@(cname :* tname :* _) = p
9701216
971−instance OVERLAPPING_ FromTaggedObject'' arity U1 False where
972− parseFromTaggedObject'' _ _ _ _ = Tagged (pure U1)
1217+instance OVERLAPPING_ FromTaggedObject' arity U1 False where
1218+ -- Nullary constructors don't need a contents field
1219+ parseFromTaggedObject' _ _ = Tagged (pure U1)
9731220
9741221--------------------------------------------------------------------------------
9751222
1223+-- | Constructors need to be decoded differently depending on whether they're
1224+-- a record or not. This distinction is made by 'ConsParseJSON'.
9761225class ConsFromJSON arity f where
977− consParseJSON :: Options -> FromArgs arity a
978− -> Value -> Parser (f a)
1226+ consParseJSON
1227+ :: ConName :* TypeName :* Options :* FromArgs arity a
1228+ -> Value -> Parser (f a)
9791229
9801230class ConsFromJSON' arity f isRecord where
981− consParseJSON' :: Options -> FromArgs arity a
982− -> Maybe Text -- ^ A dummy label
983− -- (Nothing to use proper label)
984− -> Value -> Tagged isRecord (Parser (f a))
1231+ consParseJSON'
1232+ :: ConName :* TypeName :* Options :* FromArgs arity a
1233+ -> Value -> Tagged isRecord (Parser (f a))
9851234
9861235instance ( IsRecord f isRecord
9871236 , ConsFromJSON' arity f isRecord
9881237 ) => ConsFromJSON arity f where
989− consParseJSON opts fargs v = let
990− (v2,lab) = case (unwrapUnaryRecords opts,isUnary (undefined :: f a)) of
991− -- use a dummy object with a dummy label
992− (True,True) -> (object [(pack "dummy",v)], Just $ pack "dummy")
993− _ ->(v,Nothing)
994− in (unTagged :: Tagged isRecord (Parser (f a)) -> Parser (f a))
995− $ consParseJSON' opts fargs lab v2
1238+ consParseJSON p =
1239+ (unTagged :: Tagged isRecord (Parser (f a)) -> Parser (f a))
1240+ . consParseJSON' p
9961241
1242+instance OVERLAPPING_
1243+ ( GFromJSON arity a, RecordFromJSON arity (S1 s a)
1244+ ) => ConsFromJSON' arity (S1 s a) True where
1245+ consParseJSON' p@(cname :* tname :* opts :* fargs)
1246+ | unwrapUnaryRecords opts = Tagged . fmap M1 . gParseJSON opts fargs
1247+ | otherwise = Tagged . withObject (showCons cname tname) (recordParseJSON (False :* p))
9971248
998−instance (FromRecord arity f) => ConsFromJSON' arity f True where
999− consParseJSON' opts fargs mlab = Tagged . withObject "record (:*:)"
1000− (parseRecord opts fargs mlab)
1249+instance RecordFromJSON arity f => ConsFromJSON' arity f True where
1250+ consParseJSON' p@(cname :* tname :* _) =
1251+ Tagged . withObject (showCons cname tname) (recordParseJSON (False :* p))
10011252
1002−instance (GFromJSON arity f) => ConsFromJSON' arity f False where
1003− consParseJSON' opts fargs _ = Tagged . gParseJSON opts fargs
1253+instance OVERLAPPING_
1254+ ConsFromJSON' arity U1 False where
1255+ -- Empty constructors are expected to be encoded as an empty array:
1256+ consParseJSON' (cname :* tname :* _) v =
1257+ Tagged . contextCons cname tname $ case v of
1258+ Array a | V.null a -> pure U1
1259+ | otherwise -> fail_ a
1260+ _ -> typeMismatch "Array" v
1261+ where
1262+ fail_ a = fail $
1263+ "expected an empty Array, but encountered an Array of length " ++
1264+ show (V.length a)
1265+
1266+instance OVERLAPPING_
1267+ GFromJSON arity f => ConsFromJSON' arity (S1 s f) False where
1268+ consParseJSON' (_ :* _ :* opts :* fargs) =
1269+ Tagged . fmap M1 . gParseJSON opts fargs
1270+
1271+instance (ProductFromJSON arity f, ProductSize f
1272+ ) => ConsFromJSON' arity f False where
1273+ consParseJSON' p = Tagged . productParseJSON0 p
10041274
10051275--------------------------------------------------------------------------------
10061276
1007−class FromRecord arity f where
1008− parseRecord :: Options -> FromArgs arity a
1009− -> Maybe Text -- ^ A dummy label
1010− -- (Nothing to use proper label)
1011− -> Object -> Parser (f a)
1277+class FieldNames f where
1278+ fieldNames :: f a -> [Text] -> [Text]
10121279
1013−instance ( FromRecord arity a
1014− , FromRecord arity b
1015− ) => FromRecord arity (a :*: b) where
1016− parseRecord opts fargs _ obj =
1017− (:*:) <$> parseRecord opts fargs Nothing obj
1018− <*> parseRecord opts fargs Nothing obj
1280+instance (FieldNames a, FieldNames b) => FieldNames (a :*: b) where
1281+ fieldNames _ =
1282+ fieldNames (undefined :: a x) .
1283+ fieldNames (undefined :: b y)
10191284
1020−instance OVERLAPPABLE_ (Selector s, GFromJSON arity a) =>
1021− FromRecord arity (S1 s a) where
1022− parseRecord opts fargs lab =
1023− (<?> Key label) . gParseJSON opts fargs <=< (.: label)
1285+instance (Selector s) => FieldNames (S1 s f) where
1286+ fieldNames _ = (pack (selName (undefined :: M1 _i s _f _p)) :)
1287+
1288+class RecordFromJSON arity f where
1289+ recordParseJSON
1290+ :: Bool :* ConName :* TypeName :* Options :* FromArgs arity a
1291+ -> Object -> Parser (f a)
1292+
1293+instance ( FieldNames f
1294+ , RecordFromJSON' arity f
1295+ ) => RecordFromJSON arity f where
1296+ recordParseJSON (fromTaggedSum :* p@(cname :* tname :* opts :* _)) =
1297+ \obj -> checkUnknown obj >> recordParseJSON' p obj
10241298 where
1025− label = fromMaybe defLabel lab
1026− defLabel = pack . fieldLabelModifier opts $
1027− selName (undefined :: t s a p)
1299+ knownFields :: H.HashMap Text ()
1300+ knownFields = H.fromList $ map (,()) $
1301+ fieldNames (undefined :: f a)
1302+ [pack (tagFieldName (sumEncoding opts)) | fromTaggedSum]
1303+ checkUnknown =
1304+ if not (rejectUnknownFields opts)
1305+ then \_ -> return ()
1306+ else \obj -> case H.keys (H.difference obj knownFields) of
1307+ [] -> return ()
1308+ unknownFields -> contextCons cname tname $
1309+ fail ("unknown fields: " ++ show unknownFields)
1310+
1311+class RecordFromJSON' arity f where
1312+ recordParseJSON'
1313+ :: ConName :* TypeName :* Options :* FromArgs arity a
1314+ -> Object -> Parser (f a)
1315+
1316+instance ( RecordFromJSON' arity a
1317+ , RecordFromJSON' arity b
1318+ ) => RecordFromJSON' arity (a :*: b) where
1319+ recordParseJSON' p obj =
1320+ (:*:) <$> recordParseJSON' p obj
1321+ <*> recordParseJSON' p obj
1322+
1323+instance OVERLAPPABLE_ (Selector s, GFromJSON arity a) =>
1324+ RecordFromJSON' arity (S1 s a) where
1325+ recordParseJSON' (cname :* tname :* opts :* fargs) obj = do
1326+ fv <- contextCons cname tname (obj .: label)
1327+ M1 <$> gParseJSON opts fargs fv <?> Key label
1328+ where
1329+ label = pack $ fieldLabelModifier opts sname
1330+ sname = selName (undefined :: M1 _i s _f _p)
10281331
10291332instance INCOHERENT_ (Selector s, FromJSON a) =>
1030− FromRecord arity (S1 s (K1 i (Maybe a))) where
1031− parseRecord _ _ (Just lab) obj = (M1 . K1) <$> obj .:? lab
1032− parseRecord opts _ Nothing obj = (M1 . K1) <$> obj .:? pack label
1033− where
1034− label = fieldLabelModifier opts $
1035− selName (undefined :: t s (K1 i (Maybe a)) p)
1333+ RecordFromJSON' arity (S1 s (K1 i (Maybe a))) where
1334+ recordParseJSON' (_ :* _ :* opts :* _) obj = M1 . K1 <$> obj .:? pack label
1335+ where
1336+ label = fieldLabelModifier opts sname
1337+ sname = selName (undefined :: M1 _i s _f _p)
1338+
1339+-- Parse an Option like a Maybe.
1340+instance INCOHERENT_ (Selector s, FromJSON a) =>
1341+ RecordFromJSON' arity (S1 s (K1 i (Semigroup.Option a))) where
1342+ recordParseJSON' p obj = wrap <$> recordParseJSON' p obj
1343+ where
1344+ wrap :: S1 s (K1 i (Maybe a)) p -> S1 s (K1 i (Semigroup.Option a)) p
1345+ wrap (M1 (K1 a)) = M1 (K1 (Semigroup.Option a))
10361346
10371347--------------------------------------------------------------------------------
10381348
1039−class FromProduct arity f where
1040− parseProduct :: Options -> FromArgs arity a
1349+productParseJSON0
1350+ :: forall f arity a. (ProductFromJSON arity f, ProductSize f)
1351+ => ConName :* TypeName :* Options :* FromArgs arity a
1352+ -> Value -> Parser (f a)
1353+ -- Products are expected to be encoded to an array. Here we check whether we
1354+ -- got an array of the same size as the product, then parse each of the
1355+ -- product's elements using productParseJSON:
1356+productParseJSON0 p@(cname :* tname :* _ :* _) =
1357+ withArray (showCons cname tname) $ \arr ->
1358+ let lenArray = V.length arr
1359+ lenProduct = (unTagged2 :: Tagged2 f Int -> Int)
1360+ productSize in
1361+ if lenArray == lenProduct
1362+ then productParseJSON p arr 0 lenProduct
1363+ else contextCons cname tname $
1364+ fail $ "expected an Array of length " ++ show lenProduct ++
1365+ ", but encountered an Array of length " ++ show lenArray
1366+
1367+--
1368+
1369+class ProductFromJSON arity f where
1370+ productParseJSON :: ConName :* TypeName :* Options :* FromArgs arity a
10411371 -> Array -> Int -> Int
10421372 -> Parser (f a)
10431373
1044−instance ( FromProduct arity a
1045− , FromProduct arity b
1046− ) => FromProduct arity (a :*: b) where
1047− parseProduct opts fargs arr ix len =
1048− (:*:) <$> parseProduct opts fargs arr ix lenL
1049− <*> parseProduct opts fargs arr ixR lenR
1374+instance ( ProductFromJSON arity a
1375+ , ProductFromJSON arity b
1376+ ) => ProductFromJSON arity (a :*: b) where
1377+ productParseJSON p arr ix len =
1378+ (:*:) <$> productParseJSON p arr ix lenL
1379+ <*> productParseJSON p arr ixR lenR
10501380 where
10511381 lenL = len `unsafeShiftR` 1
10521382 ixR = ix + lenL
10531383 lenR = len - lenL
10541384
1055−instance (GFromJSON arity a) => FromProduct arity (S1 s a) where
1056− parseProduct opts fargs arr ix _ =
1057− gParseJSON opts fargs $ V.unsafeIndex arr ix
1385+instance (GFromJSON arity a) => ProductFromJSON arity (S1 s a) where
1386+ productParseJSON (_ :* _ :* opts :* fargs) arr ix _ =
1387+ M1 <$> gParseJSON opts fargs (V.unsafeIndex arr ix) <?> Index ix
10581388
10591389--------------------------------------------------------------------------------
10601390
10611391class FromPair arity f where
1062− parsePair :: Options -> FromArgs arity a
1063− -> Pair -> Maybe (Parser (f a))
1392+ -- The first component of the parameter tuple is the tag to match.
1393+ parsePair :: Text :* TypeName :* Options :* FromArgs arity a
1394+ -> Value
1395+ -> Maybe (Parser (f a))
10641396
10651397instance ( FromPair arity a
10661398 , FromPair arity b
10671399 ) => FromPair arity (a :+: b) where
1068− parsePair opts fargs pair = (fmap L1 <$> parsePair opts fargs pair) <|>
1069− (fmap R1 <$> parsePair opts fargs pair)
1400+ parsePair p pair =
1401+ (fmap L1 <$> parsePair p pair) <|>
1402+ (fmap R1 <$> parsePair p pair)
10701403
10711404instance ( Constructor c
1072− , GFromJSON arity a
10731405 , ConsFromJSON arity a
10741406 ) => FromPair arity (C1 c a) where
1075− parsePair opts fargs (tag, value)
1076− | tag == tag' = Just $ gParseJSON opts fargs value
1407+ parsePair (tag :* p@(_ :* opts :* _)) v
1408+ | tag == tag' = Just $ M1 <$> consParseJSON (cname :* p) v
10771409 | otherwise = Nothing
1078− where
1079− tag' = pack $ constructorTagModifier opts $
1080− conName (undefined :: t c a p)
1410+ where
1411+ tag' = pack $ constructorTagModifier opts cname
1412+ cname = conName (undefined :: M1 _i c _a _p)
10811413
10821414--------------------------------------------------------------------------------
10831415
10841416class FromUntaggedValue arity f where
1085− parseUntaggedValue :: Options -> FromArgs arity a
1086− -> Value -> Parser (f a)
1417+ parseUntaggedValue :: TypeName :* Options :* FromArgs arity a
1418+ -> Value
1419+ -> Parser (f a)
10871420
10881421instance
10891422 ( FromUntaggedValue arity a
10901423 , FromUntaggedValue arity b
10911424 ) => FromUntaggedValue arity (a :+: b)
10921425 where
1093− parseUntaggedValue opts fargs value =
1094− L1 <$> parseUntaggedValue opts fargs value <|>
1095− R1 <$> parseUntaggedValue opts fargs value
1426+ parseUntaggedValue p value =
1427+ L1 <$> parseUntaggedValue p value <|>
1428+ R1 <$> parseUntaggedValue p value
10961429
10971430instance OVERLAPPABLE_
1098− ( GFromJSON arity a
1099− , ConsFromJSON arity a
1431+ ( ConsFromJSON arity a
1432+ , Constructor c
11001433 ) => FromUntaggedValue arity (C1 c a)
11011434 where
1102− parseUntaggedValue = gParseJSON
1435+ parseUntaggedValue p = fmap M1 . consParseJSON (cname :* p)
1436+ where
1437+ cname = conName (undefined :: M1 _i c _f _p)
11031438
11041439instance OVERLAPPING_
11051440 ( Constructor c )
11061441 => FromUntaggedValue arity (C1 c U1)
11071442 where
1108− parseUntaggedValue opts _ (String s)
1109− | s == pack (constructorTagModifier opts (conName (undefined :: t c U1 p))) =
1110− pure $ M1 U1
1111− | otherwise =
1112− fail $ "Invalid tag: " ++ unpack s
1113− parseUntaggedValue _ _ v = typeMismatch (conName (undefined :: t c U1 p)) v
1114−
1115−
1116−--------------------------------------------------------------------------------
1117−
1118−notFound :: Text -> Parser a
1119−notFound key = fail $ "The key \"" ++ unpack key ++ "\" was not found"
1120−{-# INLINE notFound #-}
1443+ parseUntaggedValue (tname :* opts :* _) v =
1444+ contextCons cname tname $ case v of
1445+ String tag
1446+ | tag == tag' -> pure $ M1 U1
1447+ | otherwise -> fail_ tag
1448+ _ -> typeMismatch "String" v
1449+ where
1450+ tag' = pack $ constructorTagModifier opts cname
1451+ cname = conName (undefined :: M1 _i c _f _p)
1452+ fail_ tag = fail $
1453+ "expected tag " ++ show tag' ++ ", but found tag " ++ show tag
11211454
11221455-------------------------------------------------------------------------------
11231456-- Instances
@@ -1175,17 +1508,20 @@ instance (FromJSON a, FromJSON b) => FromJSON (Either a b) where
11751508 parseJSON = parseJSON2
11761509 {-# INLINE parseJSON #-}
11771510
1178−
1511+instance FromJSON Void where
1512+ parseJSON _ = fail "Cannot parse Void"
1513+ {-# INLINE parseJSON #-}
11791514
11801515instance FromJSON Bool where
1181− parseJSON = withBool "Bool" pure
1516+ parseJSON (Bool b) = pure b
1517+ parseJSON v = typeMismatch "Bool" v
11821518 {-# INLINE parseJSON #-}
11831519
11841520instance FromJSONKey Bool where
11851521 fromJSONKey = FromJSONKeyTextParser $ \t -> case t of
11861522 "true" -> pure True
11871523 "false" -> pure False
1188− _ -> fail $ "Cannot parse key into Bool: " ++ T.unpack t
1524+ _ -> fail $ "cannot parse key " ++ show t ++ " into Bool"
11891525
11901526instance FromJSON Ordering where
11911527 parseJSON = withText "Ordering" $ \s ->
@@ -1193,25 +1529,30 @@ instance FromJSON Ordering where
11931529 "LT" -> return LT
11941530 "EQ" -> return EQ
11951531 "GT" -> return GT
1196− _ -> fail "Parsing Ordering value failed: expected \"LT\", \"EQ\", or \"GT\""
1532+ _ -> fail $ "parsing Ordering failed, unexpected " ++ show s ++
1533+ " (expected \"LT\", \"EQ\", or \"GT\")"
11971534
11981535instance FromJSON () where
11991536 parseJSON = withArray "()" $ \v ->
12001537 if V.null v
12011538 then pure ()
1202− else fail "Expected an empty array"
1539+ else prependContext "()" $ fail "expected an empty array"
12031540 {-# INLINE parseJSON #-}
12041541
12051542instance FromJSON Char where
1206− parseJSON = withText "Char" $ \t ->
1207− if T.compareLength t 1 == EQ
1208− then pure $ T.head t
1209− else fail "Expected a string of length 1"
1543+ parseJSON = withText "Char" parseChar
12101544 {-# INLINE parseJSON #-}
12111545
1212− parseJSONList = withText "String" $ pure . T.unpack
1546+ parseJSONList (String s) = pure (T.unpack s)
1547+ parseJSONList v = typeMismatch "String" v
12131548 {-# INLINE parseJSONList #-}
12141549
1550+parseChar :: Text -> Parser Char
1551+parseChar t =
1552+ if T.compareLength t 1 == EQ
1553+ then pure $ T.head t
1554+ else prependContext "Char" $ fail "expected a string of length 1"
1555+
12151556instance FromJSON Double where
12161557 parseJSON = parseRealFloat "Double"
12171558 {-# INLINE parseJSON #-}
@@ -1223,12 +1564,6 @@ instance FromJSONKey Double where
12231564 "-Infinity" -> pure (negate 1/0)
12241565 _ -> Scientific.toRealFloat <$> parseScientificText t
12251566
1226−instance FromJSON Number where
1227− parseJSON (Number s) = pure $ scientificToNumber s
1228− parseJSON Null = pure (D (0/0))
1229− parseJSON v = typeMismatch "Number" v
1230− {-# INLINE parseJSON #-}
1231−
12321567instance FromJSON Float where
12331568 parseJSON = parseRealFloat "Float"
12341569 {-# INLINE parseJSON #-}
@@ -1241,17 +1576,30 @@ instance FromJSONKey Float where
12411576 _ -> Scientific.toRealFloat <$> parseScientificText t
12421577
12431578instance (FromJSON a, Integral a) => FromJSON (Ratio a) where
1244− parseJSON = withObject "Rational" $ \obj ->
1245− (%) <$> obj .: "numerator"
1246− <*> obj .: "denominator"
1247− {-# INLINE parseJSON #-}
1248−
1249−-- | /WARNING:/ Only parse fixed-precision numbers from trusted input
1250−-- since an attacker could easily fill up the memory of the target
1251−-- system by specifying a scientific number with a big exponent like
1252−-- @1e1000000000@.
1579+ parseJSON (Number x)
1580+ | exp10 <= 1024
1581+ , exp10 >= -1024 = return $! realToFrac x
1582+ | otherwise = prependContext "Ratio" $ fail msg
1583+ where
1584+ exp10 = base10Exponent x
1585+ msg = "found a number with exponent " ++ show exp10
1586+ ++ ", but it must not be greater than 1024 or less than -1024"
1587+ parseJSON o = objParser o
1588+ where
1589+ objParser = withObject "Rational" $ \obj -> do
1590+ numerator <- obj .: "numerator"
1591+ denominator <- obj .: "denominator"
1592+ if denominator == 0
1593+ then fail "Ratio denominator was 0"
1594+ else pure $ numerator % denominator
1595+ {-# INLINE parseJSON #-}
1596+
1597+-- | This instance includes a bounds check to prevent maliciously
1598+-- large inputs to fill up the memory of the target system. You can
1599+-- newtype 'Scientific' and provide your own instance using
1600+-- 'withScientific' if you want to allow larger inputs.
12531601instance HasResolution a => FromJSON (Fixed a) where
1254− parseJSON = withScientific "Fixed" $ pure . realToFrac
1602+ parseJSON = prependContext "Fixed" . withBoundedScientific' (pure . realToFrac)
12551603 {-# INLINE parseJSON #-}
12561604
12571605instance FromJSON Int where
@@ -1261,10 +1609,10 @@ instance FromJSON Int where
12611609instance FromJSONKey Int where
12621610 fromJSONKey = FromJSONKeyTextParser $ parseBoundedIntegralText "Int"
12631611
1264−-- | /WARNING:/ Only parse Integers from trusted input since an
1265−-- attacker could easily fill up the memory of the target system by
1266−-- specifying a scientific number with a big exponent like
1267−-- @1e1000000000@.
1612+-- | This instance includes a bounds check to prevent maliciously
1613+-- large inputs to fill up the memory of the target system. You can
1614+-- newtype 'Scientific' and provide your own instance using
1615+-- 'withScientific' if you want to allow larger inputs.
12681616instance FromJSON Integer where
12691617 parseJSON = parseIntegral "Integer"
12701618 {-# INLINE parseJSON #-}
@@ -1274,19 +1622,20 @@ instance FromJSONKey Integer where
12741622
12751623instance FromJSON Natural where
12761624 parseJSON value = do
1277− integer :: Integer <- parseIntegral "Natural" value
1278− if integer < 0 then
1279− fail $ "expected Natural, encountered negative number " <> show integer
1280− else
1281− pure $ fromIntegral integer
1625+ integer <- parseIntegral "Natural" value
1626+ parseNatural integer
12821627
12831628instance FromJSONKey Natural where
12841629 fromJSONKey = FromJSONKeyTextParser $ \text -> do
1285− integer :: Integer <- parseIntegralText "Natural" text
1286− if integer < 0 then
1287− fail $ "expected Natural, encountered negative number " <> show integer
1288− else
1289− pure $ fromIntegral integer
1630+ integer <- parseIntegralText "Natural" text
1631+ parseNatural integer
1632+
1633+parseNatural :: Integer -> Parser Natural
1634+parseNatural integer =
1635+ if integer < 0 then
1636+ fail $ "parsing Natural failed, unexpected negative number " <> show integer
1637+ else
1638+ pure $ fromIntegral integer
12901639
12911640instance FromJSON Int8 where
12921641 parseJSON = parseBoundedIntegral "Int8"
@@ -1351,6 +1700,9 @@ instance FromJSON Word64 where
13511700instance FromJSONKey Word64 where
13521701 fromJSONKey = FromJSONKeyTextParser $ parseBoundedIntegralText "Word64"
13531702
1703+instance FromJSON CTime where
1704+ parseJSON = fmap CTime . parseJSON
1705+ {-# INLINE parseJSON #-}
13541706
13551707instance FromJSON Text where
13561708 parseJSON = withText "Text" pure
@@ -1380,17 +1732,17 @@ parseVersionText = go . readP_to_S parseVersion . unpack
13801732 where
13811733 go [(v,[])] = return v
13821734 go (_ : xs) = go xs
1383− go _ = fail "could not parse Version"
1735+ go _ = fail "parsing Version failed"
13841736
13851737-------------------------------------------------------------------------------
13861738-- semigroups NonEmpty
13871739-------------------------------------------------------------------------------
13881740
13891741instance FromJSON1 NonEmpty where
1390− liftParseJSON p _ = withArray "NonEmpty a" $
1742+ liftParseJSON p _ = withArray "NonEmpty" $
13911743 (>>= ne) . Tr.sequence . zipWith (parseIndexedJSON p) [0..] . V.toList
13921744 where
1393− ne [] = fail "Expected a NonEmpty but got an empty list"
1745+ ne [] = fail "parsing NonEmpty failed, unexpected empty list"
13941746 ne (x:xs) = pure (x :| xs)
13951747 {-# INLINE liftParseJSON #-}
13961748
@@ -1411,7 +1763,7 @@ instance FromJSON Scientific where
14111763-------------------------------------------------------------------------------
14121764
14131765instance FromJSON1 DList.DList where
1414− liftParseJSON p _ = withArray "DList a" $
1766+ liftParseJSON p _ = withArray "DList" $
14151767 fmap DList.fromList .
14161768 Tr.sequence . zipWith (parseIndexedJSON p) [0..] . V.toList
14171769 {-# INLINE liftParseJSON #-}
@@ -1488,7 +1840,7 @@ instance (FromJSON1 f, FromJSON1 g) => FromJSON1 (Sum f g) where
14881840 inr = "InR"
14891841
14901842 liftParseJSON _ _ _ = fail $
1491− "expected an object with a single property " ++
1843+ "parsing Sum failed, expected an object with a single property " ++
14921844 "where the property key should be either " ++
14931845 "\"InL\" or \"InR\""
14941846 {-# INLINE liftParseJSON #-}
@@ -1502,7 +1854,7 @@ instance (FromJSON1 f, FromJSON1 g, FromJSON a) => FromJSON (Sum f g a) where
15021854-------------------------------------------------------------------------------
15031855
15041856instance FromJSON1 Seq.Seq where
1505− liftParseJSON p _ = withArray "Seq a" $
1857+ liftParseJSON p _ = withArray "Seq" $
15061858 fmap Seq.fromList .
15071859 Tr.sequence . zipWith (parseIndexedJSON p) [0..] . V.toList
15081860 {-# INLINE liftParseJSON #-}
@@ -1536,13 +1888,13 @@ instance FromJSON a => FromJSON (IntMap.IntMap a) where
15361888
15371889instance (FromJSONKey k, Ord k) => FromJSON1 (M.Map k) where
15381890 liftParseJSON p _ = case fromJSONKey of
1539− FromJSONKeyCoerce _-> withObject "Map k v" $
1891+ FromJSONKeyCoerce _ -> withObject "Map" $
15401892 fmap (H.foldrWithKey (M.insert . unsafeCoerce) M.empty) . H.traverseWithKey (\k v -> p v <?> Key k)
1541− FromJSONKeyText f -> withObject "Map k v" $
1893+ FromJSONKeyText f -> withObject "Map" $
15421894 fmap (H.foldrWithKey (M.insert . f) M.empty) . H.traverseWithKey (\k v -> p v <?> Key k)
1543− FromJSONKeyTextParser f -> withObject "Map k v" $
1895+ FromJSONKeyTextParser f -> withObject "Map" $
15441896 H.foldrWithKey (\k v m -> M.insert <$> f k <?> Key k <*> p v <?> Key k <*> m) (pure M.empty)
1545− FromJSONKeyValue f -> withArray "Map k v" $ \arr ->
1897+ FromJSONKeyValue f -> withArray "Map" $ \arr ->
15461898 fmap M.fromList . Tr.sequence .
15471899 zipWith (parseIndexedJSONPair f p) [0..] . V.toList $ arr
15481900 {-# INLINE liftParseJSON #-}
@@ -1570,18 +1922,18 @@ instance (FromJSON v) => FromJSON (Tree.Tree v) where
15701922
15711923instance FromJSON UUID.UUID where
15721924 parseJSON = withText "UUID" $
1573− maybe (fail "Invalid UUID") pure . UUID.fromText
1925+ maybe (fail "invalid UUID") pure . UUID.fromText
15741926
15751927instance FromJSONKey UUID.UUID where
15761928 fromJSONKey = FromJSONKeyTextParser $
1577− maybe (fail "Invalid UUID") pure . UUID.fromText
1929+ maybe (fail "invalid UUID") pure . UUID.fromText
15781930
15791931-------------------------------------------------------------------------------
15801932-- vector
15811933-------------------------------------------------------------------------------
15821934
15831935instance FromJSON1 Vector where
1584− liftParseJSON p _ = withArray "Vector a" $
1936+ liftParseJSON p _ = withArray "Vector" $
15851937 V.mapM (uncurry $ parseIndexedJSON p) . V.indexed
15861938 {-# INLINE liftParseJSON #-}
15871939
@@ -1595,14 +1947,14 @@ vectorParseJSON s = withArray s $ fmap V.convert . V.mapM (uncurry $ parseIndexe
15951947{-# INLINE vectorParseJSON #-}
15961948
15971949instance (Storable a, FromJSON a) => FromJSON (VS.Vector a) where
1598− parseJSON = vectorParseJSON "Data.Vector.Storable.Vector a"
1950+ parseJSON = vectorParseJSON "Data.Vector.Storable.Vector"
15991951
16001952instance (VP.Prim a, FromJSON a) => FromJSON (VP.Vector a) where
1601− parseJSON = vectorParseJSON "Data.Vector.Primitive.Vector a"
1953+ parseJSON = vectorParseJSON "Data.Vector.Primitive.Vector"
16021954 {-# INLINE parseJSON #-}
16031955
16041956instance (VG.Vector VU.Vector a, FromJSON a) => FromJSON (VU.Vector a) where
1605− parseJSON = vectorParseJSON "Data.Vector.Unboxed.Vector a"
1957+ parseJSON = vectorParseJSON "Data.Vector.Unboxed.Vector"
16061958 {-# INLINE parseJSON #-}
16071959
16081960-------------------------------------------------------------------------------
@@ -1616,13 +1968,13 @@ instance (Eq a, Hashable a, FromJSON a) => FromJSON (HashSet.HashSet a) where
16161968
16171969instance (FromJSONKey k, Eq k, Hashable k) => FromJSON1 (H.HashMap k) where
16181970 liftParseJSON p _ = case fromJSONKey of
1619− FromJSONKeyCoerce _ -> withObject "HashMap ~Text v" $
1971+ FromJSONKeyCoerce _ -> withObject "HashMap ~Text" $
16201972 uc . H.traverseWithKey (\k v -> p v <?> Key k)
1621− FromJSONKeyText f -> withObject "HashMap k v" $
1973+ FromJSONKeyText f -> withObject "HashMap" $
16221974 fmap (mapKey f) . H.traverseWithKey (\k v -> p v <?> Key k)
1623− FromJSONKeyTextParser f -> withObject "HashMap k v" $
1975+ FromJSONKeyTextParser f -> withObject "HashMap" $
16241976 H.foldrWithKey (\k v m -> H.insert <$> f k <?> Key k <*> p v <?> Key k <*> m) (pure H.empty)
1625− FromJSONKeyValue f -> withArray "Map k v" $ \arr ->
1977+ FromJSONKeyValue f -> withArray "Map" $ \arr ->
16261978 fmap H.fromList . Tr.sequence .
16271979 zipWith (parseIndexedJSONPair f p) [0..] . V.toList $ arr
16281980 where
@@ -1645,11 +1997,33 @@ instance FromJSON DotNetTime where
16451997 parseJSON = withText "DotNetTime" $ \t ->
16461998 let (s,m) = T.splitAt (T.length t - 5) t
16471999 t' = T.concat [s,".",m]
1648− in case parseTime defaultTimeLocale "/Date(%s%Q)/" (unpack t') of
2000+ in case parseTimeM True defaultTimeLocale "/Date(%s%Q)/" (unpack t') of
16492001 Just d -> pure (DotNetTime d)
16502002 _ -> fail "could not parse .NET time"
16512003 {-# INLINE parseJSON #-}
16522004
2005+-------------------------------------------------------------------------------
2006+-- primitive
2007+-------------------------------------------------------------------------------
2008+
2009+instance FromJSON a => FromJSON (PM.Array a) where
2010+ -- note: we could do better than this if vector exposed the data
2011+ -- constructor in Data.Vector.
2012+ parseJSON = fmap Exts.fromList . parseJSON
2013+
2014+instance FromJSON a => FromJSON (PM.SmallArray a) where
2015+ parseJSON = fmap Exts.fromList . parseJSON
2016+
2017+#if MIN_VERSION_primitive(0,6,4)
2018+instance (PM.Prim a,FromJSON a) => FromJSON (PM.PrimArray a) where
2019+ parseJSON = fmap Exts.fromList . parseJSON
2020+
2021+#if !MIN_VERSION_primitive(0,7,0)
2022+instance (PM.PrimUnlifted a,FromJSON a) => FromJSON (PM.UnliftedArray a) where
2023+ parseJSON = fmap Exts.fromList . parseJSON
2024+#endif
2025+#endif
2026+
16532027-------------------------------------------------------------------------------
16542028-- time
16552029-------------------------------------------------------------------------------
@@ -1700,22 +2074,56 @@ instance FromJSONKey UTCTime where
17002074 fromJSONKey = FromJSONKeyTextParser (Time.run Time.utcTime)
17012075
17022076
1703−-- | /WARNING:/ Only parse lengths of time from trusted input
1704−-- since an attacker could easily fill up the memory of the target
1705−-- system by specifying a scientific number with a big exponent like
1706−-- @1e1000000000@.
2077+-- | This instance includes a bounds check to prevent maliciously
2078+-- large inputs to fill up the memory of the target system. You can
2079+-- newtype 'Scientific' and provide your own instance using
2080+-- 'withScientific' if you want to allow larger inputs.
17072081instance FromJSON NominalDiffTime where
1708− parseJSON = withScientific "NominalDiffTime" $ pure . realToFrac
2082+ parseJSON = withBoundedScientific "NominalDiffTime" $ pure . realToFrac
17092083 {-# INLINE parseJSON #-}
17102084
17112085
1712−-- | /WARNING:/ Only parse lengths of time from trusted input
1713−-- since an attacker could easily fill up the memory of the target
1714−-- system by specifying a scientific number with a big exponent like
1715−-- @1e1000000000@.
2086+-- | This instance includes a bounds check to prevent maliciously
2087+-- large inputs to fill up the memory of the target system. You can
2088+-- newtype 'Scientific' and provide your own instance using
2089+-- 'withScientific' if you want to allow larger inputs.
17162090instance FromJSON DiffTime where
1717− parseJSON = withScientific "DiffTime" $ pure . realToFrac
1718− {-# INLINE parseJSON #-}
2091+ parseJSON = withBoundedScientific "DiffTime" $ pure . realToFrac
2092+ {-# INLINE parseJSON #-}
2093+
2094+instance FromJSON SystemTime where
2095+ parseJSON v = prependContext "SystemTime" $ do
2096+ n <- parseJSON v
2097+ let n' = floor (n * fromInteger (resolution n) :: Nano)
2098+ let (secs, nano) = n' `divMod` resolution n
2099+ return (MkSystemTime (fromInteger secs) (fromInteger nano))
2100+
2101+instance FromJSON CalendarDiffTime where
2102+ parseJSON = withObject "CalendarDiffTime" $ \obj -> CalendarDiffTime
2103+ <$> obj .: "months"
2104+ <*> obj .: "time"
2105+
2106+instance FromJSON CalendarDiffDays where
2107+ parseJSON = withObject "CalendarDiffDays" $ \obj -> CalendarDiffDays
2108+ <$> obj .: "months"
2109+ <*> obj .: "days"
2110+
2111+instance FromJSON DayOfWeek where
2112+ parseJSON = withText "DaysOfWeek" parseDayOfWeek
2113+
2114+parseDayOfWeek :: T.Text -> Parser DayOfWeek
2115+parseDayOfWeek t = case T.toLower t of
2116+ "monday" -> return Monday
2117+ "tuesday" -> return Tuesday
2118+ "wednesday" -> return Wednesday
2119+ "thursday" -> return Thursday
2120+ "friday" -> return Friday
2121+ "saturday" -> return Saturday
2122+ "sunday" -> return Sunday
2123+ _ -> fail "Invalid week day"
2124+
2125+instance FromJSONKey DayOfWeek where
2126+ fromJSONKey = FromJSONKeyTextParser parseDayOfWeek
17192127
17202128-------------------------------------------------------------------------------
17212129-- base Monoid/Semigroup
@@ -1837,14 +2245,15 @@ instance FromJSON a => FromJSON (Semigroup.Option a) where
18372245
18382246instance FromJSON1 Proxy where
18392247 {-# INLINE liftParseJSON #-}
1840− liftParseJSON _ _ Null = pure Proxy
1841− liftParseJSON _ _ v = typeMismatch "Proxy" v
2248+ liftParseJSON _ _ = fromNull "Proxy" Proxy
18422249
18432250instance FromJSON (Proxy a) where
18442251 {-# INLINE parseJSON #-}
1845− parseJSON Null = pure Proxy
1846− parseJSON v = typeMismatch "Proxy" v
2252+ parseJSON = fromNull "Proxy" Proxy
18472253
2254+fromNull :: String -> a -> Value -> Parser a
2255+fromNull _ a Null = pure a
2256+fromNull c _ v = prependContext c (typeMismatch "Null" v)
18482257
18492258instance FromJSON2 Tagged where
18502259 liftParseJSON2 _ _ p _ = fmap Tagged . p
@@ -1871,10 +2280,7 @@ instance (FromJSON a, FromJSON b, FromJSON c) => FromJSONKey (a,b,c)
18712280instance (FromJSON a, FromJSON b, FromJSON c, FromJSON d) => FromJSONKey (a,b,c,d)
18722281
18732282instance FromJSONKey Char where
1874− fromJSONKey = FromJSONKeyTextParser $ \t ->
1875− if T.length t == 1
1876− then return (T.index t 0)
1877− else typeMismatch "Expected Char but String didn't contain exactly one character" (String t)
2283+ fromJSONKey = FromJSONKeyTextParser parseChar
18782284 fromJSONKeyList = FromJSONKeyText T.unpack
18792285
18802286instance (FromJSONKey a, FromJSON a) => FromJSONKey [a] where