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