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