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