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