The Backpack patch.
[ghc.git] / compiler / basicTypes / DataCon.hs
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
8 {-# LANGUAGE CPP, DeriveDataTypeable #-}
9
10 module DataCon (
11 -- * Main data types
12 DataCon, DataConRep(..),
13 SrcStrictness(..), SrcUnpackedness(..),
14 HsSrcBang(..), HsImplBang(..),
15 StrictnessMark(..),
16 ConTag,
17
18 -- ** Equality specs
19 EqSpec, mkEqSpec, eqSpecTyVar, eqSpecType,
20 eqSpecPair, eqSpecPreds,
21 substEqSpec, filterEqSpec,
22
23 -- ** Field labels
24 FieldLbl(..), FieldLabel, FieldLabelString,
25
26 -- ** Type construction
27 mkDataCon, buildAlgTyCon, fIRST_TAG,
28
29 -- ** Type deconstruction
30 dataConRepType, dataConSig, dataConInstSig, dataConFullSig,
31 dataConName, dataConIdentity, dataConTag, dataConTyCon,
32 dataConOrigTyCon, dataConUserType,
33 dataConUnivTyVars, dataConUnivTyVarBinders,
34 dataConExTyVars, dataConExTyVarBinders,
35 dataConAllTyVars,
36 dataConEqSpec, dataConTheta,
37 dataConStupidTheta,
38 dataConInstArgTys, dataConOrigArgTys, dataConOrigResTy,
39 dataConInstOrigArgTys, dataConRepArgTys,
40 dataConFieldLabels, dataConFieldType,
41 dataConSrcBangs,
42 dataConSourceArity, dataConRepArity,
43 dataConIsInfix,
44 dataConWorkId, dataConWrapId, dataConWrapId_maybe,
45 dataConImplicitTyThings,
46 dataConRepStrictness, dataConImplBangs, dataConBoxer,
47
48 splitDataProductType_maybe,
49
50 -- ** Predicates on DataCons
51 isNullarySrcDataCon, isNullaryRepDataCon, isTupleDataCon, isUnboxedTupleCon,
52 isUnboxedSumCon,
53 isVanillaDataCon, classDataCon, dataConCannotMatch,
54 isBanged, isMarkedStrict, eqHsBang, isSrcStrict, isSrcUnpacked,
55 specialPromotedDc, isLegacyPromotableDataCon, isLegacyPromotableTyCon,
56
57 -- ** Promotion related functions
58 promoteDataCon
59 ) where
60
61 #include "HsVersions.h"
62
63 import {-# SOURCE #-} MkId( DataConBoxer )
64 import Type
65 import ForeignCall ( CType )
66 import Coercion
67 import Unify
68 import TyCon
69 import FieldLabel
70 import Class
71 import Name
72 import PrelNames
73 import Var
74 import Outputable
75 import ListSetOps
76 import Util
77 import BasicTypes
78 import FastString
79 import Module
80 import Binary
81 import UniqSet
82 import UniqFM
83 import Unique( mkAlphaTyVarUnique )
84
85 import qualified Data.Data as Data
86 import Data.Char
87 import Data.Word
88 import Data.List( mapAccumL, find )
89
90 {-
91 Data constructor representation
92 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
93 Consider the following Haskell data type declaration
94
95 data T = T !Int ![Int]
96
97 Using the strictness annotations, GHC will represent this as
98
99 data T = T Int# [Int]
100
101 That is, the Int has been unboxed. Furthermore, the Haskell source construction
102
103 T e1 e2
104
105 is translated to
106
107 case e1 of { I# x ->
108 case e2 of { r ->
109 T x r }}
110
111 That is, the first argument is unboxed, and the second is evaluated. Finally,
112 pattern matching is translated too:
113
114 case e of { T a b -> ... }
115
116 becomes
117
118 case e of { T a' b -> let a = I# a' in ... }
119
120 To keep ourselves sane, we name the different versions of the data constructor
121 differently, as follows.
122
123
124 Note [Data Constructor Naming]
125 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
126 Each data constructor C has two, and possibly up to four, Names associated with it:
127
128 OccName Name space Name of Notes
129 ---------------------------------------------------------------------------
130 The "data con itself" C DataName DataCon In dom( GlobalRdrEnv )
131 The "worker data con" C VarName Id The worker
132 The "wrapper data con" $WC VarName Id The wrapper
133 The "newtype coercion" :CoT TcClsName TyCon
134
135 EVERY data constructor (incl for newtypes) has the former two (the
136 data con itself, and its worker. But only some data constructors have a
137 wrapper (see Note [The need for a wrapper]).
138
139 Each of these three has a distinct Unique. The "data con itself" name
140 appears in the output of the renamer, and names the Haskell-source
141 data constructor. The type checker translates it into either the wrapper Id
142 (if it exists) or worker Id (otherwise).
143
144 The data con has one or two Ids associated with it:
145
146 The "worker Id", is the actual data constructor.
147 * Every data constructor (newtype or data type) has a worker
148
149 * The worker is very like a primop, in that it has no binding.
150
151 * For a *data* type, the worker *is* the data constructor;
152 it has no unfolding
153
154 * For a *newtype*, the worker has a compulsory unfolding which
155 does a cast, e.g.
156 newtype T = MkT Int
157 The worker for MkT has unfolding
158 \\(x:Int). x `cast` sym CoT
159 Here CoT is the type constructor, witnessing the FC axiom
160 axiom CoT : T = Int
161
162 The "wrapper Id", \$WC, goes as follows
163
164 * Its type is exactly what it looks like in the source program.
165
166 * It is an ordinary function, and it gets a top-level binding
167 like any other function.
168
169 * The wrapper Id isn't generated for a data type if there is
170 nothing for the wrapper to do. That is, if its defn would be
171 \$wC = C
172
173 Note [The need for a wrapper]
174 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
175 Why might the wrapper have anything to do? Two reasons:
176
177 * Unboxing strict fields (with -funbox-strict-fields)
178 data T = MkT !(Int,Int)
179 \$wMkT :: (Int,Int) -> T
180 \$wMkT (x,y) = MkT x y
181 Notice that the worker has two fields where the wapper has
182 just one. That is, the worker has type
183 MkT :: Int -> Int -> T
184
185 * Equality constraints for GADTs
186 data T a where { MkT :: a -> T [a] }
187
188 The worker gets a type with explicit equality
189 constraints, thus:
190 MkT :: forall a b. (a=[b]) => b -> T a
191
192 The wrapper has the programmer-specified type:
193 \$wMkT :: a -> T [a]
194 \$wMkT a x = MkT [a] a [a] x
195 The third argument is a coercion
196 [a] :: [a]~[a]
197
198 INVARIANT: the dictionary constructor for a class
199 never has a wrapper.
200
201
202 A note about the stupid context
203 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
204 Data types can have a context:
205
206 data (Eq a, Ord b) => T a b = T1 a b | T2 a
207
208 and that makes the constructors have a context too
209 (notice that T2's context is "thinned"):
210
211 T1 :: (Eq a, Ord b) => a -> b -> T a b
212 T2 :: (Eq a) => a -> T a b
213
214 Furthermore, this context pops up when pattern matching
215 (though GHC hasn't implemented this, but it is in H98, and
216 I've fixed GHC so that it now does):
217
218 f (T2 x) = x
219 gets inferred type
220 f :: Eq a => T a b -> a
221
222 I say the context is "stupid" because the dictionaries passed
223 are immediately discarded -- they do nothing and have no benefit.
224 It's a flaw in the language.
225
226 Up to now [March 2002] I have put this stupid context into the
227 type of the "wrapper" constructors functions, T1 and T2, but
228 that turned out to be jolly inconvenient for generics, and
229 record update, and other functions that build values of type T
230 (because they don't have suitable dictionaries available).
231
232 So now I've taken the stupid context out. I simply deal with
233 it separately in the type checker on occurrences of a
234 constructor, either in an expression or in a pattern.
235
236 [May 2003: actually I think this decision could evasily be
237 reversed now, and probably should be. Generics could be
238 disabled for types with a stupid context; record updates now
239 (H98) needs the context too; etc. It's an unforced change, so
240 I'm leaving it for now --- but it does seem odd that the
241 wrapper doesn't include the stupid context.]
242
243 [July 04] With the advent of generalised data types, it's less obvious
244 what the "stupid context" is. Consider
245 C :: forall a. Ord a => a -> a -> T (Foo a)
246 Does the C constructor in Core contain the Ord dictionary? Yes, it must:
247
248 f :: T b -> Ordering
249 f = /\b. \x:T b.
250 case x of
251 C a (d:Ord a) (p:a) (q:a) -> compare d p q
252
253 Note that (Foo a) might not be an instance of Ord.
254
255 ************************************************************************
256 * *
257 \subsection{Data constructors}
258 * *
259 ************************************************************************
260 -}
261
262 -- | A data constructor
263 --
264 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
265 -- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnComma'
266
267 -- For details on above see note [Api annotations] in ApiAnnotation
268 data DataCon
269 = MkData {
270 dcName :: Name, -- This is the name of the *source data con*
271 -- (see "Note [Data Constructor Naming]" above)
272 dcUnique :: Unique, -- Cached from Name
273 dcTag :: ConTag, -- ^ Tag, used for ordering 'DataCon's
274
275 -- Running example:
276 --
277 -- *** As declared by the user
278 -- data T a where
279 -- MkT :: forall x y. (x~y,Ord x) => x -> y -> T (x,y)
280
281 -- *** As represented internally
282 -- data T a where
283 -- MkT :: forall a. forall x y. (a~(x,y),x~y,Ord x) => x -> y -> T a
284 --
285 -- The next six fields express the type of the constructor, in pieces
286 -- e.g.
287 --
288 -- dcUnivTyVars = [a]
289 -- dcExTyVars = [x,y]
290 -- dcEqSpec = [a~(x,y)]
291 -- dcOtherTheta = [x~y, Ord x]
292 -- dcOrigArgTys = [x,y]
293 -- dcRepTyCon = T
294
295 -- In general, the dcUnivTyVars are NOT NECESSARILY THE SAME AS THE TYVARS
296 -- FOR THE PARENT TyCon. (This is a change (Oct05): previously, vanilla
297 -- datacons guaranteed to have the same type variables as their parent TyCon,
298 -- but that seems ugly.)
299
300 dcVanilla :: Bool, -- True <=> This is a vanilla Haskell 98 data constructor
301 -- Its type is of form
302 -- forall a1..an . t1 -> ... tm -> T a1..an
303 -- No existentials, no coercions, nothing.
304 -- That is: dcExTyVars = dcEqSpec = dcOtherTheta = []
305 -- NB 1: newtypes always have a vanilla data con
306 -- NB 2: a vanilla constructor can still be declared in GADT-style
307 -- syntax, provided its type looks like the above.
308 -- The declaration format is held in the TyCon (algTcGadtSyntax)
309
310 -- Universally-quantified type vars [a,b,c]
311 -- INVARIANT: length matches arity of the dcRepTyCon
312 -- INVARIANT: result type of data con worker is exactly (T a b c)
313 dcUnivTyVars :: [TyVarBinder],
314
315 -- Existentially-quantified type vars [x,y]
316 dcExTyVars :: [TyVarBinder],
317
318 -- INVARIANT: the UnivTyVars and ExTyVars all have distinct OccNames
319 -- Reason: less confusing, and easier to generate IfaceSyn
320
321 dcEqSpec :: [EqSpec], -- Equalities derived from the result type,
322 -- _as written by the programmer_
323
324 -- This field allows us to move conveniently between the two ways
325 -- of representing a GADT constructor's type:
326 -- MkT :: forall a b. (a ~ [b]) => b -> T a
327 -- MkT :: forall b. b -> T [b]
328 -- Each equality is of the form (a ~ ty), where 'a' is one of
329 -- the universally quantified type variables
330
331 -- The next two fields give the type context of the data constructor
332 -- (aside from the GADT constraints,
333 -- which are given by the dcExpSpec)
334 -- In GADT form, this is *exactly* what the programmer writes, even if
335 -- the context constrains only universally quantified variables
336 -- MkT :: forall a b. (a ~ b, Ord b) => a -> T a b
337 dcOtherTheta :: ThetaType, -- The other constraints in the data con's type
338 -- other than those in the dcEqSpec
339
340 dcStupidTheta :: ThetaType, -- The context of the data type declaration
341 -- data Eq a => T a = ...
342 -- or, rather, a "thinned" version thereof
343 -- "Thinned", because the Report says
344 -- to eliminate any constraints that don't mention
345 -- tyvars free in the arg types for this constructor
346 --
347 -- INVARIANT: the free tyvars of dcStupidTheta are a subset of dcUnivTyVars
348 -- Reason: dcStupidTeta is gotten by thinning the stupid theta from the tycon
349 --
350 -- "Stupid", because the dictionaries aren't used for anything.
351 -- Indeed, [as of March 02] they are no longer in the type of
352 -- the wrapper Id, because that makes it harder to use the wrap-id
353 -- to rebuild values after record selection or in generics.
354
355 dcOrigArgTys :: [Type], -- Original argument types
356 -- (before unboxing and flattening of strict fields)
357 dcOrigResTy :: Type, -- Original result type, as seen by the user
358 -- NB: for a data instance, the original user result type may
359 -- differ from the DataCon's representation TyCon. Example
360 -- data instance T [a] where MkT :: a -> T [a]
361 -- The OrigResTy is T [a], but the dcRepTyCon might be :T123
362
363 -- Now the strictness annotations and field labels of the constructor
364 dcSrcBangs :: [HsSrcBang],
365 -- See Note [Bangs on data constructor arguments]
366 --
367 -- The [HsSrcBang] as written by the programmer.
368 --
369 -- Matches 1-1 with dcOrigArgTys
370 -- Hence length = dataConSourceArity dataCon
371
372 dcFields :: [FieldLabel],
373 -- Field labels for this constructor, in the
374 -- same order as the dcOrigArgTys;
375 -- length = 0 (if not a record) or dataConSourceArity.
376
377 -- The curried worker function that corresponds to the constructor:
378 -- It doesn't have an unfolding; the code generator saturates these Ids
379 -- and allocates a real constructor when it finds one.
380 dcWorkId :: Id,
381
382 -- Constructor representation
383 dcRep :: DataConRep,
384
385 -- Cached; see Note [DataCon arities]
386 -- INVARIANT: dcRepArity == length dataConRepArgTys
387 -- INVARIANT: dcSourceArity == length dcOrigArgTys
388 dcRepArity :: Arity,
389 dcSourceArity :: Arity,
390
391 -- Result type of constructor is T t1..tn
392 dcRepTyCon :: TyCon, -- Result tycon, T
393
394 dcRepType :: Type, -- Type of the constructor
395 -- forall a x y. (a~(x,y), x~y, Ord x) =>
396 -- x -> y -> T a
397 -- (this is *not* of the constructor wrapper Id:
398 -- see Note [Data con representation] below)
399 -- Notice that the existential type parameters come *second*.
400 -- Reason: in a case expression we may find:
401 -- case (e :: T t) of
402 -- MkT x y co1 co2 (d:Ord x) (v:r) (w:F s) -> ...
403 -- It's convenient to apply the rep-type of MkT to 't', to get
404 -- forall x y. (t~(x,y), x~y, Ord x) => x -> y -> T t
405 -- and use that to check the pattern. Mind you, this is really only
406 -- used in CoreLint.
407
408
409 dcInfix :: Bool, -- True <=> declared infix
410 -- Used for Template Haskell and 'deriving' only
411 -- The actual fixity is stored elsewhere
412
413 dcPromoted :: TyCon -- The promoted TyCon
414 -- See Note [Promoted data constructors] in TyCon
415 }
416
417
418 {- Note [TyVarBinders in DataCons]
419 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
420 For the TyVarBinders in a DataCon and PatSyn:
421
422 * Each argument flag is Inferred or Specified.
423 None are Required. (A DataCon is a term-level function; see
424 Note [No Required TyBinder in terms] in TyCoRep.)
425
426 Why do we need the TyVarBinders, rather than just the TyVars? So that
427 we can construct the right type for the DataCon with its foralls
428 attributed the correce visiblity. That in turn governs whether you
429 can use visible type application at a call of the data constructor.
430
431 Note [DataCon arities]
432 ~~~~~~~~~~~~~~~~~~~~~~
433 dcSourceArity does not take constraints into account,
434 but dcRepArity does. For example:
435 MkT :: Ord a => a -> T a
436 dcSourceArity = 1
437 dcRepArity = 2
438 -}
439
440 -- | Data Constructor Representation
441 data DataConRep
442 = NoDataConRep -- No wrapper
443
444 | DCR { dcr_wrap_id :: Id -- Takes src args, unboxes/flattens,
445 -- and constructs the representation
446
447 , dcr_boxer :: DataConBoxer
448
449 , dcr_arg_tys :: [Type] -- Final, representation argument types,
450 -- after unboxing and flattening,
451 -- and *including* all evidence args
452
453 , dcr_stricts :: [StrictnessMark] -- 1-1 with dcr_arg_tys
454 -- See also Note [Data-con worker strictness] in MkId.hs
455
456 , dcr_bangs :: [HsImplBang] -- The actual decisions made (including failures)
457 -- about the original arguments; 1-1 with orig_arg_tys
458 -- See Note [Bangs on data constructor arguments]
459
460 }
461 -- Algebraic data types always have a worker, and
462 -- may or may not have a wrapper, depending on whether
463 -- the wrapper does anything.
464 --
465 -- Data types have a worker with no unfolding
466 -- Newtypes just have a worker, which has a compulsory unfolding (just a cast)
467
468 -- _Neither_ the worker _nor_ the wrapper take the dcStupidTheta dicts as arguments
469
470 -- The wrapper (if it exists) takes dcOrigArgTys as its arguments
471 -- The worker takes dataConRepArgTys as its arguments
472 -- If the worker is absent, dataConRepArgTys is the same as dcOrigArgTys
473
474 -- The 'NoDataConRep' case is important
475 -- Not only is this efficient,
476 -- but it also ensures that the wrapper is replaced
477 -- by the worker (because it *is* the worker)
478 -- even when there are no args. E.g. in
479 -- f (:) x
480 -- the (:) *is* the worker.
481 -- This is really important in rule matching,
482 -- (We could match on the wrappers,
483 -- but that makes it less likely that rules will match
484 -- when we bring bits of unfoldings together.)
485
486 -------------------------
487
488 -- | Haskell Source Bang
489 --
490 -- Bangs on data constructor arguments as the user wrote them in the
491 -- source code.
492 --
493 -- @(HsSrcBang _ SrcUnpack SrcLazy)@ and
494 -- @(HsSrcBang _ SrcUnpack NoSrcStrict)@ (without StrictData) makes no sense, we
495 -- emit a warning (in checkValidDataCon) and treat it like
496 -- @(HsSrcBang _ NoSrcUnpack SrcLazy)@
497 data HsSrcBang =
498 HsSrcBang (Maybe SourceText) -- Note [Pragma source text] in BasicTypes
499 SrcUnpackedness
500 SrcStrictness
501 deriving Data.Data
502
503 -- | Haskell Implementation Bang
504 --
505 -- Bangs of data constructor arguments as generated by the compiler
506 -- after consulting HsSrcBang, flags, etc.
507 data HsImplBang
508 = HsLazy -- ^ Lazy field
509 | HsStrict -- ^ Strict but not unpacked field
510 | HsUnpack (Maybe Coercion)
511 -- ^ Strict and unpacked field
512 -- co :: arg-ty ~ product-ty HsBang
513 deriving Data.Data
514
515 -- | Source Strictness
516 --
517 -- What strictness annotation the user wrote
518 data SrcStrictness = SrcLazy -- ^ Lazy, ie '~'
519 | SrcStrict -- ^ Strict, ie '!'
520 | NoSrcStrict -- ^ no strictness annotation
521 deriving (Eq, Data.Data)
522
523 -- | Source Unpackedness
524 --
525 -- What unpackedness the user requested
526 data SrcUnpackedness = SrcUnpack -- ^ {-# UNPACK #-} specified
527 | SrcNoUnpack -- ^ {-# NOUNPACK #-} specified
528 | NoSrcUnpack -- ^ no unpack pragma
529 deriving (Eq, Data.Data)
530
531
532
533 -------------------------
534 -- StrictnessMark is internal only, used to indicate strictness
535 -- of the DataCon *worker* fields
536 data StrictnessMark = MarkedStrict | NotMarkedStrict
537
538 -- | An 'EqSpec' is a tyvar/type pair representing an equality made in
539 -- rejigging a GADT constructor
540 data EqSpec = EqSpec TyVar
541 Type
542
543 -- | Make an 'EqSpec'
544 mkEqSpec :: TyVar -> Type -> EqSpec
545 mkEqSpec tv ty = EqSpec tv ty
546
547 eqSpecTyVar :: EqSpec -> TyVar
548 eqSpecTyVar (EqSpec tv _) = tv
549
550 eqSpecType :: EqSpec -> Type
551 eqSpecType (EqSpec _ ty) = ty
552
553 eqSpecPair :: EqSpec -> (TyVar, Type)
554 eqSpecPair (EqSpec tv ty) = (tv, ty)
555
556 eqSpecPreds :: [EqSpec] -> ThetaType
557 eqSpecPreds spec = [ mkPrimEqPred (mkTyVarTy tv) ty
558 | EqSpec tv ty <- spec ]
559
560 -- | Substitute in an 'EqSpec'. Precondition: if the LHS of the EqSpec
561 -- is mapped in the substitution, it is mapped to a type variable, not
562 -- a full type.
563 substEqSpec :: TCvSubst -> EqSpec -> EqSpec
564 substEqSpec subst (EqSpec tv ty)
565 = EqSpec tv' (substTy subst ty)
566 where
567 tv' = getTyVar "substEqSpec" (substTyVar subst tv)
568
569 -- | Filter out any TyBinders mentioned in an EqSpec
570 filterEqSpec :: [EqSpec] -> [TyVarBinder] -> [TyVarBinder]
571 filterEqSpec eq_spec
572 = filter not_in_eq_spec
573 where
574 not_in_eq_spec bndr = let var = binderVar bndr in
575 all (not . (== var) . eqSpecTyVar) eq_spec
576
577 instance Outputable EqSpec where
578 ppr (EqSpec tv ty) = ppr (tv, ty)
579
580 {- Note [Bangs on data constructor arguments]
581 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
582 Consider
583 data T = MkT !Int {-# UNPACK #-} !Int Bool
584
585 When compiling the module, GHC will decide how to represent
586 MkT, depending on the optimisation level, and settings of
587 flags like -funbox-small-strict-fields.
588
589 Terminology:
590 * HsSrcBang: What the user wrote
591 Constructors: HsSrcBang
592
593 * HsImplBang: What GHC decided
594 Constructors: HsLazy, HsStrict, HsUnpack
595
596 * If T was defined in this module, MkT's dcSrcBangs field
597 records the [HsSrcBang] of what the user wrote; in the example
598 [ HsSrcBang _ NoSrcUnpack SrcStrict
599 , HsSrcBang _ SrcUnpack SrcStrict
600 , HsSrcBang _ NoSrcUnpack NoSrcStrictness]
601
602 * However, if T was defined in an imported module, the importing module
603 must follow the decisions made in the original module, regardless of
604 the flag settings in the importing module.
605 Also see Note [Bangs on imported data constructors] in MkId
606
607 * The dcr_bangs field of the dcRep field records the [HsImplBang]
608 If T was defined in this module, Without -O the dcr_bangs might be
609 [HsStrict, HsStrict, HsLazy]
610 With -O it might be
611 [HsStrict, HsUnpack _, HsLazy]
612 With -funbox-small-strict-fields it might be
613 [HsUnpack, HsUnpack _, HsLazy]
614 With -XStrictData it might be
615 [HsStrict, HsUnpack _, HsStrict]
616
617 Note [Data con representation]
618 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
619 The dcRepType field contains the type of the representation of a constructor
620 This may differ from the type of the constructor *Id* (built
621 by MkId.mkDataConId) for two reasons:
622 a) the constructor Id may be overloaded, but the dictionary isn't stored
623 e.g. data Eq a => T a = MkT a a
624
625 b) the constructor may store an unboxed version of a strict field.
626
627 Here's an example illustrating both:
628 data Ord a => T a = MkT Int! a
629 Here
630 T :: Ord a => Int -> a -> T a
631 but the rep type is
632 Trep :: Int# -> a -> T a
633 Actually, the unboxed part isn't implemented yet!
634
635
636
637 ************************************************************************
638 * *
639 \subsection{Instances}
640 * *
641 ************************************************************************
642 -}
643
644 instance Eq DataCon where
645 a == b = getUnique a == getUnique b
646 a /= b = getUnique a /= getUnique b
647
648 instance Uniquable DataCon where
649 getUnique = dcUnique
650
651 instance NamedThing DataCon where
652 getName = dcName
653
654 instance Outputable DataCon where
655 ppr con = ppr (dataConName con)
656
657 instance OutputableBndr DataCon where
658 pprInfixOcc con = pprInfixName (dataConName con)
659 pprPrefixOcc con = pprPrefixName (dataConName con)
660
661 instance Data.Data DataCon where
662 -- don't traverse?
663 toConstr _ = abstractConstr "DataCon"
664 gunfold _ _ = error "gunfold"
665 dataTypeOf _ = mkNoRepType "DataCon"
666
667 instance Outputable HsSrcBang where
668 ppr (HsSrcBang _ prag mark) = ppr prag <+> ppr mark
669
670 instance Outputable HsImplBang where
671 ppr HsLazy = text "Lazy"
672 ppr (HsUnpack Nothing) = text "Unpacked"
673 ppr (HsUnpack (Just co)) = text "Unpacked" <> parens (ppr co)
674 ppr HsStrict = text "StrictNotUnpacked"
675
676 instance Outputable SrcStrictness where
677 ppr SrcLazy = char '~'
678 ppr SrcStrict = char '!'
679 ppr NoSrcStrict = empty
680
681 instance Outputable SrcUnpackedness where
682 ppr SrcUnpack = text "{-# UNPACK #-}"
683 ppr SrcNoUnpack = text "{-# NOUNPACK #-}"
684 ppr NoSrcUnpack = empty
685
686 instance Outputable StrictnessMark where
687 ppr MarkedStrict = text "!"
688 ppr NotMarkedStrict = empty
689
690 instance Binary SrcStrictness where
691 put_ bh SrcLazy = putByte bh 0
692 put_ bh SrcStrict = putByte bh 1
693 put_ bh NoSrcStrict = putByte bh 2
694
695 get bh =
696 do h <- getByte bh
697 case h of
698 0 -> return SrcLazy
699 1 -> return SrcLazy
700 _ -> return NoSrcStrict
701
702 instance Binary SrcUnpackedness where
703 put_ bh SrcNoUnpack = putByte bh 0
704 put_ bh SrcUnpack = putByte bh 1
705 put_ bh NoSrcUnpack = putByte bh 2
706
707 get bh =
708 do h <- getByte bh
709 case h of
710 0 -> return SrcNoUnpack
711 1 -> return SrcUnpack
712 _ -> return NoSrcUnpack
713
714 -- | Compare strictness annotations
715 eqHsBang :: HsImplBang -> HsImplBang -> Bool
716 eqHsBang HsLazy HsLazy = True
717 eqHsBang HsStrict HsStrict = True
718 eqHsBang (HsUnpack Nothing) (HsUnpack Nothing) = True
719 eqHsBang (HsUnpack (Just c1)) (HsUnpack (Just c2))
720 = eqType (coercionType c1) (coercionType c2)
721 eqHsBang _ _ = False
722
723 isBanged :: HsImplBang -> Bool
724 isBanged (HsUnpack {}) = True
725 isBanged (HsStrict {}) = True
726 isBanged HsLazy = False
727
728 isSrcStrict :: SrcStrictness -> Bool
729 isSrcStrict SrcStrict = True
730 isSrcStrict _ = False
731
732 isSrcUnpacked :: SrcUnpackedness -> Bool
733 isSrcUnpacked SrcUnpack = True
734 isSrcUnpacked _ = False
735
736 isMarkedStrict :: StrictnessMark -> Bool
737 isMarkedStrict NotMarkedStrict = False
738 isMarkedStrict _ = True -- All others are strict
739
740 {- *********************************************************************
741 * *
742 \subsection{Construction}
743 * *
744 ********************************************************************* -}
745
746 -- | Build a new data constructor
747 mkDataCon :: Name
748 -> Bool -- ^ Is the constructor declared infix?
749 -> TyConRepName -- ^ TyConRepName for the promoted TyCon
750 -> [HsSrcBang] -- ^ Strictness/unpack annotations, from user
751 -> [FieldLabel] -- ^ Field labels for the constructor,
752 -- if it is a record, otherwise empty
753 -> [TyVarBinder] -- ^ Universals. See Note [TyVarBinders in DataCons]
754 -> [TyVarBinder] -- ^ Existentials.
755 -- (These last two must be Named and Inferred/Specified)
756 -> [EqSpec] -- ^ GADT equalities
757 -> ThetaType -- ^ Theta-type occuring before the arguments proper
758 -> [Type] -- ^ Original argument types
759 -> Type -- ^ Original result type
760 -> RuntimeRepInfo -- ^ See comments on 'TyCon.RuntimeRepInfo'
761 -> TyCon -- ^ Representation type constructor
762 -> ThetaType -- ^ The "stupid theta", context of the data
763 -- declaration e.g. @data Eq a => T a ...@
764 -> Id -- ^ Worker Id
765 -> DataConRep -- ^ Representation
766 -> DataCon
767 -- Can get the tag from the TyCon
768
769 mkDataCon name declared_infix prom_info
770 arg_stricts -- Must match orig_arg_tys 1-1
771 fields
772 univ_tvs ex_tvs
773 eq_spec theta
774 orig_arg_tys orig_res_ty rep_info rep_tycon
775 stupid_theta work_id rep
776 -- Warning: mkDataCon is not a good place to check invariants.
777 -- If the programmer writes the wrong result type in the decl, thus:
778 -- data T a where { MkT :: S }
779 -- then it's possible that the univ_tvs may hit an assertion failure
780 -- if you pull on univ_tvs. This case is checked by checkValidDataCon,
781 -- so the error is detected properly... it's just that asaertions here
782 -- are a little dodgy.
783
784 = con
785 where
786 is_vanilla = null ex_tvs && null eq_spec && null theta
787 con = MkData {dcName = name, dcUnique = nameUnique name,
788 dcVanilla = is_vanilla, dcInfix = declared_infix,
789 dcUnivTyVars = univ_tvs,
790 dcExTyVars = ex_tvs,
791 dcEqSpec = eq_spec,
792 dcOtherTheta = theta,
793 dcStupidTheta = stupid_theta,
794 dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
795 dcRepTyCon = rep_tycon,
796 dcSrcBangs = arg_stricts,
797 dcFields = fields, dcTag = tag, dcRepType = rep_ty,
798 dcWorkId = work_id,
799 dcRep = rep,
800 dcSourceArity = length orig_arg_tys,
801 dcRepArity = length rep_arg_tys,
802 dcPromoted = promoted }
803
804 -- The 'arg_stricts' passed to mkDataCon are simply those for the
805 -- source-language arguments. We add extra ones for the
806 -- dictionary arguments right here.
807
808 tag = assoc "mkDataCon" (tyConDataCons rep_tycon `zip` [fIRST_TAG..]) con
809 rep_arg_tys = dataConRepArgTys con
810
811 rep_ty = mkForAllTys univ_tvs $ mkForAllTys ex_tvs $
812 mkFunTys rep_arg_tys $
813 mkTyConApp rep_tycon (mkTyVarTys (binderVars univ_tvs))
814
815 -- See Note [Promoted data constructors] in TyCon
816 prom_tv_bndrs = [ mkNamedTyConBinder vis tv
817 | TvBndr tv vis <- filterEqSpec eq_spec univ_tvs ++ ex_tvs ]
818
819 prom_arg_bndrs = mkCleanAnonTyConBinders prom_tv_bndrs (theta ++ orig_arg_tys)
820 prom_res_kind = orig_res_ty
821 promoted = mkPromotedDataCon con name prom_info
822 (prom_tv_bndrs ++ prom_arg_bndrs)
823 prom_res_kind roles rep_info
824
825 roles = map (const Nominal) (univ_tvs ++ ex_tvs) ++
826 map (const Representational) orig_arg_tys
827
828 mkCleanAnonTyConBinders :: [TyConBinder] -> [Type] -> [TyConBinder]
829 -- Make sure that the "anonymous" tyvars don't clash in
830 -- name or unique with the universal/existential ones.
831 -- Tiresome! And unnecessary because these tyvars are never looked at
832 mkCleanAnonTyConBinders tc_bndrs tys
833 = [ mkAnonTyConBinder (mkTyVar name ty)
834 | (name, ty) <- fresh_names `zip` tys ]
835 where
836 fresh_names = freshNames (map getName (binderVars tc_bndrs))
837
838 freshNames :: [Name] -> [Name]
839 -- Make names whose Uniques and OccNames differ from
840 -- those in the 'avoid' list
841 freshNames avoids
842 = [ mkSystemName uniq occ
843 | n <- [0..]
844 , let uniq = mkAlphaTyVarUnique n
845 occ = mkTyVarOccFS (mkFastString ('x' : show n))
846
847 , not (uniq `elementOfUniqSet` avoid_uniqs)
848 , not (occ `elemOccSet` avoid_occs) ]
849
850 where
851 avoid_uniqs :: UniqSet Unique
852 avoid_uniqs = mkUniqSet (map getUnique avoids)
853
854 avoid_occs :: OccSet
855 avoid_occs = mkOccSet (map getOccName avoids)
856
857 -- | The 'Name' of the 'DataCon', giving it a unique, rooted identification
858 dataConName :: DataCon -> Name
859 dataConName = dcName
860
861 -- | The tag used for ordering 'DataCon's
862 dataConTag :: DataCon -> ConTag
863 dataConTag = dcTag
864
865 -- | The type constructor that we are building via this data constructor
866 dataConTyCon :: DataCon -> TyCon
867 dataConTyCon = dcRepTyCon
868
869 -- | The original type constructor used in the definition of this data
870 -- constructor. In case of a data family instance, that will be the family
871 -- type constructor.
872 dataConOrigTyCon :: DataCon -> TyCon
873 dataConOrigTyCon dc
874 | Just (tc, _) <- tyConFamInst_maybe (dcRepTyCon dc) = tc
875 | otherwise = dcRepTyCon dc
876
877 -- | The representation type of the data constructor, i.e. the sort
878 -- type that will represent values of this type at runtime
879 dataConRepType :: DataCon -> Type
880 dataConRepType = dcRepType
881
882 -- | Should the 'DataCon' be presented infix?
883 dataConIsInfix :: DataCon -> Bool
884 dataConIsInfix = dcInfix
885
886 -- | The universally-quantified type variables of the constructor
887 dataConUnivTyVars :: DataCon -> [TyVar]
888 dataConUnivTyVars (MkData { dcUnivTyVars = tvbs }) = binderVars tvbs
889
890 -- | 'TyBinder's for the universally-quantified type variables
891 dataConUnivTyVarBinders :: DataCon -> [TyVarBinder]
892 dataConUnivTyVarBinders = dcUnivTyVars
893
894 -- | The existentially-quantified type variables of the constructor
895 dataConExTyVars :: DataCon -> [TyVar]
896 dataConExTyVars (MkData { dcExTyVars = tvbs }) = binderVars tvbs
897
898 -- | 'TyBinder's for the existentially-quantified type variables
899 dataConExTyVarBinders :: DataCon -> [TyVarBinder]
900 dataConExTyVarBinders = dcExTyVars
901
902 -- | Both the universal and existentiatial type variables of the constructor
903 dataConAllTyVars :: DataCon -> [TyVar]
904 dataConAllTyVars (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs })
905 = binderVars (univ_tvs ++ ex_tvs)
906
907 -- | Equalities derived from the result type of the data constructor, as written
908 -- by the programmer in any GADT declaration. This includes *all* GADT-like
909 -- equalities, including those written in by hand by the programmer.
910 dataConEqSpec :: DataCon -> [EqSpec]
911 dataConEqSpec (MkData { dcEqSpec = eq_spec, dcOtherTheta = theta })
912 = eq_spec ++
913 [ spec -- heterogeneous equality
914 | Just (tc, [_k1, _k2, ty1, ty2]) <- map splitTyConApp_maybe theta
915 , tc `hasKey` heqTyConKey
916 , spec <- case (getTyVar_maybe ty1, getTyVar_maybe ty2) of
917 (Just tv1, _) -> [mkEqSpec tv1 ty2]
918 (_, Just tv2) -> [mkEqSpec tv2 ty1]
919 _ -> []
920 ] ++
921 [ spec -- homogeneous equality
922 | Just (tc, [_k, ty1, ty2]) <- map splitTyConApp_maybe theta
923 , tc `hasKey` eqTyConKey
924 , spec <- case (getTyVar_maybe ty1, getTyVar_maybe ty2) of
925 (Just tv1, _) -> [mkEqSpec tv1 ty2]
926 (_, Just tv2) -> [mkEqSpec tv2 ty1]
927 _ -> []
928 ]
929
930
931 -- | The *full* constraints on the constructor type.
932 dataConTheta :: DataCon -> ThetaType
933 dataConTheta (MkData { dcEqSpec = eq_spec, dcOtherTheta = theta })
934 = eqSpecPreds eq_spec ++ theta
935
936 -- | Get the Id of the 'DataCon' worker: a function that is the "actual"
937 -- constructor and has no top level binding in the program. The type may
938 -- be different from the obvious one written in the source program. Panics
939 -- if there is no such 'Id' for this 'DataCon'
940 dataConWorkId :: DataCon -> Id
941 dataConWorkId dc = dcWorkId dc
942
943 -- | Get the Id of the 'DataCon' wrapper: a function that wraps the "actual"
944 -- constructor so it has the type visible in the source program: c.f. 'dataConWorkId'.
945 -- Returns Nothing if there is no wrapper, which occurs for an algebraic data constructor
946 -- and also for a newtype (whose constructor is inlined compulsorily)
947 dataConWrapId_maybe :: DataCon -> Maybe Id
948 dataConWrapId_maybe dc = case dcRep dc of
949 NoDataConRep -> Nothing
950 DCR { dcr_wrap_id = wrap_id } -> Just wrap_id
951
952 -- | Returns an Id which looks like the Haskell-source constructor by using
953 -- the wrapper if it exists (see 'dataConWrapId_maybe') and failing over to
954 -- the worker (see 'dataConWorkId')
955 dataConWrapId :: DataCon -> Id
956 dataConWrapId dc = case dcRep dc of
957 NoDataConRep-> dcWorkId dc -- worker=wrapper
958 DCR { dcr_wrap_id = wrap_id } -> wrap_id
959
960 -- | Find all the 'Id's implicitly brought into scope by the data constructor. Currently,
961 -- the union of the 'dataConWorkId' and the 'dataConWrapId'
962 dataConImplicitTyThings :: DataCon -> [TyThing]
963 dataConImplicitTyThings (MkData { dcWorkId = work, dcRep = rep })
964 = [AnId work] ++ wrap_ids
965 where
966 wrap_ids = case rep of
967 NoDataConRep -> []
968 DCR { dcr_wrap_id = wrap } -> [AnId wrap]
969
970 -- | The labels for the fields of this particular 'DataCon'
971 dataConFieldLabels :: DataCon -> [FieldLabel]
972 dataConFieldLabels = dcFields
973
974 -- | Extract the type for any given labelled field of the 'DataCon'
975 dataConFieldType :: DataCon -> FieldLabelString -> Type
976 dataConFieldType con label
977 = case find ((== label) . flLabel . fst) (dcFields con `zip` dcOrigArgTys con) of
978 Just (_, ty) -> ty
979 Nothing -> pprPanic "dataConFieldType" (ppr con <+> ppr label)
980
981 -- | Strictness/unpack annotations, from user; or, for imported
982 -- DataCons, from the interface file
983 -- The list is in one-to-one correspondence with the arity of the 'DataCon'
984
985 dataConSrcBangs :: DataCon -> [HsSrcBang]
986 dataConSrcBangs = dcSrcBangs
987
988 -- | Source-level arity of the data constructor
989 dataConSourceArity :: DataCon -> Arity
990 dataConSourceArity (MkData { dcSourceArity = arity }) = arity
991
992 -- | Gives the number of actual fields in the /representation/ of the
993 -- data constructor. This may be more than appear in the source code;
994 -- the extra ones are the existentially quantified dictionaries
995 dataConRepArity :: DataCon -> Arity
996 dataConRepArity (MkData { dcRepArity = arity }) = arity
997
998 -- | Return whether there are any argument types for this 'DataCon's original source type
999 -- See Note [DataCon arities]
1000 isNullarySrcDataCon :: DataCon -> Bool
1001 isNullarySrcDataCon dc = dataConSourceArity dc == 0
1002
1003 -- | Return whether there are any argument types for this 'DataCon's runtime representation type
1004 -- See Note [DataCon arities]
1005 isNullaryRepDataCon :: DataCon -> Bool
1006 isNullaryRepDataCon dc = dataConRepArity dc == 0
1007
1008 dataConRepStrictness :: DataCon -> [StrictnessMark]
1009 -- ^ Give the demands on the arguments of a
1010 -- Core constructor application (Con dc args)
1011 dataConRepStrictness dc = case dcRep dc of
1012 NoDataConRep -> [NotMarkedStrict | _ <- dataConRepArgTys dc]
1013 DCR { dcr_stricts = strs } -> strs
1014
1015 dataConImplBangs :: DataCon -> [HsImplBang]
1016 -- The implementation decisions about the strictness/unpack of each
1017 -- source program argument to the data constructor
1018 dataConImplBangs dc
1019 = case dcRep dc of
1020 NoDataConRep -> replicate (dcSourceArity dc) HsLazy
1021 DCR { dcr_bangs = bangs } -> bangs
1022
1023 dataConBoxer :: DataCon -> Maybe DataConBoxer
1024 dataConBoxer (MkData { dcRep = DCR { dcr_boxer = boxer } }) = Just boxer
1025 dataConBoxer _ = Nothing
1026
1027 -- | The \"signature\" of the 'DataCon' returns, in order:
1028 --
1029 -- 1) The result of 'dataConAllTyVars',
1030 --
1031 -- 2) All the 'ThetaType's relating to the 'DataCon' (coercion, dictionary, implicit
1032 -- parameter - whatever)
1033 --
1034 -- 3) The type arguments to the constructor
1035 --
1036 -- 4) The /original/ result type of the 'DataCon'
1037 dataConSig :: DataCon -> ([TyVar], ThetaType, [Type], Type)
1038 dataConSig con@(MkData {dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
1039 = (dataConAllTyVars con, dataConTheta con, arg_tys, res_ty)
1040
1041 dataConInstSig
1042 :: DataCon
1043 -> [Type] -- Instantiate the *universal* tyvars with these types
1044 -> ([TyVar], ThetaType, [Type]) -- Return instantiated existentials
1045 -- theta and arg tys
1046 -- ^ Instantantiate the universal tyvars of a data con,
1047 -- returning the instantiated existentials, constraints, and args
1048 dataConInstSig (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs
1049 , dcEqSpec = eq_spec, dcOtherTheta = theta
1050 , dcOrigArgTys = arg_tys })
1051 univ_tys
1052 = ( ex_tvs'
1053 , substTheta subst (eqSpecPreds eq_spec ++ theta)
1054 , substTys subst arg_tys)
1055 where
1056 univ_subst = zipTvSubst (binderVars univ_tvs) univ_tys
1057 (subst, ex_tvs') = mapAccumL Type.substTyVarBndr univ_subst $
1058 binderVars ex_tvs
1059
1060
1061 -- | The \"full signature\" of the 'DataCon' returns, in order:
1062 --
1063 -- 1) The result of 'dataConUnivTyVars'
1064 --
1065 -- 2) The result of 'dataConExTyVars'
1066 --
1067 -- 3) The GADT equalities
1068 --
1069 -- 4) The result of 'dataConDictTheta'
1070 --
1071 -- 5) The original argument types to the 'DataCon' (i.e. before
1072 -- any change of the representation of the type)
1073 --
1074 -- 6) The original result type of the 'DataCon'
1075 dataConFullSig :: DataCon
1076 -> ([TyVar], [TyVar], [EqSpec], ThetaType, [Type], Type)
1077 dataConFullSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
1078 dcEqSpec = eq_spec, dcOtherTheta = theta,
1079 dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
1080 = (binderVars univ_tvs, binderVars ex_tvs, eq_spec, theta, arg_tys, res_ty)
1081
1082 dataConOrigResTy :: DataCon -> Type
1083 dataConOrigResTy dc = dcOrigResTy dc
1084
1085 -- | The \"stupid theta\" of the 'DataCon', such as @data Eq a@ in:
1086 --
1087 -- > data Eq a => T a = ...
1088 dataConStupidTheta :: DataCon -> ThetaType
1089 dataConStupidTheta dc = dcStupidTheta dc
1090
1091 dataConUserType :: DataCon -> Type
1092 -- ^ The user-declared type of the data constructor
1093 -- in the nice-to-read form:
1094 --
1095 -- > T :: forall a b. a -> b -> T [a]
1096 --
1097 -- rather than:
1098 --
1099 -- > T :: forall a c. forall b. (c~[a]) => a -> b -> T c
1100 --
1101 -- NB: If the constructor is part of a data instance, the result type
1102 -- mentions the family tycon, not the internal one.
1103 dataConUserType (MkData { dcUnivTyVars = univ_tvs,
1104 dcExTyVars = ex_tvs, dcEqSpec = eq_spec,
1105 dcOtherTheta = theta, dcOrigArgTys = arg_tys,
1106 dcOrigResTy = res_ty })
1107 = mkForAllTys (filterEqSpec eq_spec univ_tvs) $
1108 mkForAllTys ex_tvs $
1109 mkFunTys theta $
1110 mkFunTys arg_tys $
1111 res_ty
1112 where
1113
1114 -- | Finds the instantiated types of the arguments required to construct a 'DataCon' representation
1115 -- NB: these INCLUDE any dictionary args
1116 -- but EXCLUDE the data-declaration context, which is discarded
1117 -- It's all post-flattening etc; this is a representation type
1118 dataConInstArgTys :: DataCon -- ^ A datacon with no existentials or equality constraints
1119 -- However, it can have a dcTheta (notably it can be a
1120 -- class dictionary, with superclasses)
1121 -> [Type] -- ^ Instantiated at these types
1122 -> [Type]
1123 dataConInstArgTys dc@(MkData {dcUnivTyVars = univ_tvs,
1124 dcExTyVars = ex_tvs}) inst_tys
1125 = ASSERT2( length univ_tvs == length inst_tys
1126 , text "dataConInstArgTys" <+> ppr dc $$ ppr univ_tvs $$ ppr inst_tys)
1127 ASSERT2( null ex_tvs, ppr dc )
1128 map (substTyWith (binderVars univ_tvs) inst_tys) (dataConRepArgTys dc)
1129
1130 -- | Returns just the instantiated /value/ argument types of a 'DataCon',
1131 -- (excluding dictionary args)
1132 dataConInstOrigArgTys
1133 :: DataCon -- Works for any DataCon
1134 -> [Type] -- Includes existential tyvar args, but NOT
1135 -- equality constraints or dicts
1136 -> [Type]
1137 -- For vanilla datacons, it's all quite straightforward
1138 -- But for the call in MatchCon, we really do want just the value args
1139 dataConInstOrigArgTys dc@(MkData {dcOrigArgTys = arg_tys,
1140 dcUnivTyVars = univ_tvs,
1141 dcExTyVars = ex_tvs}) inst_tys
1142 = ASSERT2( length tyvars == length inst_tys
1143 , text "dataConInstOrigArgTys" <+> ppr dc $$ ppr tyvars $$ ppr inst_tys )
1144 map (substTyWith tyvars inst_tys) arg_tys
1145 where
1146 tyvars = binderVars (univ_tvs ++ ex_tvs)
1147
1148 -- | Returns the argument types of the wrapper, excluding all dictionary arguments
1149 -- and without substituting for any type variables
1150 dataConOrigArgTys :: DataCon -> [Type]
1151 dataConOrigArgTys dc = dcOrigArgTys dc
1152
1153 -- | Returns the arg types of the worker, including *all*
1154 -- evidence, after any flattening has been done and without substituting for
1155 -- any type variables
1156 dataConRepArgTys :: DataCon -> [Type]
1157 dataConRepArgTys (MkData { dcRep = rep
1158 , dcEqSpec = eq_spec
1159 , dcOtherTheta = theta
1160 , dcOrigArgTys = orig_arg_tys })
1161 = case rep of
1162 NoDataConRep -> ASSERT( null eq_spec ) theta ++ orig_arg_tys
1163 DCR { dcr_arg_tys = arg_tys } -> arg_tys
1164
1165 -- | The string @package:module.name@ identifying a constructor, which is attached
1166 -- to its info table and used by the GHCi debugger and the heap profiler
1167 dataConIdentity :: DataCon -> [Word8]
1168 -- We want this string to be UTF-8, so we get the bytes directly from the FastStrings.
1169 dataConIdentity dc = bytesFS (unitIdFS (moduleUnitId mod)) ++
1170 fromIntegral (ord ':') : bytesFS (moduleNameFS (moduleName mod)) ++
1171 fromIntegral (ord '.') : bytesFS (occNameFS (nameOccName name))
1172 where name = dataConName dc
1173 mod = ASSERT( isExternalName name ) nameModule name
1174
1175 isTupleDataCon :: DataCon -> Bool
1176 isTupleDataCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc
1177
1178 isUnboxedTupleCon :: DataCon -> Bool
1179 isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc
1180
1181 isUnboxedSumCon :: DataCon -> Bool
1182 isUnboxedSumCon (MkData {dcRepTyCon = tc}) = isUnboxedSumTyCon tc
1183
1184 -- | Vanilla 'DataCon's are those that are nice boring Haskell 98 constructors
1185 isVanillaDataCon :: DataCon -> Bool
1186 isVanillaDataCon dc = dcVanilla dc
1187
1188 -- | Should this DataCon be allowed in a type even without -XDataKinds?
1189 -- Currently, only Lifted & Unlifted
1190 specialPromotedDc :: DataCon -> Bool
1191 specialPromotedDc = isKindTyCon . dataConTyCon
1192
1193 -- | Was this datacon promotable before GHC 8.0? That is, is it promotable
1194 -- without -XTypeInType
1195 isLegacyPromotableDataCon :: DataCon -> Bool
1196 isLegacyPromotableDataCon dc
1197 = null (dataConEqSpec dc) -- no GADTs
1198 && null (dataConTheta dc) -- no context
1199 && not (isFamInstTyCon (dataConTyCon dc)) -- no data instance constructors
1200 && allUFM isLegacyPromotableTyCon (tyConsOfType (dataConUserType dc))
1201
1202 -- | Was this tycon promotable before GHC 8.0? That is, is it promotable
1203 -- without -XTypeInType
1204 isLegacyPromotableTyCon :: TyCon -> Bool
1205 isLegacyPromotableTyCon tc
1206 = isVanillaAlgTyCon tc ||
1207 -- This returns True more often than it should, but it's quite painful
1208 -- to make this fully accurate. And no harm is caused; we just don't
1209 -- require -XTypeInType every time we need to. (We'll always require
1210 -- -XDataKinds, though, so there's no standards-compliance issue.)
1211 isFunTyCon tc || isKindTyCon tc
1212
1213 classDataCon :: Class -> DataCon
1214 classDataCon clas = case tyConDataCons (classTyCon clas) of
1215 (dict_constr:no_more) -> ASSERT( null no_more ) dict_constr
1216 [] -> panic "classDataCon"
1217
1218 dataConCannotMatch :: [Type] -> DataCon -> Bool
1219 -- Returns True iff the data con *definitely cannot* match a
1220 -- scrutinee of type (T tys)
1221 -- where T is the dcRepTyCon for the data con
1222 dataConCannotMatch tys con
1223 | null inst_theta = False -- Common
1224 | all isTyVarTy tys = False -- Also common
1225 | otherwise = typesCantMatch (concatMap predEqs inst_theta)
1226 where
1227 (_, inst_theta, _) = dataConInstSig con tys
1228
1229 -- TODO: could gather equalities from superclasses too
1230 predEqs pred = case classifyPredType pred of
1231 EqPred NomEq ty1 ty2 -> [(ty1, ty2)]
1232 ClassPred eq [_, ty1, ty2]
1233 | eq `hasKey` eqTyConKey -> [(ty1, ty2)]
1234 _ -> []
1235
1236 {-
1237 %************************************************************************
1238 %* *
1239 Promoting of data types to the kind level
1240 * *
1241 ************************************************************************
1242
1243 -}
1244
1245 promoteDataCon :: DataCon -> TyCon
1246 promoteDataCon (MkData { dcPromoted = tc }) = tc
1247
1248 {-
1249 ************************************************************************
1250 * *
1251 \subsection{Splitting products}
1252 * *
1253 ************************************************************************
1254 -}
1255
1256 -- | Extract the type constructor, type argument, data constructor and it's
1257 -- /representation/ argument types from a type if it is a product type.
1258 --
1259 -- Precisely, we return @Just@ for any type that is all of:
1260 --
1261 -- * Concrete (i.e. constructors visible)
1262 --
1263 -- * Single-constructor
1264 --
1265 -- * Not existentially quantified
1266 --
1267 -- Whether the type is a @data@ type or a @newtype@
1268 splitDataProductType_maybe
1269 :: Type -- ^ A product type, perhaps
1270 -> Maybe (TyCon, -- The type constructor
1271 [Type], -- Type args of the tycon
1272 DataCon, -- The data constructor
1273 [Type]) -- Its /representation/ arg types
1274
1275 -- Rejecting existentials is conservative. Maybe some things
1276 -- could be made to work with them, but I'm not going to sweat
1277 -- it through till someone finds it's important.
1278
1279 splitDataProductType_maybe ty
1280 | Just (tycon, ty_args) <- splitTyConApp_maybe ty
1281 , Just con <- isDataProductTyCon_maybe tycon
1282 = Just (tycon, ty_args, con, dataConInstArgTys con ty_args)
1283 | otherwise
1284 = Nothing
1285
1286 {-
1287 ************************************************************************
1288 * *
1289 Building an algebraic data type
1290 * *
1291 ************************************************************************
1292
1293 buildAlgTyCon is here because it is called from TysWiredIn, which can
1294 depend on this module, but not on BuildTyCl.
1295 -}
1296
1297 buildAlgTyCon :: Name
1298 -> [TyVar] -- ^ Kind variables and type variables
1299 -> [Role]
1300 -> Maybe CType
1301 -> ThetaType -- ^ Stupid theta
1302 -> AlgTyConRhs
1303 -> Bool -- ^ True <=> was declared in GADT syntax
1304 -> AlgTyConFlav
1305 -> TyCon
1306
1307 buildAlgTyCon tc_name ktvs roles cType stupid_theta rhs
1308 gadt_syn parent
1309 = mkAlgTyCon tc_name binders liftedTypeKind roles cType stupid_theta
1310 rhs parent gadt_syn
1311 where
1312 binders = mkTyConBindersPreferAnon ktvs liftedTypeKind