Add comments
[ghc-hetmet.git] / compiler / basicTypes / DataCon.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
4 %
5 \section[DataCon]{@DataCon@: Data Constructors}
6
7 \begin{code}
8 module DataCon (
9         -- * Main data types
10         DataCon, DataConIds(..),
11         ConTag,
12         
13         -- ** Type construction
14         mkDataCon, fIRST_TAG,
15         
16         -- ** Type deconstruction
17         dataConRepType, dataConSig, dataConFullSig,
18         dataConName, dataConIdentity, dataConTag, dataConTyCon, 
19         dataConOrigTyCon, dataConUserType,
20         dataConUnivTyVars, dataConExTyVars, dataConAllTyVars, 
21         dataConEqSpec, eqSpecPreds, dataConEqTheta, dataConDictTheta,
22         dataConStupidTheta,  
23         dataConInstArgTys, dataConOrigArgTys, dataConOrigResTy,
24         dataConInstOrigArgTys, dataConRepArgTys, 
25         dataConFieldLabels, dataConFieldType,
26         dataConStrictMarks, dataConExStricts,
27         dataConSourceArity, dataConRepArity,
28         dataConIsInfix,
29         dataConWorkId, dataConWrapId, dataConWrapId_maybe, dataConImplicitIds,
30         dataConRepStrictness,
31         
32         -- ** Predicates on DataCons
33         isNullarySrcDataCon, isNullaryRepDataCon, isTupleCon, isUnboxedTupleCon,
34         isVanillaDataCon, classDataCon, 
35
36         -- * Splitting product types
37         splitProductType_maybe, splitProductType, deepSplitProductType,
38         deepSplitProductType_maybe
39     ) where
40
41 #include "HsVersions.h"
42
43 import Type
44 import Coercion
45 import TyCon
46 import Class
47 import Name
48 import Var
49 import BasicTypes
50 import Outputable
51 import Unique
52 import ListSetOps
53 import Util
54 import Maybes
55 import FastString
56 import Module
57
58 import Data.Char
59 import Data.Word
60 import Data.List ( partition )
61 \end{code}
62
63
64 Data constructor representation
65 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
66 Consider the following Haskell data type declaration
67
68         data T = T !Int ![Int]
69
70 Using the strictness annotations, GHC will represent this as
71
72         data T = T Int# [Int]
73
74 That is, the Int has been unboxed.  Furthermore, the Haskell source construction
75
76         T e1 e2
77
78 is translated to
79
80         case e1 of { I# x -> 
81         case e2 of { r ->
82         T x r }}
83
84 That is, the first argument is unboxed, and the second is evaluated.  Finally,
85 pattern matching is translated too:
86
87         case e of { T a b -> ... }
88
89 becomes
90
91         case e of { T a' b -> let a = I# a' in ... }
92
93 To keep ourselves sane, we name the different versions of the data constructor
94 differently, as follows.
95
96
97 Note [Data Constructor Naming]
98 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
99 Each data constructor C has two, and possibly up to four, Names associated with it:
100
101                              OccName    Name space      Name of
102   ---------------------------------------------------------------------------
103   * The "data con itself"       C       DataName        DataCon
104   * The "worker data con"       C       VarName         Id (the worker)
105   * The "wrapper data con"      \$WC    VarName         Id (the wrapper)
106   * The "newtype coercion"      :CoT    TcClsName       TyCon
107  
108 EVERY data constructor (incl for newtypes) has the former two (the
109 data con itself, and its worker.  But only some data constructors have a
110 wrapper (see Note [The need for a wrapper]).
111
112 Each of these three has a distinct Unique.  The "data con itself" name
113 appears in the output of the renamer, and names the Haskell-source
114 data constructor.  The type checker translates it into either the wrapper Id
115 (if it exists) or worker Id (otherwise).
116
117 The data con has one or two Ids associated with it:
118
119 The "worker Id", is the actual data constructor.
120 * Every data constructor (newtype or data type) has a worker
121
122 * The worker is very like a primop, in that it has no binding.
123
124 * For a *data* type, the worker *is* the data constructor;
125   it has no unfolding
126
127 * For a *newtype*, the worker has a compulsory unfolding which 
128   does a cast, e.g.
129         newtype T = MkT Int
130         The worker for MkT has unfolding
131                 \\(x:Int). x `cast` sym CoT
132   Here CoT is the type constructor, witnessing the FC axiom
133         axiom CoT : T = Int
134
135 The "wrapper Id", \$WC, goes as follows
136
137 * Its type is exactly what it looks like in the source program. 
138
139 * It is an ordinary function, and it gets a top-level binding 
140   like any other function.
141
142 * The wrapper Id isn't generated for a data type if there is
143   nothing for the wrapper to do.  That is, if its defn would be
144         \$wC = C
145
146 Note [The need for a wrapper]
147 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
148 Why might the wrapper have anything to do?  Two reasons:
149
150 * Unboxing strict fields (with -funbox-strict-fields)
151         data T = MkT !(Int,Int)
152         \$wMkT :: (Int,Int) -> T
153         \$wMkT (x,y) = MkT x y
154   Notice that the worker has two fields where the wapper has 
155   just one.  That is, the worker has type
156                 MkT :: Int -> Int -> T
157
158 * Equality constraints for GADTs
159         data T a where { MkT :: a -> T [a] }
160
161   The worker gets a type with explicit equality
162   constraints, thus:
163         MkT :: forall a b. (a=[b]) => b -> T a
164
165   The wrapper has the programmer-specified type:
166         \$wMkT :: a -> T [a]
167         \$wMkT a x = MkT [a] a [a] x
168   The third argument is a coerion
169         [a] :: [a]~[a]
170
171 INVARIANT: the dictionary constructor for a class
172            never has a wrapper.
173
174
175 A note about the stupid context
176 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
177 Data types can have a context:
178         
179         data (Eq a, Ord b) => T a b = T1 a b | T2 a
180
181 and that makes the constructors have a context too
182 (notice that T2's context is "thinned"):
183
184         T1 :: (Eq a, Ord b) => a -> b -> T a b
185         T2 :: (Eq a) => a -> T a b
186
187 Furthermore, this context pops up when pattern matching
188 (though GHC hasn't implemented this, but it is in H98, and
189 I've fixed GHC so that it now does):
190
191         f (T2 x) = x
192 gets inferred type
193         f :: Eq a => T a b -> a
194
195 I say the context is "stupid" because the dictionaries passed
196 are immediately discarded -- they do nothing and have no benefit.
197 It's a flaw in the language.
198
199         Up to now [March 2002] I have put this stupid context into the
200         type of the "wrapper" constructors functions, T1 and T2, but
201         that turned out to be jolly inconvenient for generics, and
202         record update, and other functions that build values of type T
203         (because they don't have suitable dictionaries available).
204
205         So now I've taken the stupid context out.  I simply deal with
206         it separately in the type checker on occurrences of a
207         constructor, either in an expression or in a pattern.
208
209         [May 2003: actually I think this decision could evasily be
210         reversed now, and probably should be.  Generics could be
211         disabled for types with a stupid context; record updates now
212         (H98) needs the context too; etc.  It's an unforced change, so
213         I'm leaving it for now --- but it does seem odd that the
214         wrapper doesn't include the stupid context.]
215
216 [July 04] With the advent of generalised data types, it's less obvious
217 what the "stupid context" is.  Consider
218         C :: forall a. Ord a => a -> a -> T (Foo a)
219 Does the C constructor in Core contain the Ord dictionary?  Yes, it must:
220
221         f :: T b -> Ordering
222         f = /\b. \x:T b. 
223             case x of
224                 C a (d:Ord a) (p:a) (q:a) -> compare d p q
225
226 Note that (Foo a) might not be an instance of Ord.
227
228 %************************************************************************
229 %*                                                                      *
230 \subsection{Data constructors}
231 %*                                                                      *
232 %************************************************************************
233
234 \begin{code}
235 -- | A data constructor
236 data DataCon
237   = MkData {
238         dcName    :: Name,      -- This is the name of the *source data con*
239                                 -- (see "Note [Data Constructor Naming]" above)
240         dcUnique :: Unique,     -- Cached from Name
241         dcTag    :: ConTag,     -- ^ Tag, used for ordering 'DataCon's
242
243         -- Running example:
244         --
245         --      *** As declared by the user
246         --  data T a where
247         --    MkT :: forall x y. (x~y,Ord x) => x -> y -> T (x,y)
248
249         --      *** As represented internally
250         --  data T a where
251         --    MkT :: forall a. forall x y. (a~(x,y),x~y,Ord x) => x -> y -> T a
252         -- 
253         -- The next six fields express the type of the constructor, in pieces
254         -- e.g.
255         --
256         --      dcUnivTyVars  = [a]
257         --      dcExTyVars    = [x,y]
258         --      dcEqSpec      = [a~(x,y)]
259         --      dcEqTheta     = [x~y]   
260         --      dcDictTheta   = [Ord x]
261         --      dcOrigArgTys  = [a,List b]
262         --      dcRepTyCon       = T
263
264         dcVanilla :: Bool,      -- True <=> This is a vanilla Haskell 98 data constructor
265                                 --          Its type is of form
266                                 --              forall a1..an . t1 -> ... tm -> T a1..an
267                                 --          No existentials, no coercions, nothing.
268                                 -- That is: dcExTyVars = dcEqSpec = dcEqTheta = dcDictTheta = []
269                 -- NB 1: newtypes always have a vanilla data con
270                 -- NB 2: a vanilla constructor can still be declared in GADT-style 
271                 --       syntax, provided its type looks like the above.
272                 --       The declaration format is held in the TyCon (algTcGadtSyntax)
273
274         dcUnivTyVars :: [TyVar],        -- Universally-quantified type vars [a,b,c]
275                                         -- INVARIANT: length matches arity of the dcRepTyCon
276                                         ---           result type of (rep) data con is exactly (T a b c)
277
278         dcExTyVars   :: [TyVar],        -- Existentially-quantified type vars 
279                 -- In general, the dcUnivTyVars are NOT NECESSARILY THE SAME AS THE TYVARS
280                 -- FOR THE PARENT TyCon. With GADTs the data con might not even have 
281                 -- the same number of type variables.
282                 -- [This is a change (Oct05): previously, vanilla datacons guaranteed to
283                 --  have the same type variables as their parent TyCon, but that seems ugly.]
284
285         -- INVARIANT: the UnivTyVars and ExTyVars all have distinct OccNames
286         -- Reason: less confusing, and easier to generate IfaceSyn
287
288         dcEqSpec :: [(TyVar,Type)],     -- Equalities derived from the result type, 
289                                         -- _as written by the programmer_
290                 -- This field allows us to move conveniently between the two ways
291                 -- of representing a GADT constructor's type:
292                 --      MkT :: forall a b. (a ~ [b]) => b -> T a
293                 --      MkT :: forall b. b -> T [b]
294                 -- Each equality is of the form (a ~ ty), where 'a' is one of 
295                 -- the universally quantified type variables
296                                         
297                 -- The next two fields give the type context of the data constructor
298                 --      (aside from the GADT constraints, 
299                 --       which are given by the dcExpSpec)
300                 -- In GADT form, this is *exactly* what the programmer writes, even if
301                 -- the context constrains only universally quantified variables
302                 --      MkT :: forall a b. (a ~ b, Ord b) => a -> T a b
303         dcEqTheta   :: ThetaType,  -- The *equational* constraints
304         dcDictTheta :: ThetaType,  -- The *type-class and implicit-param* constraints
305
306         dcStupidTheta :: ThetaType,     -- The context of the data type declaration 
307                                         --      data Eq a => T a = ...
308                                         -- or, rather, a "thinned" version thereof
309                 -- "Thinned", because the Report says
310                 -- to eliminate any constraints that don't mention
311                 -- tyvars free in the arg types for this constructor
312                 --
313                 -- INVARIANT: the free tyvars of dcStupidTheta are a subset of dcUnivTyVars
314                 -- Reason: dcStupidTeta is gotten by thinning the stupid theta from the tycon
315                 -- 
316                 -- "Stupid", because the dictionaries aren't used for anything.  
317                 -- Indeed, [as of March 02] they are no longer in the type of 
318                 -- the wrapper Id, because that makes it harder to use the wrap-id 
319                 -- to rebuild values after record selection or in generics.
320
321         dcOrigArgTys :: [Type],         -- Original argument types
322                                         -- (before unboxing and flattening of strict fields)
323         dcOrigResTy :: Type,            -- Original result type, as seen by the user
324                 -- NB: for a data instance, the original user result type may 
325                 -- differ from the DataCon's representation TyCon.  Example
326                 --      data instance T [a] where MkT :: a -> T [a]
327                 -- The OrigResTy is T [a], but the dcRepTyCon might be :T123
328
329         -- Now the strictness annotations and field labels of the constructor
330         dcStrictMarks :: [StrictnessMark],
331                 -- Strictness annotations as decided by the compiler.  
332                 -- Does *not* include the existential dictionaries
333                 -- length = dataConSourceArity dataCon
334
335         dcFields  :: [FieldLabel],
336                 -- Field labels for this constructor, in the
337                 -- same order as the dcOrigArgTys; 
338                 -- length = 0 (if not a record) or dataConSourceArity.
339
340         -- Constructor representation
341         dcRepArgTys :: [Type],          -- Final, representation argument types, 
342                                         -- after unboxing and flattening,
343                                         -- and *including* existential dictionaries
344
345         dcRepStrictness :: [StrictnessMark],    -- One for each *representation* argument       
346                 -- See also Note [Data-con worker strictness] in MkId.lhs
347
348         -- Result type of constructor is T t1..tn
349         dcRepTyCon  :: TyCon,           -- Result tycon, T
350
351         dcRepType   :: Type,    -- Type of the constructor
352                                 --      forall a x y. (a~(x,y), x~y, Ord x) =>
353                                 --        x -> y -> T a
354                                 -- (this is *not* of the constructor wrapper Id:
355                                 --  see Note [Data con representation] below)
356         -- Notice that the existential type parameters come *second*.  
357         -- Reason: in a case expression we may find:
358         --      case (e :: T t) of
359         --        MkT x y co1 co2 (d:Ord x) (v:r) (w:F s) -> ...
360         -- It's convenient to apply the rep-type of MkT to 't', to get
361         --      forall x y. (t~(x,y), x~y, Ord x) => x -> y -> T t
362         -- and use that to check the pattern.  Mind you, this is really only
363         -- used in CoreLint.
364
365
366         -- The curried worker function that corresponds to the constructor:
367         -- It doesn't have an unfolding; the code generator saturates these Ids
368         -- and allocates a real constructor when it finds one.
369         --
370         -- An entirely separate wrapper function is built in TcTyDecls
371         dcIds :: DataConIds,
372
373         dcInfix :: Bool         -- True <=> declared infix
374                                 -- Used for Template Haskell and 'deriving' only
375                                 -- The actual fixity is stored elsewhere
376   }
377
378 -- | Contains the Ids of the data constructor functions
379 data DataConIds
380   = DCIds (Maybe Id) Id         -- Algebraic data types always have a worker, and
381                                 -- may or may not have a wrapper, depending on whether
382                                 -- the wrapper does anything.  Newtypes just have a worker
383
384         -- _Neither_ the worker _nor_ the wrapper take the dcStupidTheta dicts as arguments
385
386         -- The wrapper takes dcOrigArgTys as its arguments
387         -- The worker takes dcRepArgTys as its arguments
388         -- If the worker is absent, dcRepArgTys is the same as dcOrigArgTys
389
390         -- The 'Nothing' case of DCIds is important
391         -- Not only is this efficient,
392         -- but it also ensures that the wrapper is replaced
393         -- by the worker (because it *is* the worker)
394         -- even when there are no args. E.g. in
395         --              f (:) x
396         -- the (:) *is* the worker.
397         -- This is really important in rule matching,
398         -- (We could match on the wrappers,
399         -- but that makes it less likely that rules will match
400         -- when we bring bits of unfoldings together.)
401
402 -- | Type of the tags associated with each constructor possibility
403 type ConTag = Int
404
405 fIRST_TAG :: ConTag
406 -- ^ Tags are allocated from here for real constructors
407 fIRST_TAG =  1
408 \end{code}
409
410 Note [Data con representation]
411 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
412 The dcRepType field contains the type of the representation of a contructor
413 This may differ from the type of the contructor *Id* (built
414 by MkId.mkDataConId) for two reasons:
415         a) the constructor Id may be overloaded, but the dictionary isn't stored
416            e.g.    data Eq a => T a = MkT a a
417
418         b) the constructor may store an unboxed version of a strict field.
419
420 Here's an example illustrating both:
421         data Ord a => T a = MkT Int! a
422 Here
423         T :: Ord a => Int -> a -> T a
424 but the rep type is
425         Trep :: Int# -> a -> T a
426 Actually, the unboxed part isn't implemented yet!
427
428
429 %************************************************************************
430 %*                                                                      *
431 \subsection{Instances}
432 %*                                                                      *
433 %************************************************************************
434
435 \begin{code}
436 instance Eq DataCon where
437     a == b = getUnique a == getUnique b
438     a /= b = getUnique a /= getUnique b
439
440 instance Ord DataCon where
441     a <= b = getUnique a <= getUnique b
442     a <  b = getUnique a <  getUnique b
443     a >= b = getUnique a >= getUnique b
444     a >  b = getUnique a > getUnique b
445     compare a b = getUnique a `compare` getUnique b
446
447 instance Uniquable DataCon where
448     getUnique = dcUnique
449
450 instance NamedThing DataCon where
451     getName = dcName
452
453 instance Outputable DataCon where
454     ppr con = ppr (dataConName con)
455
456 instance Show DataCon where
457     showsPrec p con = showsPrecSDoc p (ppr con)
458 \end{code}
459
460
461 %************************************************************************
462 %*                                                                      *
463 \subsection{Construction}
464 %*                                                                      *
465 %************************************************************************
466
467 \begin{code}
468 -- | Build a new data constructor
469 mkDataCon :: Name 
470           -> Bool               -- ^ Is the constructor declared infix?
471           -> [StrictnessMark]   -- ^ Strictness annotations written in the source file
472           -> [FieldLabel]       -- ^ Field labels for the constructor, if it is a record, 
473                                 --   otherwise empty
474           -> [TyVar]            -- ^ Universally quantified type variables
475           -> [TyVar]            -- ^ Existentially quantified type variables
476           -> [(TyVar,Type)]     -- ^ GADT equalities
477           -> ThetaType          -- ^ Theta-type occuring before the arguments proper
478           -> [Type]             -- ^ Original argument types
479           -> Type               -- ^ Original result type
480           -> TyCon              -- ^ Representation type constructor
481           -> ThetaType          -- ^ The "stupid theta", context of the data declaration 
482                                 --   e.g. @data Eq a => T a ...@
483           -> DataConIds         -- ^ The Ids of the actual builder functions
484           -> DataCon
485   -- Can get the tag from the TyCon
486
487 mkDataCon name declared_infix
488           arg_stricts   -- Must match orig_arg_tys 1-1
489           fields
490           univ_tvs ex_tvs 
491           eq_spec theta
492           orig_arg_tys orig_res_ty rep_tycon
493           stupid_theta ids
494 -- Warning: mkDataCon is not a good place to check invariants. 
495 -- If the programmer writes the wrong result type in the decl, thus:
496 --      data T a where { MkT :: S }
497 -- then it's possible that the univ_tvs may hit an assertion failure
498 -- if you pull on univ_tvs.  This case is checked by checkValidDataCon,
499 -- so the error is detected properly... it's just that asaertions here
500 -- are a little dodgy.
501
502   = -- ASSERT( not (any isEqPred theta) )
503         -- We don't currently allow any equality predicates on
504         -- a data constructor (apart from the GADT ones in eq_spec)
505     con
506   where
507     is_vanilla = null ex_tvs && null eq_spec && null theta
508     con = MkData {dcName = name, dcUnique = nameUnique name, 
509                   dcVanilla = is_vanilla, dcInfix = declared_infix,
510                   dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, 
511                   dcEqSpec = eq_spec, 
512                   dcStupidTheta = stupid_theta, 
513                   dcEqTheta = eq_theta, dcDictTheta = dict_theta,
514                   dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
515                   dcRepTyCon = rep_tycon, 
516                   dcRepArgTys = rep_arg_tys,
517                   dcStrictMarks = arg_stricts, 
518                   dcRepStrictness = rep_arg_stricts,
519                   dcFields = fields, dcTag = tag, dcRepType = ty,
520                   dcIds = ids }
521
522         -- Strictness marks for source-args
523         --      *after unboxing choices*, 
524         -- but  *including existential dictionaries*
525         -- 
526         -- The 'arg_stricts' passed to mkDataCon are simply those for the
527         -- source-language arguments.  We add extra ones for the
528         -- dictionary arguments right here.
529     (eq_theta,dict_theta)  = partition isEqPred theta
530     dict_tys               = mkPredTys dict_theta
531     real_arg_tys           = dict_tys ++ orig_arg_tys
532     real_stricts           = map mk_dict_strict_mark dict_theta ++ arg_stricts
533
534         -- Representation arguments and demands
535         -- To do: eliminate duplication with MkId
536     (rep_arg_stricts, rep_arg_tys) = computeRep real_stricts real_arg_tys
537
538     tag = assoc "mkDataCon" (tyConDataCons rep_tycon `zip` [fIRST_TAG..]) con
539     ty  = mkForAllTys univ_tvs $ mkForAllTys ex_tvs $ 
540           mkFunTys (mkPredTys (eqSpecPreds eq_spec)) $
541           mkFunTys (mkPredTys eq_theta) $
542                 -- NB:  the dict args are already in rep_arg_tys
543                 --      because they might be flattened..
544                 --      but the equality predicates are not
545           mkFunTys rep_arg_tys $
546           mkTyConApp rep_tycon (mkTyVarTys univ_tvs)
547
548 eqSpecPreds :: [(TyVar,Type)] -> ThetaType
549 eqSpecPreds spec = [ mkEqPred (mkTyVarTy tv, ty) | (tv,ty) <- spec ]
550
551 mk_dict_strict_mark :: PredType -> StrictnessMark
552 mk_dict_strict_mark pred | isStrictPred pred = MarkedStrict
553                          | otherwise         = NotMarkedStrict
554 \end{code}
555
556 \begin{code}
557 -- | The 'Name' of the 'DataCon', giving it a unique, rooted identification
558 dataConName :: DataCon -> Name
559 dataConName = dcName
560
561 -- | The tag used for ordering 'DataCon's
562 dataConTag :: DataCon -> ConTag
563 dataConTag  = dcTag
564
565 -- | The type constructor that we are building via this data constructor
566 dataConTyCon :: DataCon -> TyCon
567 dataConTyCon = dcRepTyCon
568
569 -- | The original type constructor used in the definition of this data
570 -- constructor.  In case of a data family instance, that will be the family
571 -- type constructor.
572 dataConOrigTyCon :: DataCon -> TyCon
573 dataConOrigTyCon dc 
574   | Just (tc, _) <- tyConFamInst_maybe (dcRepTyCon dc) = tc
575   | otherwise                                          = dcRepTyCon dc
576
577 -- | The representation type of the data constructor, i.e. the sort
578 -- type that will represent values of this type at runtime
579 dataConRepType :: DataCon -> Type
580 dataConRepType = dcRepType
581
582 -- | Should the 'DataCon' be presented infix?
583 dataConIsInfix :: DataCon -> Bool
584 dataConIsInfix = dcInfix
585
586 -- | The universally-quantified type variables of the constructor
587 dataConUnivTyVars :: DataCon -> [TyVar]
588 dataConUnivTyVars = dcUnivTyVars
589
590 -- | The existentially-quantified type variables of the constructor
591 dataConExTyVars :: DataCon -> [TyVar]
592 dataConExTyVars = dcExTyVars
593
594 -- | Both the universal and existentiatial type variables of the constructor
595 dataConAllTyVars :: DataCon -> [TyVar]
596 dataConAllTyVars (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs })
597   = univ_tvs ++ ex_tvs
598
599 -- | Equalities derived from the result type of the data constructor, as written
600 -- by the programmer in any GADT declaration
601 dataConEqSpec :: DataCon -> [(TyVar,Type)]
602 dataConEqSpec = dcEqSpec
603
604 -- | The equational constraints on the data constructor type
605 dataConEqTheta :: DataCon -> ThetaType
606 dataConEqTheta = dcEqTheta
607
608 -- | The type class and implicit parameter contsraints on the data constructor type
609 dataConDictTheta :: DataCon -> ThetaType
610 dataConDictTheta = dcDictTheta
611
612 -- | Get the Id of the 'DataCon' worker: a function that is the "actual"
613 -- constructor and has no top level binding in the program. The type may
614 -- be different from the obvious one written in the source program. Panics
615 -- if there is no such 'Id' for this 'DataCon'
616 dataConWorkId :: DataCon -> Id
617 dataConWorkId dc = case dcIds dc of
618                         DCIds _ wrk_id -> wrk_id
619
620 -- | Get the Id of the 'DataCon' wrapper: a function that wraps the "actual"
621 -- constructor so it has the type visible in the source program: c.f. 'dataConWorkId'.
622 -- Returns Nothing if there is no wrapper, which occurs for an algebraic data constructor 
623 -- and also for a newtype (whose constructor is inlined compulsorily)
624 dataConWrapId_maybe :: DataCon -> Maybe Id
625 dataConWrapId_maybe dc = case dcIds dc of
626                                 DCIds mb_wrap _ -> mb_wrap
627
628 -- | Returns an Id which looks like the Haskell-source constructor by using
629 -- the wrapper if it exists (see 'dataConWrapId_maybe') and failing over to
630 -- the worker (see 'dataConWorkId')
631 dataConWrapId :: DataCon -> Id
632 dataConWrapId dc = case dcIds dc of
633                         DCIds (Just wrap) _   -> wrap
634                         DCIds Nothing     wrk -> wrk        -- worker=wrapper
635
636 -- | Find all the 'Id's implicitly brought into scope by the data constructor. Currently,
637 -- the union of the 'dataConWorkId' and the 'dataConWrapId'
638 dataConImplicitIds :: DataCon -> [Id]
639 dataConImplicitIds dc = case dcIds dc of
640                           DCIds (Just wrap) work -> [wrap,work]
641                           DCIds Nothing     work -> [work]
642
643 -- | The labels for the fields of this particular 'DataCon'
644 dataConFieldLabels :: DataCon -> [FieldLabel]
645 dataConFieldLabels = dcFields
646
647 -- | Extract the type for any given labelled field of the 'DataCon'
648 dataConFieldType :: DataCon -> FieldLabel -> Type
649 dataConFieldType con label
650   = case lookup label (dcFields con `zip` dcOrigArgTys con) of
651       Just ty -> ty
652       Nothing -> pprPanic "dataConFieldType" (ppr con <+> ppr label)
653
654 -- | The strictness markings decided on by the compiler.  Does not include those for
655 -- existential dictionaries.  The list is in one-to-one correspondence with the arity of the 'DataCon'
656 dataConStrictMarks :: DataCon -> [StrictnessMark]
657 dataConStrictMarks = dcStrictMarks
658
659 -- | Strictness of /existential/ arguments only
660 dataConExStricts :: DataCon -> [StrictnessMark]
661 -- Usually empty, so we don't bother to cache this
662 dataConExStricts dc = map mk_dict_strict_mark $ dcDictTheta dc
663
664 -- | Source-level arity of the data constructor
665 dataConSourceArity :: DataCon -> Arity
666 dataConSourceArity dc = length (dcOrigArgTys dc)
667
668 -- | Gives the number of actual fields in the /representation/ of the 
669 -- data constructor. This may be more than appear in the source code;
670 -- the extra ones are the existentially quantified dictionaries
671 dataConRepArity :: DataCon -> Int
672 dataConRepArity (MkData {dcRepArgTys = arg_tys}) = length arg_tys
673
674 -- | Return whether there are any argument types for this 'DataCon's original source type
675 isNullarySrcDataCon :: DataCon -> Bool
676 isNullarySrcDataCon dc = null (dcOrigArgTys dc)
677
678 -- | Return whether there are any argument types for this 'DataCon's runtime representation type
679 isNullaryRepDataCon :: DataCon -> Bool
680 isNullaryRepDataCon dc = null (dcRepArgTys dc)
681
682 dataConRepStrictness :: DataCon -> [StrictnessMark]
683 -- ^ Give the demands on the arguments of a
684 -- Core constructor application (Con dc args)
685 dataConRepStrictness dc = dcRepStrictness dc
686
687 -- | The \"signature\" of the 'DataCon' returns, in order:
688 --
689 -- 1) The result of 'dataConAllTyVars',
690 --
691 -- 2) All the 'ThetaType's relating to the 'DataCon' (coercion, dictionary, implicit
692 --    parameter - whatever)
693 --
694 -- 3) The type arguments to the constructor
695 --
696 -- 4) The /original/ result type of the 'DataCon'
697 dataConSig :: DataCon -> ([TyVar], ThetaType, [Type], Type)
698 dataConSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, dcEqSpec = eq_spec,
699                     dcEqTheta  = eq_theta, dcDictTheta = dict_theta, 
700                     dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
701   = (univ_tvs ++ ex_tvs, eqSpecPreds eq_spec ++ eq_theta ++ dict_theta, arg_tys, res_ty)
702
703 -- | The \"full signature\" of the 'DataCon' returns, in order:
704 --
705 -- 1) The result of 'dataConUnivTyVars'
706 --
707 -- 2) The result of 'dataConExTyVars'
708 --
709 -- 3) The result of 'dataConEqSpec'
710 --
711 -- 4) The result of 'dataConDictTheta'
712 --
713 -- 5) The original argument types to the 'DataCon' (i.e. before 
714 --    any change of the representation of the type)
715 --
716 -- 6) The original result type of the 'DataCon'
717 dataConFullSig :: DataCon 
718                -> ([TyVar], [TyVar], [(TyVar,Type)], ThetaType, ThetaType, [Type], Type)
719 dataConFullSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, dcEqSpec = eq_spec,
720                         dcEqTheta = eq_theta, dcDictTheta = dict_theta, 
721                         dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
722   = (univ_tvs, ex_tvs, eq_spec, eq_theta, dict_theta, arg_tys, res_ty)
723
724 dataConOrigResTy :: DataCon -> Type
725 dataConOrigResTy dc = dcOrigResTy dc
726
727 -- | The \"stupid theta\" of the 'DataCon', such as @data Eq a@ in:
728 --
729 -- > data Eq a => T a = ...
730 dataConStupidTheta :: DataCon -> ThetaType
731 dataConStupidTheta dc = dcStupidTheta dc
732
733 dataConUserType :: DataCon -> Type
734 -- ^ The user-declared type of the data constructor
735 -- in the nice-to-read form:
736 --
737 -- > T :: forall a b. a -> b -> T [a]
738 --
739 -- rather than:
740 --
741 -- > T :: forall a c. forall b. (c~[a]) => a -> b -> T c
742 --
743 -- NB: If the constructor is part of a data instance, the result type
744 -- mentions the family tycon, not the internal one.
745 dataConUserType  (MkData { dcUnivTyVars = univ_tvs, 
746                            dcExTyVars = ex_tvs, dcEqSpec = eq_spec,
747                            dcEqTheta = eq_theta, dcDictTheta = dict_theta, dcOrigArgTys = arg_tys,
748                            dcOrigResTy = res_ty })
749   = mkForAllTys ((univ_tvs `minusList` map fst eq_spec) ++ ex_tvs) $
750     mkFunTys (mkPredTys eq_theta) $
751     mkFunTys (mkPredTys dict_theta) $
752     mkFunTys arg_tys $
753     res_ty
754
755 -- | Finds the instantiated types of the arguments required to construct a 'DataCon' representation
756 -- NB: these INCLUDE any dictionary args
757 --     but EXCLUDE the data-declaration context, which is discarded
758 -- It's all post-flattening etc; this is a representation type
759 dataConInstArgTys :: DataCon    -- ^ A datacon with no existentials or equality constraints
760                                 -- However, it can have a dcTheta (notably it can be a 
761                                 -- class dictionary, with superclasses)
762                   -> [Type]     -- ^ Instantiated at these types
763                   -> [Type]
764 dataConInstArgTys dc@(MkData {dcRepArgTys = rep_arg_tys, 
765                               dcUnivTyVars = univ_tvs, dcEqSpec = eq_spec,
766                               dcExTyVars = ex_tvs}) inst_tys
767  = ASSERT2 ( length univ_tvs == length inst_tys 
768            , ptext (sLit "dataConInstArgTys") <+> ppr dc $$ ppr univ_tvs $$ ppr inst_tys)
769    ASSERT2 ( null ex_tvs && null eq_spec, ppr dc )        
770    map (substTyWith univ_tvs inst_tys) rep_arg_tys
771
772 -- | Returns just the instantiated /value/ argument types of a 'DataCon',
773 -- (excluding dictionary args)
774 dataConInstOrigArgTys 
775         :: DataCon      -- Works for any DataCon
776         -> [Type]       -- Includes existential tyvar args, but NOT
777                         -- equality constraints or dicts
778         -> [Type]
779 -- For vanilla datacons, it's all quite straightforward
780 -- But for the call in MatchCon, we really do want just the value args
781 dataConInstOrigArgTys dc@(MkData {dcOrigArgTys = arg_tys,
782                                   dcUnivTyVars = univ_tvs, 
783                                   dcExTyVars = ex_tvs}) inst_tys
784   = ASSERT2( length tyvars == length inst_tys
785           , ptext (sLit "dataConInstOrigArgTys") <+> ppr dc $$ ppr tyvars $$ ppr inst_tys )
786     map (substTyWith tyvars inst_tys) arg_tys
787   where
788     tyvars = univ_tvs ++ ex_tvs
789 \end{code}
790
791 \begin{code}
792 -- | Returns the argument types of the wrapper, excluding all dictionary arguments
793 -- and without substituting for any type variables
794 dataConOrigArgTys :: DataCon -> [Type]
795 dataConOrigArgTys dc = dcOrigArgTys dc
796
797 -- | Returns the arg types of the worker, including all dictionaries, after any 
798 -- flattening has been done and without substituting for any type variables
799 dataConRepArgTys :: DataCon -> [Type]
800 dataConRepArgTys dc = dcRepArgTys dc
801 \end{code}
802
803 \begin{code}
804 -- | The string @package:module.name@ identifying a constructor, which is attached
805 -- to its info table and used by the GHCi debugger and the heap profiler
806 dataConIdentity :: DataCon -> [Word8]
807 -- We want this string to be UTF-8, so we get the bytes directly from the FastStrings.
808 dataConIdentity dc = bytesFS (packageIdFS (modulePackageId mod)) ++ 
809                   fromIntegral (ord ':') : bytesFS (moduleNameFS (moduleName mod)) ++
810                   fromIntegral (ord '.') : bytesFS (occNameFS (nameOccName name))
811   where name = dataConName dc
812         mod  = ASSERT( isExternalName name ) nameModule name
813 \end{code}
814
815 \begin{code}
816 isTupleCon :: DataCon -> Bool
817 isTupleCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc
818         
819 isUnboxedTupleCon :: DataCon -> Bool
820 isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc
821
822 -- | Vanilla 'DataCon's are those that are nice boring Haskell 98 constructors
823 isVanillaDataCon :: DataCon -> Bool
824 isVanillaDataCon dc = dcVanilla dc
825 \end{code}
826
827 \begin{code}
828 classDataCon :: Class -> DataCon
829 classDataCon clas = case tyConDataCons (classTyCon clas) of
830                       (dict_constr:no_more) -> ASSERT( null no_more ) dict_constr 
831                       [] -> panic "classDataCon"
832 \end{code}
833
834 %************************************************************************
835 %*                                                                      *
836 \subsection{Splitting products}
837 %*                                                                      *
838 %************************************************************************
839
840 \begin{code}
841 -- | Extract the type constructor, type argument, data constructor and it's
842 -- /representation/ argument types from a type if it is a product type.
843 --
844 -- Precisely, we return @Just@ for any type that is all of:
845 --
846 --  * Concrete (i.e. constructors visible)
847 --
848 --  * Single-constructor
849 --
850 --  * Not existentially quantified
851 --
852 -- Whether the type is a @data@ type or a @newtype@
853 splitProductType_maybe
854         :: Type                         -- ^ A product type, perhaps
855         -> Maybe (TyCon,                -- The type constructor
856                   [Type],               -- Type args of the tycon
857                   DataCon,              -- The data constructor
858                   [Type])               -- Its /representation/ arg types
859
860         -- Rejecing existentials is conservative.  Maybe some things
861         -- could be made to work with them, but I'm not going to sweat
862         -- it through till someone finds it's important.
863
864 splitProductType_maybe ty
865   = case splitTyConApp_maybe ty of
866         Just (tycon,ty_args)
867            | isProductTyCon tycon       -- Includes check for non-existential,
868                                         -- and for constructors visible
869            -> Just (tycon, ty_args, data_con, dataConInstArgTys data_con ty_args)
870            where
871               data_con = ASSERT( not (null (tyConDataCons tycon)) ) 
872                          head (tyConDataCons tycon)
873         _other -> Nothing
874
875 -- | As 'splitProductType_maybe', but panics if the 'Type' is not a product type
876 splitProductType :: String -> Type -> (TyCon, [Type], DataCon, [Type])
877 splitProductType str ty
878   = case splitProductType_maybe ty of
879         Just stuff -> stuff
880         Nothing    -> pprPanic (str ++ ": not a product") (pprType ty)
881
882
883 -- | As 'splitProductType_maybe', but in turn instantiates the 'TyCon' returned
884 -- and hence recursively tries to unpack it as far as it able to
885 deepSplitProductType_maybe :: Type -> Maybe (TyCon, [Type], DataCon, [Type])
886 deepSplitProductType_maybe ty
887   = do { (res@(tycon, tycon_args, _, _)) <- splitProductType_maybe ty
888        ; let {result 
889              | Just (ty', _co) <- instNewTyCon_maybe tycon tycon_args
890              , not (isRecursiveTyCon tycon)
891              = deepSplitProductType_maybe ty'   -- Ignore the coercion?
892              | isNewTyCon tycon = Nothing  -- cannot unbox through recursive
893                                            -- newtypes nor through families
894              | otherwise = Just res}
895        ; result
896        }
897
898 -- | As 'deepSplitProductType_maybe', but panics if the 'Type' is not a product type
899 deepSplitProductType :: String -> Type -> (TyCon, [Type], DataCon, [Type])
900 deepSplitProductType str ty 
901   = case deepSplitProductType_maybe ty of
902       Just stuff -> stuff
903       Nothing -> pprPanic (str ++ ": not a product") (pprType ty)
904
905 -- | Compute the representation type strictness and type suitable for a 'DataCon'
906 computeRep :: [StrictnessMark]          -- ^ Original argument strictness
907            -> [Type]                    -- ^ Original argument types
908            -> ([StrictnessMark],        -- Representation arg strictness
909                [Type])                  -- And type
910
911 computeRep stricts tys
912   = unzip $ concat $ zipWithEqual "computeRep" unbox stricts tys
913   where
914     unbox NotMarkedStrict ty = [(NotMarkedStrict, ty)]
915     unbox MarkedStrict    ty = [(MarkedStrict,    ty)]
916     unbox MarkedUnboxed   ty = zipEqual "computeRep" (dataConRepStrictness arg_dc) arg_tys
917                                where
918                                  (_tycon, _tycon_args, arg_dc, arg_tys) 
919                                      = deepSplitProductType "unbox_strict_arg_ty" ty
920 \end{code}