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, 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,
27 dataConWorkId, dataConWrapId, dataConWrapId_maybe, dataConImplicitIds,
30 -- ** Predicates on DataCons
31 isNullarySrcDataCon, isNullaryRepDataCon, isTupleCon, isUnboxedTupleCon,
32 isVanillaDataCon, classDataCon,
34 -- * Splitting product types
35 splitProductType_maybe, splitProductType, deepSplitProductType,
36 deepSplitProductType_maybe
39 #include "HsVersions.h"
58 import Data.List ( partition )
62 Data constructor representation
63 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
64 Consider the following Haskell data type declaration
66 data T = T !Int ![Int]
68 Using the strictness annotations, GHC will represent this as
72 That is, the Int has been unboxed. Furthermore, the Haskell source construction
82 That is, the first argument is unboxed, and the second is evaluated. Finally,
83 pattern matching is translated too:
85 case e of { T a b -> ... }
89 case e of { T a' b -> let a = I# a' in ... }
91 To keep ourselves sane, we name the different versions of the data constructor
92 differently, as follows.
95 Note [Data Constructor Naming]
96 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
97 Each data constructor C has two, and possibly up to four, Names associated with it:
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
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]).
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).
115 The data con has one or two Ids associated with it:
117 The "worker Id", is the actual data constructor.
118 * Every data constructor (newtype or data type) has a worker
120 * The worker is very like a primop, in that it has no binding.
122 * For a *data* type, the worker *is* the data constructor;
125 * For a *newtype*, the worker has a compulsory unfolding which
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
133 The "wrapper Id", \$WC, goes as follows
135 * Its type is exactly what it looks like in the source program.
137 * It is an ordinary function, and it gets a top-level binding
138 like any other function.
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
144 Note [The need for a wrapper]
145 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
146 Why might the wrapper have anything to do? Two reasons:
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
156 * Equality constraints for GADTs
157 data T a where { MkT :: a -> T [a] }
159 The worker gets a type with explicit equality
161 MkT :: forall a b. (a=[b]) => b -> T a
163 The wrapper has the programmer-specified type:
165 \$wMkT a x = MkT [a] a [a] x
166 The third argument is a coerion
169 INVARIANT: the dictionary constructor for a class
173 A note about the stupid context
174 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
175 Data types can have a context:
177 data (Eq a, Ord b) => T a b = T1 a b | T2 a
179 and that makes the constructors have a context too
180 (notice that T2's context is "thinned"):
182 T1 :: (Eq a, Ord b) => a -> b -> T a b
183 T2 :: (Eq a) => a -> T a b
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):
191 f :: Eq a => T a b -> a
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.
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).
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.
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.]
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:
222 C a (d:Ord a) (p:a) (q:a) -> compare d p q
224 Note that (Foo a) might not be an instance of Ord.
226 %************************************************************************
228 \subsection{Data constructors}
230 %************************************************************************
233 -- | A data constructor
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
243 -- *** As declared by the user
245 -- MkT :: forall x y. (x~y,Ord x) => x -> y -> T (x,y)
247 -- *** As represented internally
249 -- MkT :: forall a. forall x y. (a~(x,y),x~y,Ord x) => x -> y -> T a
251 -- The next six fields express the type of the constructor, in pieces
254 -- dcUnivTyVars = [a]
255 -- dcExTyVars = [x,y]
256 -- dcEqSpec = [a~(x,y)]
258 -- dcDictTheta = [Ord x]
259 -- dcOrigArgTys = [a,List b]
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)
272 dcUnivTyVars :: [TyVar], -- Universally-quantified type vars
273 -- INVARIANT: length matches arity of the dcRepTyCon
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.]
282 -- INVARIANT: the UnivTyVars and ExTyVars all have distinct OccNames
283 -- Reason: less confusing, and easier to generate IfaceSyn
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
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
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
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
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.
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
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
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.
337 -- Constructor representation
338 dcRepArgTys :: [Type], -- Final, representation argument types,
339 -- after unboxing and flattening,
340 -- and *including* existential dictionaries
342 dcRepStrictness :: [StrictnessMark], -- One for each *representation* argument
343 -- See also Note [Data-con worker strictness] in MkId.lhs
345 -- Result type of constructor is T t1..tn
346 dcRepTyCon :: TyCon, -- Result tycon, T
348 dcRepType :: Type, -- Type of the constructor
349 -- forall a x y. (a~(x,y), x~y, Ord x) =>
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
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.
367 -- An entirely separate wrapper function is built in TcTyDecls
370 dcInfix :: Bool -- True <=> declared infix
371 -- Used for Template Haskell and 'deriving' only
372 -- The actual fixity is stored elsewhere
375 -- | Contains the Ids of the data constructor functions
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
381 -- _Neither_ the worker _nor_ the wrapper take the dcStupidTheta dicts as arguments
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
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
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.)
399 -- | Type of the tags associated with each constructor possibility
403 -- ^ Tags are allocated from here for real constructors
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
415 b) the constructor may store an unboxed version of a strict field.
417 Here's an example illustrating both:
418 data Ord a => T a = MkT Int! a
420 T :: Ord a => Int -> a -> T a
422 Trep :: Int# -> a -> T a
423 Actually, the unboxed part isn't implemented yet!
426 %************************************************************************
428 \subsection{Instances}
430 %************************************************************************
433 instance Eq DataCon where
434 a == b = getUnique a == getUnique b
435 a /= b = getUnique a /= getUnique b
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
444 instance Uniquable DataCon where
447 instance NamedThing DataCon where
450 instance Outputable DataCon where
451 ppr con = ppr (dataConName con)
453 instance Show DataCon where
454 showsPrec p con = showsPrecSDoc p (ppr con)
458 %************************************************************************
460 \subsection{Construction}
462 %************************************************************************
465 -- | Build a new data constructor
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,
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
482 -- Can get the tag from the TyCon
484 mkDataCon name declared_infix
485 arg_stricts -- Must match orig_arg_tys 1-1
489 orig_arg_tys orig_res_ty rep_tycon
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.
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)
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,
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,
519 -- Strictness marks for source-args
520 -- *after unboxing choices*,
521 -- but *including existential dictionaries*
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
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
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)
545 eqSpecPreds :: [(TyVar,Type)] -> ThetaType
546 eqSpecPreds spec = [ mkEqPred (mkTyVarTy tv, ty) | (tv,ty) <- spec ]
548 mk_dict_strict_mark :: PredType -> StrictnessMark
549 mk_dict_strict_mark pred | isStrictPred pred = MarkedStrict
550 | otherwise = NotMarkedStrict
554 -- | The 'Name' of the 'DataCon', giving it a unique, rooted identification
555 dataConName :: DataCon -> Name
558 -- | The tag used for ordering 'DataCon's
559 dataConTag :: DataCon -> ConTag
562 -- | The type constructor that we are building via this data constructor
563 dataConTyCon :: DataCon -> TyCon
564 dataConTyCon = dcRepTyCon
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
571 -- | Should the 'DataCon' be presented infix?
572 dataConIsInfix :: DataCon -> Bool
573 dataConIsInfix = dcInfix
575 -- | The universally-quantified type variables of the constructor
576 dataConUnivTyVars :: DataCon -> [TyVar]
577 dataConUnivTyVars = dcUnivTyVars
579 -- | The existentially-quantified type variables of the constructor
580 dataConExTyVars :: DataCon -> [TyVar]
581 dataConExTyVars = dcExTyVars
583 -- | Both the universal and existentiatial type variables of the constructor
584 dataConAllTyVars :: DataCon -> [TyVar]
585 dataConAllTyVars (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs })
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
593 -- | The equational constraints on the data constructor type
594 dataConEqTheta :: DataCon -> ThetaType
595 dataConEqTheta = dcEqTheta
597 -- | The type class and implicit parameter contsraints on the data constructor type
598 dataConDictTheta :: DataCon -> ThetaType
599 dataConDictTheta = dcDictTheta
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
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
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
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]
632 -- | The labels for the fields of this particular 'DataCon'
633 dataConFieldLabels :: DataCon -> [FieldLabel]
634 dataConFieldLabels = dcFields
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
641 Nothing -> pprPanic "dataConFieldType" (ppr con <+> ppr label)
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
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
653 -- | Source-level arity of the data constructor
654 dataConSourceArity :: DataCon -> Arity
655 dataConSourceArity dc = length (dcOrigArgTys dc)
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
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)
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)
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
676 -- | The \"signature\" of the 'DataCon' returns, in order:
678 -- 1) The result of 'dataConAllTyVars',
680 -- 2) All the 'ThetaType's relating to the 'DataCon' (coercion, dictionary, implicit
681 -- parameter - whatever)
683 -- 3) The type arguments to the constructor
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)
692 -- | The \"full signature\" of the 'DataCon' returns, in order:
694 -- 1) The result of 'dataConUnivTyVars'
696 -- 2) The result of 'dataConExTyVars'
698 -- 3) The result of 'dataConEqSpec'
700 -- 4) The result of 'dataConDictTheta'
702 -- 5) The original argument types to the 'DataCon' (i.e. before
703 -- any change of the representation of the type)
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)
713 dataConOrigResTy :: DataCon -> Type
714 dataConOrigResTy dc = dcOrigResTy dc
716 -- | The \"stupid theta\" of the 'DataCon', such as @data Eq a@ in:
718 -- > data Eq a => T a = ...
719 dataConStupidTheta :: DataCon -> ThetaType
720 dataConStupidTheta dc = dcStupidTheta dc
722 dataConUserType :: DataCon -> Type
723 -- ^ The user-declared type of the data constructor
724 -- in the nice-to-read form:
726 -- > T :: forall a b. a -> b -> T [a]
730 -- > T :: forall a c. forall b. (c~[a]) => a -> b -> T c
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) $
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
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
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
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
777 tyvars = univ_tvs ++ ex_tvs
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
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
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
805 isTupleCon :: DataCon -> Bool
806 isTupleCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc
808 isUnboxedTupleCon :: DataCon -> Bool
809 isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc
811 -- | Vanilla 'DataCon's are those that are nice boring Haskell 98 constructors
812 isVanillaDataCon :: DataCon -> Bool
813 isVanillaDataCon dc = dcVanilla dc
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"
823 %************************************************************************
825 \subsection{Splitting products}
827 %************************************************************************
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.
833 -- Precisely, we return @Just@ for any type that is all of:
835 -- * Concrete (i.e. constructors visible)
837 -- * Single-constructor
839 -- * Not existentially quantified
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
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.
853 splitProductType_maybe ty
854 = case splitTyConApp_maybe ty of
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)
860 data_con = ASSERT( not (null (tyConDataCons tycon)) )
861 head (tyConDataCons tycon)
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
869 Nothing -> pprPanic (str ++ ": not a product") (pprType ty)
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
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}
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
892 Nothing -> pprPanic (str ++ ": not a product") (pprType ty)
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
900 computeRep stricts tys
901 = unzip $ concat $ zipWithEqual "computeRep" unbox stricts tys
903 unbox NotMarkedStrict ty = [(NotMarkedStrict, ty)]
904 unbox MarkedStrict ty = [(MarkedStrict, ty)]
905 unbox MarkedUnboxed ty = zipEqual "computeRep" (dataConRepStrictness arg_dc) arg_tys
907 (_tycon, _tycon_args, arg_dc, arg_tys)
908 = deepSplitProductType "unbox_strict_arg_ty" ty