Remove unused imports from base
[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 :: (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 c = do { c' <- c; b <- f; return (c' b) }
461   z = return
462
463
464
465 ------------------------------------------------------------------------------
466 --
467 --      Datatype and constructor representations
468 --
469 ------------------------------------------------------------------------------
470
471
472 --
473 -- | Representation of datatypes.
474 -- A package of constructor representations with names of type and module.
475 --
476 data DataType = DataType
477                         { tycon   :: String
478                         , datarep :: DataRep
479                         }
480
481               deriving Show
482
483
484 -- | Representation of constructors
485 data Constr = Constr
486                         { conrep    :: ConstrRep
487                         , constring :: String
488                         , confields :: [String] -- for AlgRep only
489                         , confixity :: Fixity   -- for AlgRep only
490                         , datatype  :: DataType
491                         }
492
493 instance Show Constr where
494  show = constring
495
496
497 -- | Equality of constructors
498 instance Eq Constr where
499   c == c' = constrRep c == constrRep c'
500
501
502 -- | Public representation of datatypes
503 data DataRep = AlgRep [Constr]
504              | IntRep
505              | FloatRep
506              | CharRep
507              | NoRep
508
509             deriving (Eq,Show)
510 -- The list of constructors could be an array, a balanced tree, or others.
511
512
513 -- | Public representation of constructors
514 data ConstrRep = AlgConstr    ConIndex
515                | IntConstr    Integer
516                | FloatConstr  Rational
517                | CharConstr   Char
518
519                deriving (Eq,Show)
520
521
522 -- | Unique index for datatype constructors,
523 -- counting from 1 in the order they are given in the program text.
524 type ConIndex = Int
525
526
527 -- | Fixity of constructors
528 data Fixity = Prefix
529             | Infix     -- Later: add associativity and precedence
530
531             deriving (Eq,Show)
532
533
534 ------------------------------------------------------------------------------
535 --
536 --      Observers for datatype representations
537 --
538 ------------------------------------------------------------------------------
539
540
541 -- | Gets the type constructor including the module
542 dataTypeName :: DataType -> String
543 dataTypeName = tycon
544
545
546
547 -- | Gets the public presentation of a datatype
548 dataTypeRep :: DataType -> DataRep
549 dataTypeRep = datarep
550
551
552 -- | Gets the datatype of a constructor
553 constrType :: Constr -> DataType
554 constrType = datatype
555
556
557 -- | Gets the public presentation of constructors
558 constrRep :: Constr -> ConstrRep
559 constrRep = conrep
560
561
562 -- | Look up a constructor by its representation
563 repConstr :: DataType -> ConstrRep -> Constr
564 repConstr dt cr =
565       case (dataTypeRep dt, cr) of
566         (AlgRep cs, AlgConstr i)      -> cs !! (i-1)
567         (IntRep,    IntConstr i)      -> mkIntConstr dt i
568         (FloatRep,  FloatConstr f)    -> mkRealConstr dt f
569         (CharRep,   CharConstr c)     -> mkCharConstr dt c
570         _ -> error "repConstr"
571
572
573
574 ------------------------------------------------------------------------------
575 --
576 --      Representations of algebraic data types
577 --
578 ------------------------------------------------------------------------------
579
580
581 -- | Constructs an algebraic datatype
582 mkDataType :: String -> [Constr] -> DataType
583 mkDataType str cs = DataType
584                         { tycon   = str
585                         , datarep = AlgRep cs
586                         }
587
588
589 -- | Constructs a constructor
590 mkConstr :: DataType -> String -> [String] -> Fixity -> Constr
591 mkConstr dt str fields fix =
592         Constr
593                 { conrep    = AlgConstr idx
594                 , constring = str
595                 , confields = fields
596                 , confixity = fix
597                 , datatype  = dt
598                 }
599   where
600     idx = head [ i | (c,i) <- dataTypeConstrs dt `zip` [1..],
601                      showConstr c == str ]
602
603
604 -- | Gets the constructors of an algebraic datatype
605 dataTypeConstrs :: DataType -> [Constr]
606 dataTypeConstrs dt = case datarep dt of
607                         (AlgRep cons) -> cons
608                         _ -> error "dataTypeConstrs"
609
610
611 -- | Gets the field labels of a constructor.  The list of labels
612 -- is returned in the same order as they were given in the original 
613 -- constructor declaration.
614 constrFields :: Constr -> [String]
615 constrFields = confields
616
617
618 -- | Gets the fixity of a constructor
619 constrFixity :: Constr -> Fixity
620 constrFixity = confixity
621
622
623
624 ------------------------------------------------------------------------------
625 --
626 --      From strings to constr's and vice versa: all data types
627 --      
628 ------------------------------------------------------------------------------
629
630
631 -- | Gets the string for a constructor
632 showConstr :: Constr -> String
633 showConstr = constring
634
635
636 -- | Lookup a constructor via a string
637 readConstr :: DataType -> String -> Maybe Constr
638 readConstr dt str =
639       case dataTypeRep dt of
640         AlgRep cons -> idx cons
641         IntRep      -> mkReadCon (\i -> (mkPrimCon dt str (IntConstr i)))
642         FloatRep    -> mkReadCon ffloat
643         CharRep     -> mkReadCon (\c -> (mkPrimCon dt str (CharConstr c)))
644         NoRep       -> Nothing
645   where
646
647     -- Read a value and build a constructor
648     mkReadCon :: Read t => (t -> Constr) -> Maybe Constr
649     mkReadCon f = case (reads str) of
650                     [(t,"")] -> Just (f t)
651                     _ -> Nothing
652
653     -- Traverse list of algebraic datatype constructors
654     idx :: [Constr] -> Maybe Constr
655     idx cons = let fit = filter ((==) str . showConstr) cons
656                 in if fit == []
657                      then Nothing
658                      else Just (head fit)
659
660     ffloat :: Double -> Constr
661     ffloat =  mkPrimCon dt str . FloatConstr . toRational
662
663 ------------------------------------------------------------------------------
664 --
665 --      Convenience funtions: algebraic data types
666 --
667 ------------------------------------------------------------------------------
668
669
670 -- | Test for an algebraic type
671 isAlgType :: DataType -> Bool
672 isAlgType dt = case datarep dt of
673                  (AlgRep _) -> True
674                  _ -> False
675
676
677 -- | Gets the constructor for an index (algebraic datatypes only)
678 indexConstr :: DataType -> ConIndex -> Constr
679 indexConstr dt idx = case datarep dt of
680                         (AlgRep cs) -> cs !! (idx-1)
681                         _           -> error "indexConstr"
682
683
684 -- | Gets the index of a constructor (algebraic datatypes only)
685 constrIndex :: Constr -> ConIndex
686 constrIndex con = case constrRep con of
687                     (AlgConstr idx) -> idx
688                     _ -> error "constrIndex"
689
690
691 -- | Gets the maximum constructor index of an algebraic datatype
692 maxConstrIndex :: DataType -> ConIndex
693 maxConstrIndex dt = case dataTypeRep dt of
694                         AlgRep cs -> length cs
695                         _            -> error "maxConstrIndex"
696
697
698
699 ------------------------------------------------------------------------------
700 --
701 --      Representation of primitive types
702 --
703 ------------------------------------------------------------------------------
704
705
706 -- | Constructs the 'Int' type
707 mkIntType :: String -> DataType
708 mkIntType = mkPrimType IntRep
709
710
711 -- | Constructs the 'Float' type
712 mkFloatType :: String -> DataType
713 mkFloatType = mkPrimType FloatRep
714
715
716 -- | This function is now deprecated. Please use 'mkCharType' instead.
717 {-# DEPRECATED mkStringType "Use mkCharType instead" #-}
718 mkStringType :: String -> DataType
719 mkStringType = mkCharType
720
721 -- | Constructs the 'Char' type
722 mkCharType :: String -> DataType
723 mkCharType = mkPrimType CharRep
724
725
726 -- | Helper for 'mkIntType', 'mkFloatType', 'mkStringType'
727 mkPrimType :: DataRep -> String -> DataType
728 mkPrimType dr str = DataType
729                         { tycon   = str
730                         , datarep = dr
731                         }
732
733
734 -- Makes a constructor for primitive types
735 mkPrimCon :: DataType -> String -> ConstrRep -> Constr
736 mkPrimCon dt str cr = Constr
737                         { datatype  = dt
738                         , conrep    = cr
739                         , constring = str
740                         , confields = error "constrFields"
741                         , confixity = error "constrFixity"
742                         }
743
744 -- | This function is now deprecated. Please use 'mkIntegralConstr' instead.
745 {-# DEPRECATED mkIntConstr "Use mkIntegralConstr instead" #-}
746 mkIntConstr :: DataType -> Integer -> Constr
747 mkIntConstr = mkIntegralConstr
748
749 mkIntegralConstr :: (Integral a) => DataType -> a -> Constr
750 mkIntegralConstr dt i = case datarep dt of
751                   IntRep -> mkPrimCon dt (show i) (IntConstr (toInteger  i))
752                   _ -> error "mkIntegralConstr"
753
754 -- | This function is now deprecated. Please use 'mkRealConstr' instead.
755 {-# DEPRECATED mkFloatConstr "Use mkRealConstr instead" #-}
756 mkFloatConstr :: DataType -> Double -> Constr
757 mkFloatConstr dt = mkRealConstr dt . toRational
758
759 mkRealConstr :: (Real a) => DataType -> a -> Constr
760 mkRealConstr dt f = case datarep dt of
761                     FloatRep -> mkPrimCon dt (show f) (FloatConstr (toRational f))
762                     _ -> error "mkRealConstr"
763
764 -- | This function is now deprecated. Please use 'mkCharConstr' instead.
765 {-# DEPRECATED mkStringConstr "Use mkCharConstr instead" #-}
766 mkStringConstr :: DataType -> String -> Constr
767 mkStringConstr dt str =
768   case datarep dt of
769     CharRep -> case str of
770       [c] -> mkPrimCon dt (show c) (CharConstr c)
771       _ -> error "mkStringConstr: input String must contain a single character"
772     _ -> error "mkStringConstr"
773
774 -- | Makes a constructor for 'Char'.
775 mkCharConstr :: DataType -> Char -> Constr
776 mkCharConstr dt c = case datarep dt of
777                    CharRep -> mkPrimCon dt (show c) (CharConstr c)
778                    _ -> error "mkCharConstr"
779
780
781 ------------------------------------------------------------------------------
782 --
783 --      Non-representations for non-presentable types
784 --
785 ------------------------------------------------------------------------------
786
787
788 -- | Deprecated version (misnamed)
789 {-# DEPRECATED mkNorepType "Use mkNoRepType instead" #-}
790 mkNorepType :: String -> DataType
791 mkNorepType str = DataType
792                         { tycon   = str
793                         , datarep = NoRep
794                         }
795
796 -- | Constructs a non-representation for a non-presentable type
797 mkNoRepType :: String -> DataType
798 mkNoRepType str = DataType
799                         { tycon   = str
800                         , datarep = NoRep
801                         }
802
803 -- | Test for a non-representable type
804 isNorepType :: DataType -> Bool
805 isNorepType dt = case datarep dt of
806                    NoRep -> True
807                    _ -> False
808
809
810
811 ------------------------------------------------------------------------------
812 --
813 --      Convenience for qualified type constructors
814 --
815 ------------------------------------------------------------------------------
816
817
818 -- | Gets the unqualified type constructor:
819 -- drop *.*.*... before name
820 --
821 tyconUQname :: String -> String
822 tyconUQname x = let x' = dropWhile (not . (==) '.') x
823                  in if x' == [] then x else tyconUQname (tail x')
824
825
826 -- | Gets the module of a type constructor:
827 -- take *.*.*... before name
828 tyconModule :: String -> String
829 tyconModule x = let (a,b) = break ((==) '.') x
830                  in if b == ""
831                       then b
832                       else a ++ tyconModule' (tail b)
833   where
834     tyconModule' y = let y' = tyconModule y
835                       in if y' == "" then "" else ('.':y')
836
837
838
839
840 ------------------------------------------------------------------------------
841 ------------------------------------------------------------------------------
842 --
843 --      Instances of the Data class for Prelude-like types.
844 --      We define top-level definitions for representations.
845 --
846 ------------------------------------------------------------------------------
847
848
849 falseConstr :: Constr
850 falseConstr  = mkConstr boolDataType "False" [] Prefix
851 trueConstr :: Constr
852 trueConstr   = mkConstr boolDataType "True"  [] Prefix
853
854 boolDataType :: DataType
855 boolDataType = mkDataType "Prelude.Bool" [falseConstr,trueConstr]
856
857 instance Data Bool where
858   toConstr False = falseConstr
859   toConstr True  = trueConstr
860   gunfold _ z c  = case constrIndex c of
861                      1 -> z False
862                      2 -> z True
863                      _ -> error "gunfold"
864   dataTypeOf _ = boolDataType
865
866
867 ------------------------------------------------------------------------------
868
869 charType :: DataType
870 charType = mkCharType "Prelude.Char"
871
872 instance Data Char where
873   toConstr x = mkCharConstr charType x
874   gunfold _ z c = case constrRep c of
875                     (CharConstr x) -> z x
876                     _ -> error "gunfold"
877   dataTypeOf _ = charType
878
879
880 ------------------------------------------------------------------------------
881
882 floatType :: DataType
883 floatType = mkFloatType "Prelude.Float"
884
885 instance Data Float where
886   toConstr = mkRealConstr floatType
887   gunfold _ z c = case constrRep c of
888                     (FloatConstr x) -> z (realToFrac x)
889                     _ -> error "gunfold"
890   dataTypeOf _ = floatType
891
892
893 ------------------------------------------------------------------------------
894
895 doubleType :: DataType
896 doubleType = mkFloatType "Prelude.Double"
897
898 instance Data Double where
899   toConstr = mkRealConstr doubleType
900   gunfold _ z c = case constrRep c of
901                     (FloatConstr x) -> z (realToFrac x)
902                     _ -> error "gunfold"
903   dataTypeOf _ = doubleType
904
905
906 ------------------------------------------------------------------------------
907
908 intType :: DataType
909 intType = mkIntType "Prelude.Int"
910
911 instance Data Int where
912   toConstr x = mkIntConstr intType (fromIntegral x)
913   gunfold _ z c = case constrRep c of
914                     (IntConstr x) -> z (fromIntegral x)
915                     _ -> error "gunfold"
916   dataTypeOf _ = intType
917
918
919 ------------------------------------------------------------------------------
920
921 integerType :: DataType
922 integerType = mkIntType "Prelude.Integer"
923
924 instance Data Integer where
925   toConstr = mkIntConstr integerType
926   gunfold _ z c = case constrRep c of
927                     (IntConstr x) -> z x
928                     _ -> error "gunfold"
929   dataTypeOf _ = integerType
930
931
932 ------------------------------------------------------------------------------
933
934 int8Type :: DataType
935 int8Type = mkIntType "Data.Int.Int8"
936
937 instance Data Int8 where
938   toConstr x = mkIntConstr int8Type (fromIntegral x)
939   gunfold _ z c = case constrRep c of
940                     (IntConstr x) -> z (fromIntegral x)
941                     _ -> error "gunfold"
942   dataTypeOf _ = int8Type
943
944
945 ------------------------------------------------------------------------------
946
947 int16Type :: DataType
948 int16Type = mkIntType "Data.Int.Int16"
949
950 instance Data Int16 where
951   toConstr x = mkIntConstr int16Type (fromIntegral x)
952   gunfold _ z c = case constrRep c of
953                     (IntConstr x) -> z (fromIntegral x)
954                     _ -> error "gunfold"
955   dataTypeOf _ = int16Type
956
957
958 ------------------------------------------------------------------------------
959
960 int32Type :: DataType
961 int32Type = mkIntType "Data.Int.Int32"
962
963 instance Data Int32 where
964   toConstr x = mkIntConstr int32Type (fromIntegral x)
965   gunfold _ z c = case constrRep c of
966                     (IntConstr x) -> z (fromIntegral x)
967                     _ -> error "gunfold"
968   dataTypeOf _ = int32Type
969
970
971 ------------------------------------------------------------------------------
972
973 int64Type :: DataType
974 int64Type = mkIntType "Data.Int.Int64"
975
976 instance Data Int64 where
977   toConstr x = mkIntConstr int64Type (fromIntegral x)
978   gunfold _ z c = case constrRep c of
979                     (IntConstr x) -> z (fromIntegral x)
980                     _ -> error "gunfold"
981   dataTypeOf _ = int64Type
982
983
984 ------------------------------------------------------------------------------
985
986 wordType :: DataType
987 wordType = mkIntType "Data.Word.Word"
988
989 instance Data Word where
990   toConstr x = mkIntConstr wordType (fromIntegral x)
991   gunfold _ z c = case constrRep c of
992                     (IntConstr x) -> z (fromIntegral x)
993                     _ -> error "gunfold"
994   dataTypeOf _ = wordType
995
996
997 ------------------------------------------------------------------------------
998
999 word8Type :: DataType
1000 word8Type = mkIntType "Data.Word.Word8"
1001
1002 instance Data Word8 where
1003   toConstr x = mkIntConstr word8Type (fromIntegral x)
1004   gunfold _ z c = case constrRep c of
1005                     (IntConstr x) -> z (fromIntegral x)
1006                     _ -> error "gunfold"
1007   dataTypeOf _ = word8Type
1008
1009
1010 ------------------------------------------------------------------------------
1011
1012 word16Type :: DataType
1013 word16Type = mkIntType "Data.Word.Word16"
1014
1015 instance Data Word16 where
1016   toConstr x = mkIntConstr word16Type (fromIntegral x)
1017   gunfold _ z c = case constrRep c of
1018                     (IntConstr x) -> z (fromIntegral x)
1019                     _ -> error "gunfold"
1020   dataTypeOf _ = word16Type
1021
1022
1023 ------------------------------------------------------------------------------
1024
1025 word32Type :: DataType
1026 word32Type = mkIntType "Data.Word.Word32"
1027
1028 instance Data Word32 where
1029   toConstr x = mkIntConstr word32Type (fromIntegral x)
1030   gunfold _ z c = case constrRep c of
1031                     (IntConstr x) -> z (fromIntegral x)
1032                     _ -> error "gunfold"
1033   dataTypeOf _ = word32Type
1034
1035
1036 ------------------------------------------------------------------------------
1037
1038 word64Type :: DataType
1039 word64Type = mkIntType "Data.Word.Word64"
1040
1041 instance Data Word64 where
1042   toConstr x = mkIntConstr word64Type (fromIntegral x)
1043   gunfold _ z c = case constrRep c of
1044                     (IntConstr x) -> z (fromIntegral x)
1045                     _ -> error "gunfold"
1046   dataTypeOf _ = word64Type
1047
1048
1049 ------------------------------------------------------------------------------
1050
1051 ratioConstr :: Constr
1052 ratioConstr = mkConstr ratioDataType ":%" [] Infix
1053
1054 ratioDataType :: DataType
1055 ratioDataType = mkDataType "GHC.Real.Ratio" [ratioConstr]
1056
1057 instance (Data a, Integral a) => Data (Ratio a) where
1058   gfoldl k z (a :% b) = z (:%) `k` a `k` b
1059   toConstr _ = ratioConstr
1060   gunfold k z c | constrIndex c == 1 = k (k (z (:%)))
1061   gunfold _ _ _ = error "gunfold"
1062   dataTypeOf _  = ratioDataType
1063
1064
1065 ------------------------------------------------------------------------------
1066
1067 nilConstr :: Constr
1068 nilConstr    = mkConstr listDataType "[]" [] Prefix
1069 consConstr :: Constr
1070 consConstr   = mkConstr listDataType "(:)" [] Infix
1071
1072 listDataType :: DataType
1073 listDataType = mkDataType "Prelude.[]" [nilConstr,consConstr]
1074
1075 instance Data a => Data [a] where
1076   gfoldl _ z []     = z []
1077   gfoldl f z (x:xs) = z (:) `f` x `f` xs
1078   toConstr []    = nilConstr
1079   toConstr (_:_) = consConstr
1080   gunfold k z c = case constrIndex c of
1081                     1 -> z []
1082                     2 -> k (k (z (:)))
1083                     _ -> error "gunfold"
1084   dataTypeOf _ = listDataType
1085   dataCast1 f  = gcast1 f
1086
1087 --
1088 -- The gmaps are given as an illustration.
1089 -- This shows that the gmaps for lists are different from list maps.
1090 --
1091   gmapT  _   []     = []
1092   gmapT  f   (x:xs) = (f x:f xs)
1093   gmapQ  _   []     = []
1094   gmapQ  f   (x:xs) = [f x,f xs]
1095   gmapM  _   []     = return []
1096   gmapM  f   (x:xs) = f x >>= \x' -> f xs >>= \xs' -> return (x':xs')
1097
1098
1099 ------------------------------------------------------------------------------
1100
1101 nothingConstr :: Constr
1102 nothingConstr = mkConstr maybeDataType "Nothing" [] Prefix
1103 justConstr :: Constr
1104 justConstr    = mkConstr maybeDataType "Just"    [] Prefix
1105
1106 maybeDataType :: DataType
1107 maybeDataType = mkDataType "Prelude.Maybe" [nothingConstr,justConstr]
1108
1109 instance Data a => Data (Maybe a) where
1110   gfoldl _ z Nothing  = z Nothing
1111   gfoldl f z (Just x) = z Just `f` x
1112   toConstr Nothing  = nothingConstr
1113   toConstr (Just _) = justConstr
1114   gunfold k z c = case constrIndex c of
1115                     1 -> z Nothing
1116                     2 -> k (z Just)
1117                     _ -> error "gunfold"
1118   dataTypeOf _ = maybeDataType
1119   dataCast1 f  = gcast1 f
1120
1121
1122 ------------------------------------------------------------------------------
1123
1124 ltConstr :: Constr
1125 ltConstr         = mkConstr orderingDataType "LT" [] Prefix
1126 eqConstr :: Constr
1127 eqConstr         = mkConstr orderingDataType "EQ" [] Prefix
1128 gtConstr :: Constr
1129 gtConstr         = mkConstr orderingDataType "GT" [] Prefix
1130
1131 orderingDataType :: DataType
1132 orderingDataType = mkDataType "Prelude.Ordering" [ltConstr,eqConstr,gtConstr]
1133
1134 instance Data Ordering where
1135   gfoldl _ z LT  = z LT
1136   gfoldl _ z EQ  = z EQ
1137   gfoldl _ z GT  = z GT
1138   toConstr LT  = ltConstr
1139   toConstr EQ  = eqConstr
1140   toConstr GT  = gtConstr
1141   gunfold _ z c = case constrIndex c of
1142                     1 -> z LT
1143                     2 -> z EQ
1144                     3 -> z GT
1145                     _ -> error "gunfold"
1146   dataTypeOf _ = orderingDataType
1147
1148
1149 ------------------------------------------------------------------------------
1150
1151 leftConstr :: Constr
1152 leftConstr     = mkConstr eitherDataType "Left"  [] Prefix
1153
1154 rightConstr :: Constr
1155 rightConstr    = mkConstr eitherDataType "Right" [] Prefix
1156
1157 eitherDataType :: DataType
1158 eitherDataType = mkDataType "Prelude.Either" [leftConstr,rightConstr]
1159
1160 instance (Data a, Data b) => Data (Either a b) where
1161   gfoldl f z (Left a)   = z Left  `f` a
1162   gfoldl f z (Right a)  = z Right `f` a
1163   toConstr (Left _)  = leftConstr
1164   toConstr (Right _) = rightConstr
1165   gunfold k z c = case constrIndex c of
1166                     1 -> k (z Left)
1167                     2 -> k (z Right)
1168                     _ -> error "gunfold"
1169   dataTypeOf _ = eitherDataType
1170   dataCast2 f  = gcast2 f
1171
1172
1173 ------------------------------------------------------------------------------
1174
1175 tuple0Constr :: Constr
1176 tuple0Constr = mkConstr tuple0DataType "()" [] Prefix
1177
1178 tuple0DataType :: DataType
1179 tuple0DataType = mkDataType "Prelude.()" [tuple0Constr]
1180
1181 instance Data () where
1182   toConstr ()   = tuple0Constr
1183   gunfold _ z c | constrIndex c == 1 = z ()
1184   gunfold _ _ _ = error "gunfold"
1185   dataTypeOf _  = tuple0DataType
1186
1187
1188 ------------------------------------------------------------------------------
1189
1190 tuple2Constr :: Constr
1191 tuple2Constr = mkConstr tuple2DataType "(,)" [] Infix
1192
1193 tuple2DataType :: DataType
1194 tuple2DataType = mkDataType "Prelude.(,)" [tuple2Constr]
1195
1196 instance (Data a, Data b) => Data (a,b) where
1197   gfoldl f z (a,b) = z (,) `f` a `f` b
1198   toConstr (_,_) = tuple2Constr
1199   gunfold k z c | constrIndex c == 1 = k (k (z (,)))
1200   gunfold _ _ _ = error "gunfold"
1201   dataTypeOf _  = tuple2DataType
1202   dataCast2 f   = gcast2 f
1203
1204
1205 ------------------------------------------------------------------------------
1206
1207 tuple3Constr :: Constr
1208 tuple3Constr = mkConstr tuple3DataType "(,,)" [] Infix
1209
1210 tuple3DataType :: DataType
1211 tuple3DataType = mkDataType "Prelude.(,,)" [tuple3Constr]
1212
1213 instance (Data a, Data b, Data c) => Data (a,b,c) where
1214   gfoldl f z (a,b,c) = z (,,) `f` a `f` b `f` c
1215   toConstr (_,_,_) = tuple3Constr
1216   gunfold k z c | constrIndex c == 1 = k (k (k (z (,,))))
1217   gunfold _ _ _ = error "gunfold"
1218   dataTypeOf _  = tuple3DataType
1219
1220
1221 ------------------------------------------------------------------------------
1222
1223 tuple4Constr :: Constr
1224 tuple4Constr = mkConstr tuple4DataType "(,,,)" [] Infix
1225
1226 tuple4DataType :: DataType
1227 tuple4DataType = mkDataType "Prelude.(,,,)" [tuple4Constr]
1228
1229 instance (Data a, Data b, Data c, Data d)
1230          => Data (a,b,c,d) where
1231   gfoldl f z (a,b,c,d) = z (,,,) `f` a `f` b `f` c `f` d
1232   toConstr (_,_,_,_) = tuple4Constr
1233   gunfold k z c = case constrIndex c of
1234                     1 -> k (k (k (k (z (,,,)))))
1235                     _ -> error "gunfold"
1236   dataTypeOf _ = tuple4DataType
1237
1238
1239 ------------------------------------------------------------------------------
1240
1241 tuple5Constr :: Constr
1242 tuple5Constr = mkConstr tuple5DataType "(,,,,)" [] Infix
1243
1244 tuple5DataType :: DataType
1245 tuple5DataType = mkDataType "Prelude.(,,,,)" [tuple5Constr]
1246
1247 instance (Data a, Data b, Data c, Data d, Data e)
1248          => Data (a,b,c,d,e) where
1249   gfoldl f z (a,b,c,d,e) = z (,,,,) `f` a `f` b `f` c `f` d `f` e
1250   toConstr (_,_,_,_,_) = tuple5Constr
1251   gunfold k z c = case constrIndex c of
1252                     1 -> k (k (k (k (k (z (,,,,))))))
1253                     _ -> error "gunfold"
1254   dataTypeOf _ = tuple5DataType
1255
1256
1257 ------------------------------------------------------------------------------
1258
1259 tuple6Constr :: Constr
1260 tuple6Constr = mkConstr tuple6DataType "(,,,,,)" [] Infix
1261
1262 tuple6DataType :: DataType
1263 tuple6DataType = mkDataType "Prelude.(,,,,,)" [tuple6Constr]
1264
1265 instance (Data a, Data b, Data c, Data d, Data e, Data f)
1266          => Data (a,b,c,d,e,f) where
1267   gfoldl f z (a,b,c,d,e,f') = z (,,,,,) `f` a `f` b `f` c `f` d `f` e `f` f'
1268   toConstr (_,_,_,_,_,_) = tuple6Constr
1269   gunfold k z c = case constrIndex c of
1270                     1 -> k (k (k (k (k (k (z (,,,,,)))))))
1271                     _ -> error "gunfold"
1272   dataTypeOf _ = tuple6DataType
1273
1274
1275 ------------------------------------------------------------------------------
1276
1277 tuple7Constr :: Constr
1278 tuple7Constr = mkConstr tuple7DataType "(,,,,,,)" [] Infix
1279
1280 tuple7DataType :: DataType
1281 tuple7DataType = mkDataType "Prelude.(,,,,,,)" [tuple7Constr]
1282
1283 instance (Data a, Data b, Data c, Data d, Data e, Data f, Data g)
1284          => Data (a,b,c,d,e,f,g) where
1285   gfoldl f z (a,b,c,d,e,f',g) =
1286     z (,,,,,,) `f` a `f` b `f` c `f` d `f` e `f` f' `f` g
1287   toConstr  (_,_,_,_,_,_,_) = tuple7Constr
1288   gunfold k z c = case constrIndex c of
1289                     1 -> k (k (k (k (k (k (k (z (,,,,,,))))))))
1290                     _ -> error "gunfold"
1291   dataTypeOf _ = tuple7DataType
1292
1293
1294 ------------------------------------------------------------------------------
1295
1296 instance Typeable a => Data (Ptr a) where
1297   toConstr _   = error "toConstr"
1298   gunfold _ _  = error "gunfold"
1299   dataTypeOf _ = mkNoRepType "GHC.Ptr.Ptr"
1300
1301
1302 ------------------------------------------------------------------------------
1303
1304 instance Typeable a => Data (ForeignPtr a) where
1305   toConstr _   = error "toConstr"
1306   gunfold _ _  = error "gunfold"
1307   dataTypeOf _ = mkNoRepType "GHC.ForeignPtr.ForeignPtr"
1308
1309
1310 ------------------------------------------------------------------------------
1311 -- The Data instance for Array preserves data abstraction at the cost of 
1312 -- inefficiency. We omit reflection services for the sake of data abstraction.
1313 instance (Typeable a, Data b, Ix a) => Data (Array a b)
1314  where
1315   gfoldl f z a = z (listArray (bounds a)) `f` (elems a)
1316   toConstr _   = error "toConstr"
1317   gunfold _ _  = error "gunfold"
1318   dataTypeOf _ = mkNoRepType "Data.Array.Array"
1319