fix haddock submodule pointer
[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, dataConTheta,
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, dataConCannotMatch,
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 Unify
45 import Coercion
46 import TyCon
47 import Class
48 import Name
49 import Var
50 import BasicTypes
51 import Outputable
52 import Unique
53 import ListSetOps
54 import Util
55 import FastString
56 import Module
57
58 import qualified Data.Data as Data
59 import Data.Char
60 import Data.Word
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   Notes
102  ---------------------------------------------------------------------------
103  The "data con itself"   C     DataName   DataCon   In dom( GlobalRdrEnv )
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         --      dcOtherTheta  = [x~y, 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 = dcOtherTheta = []
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 [a,b,c]
274                                         -- INVARIANT: length matches arity of the dcRepTyCon
275                                         ---           result type of (rep) data con is exactly (T a b c)
276
277         dcExTyVars   :: [TyVar],        -- Existentially-quantified type vars 
278                 -- In general, the dcUnivTyVars are NOT NECESSARILY THE SAME AS THE TYVARS
279                 -- FOR THE PARENT TyCon. With GADTs the data con might not even have 
280                 -- the same number of type variables.
281                 -- [This is a change (Oct05): previously, vanilla datacons guaranteed to
282                 --  have the same type variables as their parent TyCon, but that seems ugly.]
283
284         -- INVARIANT: the UnivTyVars and ExTyVars all have distinct OccNames
285         -- Reason: less confusing, and easier to generate IfaceSyn
286
287         dcEqSpec :: [(TyVar,Type)],     -- Equalities derived from the result type, 
288                                         -- _as written by the programmer_
289                 -- This field allows us to move conveniently between the two ways
290                 -- of representing a GADT constructor's type:
291                 --      MkT :: forall a b. (a ~ [b]) => b -> T a
292                 --      MkT :: forall b. b -> T [b]
293                 -- Each equality is of the form (a ~ ty), where 'a' is one of 
294                 -- the universally quantified type variables
295                                         
296                 -- The next two fields give the type context of the data constructor
297                 --      (aside from the GADT constraints, 
298                 --       which are given by the dcExpSpec)
299                 -- In GADT form, this is *exactly* what the programmer writes, even if
300                 -- the context constrains only universally quantified variables
301                 --      MkT :: forall a b. (a ~ b, Ord b) => a -> T a b
302         dcOtherTheta :: ThetaType,  -- The other constraints in the data con's type
303                                     -- other than those in the dcEqSpec
304
305         dcStupidTheta :: ThetaType,     -- The context of the data type declaration 
306                                         --      data Eq a => T a = ...
307                                         -- or, rather, a "thinned" version thereof
308                 -- "Thinned", because the Report says
309                 -- to eliminate any constraints that don't mention
310                 -- tyvars free in the arg types for this constructor
311                 --
312                 -- INVARIANT: the free tyvars of dcStupidTheta are a subset of dcUnivTyVars
313                 -- Reason: dcStupidTeta is gotten by thinning the stupid theta from the tycon
314                 -- 
315                 -- "Stupid", because the dictionaries aren't used for anything.  
316                 -- Indeed, [as of March 02] they are no longer in the type of 
317                 -- the wrapper Id, because that makes it harder to use the wrap-id 
318                 -- to rebuild values after record selection or in generics.
319
320         dcOrigArgTys :: [Type],         -- Original argument types
321                                         -- (before unboxing and flattening of strict fields)
322         dcOrigResTy :: Type,            -- Original result type, as seen by the user
323                 -- NB: for a data instance, the original user result type may 
324                 -- differ from the DataCon's representation TyCon.  Example
325                 --      data instance T [a] where MkT :: a -> T [a]
326                 -- The OrigResTy is T [a], but the dcRepTyCon might be :T123
327
328         -- Now the strictness annotations and field labels of the constructor
329         dcStrictMarks :: [HsBang],
330                 -- Strictness annotations as decided by the compiler.  
331                 -- Does *not* include the existential dictionaries
332                 -- length = dataConSourceArity dataCon
333
334         dcFields  :: [FieldLabel],
335                 -- Field labels for this constructor, in the
336                 -- same order as the dcOrigArgTys; 
337                 -- length = 0 (if not a record) or dataConSourceArity.
338
339         -- Constructor representation
340         dcRepArgTys :: [Type],  -- Final, representation argument types, 
341                                 -- after unboxing and flattening,
342                                 -- and *including* all existential evidence args
343
344         dcRepStrictness :: [StrictnessMark],
345                 -- One for each *representation* *value* 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
459 instance Data.Typeable DataCon where
460     typeOf _ = Data.mkTyConApp (Data.mkTyCon "DataCon") []
461
462 instance Data.Data DataCon where
463     -- don't traverse?
464     toConstr _   = abstractConstr "DataCon"
465     gunfold _ _  = error "gunfold"
466     dataTypeOf _ = mkNoRepType "DataCon"
467 \end{code}
468
469
470 %************************************************************************
471 %*                                                                      *
472 \subsection{Construction}
473 %*                                                                      *
474 %************************************************************************
475
476 \begin{code}
477 -- | Build a new data constructor
478 mkDataCon :: Name 
479           -> Bool               -- ^ Is the constructor declared infix?
480           -> [HsBang]           -- ^ Strictness annotations written in the source file
481           -> [FieldLabel]       -- ^ Field labels for the constructor, if it is a record, 
482                                 --   otherwise empty
483           -> [TyVar]            -- ^ Universally quantified type variables
484           -> [TyVar]            -- ^ Existentially quantified type variables
485           -> [(TyVar,Type)]     -- ^ GADT equalities
486           -> ThetaType          -- ^ Theta-type occuring before the arguments proper
487           -> [Type]             -- ^ Original argument types
488           -> Type               -- ^ Original result type
489           -> TyCon              -- ^ Representation type constructor
490           -> ThetaType          -- ^ The "stupid theta", context of the data declaration 
491                                 --   e.g. @data Eq a => T a ...@
492           -> DataConIds         -- ^ The Ids of the actual builder functions
493           -> DataCon
494   -- Can get the tag from the TyCon
495
496 mkDataCon name declared_infix
497           arg_stricts   -- Must match orig_arg_tys 1-1
498           fields
499           univ_tvs ex_tvs 
500           eq_spec theta
501           orig_arg_tys orig_res_ty rep_tycon
502           stupid_theta ids
503 -- Warning: mkDataCon is not a good place to check invariants. 
504 -- If the programmer writes the wrong result type in the decl, thus:
505 --      data T a where { MkT :: S }
506 -- then it's possible that the univ_tvs may hit an assertion failure
507 -- if you pull on univ_tvs.  This case is checked by checkValidDataCon,
508 -- so the error is detected properly... it's just that asaertions here
509 -- are a little dodgy.
510
511   = -- ASSERT( not (any isEqPred theta) )
512         -- We don't currently allow any equality predicates on
513         -- a data constructor (apart from the GADT ones in eq_spec)
514     con
515   where
516     is_vanilla = null ex_tvs && null eq_spec && null theta
517     con = MkData {dcName = name, dcUnique = nameUnique name, 
518                   dcVanilla = is_vanilla, dcInfix = declared_infix,
519                   dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, 
520                   dcEqSpec = eq_spec, 
521                   dcOtherTheta = theta,
522                   dcStupidTheta = stupid_theta, 
523                   dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
524                   dcRepTyCon = rep_tycon, 
525                   dcRepArgTys = rep_arg_tys,
526                   dcStrictMarks = arg_stricts, 
527                   dcRepStrictness = rep_arg_stricts,
528                   dcFields = fields, dcTag = tag, dcRepType = ty,
529                   dcIds = ids }
530
531         -- Strictness marks for source-args
532         --      *after unboxing choices*, 
533         -- but  *including existential dictionaries*
534         -- 
535         -- The 'arg_stricts' passed to mkDataCon are simply those for the
536         -- source-language arguments.  We add extra ones for the
537         -- dictionary arguments right here.
538     full_theta   = eqSpecPreds eq_spec ++ theta
539     real_arg_tys = mkPredTys full_theta               ++ orig_arg_tys
540     real_stricts = map mk_dict_strict_mark full_theta ++ arg_stricts
541
542         -- Representation arguments and demands
543         -- To do: eliminate duplication with MkId
544     (rep_arg_stricts, rep_arg_tys) = computeRep real_stricts real_arg_tys
545
546     tag = assoc "mkDataCon" (tyConDataCons rep_tycon `zip` [fIRST_TAG..]) con
547     ty  = mkForAllTys univ_tvs $ mkForAllTys ex_tvs $ 
548           mkFunTys rep_arg_tys $
549           mkTyConApp rep_tycon (mkTyVarTys univ_tvs)
550
551 eqSpecPreds :: [(TyVar,Type)] -> ThetaType
552 eqSpecPreds spec = [ mkEqPred (mkTyVarTy tv, ty) | (tv,ty) <- spec ]
553
554 mk_dict_strict_mark :: PredType -> HsBang
555 mk_dict_strict_mark pred | isStrictPred pred = HsStrict
556                          | otherwise         = HsNoBang
557 \end{code}
558
559 \begin{code}
560 -- | The 'Name' of the 'DataCon', giving it a unique, rooted identification
561 dataConName :: DataCon -> Name
562 dataConName = dcName
563
564 -- | The tag used for ordering 'DataCon's
565 dataConTag :: DataCon -> ConTag
566 dataConTag  = dcTag
567
568 -- | The type constructor that we are building via this data constructor
569 dataConTyCon :: DataCon -> TyCon
570 dataConTyCon = dcRepTyCon
571
572 -- | The original type constructor used in the definition of this data
573 -- constructor.  In case of a data family instance, that will be the family
574 -- type constructor.
575 dataConOrigTyCon :: DataCon -> TyCon
576 dataConOrigTyCon dc 
577   | Just (tc, _) <- tyConFamInst_maybe (dcRepTyCon dc) = tc
578   | otherwise                                          = dcRepTyCon dc
579
580 -- | The representation type of the data constructor, i.e. the sort
581 -- type that will represent values of this type at runtime
582 dataConRepType :: DataCon -> Type
583 dataConRepType = dcRepType
584
585 -- | Should the 'DataCon' be presented infix?
586 dataConIsInfix :: DataCon -> Bool
587 dataConIsInfix = dcInfix
588
589 -- | The universally-quantified type variables of the constructor
590 dataConUnivTyVars :: DataCon -> [TyVar]
591 dataConUnivTyVars = dcUnivTyVars
592
593 -- | The existentially-quantified type variables of the constructor
594 dataConExTyVars :: DataCon -> [TyVar]
595 dataConExTyVars = dcExTyVars
596
597 -- | Both the universal and existentiatial type variables of the constructor
598 dataConAllTyVars :: DataCon -> [TyVar]
599 dataConAllTyVars (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs })
600   = univ_tvs ++ ex_tvs
601
602 -- | Equalities derived from the result type of the data constructor, as written
603 -- by the programmer in any GADT declaration
604 dataConEqSpec :: DataCon -> [(TyVar,Type)]
605 dataConEqSpec = dcEqSpec
606
607 -- | The *full* constraints on the constructor type
608 dataConTheta :: DataCon -> ThetaType
609 dataConTheta (MkData { dcEqSpec = eq_spec, dcOtherTheta = theta }) 
610   = eqSpecPreds eq_spec ++ theta
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 -> [HsBang]
657 dataConStrictMarks = dcStrictMarks
658
659 -- | Strictness of evidence arguments to the wrapper function
660 dataConExStricts :: DataCon -> [HsBang]
661 -- Usually empty, so we don't bother to cache this
662 dataConExStricts dc = map mk_dict_strict_mark $ (dataConTheta 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, 
699                     dcEqSpec = eq_spec, dcOtherTheta  = theta, 
700                     dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
701   = (univ_tvs ++ ex_tvs, eqSpecPreds eq_spec ++ 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, [Type], Type)
719 dataConFullSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, 
720                         dcEqSpec = eq_spec, dcOtherTheta = theta,
721                         dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
722   = (univ_tvs, ex_tvs, eq_spec, 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                            dcOtherTheta = theta, dcOrigArgTys = arg_tys,
748                            dcOrigResTy = res_ty })
749   = mkForAllTys ((univ_tvs `minusList` map fst eq_spec) ++ ex_tvs) $
750     mkFunTys (mkPredTys theta) $
751     mkFunTys arg_tys $
752     res_ty
753
754 -- | Finds the instantiated types of the arguments required to construct a 'DataCon' representation
755 -- NB: these INCLUDE any dictionary args
756 --     but EXCLUDE the data-declaration context, which is discarded
757 -- It's all post-flattening etc; this is a representation type
758 dataConInstArgTys :: DataCon    -- ^ A datacon with no existentials or equality constraints
759                                 -- However, it can have a dcTheta (notably it can be a 
760                                 -- class dictionary, with superclasses)
761                   -> [Type]     -- ^ Instantiated at these types
762                   -> [Type]
763 dataConInstArgTys dc@(MkData {dcRepArgTys = rep_arg_tys, 
764                               dcUnivTyVars = univ_tvs, dcEqSpec = eq_spec,
765                               dcExTyVars = ex_tvs}) inst_tys
766  = ASSERT2 ( length univ_tvs == length inst_tys 
767            , ptext (sLit "dataConInstArgTys") <+> ppr dc $$ ppr univ_tvs $$ ppr inst_tys)
768    ASSERT2 ( null ex_tvs && null eq_spec, ppr dc )        
769    map (substTyWith univ_tvs inst_tys) rep_arg_tys
770
771 -- | Returns just the instantiated /value/ argument types of a 'DataCon',
772 -- (excluding dictionary args)
773 dataConInstOrigArgTys 
774         :: DataCon      -- Works for any DataCon
775         -> [Type]       -- Includes existential tyvar args, but NOT
776                         -- equality constraints or dicts
777         -> [Type]
778 -- For vanilla datacons, it's all quite straightforward
779 -- But for the call in MatchCon, we really do want just the value args
780 dataConInstOrigArgTys dc@(MkData {dcOrigArgTys = arg_tys,
781                                   dcUnivTyVars = univ_tvs, 
782                                   dcExTyVars = ex_tvs}) inst_tys
783   = ASSERT2( length tyvars == length inst_tys
784           , ptext (sLit "dataConInstOrigArgTys") <+> ppr dc $$ ppr tyvars $$ ppr inst_tys )
785     map (substTyWith tyvars inst_tys) arg_tys
786   where
787     tyvars = univ_tvs ++ ex_tvs
788 \end{code}
789
790 \begin{code}
791 -- | Returns the argument types of the wrapper, excluding all dictionary arguments
792 -- and without substituting for any type variables
793 dataConOrigArgTys :: DataCon -> [Type]
794 dataConOrigArgTys dc = dcOrigArgTys dc
795
796 -- | Returns the arg types of the worker, including all dictionaries, after any 
797 -- flattening has been done and without substituting for any type variables
798 dataConRepArgTys :: DataCon -> [Type]
799 dataConRepArgTys dc = dcRepArgTys dc
800 \end{code}
801
802 \begin{code}
803 -- | The string @package:module.name@ identifying a constructor, which is attached
804 -- to its info table and used by the GHCi debugger and the heap profiler
805 dataConIdentity :: DataCon -> [Word8]
806 -- We want this string to be UTF-8, so we get the bytes directly from the FastStrings.
807 dataConIdentity dc = bytesFS (packageIdFS (modulePackageId mod)) ++ 
808                   fromIntegral (ord ':') : bytesFS (moduleNameFS (moduleName mod)) ++
809                   fromIntegral (ord '.') : bytesFS (occNameFS (nameOccName name))
810   where name = dataConName dc
811         mod  = ASSERT( isExternalName name ) nameModule name
812 \end{code}
813
814 \begin{code}
815 isTupleCon :: DataCon -> Bool
816 isTupleCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc
817         
818 isUnboxedTupleCon :: DataCon -> Bool
819 isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc
820
821 -- | Vanilla 'DataCon's are those that are nice boring Haskell 98 constructors
822 isVanillaDataCon :: DataCon -> Bool
823 isVanillaDataCon dc = dcVanilla dc
824 \end{code}
825
826 \begin{code}
827 classDataCon :: Class -> DataCon
828 classDataCon clas = case tyConDataCons (classTyCon clas) of
829                       (dict_constr:no_more) -> ASSERT( null no_more ) dict_constr 
830                       [] -> panic "classDataCon"
831 \end{code}
832
833 \begin{code}
834 dataConCannotMatch :: [Type] -> DataCon -> Bool
835 -- Returns True iff the data con *definitely cannot* match a 
836 --                  scrutinee of type (T tys)
837 --                  where T is the type constructor for the data con
838 -- NB: look at *all* equality constraints, not only those
839 --     in dataConEqSpec; see Trac #5168
840 dataConCannotMatch tys con
841   | null theta        = False   -- Common
842   | all isTyVarTy tys = False   -- Also common
843   | otherwise
844   = typesCantMatch [(Type.substTy subst ty1, Type.substTy subst ty2)
845                    | EqPred ty1 ty2 <- theta ]
846   where
847     dc_tvs  = dataConUnivTyVars con
848     theta   = dataConTheta con
849     subst   = zipTopTvSubst dc_tvs tys
850 \end{code}
851
852 %************************************************************************
853 %*                                                                      *
854 \subsection{Splitting products}
855 %*                                                                      *
856 %************************************************************************
857
858 \begin{code}
859 -- | Extract the type constructor, type argument, data constructor and it's
860 -- /representation/ argument types from a type if it is a product type.
861 --
862 -- Precisely, we return @Just@ for any type that is all of:
863 --
864 --  * Concrete (i.e. constructors visible)
865 --
866 --  * Single-constructor
867 --
868 --  * Not existentially quantified
869 --
870 -- Whether the type is a @data@ type or a @newtype@
871 splitProductType_maybe
872         :: Type                         -- ^ A product type, perhaps
873         -> Maybe (TyCon,                -- The type constructor
874                   [Type],               -- Type args of the tycon
875                   DataCon,              -- The data constructor
876                   [Type])               -- Its /representation/ arg types
877
878         -- Rejecing existentials is conservative.  Maybe some things
879         -- could be made to work with them, but I'm not going to sweat
880         -- it through till someone finds it's important.
881
882 splitProductType_maybe ty
883   = case splitTyConApp_maybe ty of
884         Just (tycon,ty_args)
885            | isProductTyCon tycon       -- Includes check for non-existential,
886                                         -- and for constructors visible
887            -> Just (tycon, ty_args, data_con, dataConInstArgTys data_con ty_args)
888            where
889               data_con = ASSERT( not (null (tyConDataCons tycon)) ) 
890                          head (tyConDataCons tycon)
891         _other -> Nothing
892
893 -- | As 'splitProductType_maybe', but panics if the 'Type' is not a product type
894 splitProductType :: String -> Type -> (TyCon, [Type], DataCon, [Type])
895 splitProductType str ty
896   = case splitProductType_maybe ty of
897         Just stuff -> stuff
898         Nothing    -> pprPanic (str ++ ": not a product") (pprType ty)
899
900
901 -- | As 'splitProductType_maybe', but in turn instantiates the 'TyCon' returned
902 -- and hence recursively tries to unpack it as far as it able to
903 deepSplitProductType_maybe :: Type -> Maybe (TyCon, [Type], DataCon, [Type])
904 deepSplitProductType_maybe ty
905   = do { (res@(tycon, tycon_args, _, _)) <- splitProductType_maybe ty
906        ; let {result 
907              | Just (ty', _co) <- instNewTyCon_maybe tycon tycon_args
908              , not (isRecursiveTyCon tycon)
909              = deepSplitProductType_maybe ty'   -- Ignore the coercion?
910              | isNewTyCon tycon = Nothing  -- cannot unbox through recursive
911                                            -- newtypes nor through families
912              | otherwise = Just res}
913        ; result
914        }
915
916 -- | As 'deepSplitProductType_maybe', but panics if the 'Type' is not a product type
917 deepSplitProductType :: String -> Type -> (TyCon, [Type], DataCon, [Type])
918 deepSplitProductType str ty 
919   = case deepSplitProductType_maybe ty of
920       Just stuff -> stuff
921       Nothing -> pprPanic (str ++ ": not a product") (pprType ty)
922
923 -- | Compute the representation type strictness and type suitable for a 'DataCon'
924 computeRep :: [HsBang]                  -- ^ Original argument strictness
925            -> [Type]                    -- ^ Original argument types
926            -> ([StrictnessMark],        -- Representation arg strictness
927                [Type])                  -- And type
928
929 computeRep stricts tys
930   = unzip $ concat $ zipWithEqual "computeRep" unbox stricts tys
931   where
932     unbox HsNoBang       ty = [(NotMarkedStrict, ty)]
933     unbox HsStrict       ty = [(MarkedStrict,    ty)]
934     unbox HsUnpackFailed ty = [(MarkedStrict,    ty)]
935     unbox HsUnpack ty = zipEqual "computeRep" (dataConRepStrictness arg_dc) arg_tys
936                       where
937                         (_tycon, _tycon_args, arg_dc, arg_tys) 
938                            = deepSplitProductType "unbox_strict_arg_ty" ty
939 \end{code}