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