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