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