Built-in Natural literals in Core
[ghc.git] / libraries / base / Data / Data.hs
1 {-# LANGUAGE BangPatterns #-}
2 {-# LANGUAGE DeriveDataTypeable #-}
3 {-# LANGUAGE FlexibleContexts #-}
4 {-# LANGUAGE FlexibleInstances #-}
5 {-# LANGUAGE GADTs #-}
6 {-# LANGUAGE NoImplicitPrelude #-}
7 {-# LANGUAGE DataKinds #-}
8 {-# LANGUAGE PolyKinds #-}
9 {-# LANGUAGE RankNTypes #-}
10 {-# LANGUAGE ScopedTypeVariables #-}
11 {-# LANGUAGE StandaloneDeriving #-}
12 {-# LANGUAGE Trustworthy #-}
13 {-# LANGUAGE TypeOperators #-}
14
15 -----------------------------------------------------------------------------
16 -- |
17 -- Module : Data.Data
18 -- Copyright : (c) The University of Glasgow, CWI 2001--2004
19 -- License : BSD-style (see the file libraries/base/LICENSE)
20 --
21 -- Maintainer : libraries@haskell.org
22 -- Stability : experimental
23 -- Portability : non-portable (local universal quantification)
24 --
25 -- \"Scrap your boilerplate\" --- Generic programming in Haskell. See
26 -- <http://www.haskell.org/haskellwiki/Research_papers/Generics#Scrap_your_boilerplate.21>.
27 -- This module provides the 'Data' class with its primitives for
28 -- generic programming, along with instances for many datatypes. It
29 -- corresponds to a merge between the previous "Data.Generics.Basics"
30 -- and almost all of "Data.Generics.Instances". The instances that are
31 -- not present in this module were moved to the
32 -- @Data.Generics.Instances@ module in the @syb@ package.
33 --
34 -- For more information, please visit the new
35 -- SYB wiki: <http://www.cs.uu.nl/wiki/bin/view/GenericProgramming/SYB>.
36 --
37 -----------------------------------------------------------------------------
38
39 module Data.Data (
40
41 -- * Module Data.Typeable re-exported for convenience
42 module Data.Typeable,
43
44 -- * The Data class for processing constructor applications
45 Data(
46 gfoldl,
47 gunfold,
48 toConstr,
49 dataTypeOf,
50 dataCast1, -- mediate types and unary type constructors
51 dataCast2, -- mediate types and binary type constructors
52 -- Generic maps defined in terms of gfoldl
53 gmapT,
54 gmapQ,
55 gmapQl,
56 gmapQr,
57 gmapQi,
58 gmapM,
59 gmapMp,
60 gmapMo
61 ),
62
63 -- * Datatype representations
64 DataType, -- abstract
65 -- ** Constructors
66 mkDataType,
67 mkIntType,
68 mkFloatType,
69 mkCharType,
70 mkNoRepType,
71 -- ** Observers
72 dataTypeName,
73 DataRep(..),
74 dataTypeRep,
75 -- ** Convenience functions
76 repConstr,
77 isAlgType,
78 dataTypeConstrs,
79 indexConstr,
80 maxConstrIndex,
81 isNorepType,
82
83 -- * Data constructor representations
84 Constr, -- abstract
85 ConIndex, -- alias for Int, start at 1
86 Fixity(..),
87 -- ** Constructors
88 mkConstr,
89 mkIntegralConstr,
90 mkRealConstr,
91 mkCharConstr,
92 -- ** Observers
93 constrType,
94 ConstrRep(..),
95 constrRep,
96 constrFields,
97 constrFixity,
98 -- ** Convenience function: algebraic data types
99 constrIndex,
100 -- ** From strings to constructors and vice versa: all data types
101 showConstr,
102 readConstr,
103
104 -- * Convenience functions: take type constructors apart
105 tyconUQname,
106 tyconModule,
107
108 -- * Generic operations defined in terms of 'gunfold'
109 fromConstr,
110 fromConstrB,
111 fromConstrM
112
113 ) where
114
115
116 ------------------------------------------------------------------------------
117
118 import Data.Functor.Const
119 import Data.Either
120 import Data.Eq
121 import Data.Maybe
122 import Data.Monoid
123 import Data.Ord
124 import Data.Typeable
125 import Data.Version( Version(..) )
126 import GHC.Base hiding (Any, IntRep, FloatRep)
127 import GHC.List
128 import GHC.Num
129 import GHC.Read
130 import GHC.Show
131 import Text.Read( reads )
132
133 -- Imports for the instances
134 import Data.Functor.Identity -- So we can give Data instance for Identity
135 import Data.Int -- So we can give Data instance for Int8, ...
136 import Data.Type.Coercion
137 import Data.Word -- So we can give Data instance for Word8, ...
138 import GHC.Real -- So we can give Data instance for Ratio
139 --import GHC.IOBase -- So we can give Data instance for IO, Handle
140 import GHC.Ptr -- So we can give Data instance for Ptr
141 import GHC.ForeignPtr -- So we can give Data instance for ForeignPtr
142 import Foreign.Ptr (IntPtr(..), WordPtr(..))
143 -- So we can give Data instance for IntPtr and WordPtr
144 --import GHC.Stable -- So we can give Data instance for StablePtr
145 --import GHC.ST -- So we can give Data instance for ST
146 --import GHC.Conc -- So we can give Data instance for MVar & Co.
147 import GHC.Arr -- So we can give Data instance for Array
148 import qualified GHC.Generics as Generics (Fixity(..))
149 import GHC.Generics hiding (Fixity(..))
150 -- So we can give Data instance for U1, V1, ...
151
152 ------------------------------------------------------------------------------
153 --
154 -- The Data class
155 --
156 ------------------------------------------------------------------------------
157
158 {- |
159 The 'Data' class comprehends a fundamental primitive 'gfoldl' for
160 folding over constructor applications, say terms. This primitive can
161 be instantiated in several ways to map over the immediate subterms
162 of a term; see the @gmap@ combinators later in this class. Indeed, a
163 generic programmer does not necessarily need to use the ingenious gfoldl
164 primitive but rather the intuitive @gmap@ combinators. The 'gfoldl'
165 primitive is completed by means to query top-level constructors, to
166 turn constructor representations into proper terms, and to list all
167 possible datatype constructors. This completion allows us to serve
168 generic programming scenarios like read, show, equality, term generation.
169
170 The combinators 'gmapT', 'gmapQ', 'gmapM', etc are all provided with
171 default definitions in terms of 'gfoldl', leaving open the opportunity
172 to provide datatype-specific definitions.
173 (The inclusion of the @gmap@ combinators as members of class 'Data'
174 allows the programmer or the compiler to derive specialised, and maybe
175 more efficient code per datatype. /Note/: 'gfoldl' is more higher-order
176 than the @gmap@ combinators. This is subject to ongoing benchmarking
177 experiments. It might turn out that the @gmap@ combinators will be
178 moved out of the class 'Data'.)
179
180 Conceptually, the definition of the @gmap@ combinators in terms of the
181 primitive 'gfoldl' requires the identification of the 'gfoldl' function
182 arguments. Technically, we also need to identify the type constructor
183 @c@ for the construction of the result type from the folded term type.
184
185 In the definition of @gmapQ@/x/ combinators, we use phantom type
186 constructors for the @c@ in the type of 'gfoldl' because the result type
187 of a query does not involve the (polymorphic) type of the term argument.
188 In the definition of 'gmapQl' we simply use the plain constant type
189 constructor because 'gfoldl' is left-associative anyway and so it is
190 readily suited to fold a left-associative binary operation over the
191 immediate subterms. In the definition of gmapQr, extra effort is
192 needed. We use a higher-order accumulation trick to mediate between
193 left-associative constructor application vs. right-associative binary
194 operation (e.g., @(:)@). When the query is meant to compute a value
195 of type @r@, then the result type withing generic folding is @r -> r@.
196 So the result of folding is a function to which we finally pass the
197 right unit.
198
199 With the @-XDeriveDataTypeable@ option, GHC can generate instances of the
200 'Data' class automatically. For example, given the declaration
201
202 > data T a b = C1 a b | C2 deriving (Typeable, Data)
203
204 GHC will generate an instance that is equivalent to
205
206 > instance (Data a, Data b) => Data (T a b) where
207 > gfoldl k z (C1 a b) = z C1 `k` a `k` b
208 > gfoldl k z C2 = z C2
209 >
210 > gunfold k z c = case constrIndex c of
211 > 1 -> k (k (z C1))
212 > 2 -> z C2
213 >
214 > toConstr (C1 _ _) = con_C1
215 > toConstr C2 = con_C2
216 >
217 > dataTypeOf _ = ty_T
218 >
219 > con_C1 = mkConstr ty_T "C1" [] Prefix
220 > con_C2 = mkConstr ty_T "C2" [] Prefix
221 > ty_T = mkDataType "Module.T" [con_C1, con_C2]
222
223 This is suitable for datatypes that are exported transparently.
224
225 -}
226
227 class Typeable a => Data a where
228
229 -- | Left-associative fold operation for constructor applications.
230 --
231 -- The type of 'gfoldl' is a headache, but operationally it is a simple
232 -- generalisation of a list fold.
233 --
234 -- The default definition for 'gfoldl' is @'const' 'id'@, which is
235 -- suitable for abstract datatypes with no substructures.
236 gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b)
237 -- ^ defines how nonempty constructor applications are
238 -- folded. It takes the folded tail of the constructor
239 -- application and its head, i.e., an immediate subterm,
240 -- and combines them in some way.
241 -> (forall g. g -> c g)
242 -- ^ defines how the empty constructor application is
243 -- folded, like the neutral \/ start element for list
244 -- folding.
245 -> a
246 -- ^ structure to be folded.
247 -> c a
248 -- ^ result, with a type defined in terms of @a@, but
249 -- variability is achieved by means of type constructor
250 -- @c@ for the construction of the actual result type.
251
252 -- See the 'Data' instances in this file for an illustration of 'gfoldl'.
253
254 gfoldl _ z = z
255
256 -- | Unfolding constructor applications
257 gunfold :: (forall b r. Data b => c (b -> r) -> c r)
258 -> (forall r. r -> c r)
259 -> Constr
260 -> c a
261
262 -- | Obtaining the constructor from a given datum.
263 -- For proper terms, this is meant to be the top-level constructor.
264 -- Primitive datatypes are here viewed as potentially infinite sets of
265 -- values (i.e., constructors).
266 toConstr :: a -> Constr
267
268
269 -- | The outer type constructor of the type
270 dataTypeOf :: a -> DataType
271
272
273
274 ------------------------------------------------------------------------------
275 --
276 -- Mediate types and type constructors
277 --
278 ------------------------------------------------------------------------------
279
280 -- | Mediate types and unary type constructors.
281 --
282 -- In 'Data' instances of the form
283 --
284 -- @
285 -- instance (Data a, ...) => Data (T a)
286 -- @
287 --
288 -- 'dataCast1' should be defined as 'gcast1'.
289 --
290 -- The default definition is @'const' 'Nothing'@, which is appropriate
291 -- for instances of other forms.
292 dataCast1 :: Typeable t
293 => (forall d. Data d => c (t d))
294 -> Maybe (c a)
295 dataCast1 _ = Nothing
296
297 -- | Mediate types and binary type constructors.
298 --
299 -- In 'Data' instances of the form
300 --
301 -- @
302 -- instance (Data a, Data b, ...) => Data (T a b)
303 -- @
304 --
305 -- 'dataCast2' should be defined as 'gcast2'.
306 --
307 -- The default definition is @'const' 'Nothing'@, which is appropriate
308 -- for instances of other forms.
309 dataCast2 :: Typeable t
310 => (forall d e. (Data d, Data e) => c (t d e))
311 -> Maybe (c a)
312 dataCast2 _ = Nothing
313
314
315
316 ------------------------------------------------------------------------------
317 --
318 -- Typical generic maps defined in terms of gfoldl
319 --
320 ------------------------------------------------------------------------------
321
322
323 -- | A generic transformation that maps over the immediate subterms
324 --
325 -- The default definition instantiates the type constructor @c@ in the
326 -- type of 'gfoldl' to an identity datatype constructor, using the
327 -- isomorphism pair as injection and projection.
328 gmapT :: (forall b. Data b => b -> b) -> a -> a
329
330 -- Use the Identity datatype constructor
331 -- to instantiate the type constructor c in the type of gfoldl,
332 -- and perform injections Identity and projections runIdentity accordingly.
333 --
334 gmapT f x0 = runIdentity (gfoldl k Identity x0)
335 where
336 k :: Data d => Identity (d->b) -> d -> Identity b
337 k (Identity c) x = Identity (c (f x))
338
339
340 -- | A generic query with a left-associative binary operator
341 gmapQl :: forall r r'. (r -> r' -> r) -> r -> (forall d. Data d => d -> r') -> a -> r
342 gmapQl o r f = getConst . gfoldl k z
343 where
344 k :: Data d => Const r (d->b) -> d -> Const r b
345 k c x = Const $ (getConst c) `o` f x
346 z :: g -> Const r g
347 z _ = Const r
348
349 -- | A generic query with a right-associative binary operator
350 gmapQr :: forall r r'. (r' -> r -> r) -> r -> (forall d. Data d => d -> r') -> a -> r
351 gmapQr o r0 f x0 = unQr (gfoldl k (const (Qr id)) x0) r0
352 where
353 k :: Data d => Qr r (d->b) -> d -> Qr r b
354 k (Qr c) x = Qr (\r -> c (f x `o` r))
355
356
357 -- | A generic query that processes the immediate subterms and returns a list
358 -- of results. The list is given in the same order as originally specified
359 -- in the declaration of the data constructors.
360 gmapQ :: (forall d. Data d => d -> u) -> a -> [u]
361 gmapQ f = gmapQr (:) [] f
362
363
364 -- | A generic query that processes one child by index (zero-based)
365 gmapQi :: forall u. Int -> (forall d. Data d => d -> u) -> a -> u
366 gmapQi i f x = case gfoldl k z x of { Qi _ q -> fromJust q }
367 where
368 k :: Data d => Qi u (d -> b) -> d -> Qi u b
369 k (Qi i' q) a = Qi (i'+1) (if i==i' then Just (f a) else q)
370 z :: g -> Qi q g
371 z _ = Qi 0 Nothing
372
373
374 -- | A generic monadic transformation that maps over the immediate subterms
375 --
376 -- The default definition instantiates the type constructor @c@ in
377 -- the type of 'gfoldl' to the monad datatype constructor, defining
378 -- injection and projection using 'return' and '>>='.
379 gmapM :: forall m. Monad m => (forall d. Data d => d -> m d) -> a -> m a
380
381 -- Use immediately the monad datatype constructor
382 -- to instantiate the type constructor c in the type of gfoldl,
383 -- so injection and projection is done by return and >>=.
384 --
385 gmapM f = gfoldl k return
386 where
387 k :: Data d => m (d -> b) -> d -> m b
388 k c x = do c' <- c
389 x' <- f x
390 return (c' x')
391
392
393 -- | Transformation of at least one immediate subterm does not fail
394 gmapMp :: forall m. MonadPlus m => (forall d. Data d => d -> m d) -> a -> m a
395
396 {-
397
398 The type constructor that we use here simply keeps track of the fact
399 if we already succeeded for an immediate subterm; see Mp below. To
400 this end, we couple the monadic computation with a Boolean.
401
402 -}
403
404 gmapMp f x = unMp (gfoldl k z x) >>= \(x',b) ->
405 if b then return x' else mzero
406 where
407 z :: g -> Mp m g
408 z g = Mp (return (g,False))
409 k :: Data d => Mp m (d -> b) -> d -> Mp m b
410 k (Mp c) y
411 = Mp ( c >>= \(h, b) ->
412 (f y >>= \y' -> return (h y', True))
413 `mplus` return (h y, b)
414 )
415
416 -- | Transformation of one immediate subterm with success
417 gmapMo :: forall m. MonadPlus m => (forall d. Data d => d -> m d) -> a -> m a
418
419 {-
420
421 We use the same pairing trick as for gmapMp,
422 i.e., we use an extra Bool component to keep track of the
423 fact whether an immediate subterm was processed successfully.
424 However, we cut of mapping over subterms once a first subterm
425 was transformed successfully.
426
427 -}
428
429 gmapMo f x = unMp (gfoldl k z x) >>= \(x',b) ->
430 if b then return x' else mzero
431 where
432 z :: g -> Mp m g
433 z g = Mp (return (g,False))
434 k :: Data d => Mp m (d -> b) -> d -> Mp m b
435 k (Mp c) y
436 = Mp ( c >>= \(h,b) -> if b
437 then return (h y, b)
438 else (f y >>= \y' -> return (h y',True))
439 `mplus` return (h y, b)
440 )
441
442
443 -- | Type constructor for adding counters to queries
444 data Qi q a = Qi Int (Maybe q)
445
446
447 -- | The type constructor used in definition of gmapQr
448 newtype Qr r a = Qr { unQr :: r -> r }
449
450
451 -- | The type constructor used in definition of gmapMp
452 newtype Mp m x = Mp { unMp :: m (x, Bool) }
453
454
455
456 ------------------------------------------------------------------------------
457 --
458 -- Generic unfolding
459 --
460 ------------------------------------------------------------------------------
461
462
463 -- | Build a term skeleton
464 fromConstr :: Data a => Constr -> a
465 fromConstr = fromConstrB (errorWithoutStackTrace "Data.Data.fromConstr")
466
467
468 -- | Build a term and use a generic function for subterms
469 fromConstrB :: Data a
470 => (forall d. Data d => d)
471 -> Constr
472 -> a
473 fromConstrB f = runIdentity . gunfold k z
474 where
475 k :: forall b r. Data b => Identity (b -> r) -> Identity r
476 k c = Identity (runIdentity c f)
477
478 z :: forall r. r -> Identity r
479 z = Identity
480
481
482 -- | Monadic variation on 'fromConstrB'
483 fromConstrM :: forall m a. (Monad m, Data a)
484 => (forall d. Data d => m d)
485 -> Constr
486 -> m a
487 fromConstrM f = gunfold k z
488 where
489 k :: forall b r. Data b => m (b -> r) -> m r
490 k c = do { c' <- c; b <- f; return (c' b) }
491
492 z :: forall r. r -> m r
493 z = return
494
495
496
497 ------------------------------------------------------------------------------
498 --
499 -- Datatype and constructor representations
500 --
501 ------------------------------------------------------------------------------
502
503
504 --
505 -- | Representation of datatypes.
506 -- A package of constructor representations with names of type and module.
507 --
508 data DataType = DataType
509 { tycon :: String
510 , datarep :: DataRep
511 }
512
513 deriving Show -- ^ @since 4.0.0.0
514
515 -- | Representation of constructors. Note that equality on constructors
516 -- with different types may not work -- i.e. the constructors for 'False' and
517 -- 'Nothing' may compare equal.
518 data Constr = Constr
519 { conrep :: ConstrRep
520 , constring :: String
521 , confields :: [String] -- for AlgRep only
522 , confixity :: Fixity -- for AlgRep only
523 , datatype :: DataType
524 }
525
526 -- | @since 4.0.0.0
527 instance Show Constr where
528 show = constring
529
530
531 -- | Equality of constructors
532 --
533 -- @since 4.0.0.0
534 instance Eq Constr where
535 c == c' = constrRep c == constrRep c'
536
537
538 -- | Public representation of datatypes
539 data DataRep = AlgRep [Constr]
540 | IntRep
541 | FloatRep
542 | CharRep
543 | NoRep
544
545 deriving ( Eq -- ^ @since 4.0.0.0
546 , Show -- ^ @since 4.0.0.0
547 )
548 -- The list of constructors could be an array, a balanced tree, or others.
549
550
551 -- | Public representation of constructors
552 data ConstrRep = AlgConstr ConIndex
553 | IntConstr Integer
554 | FloatConstr Rational
555 | CharConstr Char
556
557 deriving ( Eq -- ^ @since 4.0.0.0
558 , Show -- ^ @since 4.0.0.0
559 )
560
561
562 -- | Unique index for datatype constructors,
563 -- counting from 1 in the order they are given in the program text.
564 type ConIndex = Int
565
566
567 -- | Fixity of constructors
568 data Fixity = Prefix
569 | Infix -- Later: add associativity and precedence
570
571 deriving ( Eq -- ^ @since 4.0.0.0
572 , Show -- ^ @since 4.0.0.0
573 )
574
575
576 ------------------------------------------------------------------------------
577 --
578 -- Observers for datatype representations
579 --
580 ------------------------------------------------------------------------------
581
582
583 -- | Gets the type constructor including the module
584 dataTypeName :: DataType -> String
585 dataTypeName = tycon
586
587
588
589 -- | Gets the public presentation of a datatype
590 dataTypeRep :: DataType -> DataRep
591 dataTypeRep = datarep
592
593
594 -- | Gets the datatype of a constructor
595 constrType :: Constr -> DataType
596 constrType = datatype
597
598
599 -- | Gets the public presentation of constructors
600 constrRep :: Constr -> ConstrRep
601 constrRep = conrep
602
603
604 -- | Look up a constructor by its representation
605 repConstr :: DataType -> ConstrRep -> Constr
606 repConstr dt cr =
607 case (dataTypeRep dt, cr) of
608 (AlgRep cs, AlgConstr i) -> cs !! (i-1)
609 (IntRep, IntConstr i) -> mkIntegralConstr dt i
610 (FloatRep, FloatConstr f) -> mkRealConstr dt f
611 (CharRep, CharConstr c) -> mkCharConstr dt c
612 _ -> errorWithoutStackTrace "Data.Data.repConstr: The given ConstrRep does not fit to the given DataType."
613
614
615
616 ------------------------------------------------------------------------------
617 --
618 -- Representations of algebraic data types
619 --
620 ------------------------------------------------------------------------------
621
622
623 -- | Constructs an algebraic datatype
624 mkDataType :: String -> [Constr] -> DataType
625 mkDataType str cs = DataType
626 { tycon = str
627 , datarep = AlgRep cs
628 }
629
630
631 -- | Constructs a constructor
632 mkConstr :: DataType -> String -> [String] -> Fixity -> Constr
633 mkConstr dt str fields fix =
634 Constr
635 { conrep = AlgConstr idx
636 , constring = str
637 , confields = fields
638 , confixity = fix
639 , datatype = dt
640 }
641 where
642 idx = head [ i | (c,i) <- dataTypeConstrs dt `zip` [1..],
643 showConstr c == str ]
644
645
646 -- | Gets the constructors of an algebraic datatype
647 dataTypeConstrs :: DataType -> [Constr]
648 dataTypeConstrs dt = case datarep dt of
649 (AlgRep cons) -> cons
650 _ -> errorWithoutStackTrace $ "Data.Data.dataTypeConstrs is not supported for "
651 ++ dataTypeName dt ++
652 ", as it is not an algebraic data type."
653
654
655 -- | Gets the field labels of a constructor. The list of labels
656 -- is returned in the same order as they were given in the original
657 -- constructor declaration.
658 constrFields :: Constr -> [String]
659 constrFields = confields
660
661
662 -- | Gets the fixity of a constructor
663 constrFixity :: Constr -> Fixity
664 constrFixity = confixity
665
666
667
668 ------------------------------------------------------------------------------
669 --
670 -- From strings to constr's and vice versa: all data types
671 --
672 ------------------------------------------------------------------------------
673
674
675 -- | Gets the string for a constructor
676 showConstr :: Constr -> String
677 showConstr = constring
678
679
680 -- | Lookup a constructor via a string
681 readConstr :: DataType -> String -> Maybe Constr
682 readConstr dt str =
683 case dataTypeRep dt of
684 AlgRep cons -> idx cons
685 IntRep -> mkReadCon (\i -> (mkPrimCon dt str (IntConstr i)))
686 FloatRep -> mkReadCon ffloat
687 CharRep -> mkReadCon (\c -> (mkPrimCon dt str (CharConstr c)))
688 NoRep -> Nothing
689 where
690
691 -- Read a value and build a constructor
692 mkReadCon :: Read t => (t -> Constr) -> Maybe Constr
693 mkReadCon f = case (reads str) of
694 [(t,"")] -> Just (f t)
695 _ -> Nothing
696
697 -- Traverse list of algebraic datatype constructors
698 idx :: [Constr] -> Maybe Constr
699 idx cons = let fit = filter ((==) str . showConstr) cons
700 in if fit == []
701 then Nothing
702 else Just (head fit)
703
704 ffloat :: Double -> Constr
705 ffloat = mkPrimCon dt str . FloatConstr . toRational
706
707 ------------------------------------------------------------------------------
708 --
709 -- Convenience functions: algebraic data types
710 --
711 ------------------------------------------------------------------------------
712
713
714 -- | Test for an algebraic type
715 isAlgType :: DataType -> Bool
716 isAlgType dt = case datarep dt of
717 (AlgRep _) -> True
718 _ -> False
719
720
721 -- | Gets the constructor for an index (algebraic datatypes only)
722 indexConstr :: DataType -> ConIndex -> Constr
723 indexConstr dt idx = case datarep dt of
724 (AlgRep cs) -> cs !! (idx-1)
725 _ -> errorWithoutStackTrace $ "Data.Data.indexConstr is not supported for "
726 ++ dataTypeName dt ++
727 ", as it is not an algebraic data type."
728
729
730 -- | Gets the index of a constructor (algebraic datatypes only)
731 constrIndex :: Constr -> ConIndex
732 constrIndex con = case constrRep con of
733 (AlgConstr idx) -> idx
734 _ -> errorWithoutStackTrace $ "Data.Data.constrIndex is not supported for "
735 ++ dataTypeName (constrType con) ++
736 ", as it is not an algebraic data type."
737
738
739 -- | Gets the maximum constructor index of an algebraic datatype
740 maxConstrIndex :: DataType -> ConIndex
741 maxConstrIndex dt = case dataTypeRep dt of
742 AlgRep cs -> length cs
743 _ -> errorWithoutStackTrace $ "Data.Data.maxConstrIndex is not supported for "
744 ++ dataTypeName dt ++
745 ", as it is not an algebraic data type."
746
747
748
749 ------------------------------------------------------------------------------
750 --
751 -- Representation of primitive types
752 --
753 ------------------------------------------------------------------------------
754
755
756 -- | Constructs the 'Int' type
757 mkIntType :: String -> DataType
758 mkIntType = mkPrimType IntRep
759
760
761 -- | Constructs the 'Float' type
762 mkFloatType :: String -> DataType
763 mkFloatType = mkPrimType FloatRep
764
765
766 -- | Constructs the 'Char' type
767 mkCharType :: String -> DataType
768 mkCharType = mkPrimType CharRep
769
770
771 -- | Helper for 'mkIntType', 'mkFloatType'
772 mkPrimType :: DataRep -> String -> DataType
773 mkPrimType dr str = DataType
774 { tycon = str
775 , datarep = dr
776 }
777
778
779 -- Makes a constructor for primitive types
780 mkPrimCon :: DataType -> String -> ConstrRep -> Constr
781 mkPrimCon dt str cr = Constr
782 { datatype = dt
783 , conrep = cr
784 , constring = str
785 , confields = errorWithoutStackTrace "Data.Data.confields"
786 , confixity = errorWithoutStackTrace "Data.Data.confixity"
787 }
788
789 mkIntegralConstr :: (Integral a, Show a) => DataType -> a -> Constr
790 mkIntegralConstr dt i = case datarep dt of
791 IntRep -> mkPrimCon dt (show i) (IntConstr (toInteger i))
792 _ -> errorWithoutStackTrace $ "Data.Data.mkIntegralConstr is not supported for "
793 ++ dataTypeName dt ++
794 ", as it is not an Integral data type."
795
796 mkRealConstr :: (Real a, Show a) => DataType -> a -> Constr
797 mkRealConstr dt f = case datarep dt of
798 FloatRep -> mkPrimCon dt (show f) (FloatConstr (toRational f))
799 _ -> errorWithoutStackTrace $ "Data.Data.mkRealConstr is not supported for "
800 ++ dataTypeName dt ++
801 ", as it is not a Real data type."
802
803 -- | Makes a constructor for 'Char'.
804 mkCharConstr :: DataType -> Char -> Constr
805 mkCharConstr dt c = case datarep dt of
806 CharRep -> mkPrimCon dt (show c) (CharConstr c)
807 _ -> errorWithoutStackTrace $ "Data.Data.mkCharConstr is not supported for "
808 ++ dataTypeName dt ++
809 ", as it is not an Char data type."
810
811
812 ------------------------------------------------------------------------------
813 --
814 -- Non-representations for non-representable types
815 --
816 ------------------------------------------------------------------------------
817
818
819 -- | Constructs a non-representation for a non-representable type
820 mkNoRepType :: String -> DataType
821 mkNoRepType str = DataType
822 { tycon = str
823 , datarep = NoRep
824 }
825
826 -- | Test for a non-representable type
827 isNorepType :: DataType -> Bool
828 isNorepType dt = case datarep dt of
829 NoRep -> True
830 _ -> False
831
832
833
834 ------------------------------------------------------------------------------
835 --
836 -- Convenience for qualified type constructors
837 --
838 ------------------------------------------------------------------------------
839
840
841 -- | Gets the unqualified type constructor:
842 -- drop *.*.*... before name
843 --
844 tyconUQname :: String -> String
845 tyconUQname x = let x' = dropWhile (not . (==) '.') x
846 in if x' == [] then x else tyconUQname (tail x')
847
848
849 -- | Gets the module of a type constructor:
850 -- take *.*.*... before name
851 tyconModule :: String -> String
852 tyconModule x = let (a,b) = break ((==) '.') x
853 in if b == ""
854 then b
855 else a ++ tyconModule' (tail b)
856 where
857 tyconModule' y = let y' = tyconModule y
858 in if y' == "" then "" else ('.':y')
859
860
861
862
863 ------------------------------------------------------------------------------
864 ------------------------------------------------------------------------------
865 --
866 -- Instances of the Data class for Prelude-like types.
867 -- We define top-level definitions for representations.
868 --
869 ------------------------------------------------------------------------------
870
871 -- | @since 4.0.0.0
872 deriving instance Data Bool
873
874 ------------------------------------------------------------------------------
875
876 charType :: DataType
877 charType = mkCharType "Prelude.Char"
878
879 -- | @since 4.0.0.0
880 instance Data Char where
881 toConstr x = mkCharConstr charType x
882 gunfold _ z c = case constrRep c of
883 (CharConstr x) -> z x
884 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
885 ++ " is not of type Char."
886 dataTypeOf _ = charType
887
888
889 ------------------------------------------------------------------------------
890
891 floatType :: DataType
892 floatType = mkFloatType "Prelude.Float"
893
894 -- | @since 4.0.0.0
895 instance Data Float where
896 toConstr = mkRealConstr floatType
897 gunfold _ z c = case constrRep c of
898 (FloatConstr x) -> z (realToFrac x)
899 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
900 ++ " is not of type Float."
901 dataTypeOf _ = floatType
902
903
904 ------------------------------------------------------------------------------
905
906 doubleType :: DataType
907 doubleType = mkFloatType "Prelude.Double"
908
909 -- | @since 4.0.0.0
910 instance Data Double where
911 toConstr = mkRealConstr doubleType
912 gunfold _ z c = case constrRep c of
913 (FloatConstr x) -> z (realToFrac x)
914 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
915 ++ " is not of type Double."
916 dataTypeOf _ = doubleType
917
918
919 ------------------------------------------------------------------------------
920
921 intType :: DataType
922 intType = mkIntType "Prelude.Int"
923
924 -- | @since 4.0.0.0
925 instance Data Int where
926 toConstr x = mkIntegralConstr intType x
927 gunfold _ z c = case constrRep c of
928 (IntConstr x) -> z (fromIntegral x)
929 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
930 ++ " is not of type Int."
931 dataTypeOf _ = intType
932
933
934 ------------------------------------------------------------------------------
935
936 integerType :: DataType
937 integerType = mkIntType "Prelude.Integer"
938
939 -- | @since 4.0.0.0
940 instance Data Integer where
941 toConstr = mkIntegralConstr integerType
942 gunfold _ z c = case constrRep c of
943 (IntConstr x) -> z x
944 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
945 ++ " is not of type Integer."
946 dataTypeOf _ = integerType
947
948
949 ------------------------------------------------------------------------------
950
951 -- This follows the same style as the other integral 'Data' instances
952 -- defined in "Data.Data"
953 naturalType :: DataType
954 naturalType = mkIntType "Numeric.Natural.Natural"
955
956 -- | @since 4.8.0.0
957 instance Data Natural where
958 toConstr x = mkIntegralConstr naturalType x
959 gunfold _ z c = case constrRep c of
960 (IntConstr x) -> z (fromIntegral x)
961 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
962 ++ " is not of type Natural"
963 dataTypeOf _ = naturalType
964
965
966 ------------------------------------------------------------------------------
967
968 int8Type :: DataType
969 int8Type = mkIntType "Data.Int.Int8"
970
971 -- | @since 4.0.0.0
972 instance Data Int8 where
973 toConstr x = mkIntegralConstr int8Type x
974 gunfold _ z c = case constrRep c of
975 (IntConstr x) -> z (fromIntegral x)
976 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
977 ++ " is not of type Int8."
978 dataTypeOf _ = int8Type
979
980
981 ------------------------------------------------------------------------------
982
983 int16Type :: DataType
984 int16Type = mkIntType "Data.Int.Int16"
985
986 -- | @since 4.0.0.0
987 instance Data Int16 where
988 toConstr x = mkIntegralConstr int16Type x
989 gunfold _ z c = case constrRep c of
990 (IntConstr x) -> z (fromIntegral x)
991 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
992 ++ " is not of type Int16."
993 dataTypeOf _ = int16Type
994
995
996 ------------------------------------------------------------------------------
997
998 int32Type :: DataType
999 int32Type = mkIntType "Data.Int.Int32"
1000
1001 -- | @since 4.0.0.0
1002 instance Data Int32 where
1003 toConstr x = mkIntegralConstr int32Type x
1004 gunfold _ z c = case constrRep c of
1005 (IntConstr x) -> z (fromIntegral x)
1006 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
1007 ++ " is not of type Int32."
1008 dataTypeOf _ = int32Type
1009
1010
1011 ------------------------------------------------------------------------------
1012
1013 int64Type :: DataType
1014 int64Type = mkIntType "Data.Int.Int64"
1015
1016 -- | @since 4.0.0.0
1017 instance Data Int64 where
1018 toConstr x = mkIntegralConstr int64Type x
1019 gunfold _ z c = case constrRep c of
1020 (IntConstr x) -> z (fromIntegral x)
1021 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
1022 ++ " is not of type Int64."
1023 dataTypeOf _ = int64Type
1024
1025
1026 ------------------------------------------------------------------------------
1027
1028 wordType :: DataType
1029 wordType = mkIntType "Data.Word.Word"
1030
1031 -- | @since 4.0.0.0
1032 instance Data Word where
1033 toConstr x = mkIntegralConstr wordType x
1034 gunfold _ z c = case constrRep c of
1035 (IntConstr x) -> z (fromIntegral x)
1036 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
1037 ++ " is not of type Word"
1038 dataTypeOf _ = wordType
1039
1040
1041 ------------------------------------------------------------------------------
1042
1043 word8Type :: DataType
1044 word8Type = mkIntType "Data.Word.Word8"
1045
1046 -- | @since 4.0.0.0
1047 instance Data Word8 where
1048 toConstr x = mkIntegralConstr word8Type x
1049 gunfold _ z c = case constrRep c of
1050 (IntConstr x) -> z (fromIntegral x)
1051 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
1052 ++ " is not of type Word8."
1053 dataTypeOf _ = word8Type
1054
1055
1056 ------------------------------------------------------------------------------
1057
1058 word16Type :: DataType
1059 word16Type = mkIntType "Data.Word.Word16"
1060
1061 -- | @since 4.0.0.0
1062 instance Data Word16 where
1063 toConstr x = mkIntegralConstr word16Type x
1064 gunfold _ z c = case constrRep c of
1065 (IntConstr x) -> z (fromIntegral x)
1066 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
1067 ++ " is not of type Word16."
1068 dataTypeOf _ = word16Type
1069
1070
1071 ------------------------------------------------------------------------------
1072
1073 word32Type :: DataType
1074 word32Type = mkIntType "Data.Word.Word32"
1075
1076 -- | @since 4.0.0.0
1077 instance Data Word32 where
1078 toConstr x = mkIntegralConstr word32Type x
1079 gunfold _ z c = case constrRep c of
1080 (IntConstr x) -> z (fromIntegral x)
1081 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
1082 ++ " is not of type Word32."
1083 dataTypeOf _ = word32Type
1084
1085
1086 ------------------------------------------------------------------------------
1087
1088 word64Type :: DataType
1089 word64Type = mkIntType "Data.Word.Word64"
1090
1091 -- | @since 4.0.0.0
1092 instance Data Word64 where
1093 toConstr x = mkIntegralConstr word64Type x
1094 gunfold _ z c = case constrRep c of
1095 (IntConstr x) -> z (fromIntegral x)
1096 _ -> errorWithoutStackTrace $ "Data.Data.gunfold: Constructor " ++ show c
1097 ++ " is not of type Word64."
1098 dataTypeOf _ = word64Type
1099
1100
1101 ------------------------------------------------------------------------------
1102
1103 ratioConstr :: Constr
1104 ratioConstr = mkConstr ratioDataType ":%" [] Infix
1105
1106 ratioDataType :: DataType
1107 ratioDataType = mkDataType "GHC.Real.Ratio" [ratioConstr]
1108
1109 -- NB: This Data instance intentionally uses the (%) smart constructor instead
1110 -- of the internal (:%) constructor to preserve the invariant that a Ratio
1111 -- value is reduced to normal form. See Trac #10011.
1112
1113 -- | @since 4.0.0.0
1114 instance (Data a, Integral a) => Data (Ratio a) where
1115 gfoldl k z (a :% b) = z (%) `k` a `k` b
1116 toConstr _ = ratioConstr
1117 gunfold k z c | constrIndex c == 1 = k (k (z (%)))
1118 gunfold _ _ _ = errorWithoutStackTrace "Data.Data.gunfold(Ratio)"
1119 dataTypeOf _ = ratioDataType
1120
1121
1122 ------------------------------------------------------------------------------
1123
1124 nilConstr :: Constr
1125 nilConstr = mkConstr listDataType "[]" [] Prefix
1126 consConstr :: Constr
1127 consConstr = mkConstr listDataType "(:)" [] Infix
1128
1129 listDataType :: DataType
1130 listDataType = mkDataType "Prelude.[]" [nilConstr,consConstr]
1131
1132 -- | @since 4.0.0.0
1133 instance Data a => Data [a] where
1134 gfoldl _ z [] = z []
1135 gfoldl f z (x:xs) = z (:) `f` x `f` xs
1136 toConstr [] = nilConstr
1137 toConstr (_:_) = consConstr
1138 gunfold k z c = case constrIndex c of
1139 1 -> z []
1140 2 -> k (k (z (:)))
1141 _ -> errorWithoutStackTrace "Data.Data.gunfold(List)"
1142 dataTypeOf _ = listDataType
1143 dataCast1 f = gcast1 f
1144
1145 --
1146 -- The gmaps are given as an illustration.
1147 -- This shows that the gmaps for lists are different from list maps.
1148 --
1149 gmapT _ [] = []
1150 gmapT f (x:xs) = (f x:f xs)
1151 gmapQ _ [] = []
1152 gmapQ f (x:xs) = [f x,f xs]
1153 gmapM _ [] = return []
1154 gmapM f (x:xs) = f x >>= \x' -> f xs >>= \xs' -> return (x':xs')
1155
1156
1157 ------------------------------------------------------------------------------
1158
1159 -- | @since 4.9.0.0
1160 deriving instance Data a => Data (NonEmpty a)
1161
1162 -- | @since 4.0.0.0
1163 deriving instance Data a => Data (Maybe a)
1164
1165 -- | @since 4.0.0.0
1166 deriving instance Data Ordering
1167
1168 -- | @since 4.0.0.0
1169 deriving instance (Data a, Data b) => Data (Either a b)
1170
1171 -- | @since 4.0.0.0
1172 deriving instance Data ()
1173
1174 -- | @since 4.0.0.0
1175 deriving instance (Data a, Data b) => Data (a,b)
1176
1177 -- | @since 4.0.0.0
1178 deriving instance (Data a, Data b, Data c) => Data (a,b,c)
1179
1180 -- | @since 4.0.0.0
1181 deriving instance (Data a, Data b, Data c, Data d)
1182 => Data (a,b,c,d)
1183
1184 -- | @since 4.0.0.0
1185 deriving instance (Data a, Data b, Data c, Data d, Data e)
1186 => Data (a,b,c,d,e)
1187
1188 -- | @since 4.0.0.0
1189 deriving instance (Data a, Data b, Data c, Data d, Data e, Data f)
1190 => Data (a,b,c,d,e,f)
1191
1192 -- | @since 4.0.0.0
1193 deriving instance (Data a, Data b, Data c, Data d, Data e, Data f, Data g)
1194 => Data (a,b,c,d,e,f,g)
1195
1196 ------------------------------------------------------------------------------
1197
1198 -- | @since 4.8.0.0
1199 instance Data a => Data (Ptr a) where
1200 toConstr _ = errorWithoutStackTrace "Data.Data.toConstr(Ptr)"
1201 gunfold _ _ = errorWithoutStackTrace "Data.Data.gunfold(Ptr)"
1202 dataTypeOf _ = mkNoRepType "GHC.Ptr.Ptr"
1203 dataCast1 x = gcast1 x
1204
1205 ------------------------------------------------------------------------------
1206
1207 -- | @since 4.8.0.0
1208 instance Data a => Data (ForeignPtr a) where
1209 toConstr _ = errorWithoutStackTrace "Data.Data.toConstr(ForeignPtr)"
1210 gunfold _ _ = errorWithoutStackTrace "Data.Data.gunfold(ForeignPtr)"
1211 dataTypeOf _ = mkNoRepType "GHC.ForeignPtr.ForeignPtr"
1212 dataCast1 x = gcast1 x
1213
1214 -- | @since 4.11.0.0
1215 deriving instance Data IntPtr
1216
1217 -- | @since 4.11.0.0
1218 deriving instance Data WordPtr
1219
1220 ------------------------------------------------------------------------------
1221 -- The Data instance for Array preserves data abstraction at the cost of
1222 -- inefficiency. We omit reflection services for the sake of data abstraction.
1223 -- | @since 4.8.0.0
1224 instance (Data a, Data b, Ix a) => Data (Array a b)
1225 where
1226 gfoldl f z a = z (listArray (bounds a)) `f` (elems a)
1227 toConstr _ = errorWithoutStackTrace "Data.Data.toConstr(Array)"
1228 gunfold _ _ = errorWithoutStackTrace "Data.Data.gunfold(Array)"
1229 dataTypeOf _ = mkNoRepType "Data.Array.Array"
1230 dataCast2 x = gcast2 x
1231
1232 ----------------------------------------------------------------------------
1233 -- Data instance for Proxy
1234
1235 -- | @since 4.7.0.0
1236 deriving instance (Data t) => Data (Proxy t)
1237
1238 -- | @since 4.7.0.0
1239 deriving instance (a ~ b, Data a) => Data (a :~: b)
1240
1241 -- | @since 4.10.0.0
1242 deriving instance (Typeable i, Typeable j, Typeable a, Typeable b,
1243 (a :: i) ~~ (b :: j))
1244 => Data (a :~~: b)
1245
1246 -- | @since 4.7.0.0
1247 deriving instance (Coercible a b, Data a, Data b) => Data (Coercion a b)
1248
1249 -- | @since 4.9.0.0
1250 deriving instance Data a => Data (Identity a)
1251
1252 -- | @since 4.10.0.0
1253 deriving instance (Typeable k, Data a, Typeable (b :: k)) => Data (Const a b)
1254
1255 -- | @since 4.7.0.0
1256 deriving instance Data Version
1257
1258 ----------------------------------------------------------------------------
1259 -- Data instances for Data.Monoid wrappers
1260
1261 -- | @since 4.8.0.0
1262 deriving instance Data a => Data (Dual a)
1263
1264 -- | @since 4.8.0.0
1265 deriving instance Data All
1266
1267 -- | @since 4.8.0.0
1268 deriving instance Data Any
1269
1270 -- | @since 4.8.0.0
1271 deriving instance Data a => Data (Sum a)
1272
1273 -- | @since 4.8.0.0
1274 deriving instance Data a => Data (Product a)
1275
1276 -- | @since 4.8.0.0
1277 deriving instance Data a => Data (First a)
1278
1279 -- | @since 4.8.0.0
1280 deriving instance Data a => Data (Last a)
1281
1282 -- | @since 4.8.0.0
1283 deriving instance (Data (f a), Data a, Typeable f) => Data (Alt f a)
1284
1285 -- | @since 4.12.0.0
1286 deriving instance (Data (f a), Data a, Typeable f) => Data (Ap f a)
1287
1288 ----------------------------------------------------------------------------
1289 -- Data instances for GHC.Generics representations
1290
1291 -- | @since 4.9.0.0
1292 deriving instance Data p => Data (U1 p)
1293
1294 -- | @since 4.9.0.0
1295 deriving instance Data p => Data (Par1 p)
1296
1297 -- | @since 4.9.0.0
1298 deriving instance (Data (f p), Typeable f, Data p) => Data (Rec1 f p)
1299
1300 -- | @since 4.9.0.0
1301 deriving instance (Typeable i, Data p, Data c) => Data (K1 i c p)
1302
1303 -- | @since 4.9.0.0
1304 deriving instance (Data p, Data (f p), Typeable c, Typeable i, Typeable f)
1305 => Data (M1 i c f p)
1306
1307 -- | @since 4.9.0.0
1308 deriving instance (Typeable f, Typeable g, Data p, Data (f p), Data (g p))
1309 => Data ((f :+: g) p)
1310
1311 -- | @since 4.9.0.0
1312 deriving instance (Typeable (f :: Type -> Type), Typeable (g :: Type -> Type),
1313 Data p, Data (f (g p)))
1314 => Data ((f :.: g) p)
1315
1316 -- | @since 4.9.0.0
1317 deriving instance Data p => Data (V1 p)
1318
1319 -- | @since 4.9.0.0
1320 deriving instance (Typeable f, Typeable g, Data p, Data (f p), Data (g p))
1321 => Data ((f :*: g) p)
1322
1323 -- | @since 4.9.0.0
1324 deriving instance Data Generics.Fixity
1325
1326 -- | @since 4.9.0.0
1327 deriving instance Data Associativity
1328
1329 -- | @since 4.9.0.0
1330 deriving instance Data SourceUnpackedness
1331
1332 -- | @since 4.9.0.0
1333 deriving instance Data SourceStrictness
1334
1335 -- | @since 4.9.0.0
1336 deriving instance Data DecidedStrictness