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