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