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