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