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