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