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