[project @ 2004-08-16 09:53:47 by simonpj]
[ghc-hetmet.git] / ghc / compiler / basicTypes / DataCon.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1998
3 %
4 \section[DataCon]{@DataCon@: Data Constructors}
5
6 \begin{code}
7 module DataCon (
8         DataCon, DataConIds(..),
9         ConTag, fIRST_TAG,
10         mkDataCon,
11         dataConRepType, dataConSig, dataConName, dataConTag, dataConTyCon,
12         dataConArgTys, dataConOrigArgTys, dataConInstOrigArgTys,
13         dataConRepArgTys, dataConTheta, 
14         dataConFieldLabels, dataConStrictMarks, dataConExStricts,
15         dataConSourceArity, dataConRepArity,
16         dataConNumInstArgs, dataConIsInfix,
17         dataConWorkId, dataConWrapId, dataConWrapId_maybe, dataConImplicitIds,
18         dataConRepStrictness,
19         isNullaryDataCon, isTupleCon, isUnboxedTupleCon,
20         isExistentialDataCon, classDataCon, dataConExistentialTyVars,
21
22         splitProductType_maybe, splitProductType,
23     ) where
24
25 #include "HsVersions.h"
26
27 import {-# SOURCE #-} Subst( substTyWith )
28
29 import Type             ( Type, ThetaType, 
30                           mkForAllTys, mkFunTys, mkTyConApp,
31                           mkTyVarTys, splitTyConApp_maybe, 
32                           mkPredTys, isStrictPred, pprType
33                         )
34 import TyCon            ( TyCon, tyConDataCons, tyConDataCons, isProductTyCon,
35                           isTupleTyCon, isUnboxedTupleTyCon )
36 import Class            ( Class, classTyCon )
37 import Name             ( Name, NamedThing(..), nameUnique )
38 import Var              ( TyVar, Id )
39 import FieldLabel       ( FieldLabel )
40 import BasicTypes       ( Arity, StrictnessMark(..) )
41 import Outputable
42 import Unique           ( Unique, Uniquable(..) )
43 import ListSetOps       ( assoc )
44 import Util             ( zipEqual, zipWithEqual, notNull )
45 \end{code}
46
47
48 Data constructor representation
49 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
50 Consider the following Haskell data type declaration
51
52         data T = T !Int ![Int]
53
54 Using the strictness annotations, GHC will represent this as
55
56         data T = T Int# [Int]
57
58 That is, the Int has been unboxed.  Furthermore, the Haskell source construction
59
60         T e1 e2
61
62 is translated to
63
64         case e1 of { I# x -> 
65         case e2 of { r ->
66         T x r }}
67
68 That is, the first argument is unboxed, and the second is evaluated.  Finally,
69 pattern matching is translated too:
70
71         case e of { T a b -> ... }
72
73 becomes
74
75         case e of { T a' b -> let a = I# a' in ... }
76
77 To keep ourselves sane, we name the different versions of the data constructor
78 differently, as follows.
79
80
81 Note [Data Constructor Naming]
82 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
83 Each data constructor C has two, and possibly three, Names associated with it:
84
85                              OccName    Name space      Used for
86   ---------------------------------------------------------------------------
87   * The "source data con"       C       DataName        The DataCon itself
88   * The "real data con"         C       VarName         Its worker Id
89   * The "wrapper data con"      $WC     VarName         Wrapper Id (optional)
90
91 Each of these three has a distinct Unique.  The "source data con" name
92 appears in the output of the renamer, and names the Haskell-source
93 data constructor.  The type checker translates it into either the wrapper Id
94 (if it exists) or worker Id (otherwise).
95
96 The data con has one or two Ids associated with it:
97
98   The "worker Id", is the actual data constructor.
99         Its type may be different to the Haskell source constructor
100         because:
101                 - useless dict args are dropped
102                 - strict args may be flattened
103         The worker is very like a primop, in that it has no binding.
104
105         Newtypes currently do get a worker-Id, but it is never used.
106
107
108   The "wrapper Id", $wC, whose type is exactly what it looks like
109         in the source program. It is an ordinary function,
110         and it gets a top-level binding like any other function.
111
112         The wrapper Id isn't generated for a data type if the worker
113         and wrapper are identical.  It's always generated for a newtype.
114
115
116
117 A note about the stupid context
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
119 Data types can have a context:
120         
121         data (Eq a, Ord b) => T a b = T1 a b | T2 a
122
123 and that makes the constructors have a context too
124 (notice that T2's context is "thinned"):
125
126         T1 :: (Eq a, Ord b) => a -> b -> T a b
127         T2 :: (Eq a) => a -> T a b
128
129 Furthermore, this context pops up when pattern matching
130 (though GHC hasn't implemented this, but it is in H98, and
131 I've fixed GHC so that it now does):
132
133         f (T2 x) = x
134 gets inferred type
135         f :: Eq a => T a b -> a
136
137 I say the context is "stupid" because the dictionaries passed
138 are immediately discarded -- they do nothing and have no benefit.
139 It's a flaw in the language.
140
141 Up to now [March 2002] I have put this stupid context into the type of
142 the "wrapper" constructors functions, T1 and T2, but that turned out
143 to be jolly inconvenient for generics, and record update, and other
144 functions that build values of type T (because they don't have
145 suitable dictionaries available).
146
147 So now I've taken the stupid context out.  I simply deal with it
148 separately in the type checker on occurrences of a constructor, either
149 in an expression or in a pattern.
150
151 [May 2003: actually I think this decision could evasily be reversed now,
152 and probably should be.  Generics could be disabled for types with 
153 a stupid context; record updates now (H98) needs the context too; etc.
154 It's an unforced change, so I'm leaving it for now --- but it does seem
155 odd that the wrapper doesn't include the stupid context.]
156
157
158
159 %************************************************************************
160 %*                                                                      *
161 \subsection{Data constructors}
162 %*                                                                      *
163 %************************************************************************
164
165 \begin{code}
166 data DataCon
167   = MkData {                    -- Used for data constructors only;
168                                 -- there *is* no constructor for a newtype
169
170         dcName    :: Name,      -- This is the name of the *source data con*
171                                 -- (see "Note [Data Constructor Naming]" above)
172
173         dcUnique :: Unique,             -- Cached from Name
174         dcTag    :: ConTag,
175
176         -- Running example:
177         --
178         --      data Eq a => T a = forall b. Ord b => MkT a [b]
179
180         dcRepType   :: Type,    -- Type of the constructor
181                                 --      forall a b . Ord b => a -> [b] -> MkT a
182                                 -- (this is *not* of the constructor wrapper Id:
183                                 --  see notes after this data type declaration)
184                                 --
185         -- Notice that the existential type parameters come *second*.  
186         -- Reason: in a case expression we may find:
187         --      case (e :: T t) of { MkT b (d:Ord b) (x:t) (xs:[b]) -> ... }
188         -- It's convenient to apply the rep-type of MkT to 't', to get
189         --      forall b. Ord b => ...
190         -- and use that to check the pattern.  Mind you, this is really only
191         -- use in CoreLint.
192
193
194         -- The next six fields express the type of the constructor, in pieces
195         -- e.g.
196         --
197         --      dcTyVars   = [a]
198         --      dcTheta    = [Eq a]
199         --      dcExTyVars = [b]
200         --      dcExTheta  = [Ord b]
201         --      dcOrigArgTys   = [a,List b]
202         --      dcTyCon    = T
203
204         dcTyVars :: [TyVar],            -- Type vars for the data type decl
205                                         -- These are ALWAYS THE SAME AS THE TYVARS
206                                         -- FOR THE PARENT TyCon.  We occasionally rely on
207                                         -- this just to avoid redundant instantiation
208
209         dcStupidTheta  ::  ThetaType,   -- This is a "thinned" version of the context of 
210                                         -- the data decl.  
211                 -- "Thinned", because the Report says
212                 -- to eliminate any constraints that don't mention
213                 -- tyvars free in the arg types for this constructor
214                 --
215                 -- "Stupid", because the dictionaries aren't used for anything.  
216                 -- 
217                 -- Indeed, [as of March 02] they are no 
218                 -- longer in the type of the wrapper Id, because
219                 -- that makes it harder to use the wrap-id to rebuild
220                 -- values after record selection or in generics.
221
222         dcExTyVars :: [TyVar],          -- Ditto for the context of the constructor,
223         dcExTheta  :: ThetaType,        -- the existentially quantified stuff
224                                         
225         dcOrigArgTys :: [Type],         -- Original argument types
226                                         -- (before unboxing and flattening of
227                                         --  strict fields)
228
229         -- Now the strictness annotations and field labels of the constructor
230         dcStrictMarks :: [StrictnessMark],
231                 -- Strictness annotations as decided by the compiler.  
232                 -- Does *not* include the existential dictionaries
233                 -- length = dataConSourceArity dataCon
234
235         dcFields  :: [FieldLabel],
236                 -- Field labels for this constructor, in the
237                 -- same order as the argument types; 
238                 -- length = 0 (if not a record) or dataConSourceArity.
239
240         -- Constructor representation
241         dcRepArgTys :: [Type],          -- Final, representation argument types, 
242                                         -- after unboxing and flattening,
243                                         -- and *including* existential dictionaries
244
245         dcRepStrictness :: [StrictnessMark],    -- One for each representation argument 
246
247         dcTyCon  :: TyCon,              -- Result tycon
248
249         -- Finally, the curried worker function that corresponds to the constructor
250         -- It doesn't have an unfolding; the code generator saturates these Ids
251         -- and allocates a real constructor when it finds one.
252         --
253         -- An entirely separate wrapper function is built in TcTyDecls
254
255         dcIds :: DataConIds,
256
257         dcInfix :: Bool         -- True <=> declared infix
258                                 -- Used for Template Haskell and 'deriving' only
259                                 -- The actual fixity is stored elsewhere
260   }
261
262 data DataConIds
263   = NewDC Id                    -- Newtypes have only a wrapper, but no worker
264   | AlgDC (Maybe Id) Id         -- Algebraic data types always have a worker, and
265                                 -- may or may not have a wrapper, depending on whether
266                                 -- the wrapper does anything.
267
268         -- *Neither* the worker *nor* the wrapper take the dcStupidTheta dicts as arguments
269
270         -- The wrapper takes dcOrigArgTys as its arguments
271         -- The worker takes dcRepArgTys as its arguments
272         -- If the worker is absent, dcRepArgTys is the same as dcOrigArgTys
273
274         -- The 'Nothing' case of AlgDC is important
275         -- Not only is this efficient,
276         -- but it also ensures that the wrapper is replaced
277         -- by the worker (becuase it *is* the wroker)
278         -- even when there are no args. E.g. in
279         --              f (:) x
280         -- the (:) *is* the worker.
281         -- This is really important in rule matching,
282         -- (We could match on the wrappers,
283         -- but that makes it less likely that rules will match
284         -- when we bring bits of unfoldings together.)
285
286 type ConTag = Int
287
288 fIRST_TAG :: ConTag
289 fIRST_TAG =  1  -- Tags allocated from here for real constructors
290 \end{code}
291
292 The dcRepType field contains the type of the representation of a contructor
293 This may differ from the type of the contructor *Id* (built
294 by MkId.mkDataConId) for two reasons:
295         a) the constructor Id may be overloaded, but the dictionary isn't stored
296            e.g.    data Eq a => T a = MkT a a
297
298         b) the constructor may store an unboxed version of a strict field.
299
300 Here's an example illustrating both:
301         data Ord a => T a = MkT Int! a
302 Here
303         T :: Ord a => Int -> a -> T a
304 but the rep type is
305         Trep :: Int# -> a -> T a
306 Actually, the unboxed part isn't implemented yet!
307
308
309 %************************************************************************
310 %*                                                                      *
311 \subsection{Instances}
312 %*                                                                      *
313 %************************************************************************
314
315 \begin{code}
316 instance Eq DataCon where
317     a == b = getUnique a == getUnique b
318     a /= b = getUnique a /= getUnique b
319
320 instance Ord DataCon where
321     a <= b = getUnique a <= getUnique b
322     a <  b = getUnique a <  getUnique b
323     a >= b = getUnique a >= getUnique b
324     a >  b = getUnique a > getUnique b
325     compare a b = getUnique a `compare` getUnique b
326
327 instance Uniquable DataCon where
328     getUnique = dcUnique
329
330 instance NamedThing DataCon where
331     getName = dcName
332
333 instance Outputable DataCon where
334     ppr con = ppr (dataConName con)
335
336 instance Show DataCon where
337     showsPrec p con = showsPrecSDoc p (ppr con)
338 \end{code}
339
340
341 %************************************************************************
342 %*                                                                      *
343 \subsection{Construction}
344 %*                                                                      *
345 %************************************************************************
346
347 \begin{code}
348 mkDataCon :: Name 
349           -> Bool       -- Declared infix
350           -> [StrictnessMark] -> [FieldLabel]
351           -> [TyVar] -> ThetaType
352           -> [TyVar] -> ThetaType
353           -> [Type] -> TyCon
354           -> DataConIds
355           -> DataCon
356   -- Can get the tag from the TyCon
357
358 mkDataCon name declared_infix
359           arg_stricts   -- Must match orig_arg_tys 1-1
360           fields
361           tyvars theta ex_tyvars ex_theta orig_arg_tys tycon
362           ids
363   = con
364   where
365     con = MkData {dcName = name, 
366                   dcUnique = nameUnique name,
367                   dcTyVars = tyvars, dcStupidTheta = theta,
368                   dcOrigArgTys = orig_arg_tys,
369                   dcRepArgTys = rep_arg_tys,
370                   dcExTyVars = ex_tyvars, dcExTheta = ex_theta,
371                   dcStrictMarks = arg_stricts, dcRepStrictness = rep_arg_stricts,
372                   dcFields = fields, dcTag = tag, dcTyCon = tycon, dcRepType = ty,
373                   dcIds = ids, dcInfix = declared_infix}
374
375         -- Strictness marks for source-args
376         --      *after unboxing choices*, 
377         -- but  *including existential dictionaries*
378         -- 
379         -- The 'arg_stricts' passed to mkDataCon are simply those for the
380         -- source-language arguments.  We add extra ones for the
381         -- dictionary arguments right here.
382     ex_dict_tys  = mkPredTys ex_theta
383     real_arg_tys = ex_dict_tys                      ++ orig_arg_tys
384     real_stricts = map mk_dict_strict_mark ex_theta ++ arg_stricts
385
386         -- Representation arguments and demands
387     (rep_arg_stricts, rep_arg_tys) = computeRep real_stricts real_arg_tys
388
389     tag = assoc "mkDataCon" (tyConDataCons tycon `zip` [fIRST_TAG..]) con
390     ty  = mkForAllTys (tyvars ++ ex_tyvars)
391                       (mkFunTys rep_arg_tys result_ty)
392                 -- NB: the existential dict args are already in rep_arg_tys
393
394     result_ty = mkTyConApp tycon (mkTyVarTys tyvars)
395
396 mk_dict_strict_mark pred | isStrictPred pred = MarkedStrict
397                          | otherwise         = NotMarkedStrict
398 \end{code}
399
400 \begin{code}
401 dataConName :: DataCon -> Name
402 dataConName = dcName
403
404 dataConTag :: DataCon -> ConTag
405 dataConTag  = dcTag
406
407 dataConTyCon :: DataCon -> TyCon
408 dataConTyCon = dcTyCon
409
410 dataConRepType :: DataCon -> Type
411 dataConRepType = dcRepType
412
413 dataConIsInfix :: DataCon -> Bool
414 dataConIsInfix = dcInfix
415
416 dataConWorkId :: DataCon -> Id
417 dataConWorkId dc = case dcIds dc of
418                         AlgDC _ wrk_id -> wrk_id
419                         NewDC _ -> pprPanic "dataConWorkId" (ppr dc)
420
421 dataConWrapId_maybe :: DataCon -> Maybe Id
422 dataConWrapId_maybe dc = case dcIds dc of
423                                 AlgDC mb_wrap _ -> mb_wrap
424                                 NewDC wrap      -> Just wrap
425
426 dataConWrapId :: DataCon -> Id
427 -- Returns an Id which looks like the Haskell-source constructor
428 dataConWrapId dc = case dcIds dc of
429                         AlgDC (Just wrap) _   -> wrap
430                         AlgDC Nothing     wrk -> wrk        -- worker=wrapper
431                         NewDC wrap            -> wrap
432
433 dataConImplicitIds :: DataCon -> [Id]
434 dataConImplicitIds dc = case dcIds dc of
435                           AlgDC (Just wrap) work -> [wrap,work]
436                           AlgDC Nothing     work -> [work]
437                           NewDC wrap             -> [wrap]
438
439 dataConFieldLabels :: DataCon -> [FieldLabel]
440 dataConFieldLabels = dcFields
441
442 dataConStrictMarks :: DataCon -> [StrictnessMark]
443 dataConStrictMarks = dcStrictMarks
444
445 dataConExStricts :: DataCon -> [StrictnessMark]
446 -- Strictness of *existential* arguments only
447 -- Usually empty, so we don't bother to cache this
448 dataConExStricts dc = map mk_dict_strict_mark (dcExTheta dc)
449
450 -- Number of type-instantiation arguments
451 -- All the remaining arguments of the DataCon are (notionally)
452 -- stored in the DataCon, and are matched in a case expression
453 dataConNumInstArgs (MkData {dcTyVars = tyvars}) = length tyvars
454
455 dataConSourceArity :: DataCon -> Arity
456         -- Source-level arity of the data constructor
457 dataConSourceArity dc = length (dcOrigArgTys dc)
458
459 -- dataConRepArity gives the number of actual fields in the
460 -- {\em representation} of the data constructor.  This may be more than appear
461 -- in the source code; the extra ones are the existentially quantified
462 -- dictionaries
463 dataConRepArity (MkData {dcRepArgTys = arg_tys}) = length arg_tys
464
465 isNullaryDataCon con  = dataConRepArity con == 0
466
467 dataConRepStrictness :: DataCon -> [StrictnessMark]
468         -- Give the demands on the arguments of a
469         -- Core constructor application (Con dc args)
470 dataConRepStrictness dc = dcRepStrictness dc
471
472 dataConSig :: DataCon -> ([TyVar], ThetaType,
473                           [TyVar], ThetaType,
474                           [Type], TyCon)
475
476 dataConSig (MkData {dcTyVars = tyvars, dcStupidTheta = theta,
477                      dcExTyVars = ex_tyvars, dcExTheta = ex_theta,
478                      dcOrigArgTys = arg_tys, dcTyCon = tycon})
479   = (tyvars, theta, ex_tyvars, ex_theta, arg_tys, tycon)
480
481 dataConArgTys :: DataCon
482               -> [Type]         -- Instantiated at these types
483                                 -- NB: these INCLUDE the existentially quantified arg types
484               -> [Type]         -- Needs arguments of these types
485                                 -- NB: these INCLUDE the existentially quantified dict args
486                                 --     but EXCLUDE the data-decl context which is discarded
487                                 -- It's all post-flattening etc; this is a representation type
488
489 dataConArgTys (MkData {dcRepArgTys = arg_tys, dcTyVars = tyvars,
490                        dcExTyVars = ex_tyvars}) inst_tys
491  = map (substTyWith (tyvars ++ ex_tyvars) inst_tys) arg_tys
492
493 dataConTheta :: DataCon -> ThetaType
494 dataConTheta dc = dcStupidTheta dc
495
496 dataConExistentialTyVars :: DataCon -> [TyVar]
497 dataConExistentialTyVars dc = dcExTyVars dc
498
499 -- And the same deal for the original arg tys:
500
501 dataConInstOrigArgTys :: DataCon -> [Type] -> [Type]
502 dataConInstOrigArgTys (MkData {dcOrigArgTys = arg_tys, dcTyVars = tyvars,
503                        dcExTyVars = ex_tyvars}) inst_tys
504  = map (substTyWith (tyvars ++ ex_tyvars) inst_tys) arg_tys
505 \end{code}
506
507 These two functions get the real argument types of the constructor,
508 without substituting for any type variables.
509
510 dataConOrigArgTys returns the arg types of the wrapper, excluding all dictionary args.
511
512 dataConRepArgTys retuns the arg types of the worker, including all dictionaries, and
513 after any flattening has been done.
514
515 \begin{code}
516 dataConOrigArgTys :: DataCon -> [Type]
517 dataConOrigArgTys dc = dcOrigArgTys dc
518
519 dataConRepArgTys :: DataCon -> [Type]
520 dataConRepArgTys dc = dcRepArgTys dc
521 \end{code}
522
523
524 \begin{code}
525 isTupleCon :: DataCon -> Bool
526 isTupleCon (MkData {dcTyCon = tc}) = isTupleTyCon tc
527         
528 isUnboxedTupleCon :: DataCon -> Bool
529 isUnboxedTupleCon (MkData {dcTyCon = tc}) = isUnboxedTupleTyCon tc
530
531 isExistentialDataCon :: DataCon -> Bool
532 isExistentialDataCon (MkData {dcExTyVars = tvs}) = notNull tvs
533 \end{code}
534
535
536 \begin{code}
537 classDataCon :: Class -> DataCon
538 classDataCon clas = case tyConDataCons (classTyCon clas) of
539                       (dict_constr:no_more) -> ASSERT( null no_more ) dict_constr 
540 \end{code}
541
542 %************************************************************************
543 %*                                                                      *
544 \subsection{Splitting products}
545 %*                                                                      *
546 %************************************************************************
547
548 \begin{code}
549 splitProductType_maybe
550         :: Type                         -- A product type, perhaps
551         -> Maybe (TyCon,                -- The type constructor
552                   [Type],               -- Type args of the tycon
553                   DataCon,              -- The data constructor
554                   [Type])               -- Its *representation* arg types
555
556         -- Returns (Just ...) for any
557         --      concrete (i.e. constructors visible)
558         --      single-constructor
559         --      not existentially quantified
560         -- type whether a data type or a new type
561         --
562         -- Rejecing existentials is conservative.  Maybe some things
563         -- could be made to work with them, but I'm not going to sweat
564         -- it through till someone finds it's important.
565
566 splitProductType_maybe ty
567   = case splitTyConApp_maybe ty of
568         Just (tycon,ty_args)
569            | isProductTyCon tycon       -- Includes check for non-existential,
570                                         -- and for constructors visible
571            -> Just (tycon, ty_args, data_con, dataConArgTys data_con ty_args)
572            where
573               data_con = head (tyConDataCons tycon)
574         other -> Nothing
575
576 splitProductType str ty
577   = case splitProductType_maybe ty of
578         Just stuff -> stuff
579         Nothing    -> pprPanic (str ++ ": not a product") (pprType ty)
580
581
582 computeRep :: [StrictnessMark]          -- Original arg strictness
583            -> [Type]                    -- and types
584            -> ([StrictnessMark],        -- Representation arg strictness
585                [Type])                  -- And type
586
587 computeRep stricts tys
588   = unzip $ concat $ zipWithEqual "computeRep" unbox stricts tys
589   where
590     unbox NotMarkedStrict ty = [(NotMarkedStrict, ty)]
591     unbox MarkedStrict    ty = [(MarkedStrict,    ty)]
592     unbox MarkedUnboxed   ty = zipEqual "computeRep" (dataConRepStrictness arg_dc) arg_tys
593                              where
594                                (_, _, arg_dc, arg_tys) = splitProductType "unbox_strict_arg_ty" ty
595 \end{code}