DataCon.hs 44.3 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998

5
\section[DataCon]{@DataCon@: Data Constructors}
Austin Seipp's avatar
Austin Seipp committed
6
-}
7

8
{-# LANGUAGE CPP, DeriveDataTypeable #-}
Ian Lynagh's avatar
Ian Lynagh committed
9

10
module DataCon (
batterseapower's avatar
batterseapower committed
11
        -- * Main data types
Edward Z. Yang's avatar
Edward Z. Yang committed
12 13 14 15 16 17 18 19 20 21
        DataCon, DataConRep(..), HsBang(..), StrictnessMark(..),
        ConTag,

        -- ** Type construction
        mkDataCon, fIRST_TAG,
        buildAlgTyCon,

        -- ** Type deconstruction
        dataConRepType, dataConSig, dataConFullSig,
        dataConName, dataConIdentity, dataConTag, dataConTyCon,
22
        dataConOrigTyCon, dataConUserType,
Edward Z. Yang's avatar
Edward Z. Yang committed
23 24 25 26 27 28 29 30 31 32 33 34 35
        dataConUnivTyVars, dataConExTyVars, dataConAllTyVars,
        dataConEqSpec, eqSpecPreds, dataConTheta,
        dataConStupidTheta,
        dataConInstArgTys, dataConOrigArgTys, dataConOrigResTy,
        dataConInstOrigArgTys, dataConRepArgTys,
        dataConFieldLabels, dataConFieldType,
        dataConStrictMarks,
        dataConSourceArity, dataConRepArity, dataConRepRepArity,
        dataConIsInfix,
        dataConWorkId, dataConWrapId, dataConWrapId_maybe, dataConImplicitIds,
        dataConRepStrictness, dataConRepBangs, dataConBoxer,

        splitDataProductType_maybe,
36

Edward Z. Yang's avatar
Edward Z. Yang committed
37 38 39
        -- ** Predicates on DataCons
        isNullarySrcDataCon, isNullaryRepDataCon, isTupleDataCon, isUnboxedTupleCon,
        isVanillaDataCon, classDataCon, dataConCannotMatch,
40
        isBanged, isMarkedStrict, eqHsBang,
41

42
        -- ** Promotion related functions
43
        promoteKind, promoteDataCon, promoteDataCon_maybe
44 45 46 47
    ) where

#include "HsVersions.h"

48
import {-# SOURCE #-} MkId( DataConBoxer )
Simon Marlow's avatar
Simon Marlow committed
49
import Type
50
import TypeRep( Type(..) )  -- Used in promoteType
51
import PrelNames( liftedTypeKindTyConKey )
52
import ForeignCall( CType )
53
import Coercion
54
import Kind
55
import Unify
Simon Marlow's avatar
Simon Marlow committed
56 57 58 59
import TyCon
import Class
import Name
import Var
60
import Outputable
Simon Marlow's avatar
Simon Marlow committed
61 62 63
import Unique
import ListSetOps
import Util
batterseapower's avatar
batterseapower committed
64
import BasicTypes
65
import FastString
66
import Module
67
import VarEnv
68

69
import qualified Data.Data as Data
70
import qualified Data.Typeable
71
import Data.Maybe
72 73
import Data.Char
import Data.Word
74

Austin Seipp's avatar
Austin Seipp committed
75
{-
76 77 78
Data constructor representation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following Haskell data type declaration
79

Edward Z. Yang's avatar
Edward Z. Yang committed
80
        data T = T !Int ![Int]
81 82 83

Using the strictness annotations, GHC will represent this as

Edward Z. Yang's avatar
Edward Z. Yang committed
84
        data T = T Int# [Int]
85 86 87

That is, the Int has been unboxed.  Furthermore, the Haskell source construction

Edward Z. Yang's avatar
Edward Z. Yang committed
88
        T e1 e2
89 90 91

is translated to

Edward Z. Yang's avatar
Edward Z. Yang committed
92 93 94
        case e1 of { I# x ->
        case e2 of { r ->
        T x r }}
95 96 97 98

That is, the first argument is unboxed, and the second is evaluated.  Finally,
pattern matching is translated too:

Edward Z. Yang's avatar
Edward Z. Yang committed
99
        case e of { T a b -> ... }
100 101 102

becomes

Edward Z. Yang's avatar
Edward Z. Yang committed
103
        case e of { T a' b -> let a = I# a' in ... }
104 105 106 107 108 109 110

To keep ourselves sane, we name the different versions of the data constructor
differently, as follows.


Note [Data Constructor Naming]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
111
Each data constructor C has two, and possibly up to four, Names associated with it:
112

Edward Z. Yang's avatar
Edward Z. Yang committed
113
                   OccName   Name space   Name of   Notes
114
 ---------------------------------------------------------------------------
Edward Z. Yang's avatar
Edward Z. Yang committed
115 116 117
 The "data con itself"   C     DataName   DataCon   In dom( GlobalRdrEnv )
 The "worker data con"   C     VarName    Id        The worker
 The "wrapper data con"  $WC   VarName    Id        The wrapper
118
 The "newtype coercion"  :CoT  TcClsName  TyCon
Edward Z. Yang's avatar
Edward Z. Yang committed
119

120 121 122 123 124
EVERY data constructor (incl for newtypes) has the former two (the
data con itself, and its worker.  But only some data constructors have a
wrapper (see Note [The need for a wrapper]).

Each of these three has a distinct Unique.  The "data con itself" name
125 126 127 128 129 130
appears in the output of the renamer, and names the Haskell-source
data constructor.  The type checker translates it into either the wrapper Id
(if it exists) or worker Id (otherwise).

The data con has one or two Ids associated with it:

131 132
The "worker Id", is the actual data constructor.
* Every data constructor (newtype or data type) has a worker
133

134
* The worker is very like a primop, in that it has no binding.
135

136 137
* For a *data* type, the worker *is* the data constructor;
  it has no unfolding
138

Edward Z. Yang's avatar
Edward Z. Yang committed
139
* For a *newtype*, the worker has a compulsory unfolding which
140
  does a cast, e.g.
Edward Z. Yang's avatar
Edward Z. Yang committed
141 142 143
        newtype T = MkT Int
        The worker for MkT has unfolding
                \\(x:Int). x `cast` sym CoT
144
  Here CoT is the type constructor, witnessing the FC axiom
Edward Z. Yang's avatar
Edward Z. Yang committed
145
        axiom CoT : T = Int
146

batterseapower's avatar
batterseapower committed
147
The "wrapper Id", \$WC, goes as follows
148

Edward Z. Yang's avatar
Edward Z. Yang committed
149
* Its type is exactly what it looks like in the source program.
150

Edward Z. Yang's avatar
Edward Z. Yang committed
151
* It is an ordinary function, and it gets a top-level binding
152 153 154 155
  like any other function.

* The wrapper Id isn't generated for a data type if there is
  nothing for the wrapper to do.  That is, if its defn would be
Edward Z. Yang's avatar
Edward Z. Yang committed
156
        \$wC = C
157

158 159
Note [The need for a wrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
160 161 162
Why might the wrapper have anything to do?  Two reasons:

* Unboxing strict fields (with -funbox-strict-fields)
Edward Z. Yang's avatar
Edward Z. Yang committed
163 164 165 166
        data T = MkT !(Int,Int)
        \$wMkT :: (Int,Int) -> T
        \$wMkT (x,y) = MkT x y
  Notice that the worker has two fields where the wapper has
167
  just one.  That is, the worker has type
Edward Z. Yang's avatar
Edward Z. Yang committed
168
                MkT :: Int -> Int -> T
169 170

* Equality constraints for GADTs
Edward Z. Yang's avatar
Edward Z. Yang committed
171
        data T a where { MkT :: a -> T [a] }
172 173 174

  The worker gets a type with explicit equality
  constraints, thus:
Edward Z. Yang's avatar
Edward Z. Yang committed
175
        MkT :: forall a b. (a=[b]) => b -> T a
176 177

  The wrapper has the programmer-specified type:
Edward Z. Yang's avatar
Edward Z. Yang committed
178 179
        \$wMkT :: a -> T [a]
        \$wMkT a x = MkT [a] a [a] x
180
  The third argument is a coerion
Edward Z. Yang's avatar
Edward Z. Yang committed
181
        [a] :: [a]~[a]
182

183
INVARIANT: the dictionary constructor for a class
Edward Z. Yang's avatar
Edward Z. Yang committed
184
           never has a wrapper.
185 186


187 188 189
A note about the stupid context
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Data types can have a context:
Edward Z. Yang's avatar
Edward Z. Yang committed
190 191

        data (Eq a, Ord b) => T a b = T1 a b | T2 a
192 193 194 195

and that makes the constructors have a context too
(notice that T2's context is "thinned"):

Edward Z. Yang's avatar
Edward Z. Yang committed
196 197
        T1 :: (Eq a, Ord b) => a -> b -> T a b
        T2 :: (Eq a) => a -> T a b
198 199 200 201 202

Furthermore, this context pops up when pattern matching
(though GHC hasn't implemented this, but it is in H98, and
I've fixed GHC so that it now does):

Edward Z. Yang's avatar
Edward Z. Yang committed
203
        f (T2 x) = x
204
gets inferred type
Edward Z. Yang's avatar
Edward Z. Yang committed
205
        f :: Eq a => T a b -> a
206 207 208 209 210

I say the context is "stupid" because the dictionaries passed
are immediately discarded -- they do nothing and have no benefit.
It's a flaw in the language.

Edward Z. Yang's avatar
Edward Z. Yang committed
211 212 213 214 215
        Up to now [March 2002] I have put this stupid context into the
        type of the "wrapper" constructors functions, T1 and T2, but
        that turned out to be jolly inconvenient for generics, and
        record update, and other functions that build values of type T
        (because they don't have suitable dictionaries available).
216

Edward Z. Yang's avatar
Edward Z. Yang committed
217 218 219
        So now I've taken the stupid context out.  I simply deal with
        it separately in the type checker on occurrences of a
        constructor, either in an expression or in a pattern.
220

Edward Z. Yang's avatar
Edward Z. Yang committed
221 222 223 224 225 226
        [May 2003: actually I think this decision could evasily be
        reversed now, and probably should be.  Generics could be
        disabled for types with a stupid context; record updates now
        (H98) needs the context too; etc.  It's an unforced change, so
        I'm leaving it for now --- but it does seem odd that the
        wrapper doesn't include the stupid context.]
227

228 229
[July 04] With the advent of generalised data types, it's less obvious
what the "stupid context" is.  Consider
Edward Z. Yang's avatar
Edward Z. Yang committed
230
        C :: forall a. Ord a => a -> a -> T (Foo a)
231
Does the C constructor in Core contain the Ord dictionary?  Yes, it must:
232

Edward Z. Yang's avatar
Edward Z. Yang committed
233 234 235 236
        f :: T b -> Ordering
        f = /\b. \x:T b.
            case x of
                C a (d:Ord a) (p:a) (q:a) -> compare d p q
237

238
Note that (Foo a) might not be an instance of Ord.
239

Austin Seipp's avatar
Austin Seipp committed
240 241
************************************************************************
*                                                                      *
242
\subsection{Data constructors}
Austin Seipp's avatar
Austin Seipp committed
243 244 245
*                                                                      *
************************************************************************
-}
246

batterseapower's avatar
batterseapower committed
247
-- | A data constructor
Alan Zimmerman's avatar
Alan Zimmerman committed
248 249 250
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
--             'ApiAnnotation.AnnClose','ApiAnnotation.AnnComma'
251
data DataCon
252
  = MkData {
Edward Z. Yang's avatar
Edward Z. Yang committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
        dcName    :: Name,      -- This is the name of the *source data con*
                                -- (see "Note [Data Constructor Naming]" above)
        dcUnique :: Unique,     -- Cached from Name
        dcTag    :: ConTag,     -- ^ Tag, used for ordering 'DataCon's

        -- Running example:
        --
        --      *** As declared by the user
        --  data T a where
        --    MkT :: forall x y. (x~y,Ord x) => x -> y -> T (x,y)

        --      *** As represented internally
        --  data T a where
        --    MkT :: forall a. forall x y. (a~(x,y),x~y,Ord x) => x -> y -> T a
        --
        -- The next six fields express the type of the constructor, in pieces
        -- e.g.
        --
        --      dcUnivTyVars  = [a]
        --      dcExTyVars    = [x,y]
        --      dcEqSpec      = [a~(x,y)]
        --      dcOtherTheta  = [x~y, Ord x]
        --      dcOrigArgTys  = [x,y]
        --      dcRepTyCon       = T

        dcVanilla :: Bool,      -- True <=> This is a vanilla Haskell 98 data constructor
                                --          Its type is of form
                                --              forall a1..an . t1 -> ... tm -> T a1..an
                                --          No existentials, no coercions, nothing.
                                -- That is: dcExTyVars = dcEqSpec = dcOtherTheta = []
                -- NB 1: newtypes always have a vanilla data con
                -- NB 2: a vanilla constructor can still be declared in GADT-style
                --       syntax, provided its type looks like the above.
                --       The declaration format is held in the TyCon (algTcGadtSyntax)

        dcUnivTyVars :: [TyVar],        -- Universally-quantified type vars [a,b,c]
                                        -- INVARIANT: length matches arity of the dcRepTyCon
                                        ---           result type of (rep) data con is exactly (T a b c)

        dcExTyVars   :: [TyVar],        -- Existentially-quantified type vars
                -- In general, the dcUnivTyVars are NOT NECESSARILY THE SAME AS THE TYVARS
                -- FOR THE PARENT TyCon. With GADTs the data con might not even have
                -- the same number of type variables.
                -- [This is a change (Oct05): previously, vanilla datacons guaranteed to
                --  have the same type variables as their parent TyCon, but that seems ugly.]

        -- INVARIANT: the UnivTyVars and ExTyVars all have distinct OccNames
        -- Reason: less confusing, and easier to generate IfaceSyn

        dcEqSpec :: [(TyVar,Type)],     -- Equalities derived from the result type,
                                        -- _as written by the programmer_
                -- This field allows us to move conveniently between the two ways
                -- of representing a GADT constructor's type:
                --      MkT :: forall a b. (a ~ [b]) => b -> T a
                --      MkT :: forall b. b -> T [b]
                -- Each equality is of the form (a ~ ty), where 'a' is one of
                -- the universally quantified type variables

                -- The next two fields give the type context of the data constructor
                --      (aside from the GADT constraints,
                --       which are given by the dcExpSpec)
                -- In GADT form, this is *exactly* what the programmer writes, even if
                -- the context constrains only universally quantified variables
                --      MkT :: forall a b. (a ~ b, Ord b) => a -> T a b
        dcOtherTheta :: ThetaType,  -- The other constraints in the data con's type
                                    -- other than those in the dcEqSpec

        dcStupidTheta :: ThetaType,     -- The context of the data type declaration
                                        --      data Eq a => T a = ...
                                        -- or, rather, a "thinned" version thereof
                -- "Thinned", because the Report says
                -- to eliminate any constraints that don't mention
                -- tyvars free in the arg types for this constructor
                --
                -- INVARIANT: the free tyvars of dcStupidTheta are a subset of dcUnivTyVars
                -- Reason: dcStupidTeta is gotten by thinning the stupid theta from the tycon
                --
                -- "Stupid", because the dictionaries aren't used for anything.
                -- Indeed, [as of March 02] they are no longer in the type of
                -- the wrapper Id, because that makes it harder to use the wrap-id
                -- to rebuild values after record selection or in generics.

        dcOrigArgTys :: [Type],         -- Original argument types
                                        -- (before unboxing and flattening of strict fields)
        dcOrigResTy :: Type,            -- Original result type, as seen by the user
                -- NB: for a data instance, the original user result type may
                -- differ from the DataCon's representation TyCon.  Example
                --      data instance T [a] where MkT :: a -> T [a]
                -- The OrigResTy is T [a], but the dcRepTyCon might be :T123

        -- Now the strictness annotations and field labels of the constructor
344
        -- See Note [Bangs on data constructor arguments]
Edward Z. Yang's avatar
Edward Z. Yang committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
        dcArgBangs :: [HsBang],
                -- Strictness annotations as decided by the compiler.
                -- Matches 1-1 with dcOrigArgTys
                -- Hence length = dataConSourceArity dataCon

        dcFields  :: [FieldLabel],
                -- Field labels for this constructor, in the
                -- same order as the dcOrigArgTys;
                -- length = 0 (if not a record) or dataConSourceArity.

        -- The curried worker function that corresponds to the constructor:
        -- It doesn't have an unfolding; the code generator saturates these Ids
        -- and allocates a real constructor when it finds one.
        dcWorkId :: Id,

        -- Constructor representation
361
        dcRep      :: DataConRep,
362

363 364 365
        -- Cached
        dcRepArity    :: Arity,  -- == length dataConRepArgTys
        dcSourceArity :: Arity,  -- == length dcOrigArgTys
366

Edward Z. Yang's avatar
Edward Z. Yang committed
367 368
        -- Result type of constructor is T t1..tn
        dcRepTyCon  :: TyCon,           -- Result tycon, T
369

Edward Z. Yang's avatar
Edward Z. Yang committed
370 371
        dcRepType   :: Type,    -- Type of the constructor
                                --      forall a x y. (a~(x,y), x~y, Ord x) =>
372
                                --        x -> y -> T a
Edward Z. Yang's avatar
Edward Z. Yang committed
373 374 375 376 377
                                -- (this is *not* of the constructor wrapper Id:
                                --  see Note [Data con representation] below)
        -- Notice that the existential type parameters come *second*.
        -- Reason: in a case expression we may find:
        --      case (e :: T t) of
378
        --        MkT x y co1 co2 (d:Ord x) (v:r) (w:F s) -> ...
Edward Z. Yang's avatar
Edward Z. Yang committed
379 380 381 382
        -- It's convenient to apply the rep-type of MkT to 't', to get
        --      forall x y. (t~(x,y), x~y, Ord x) => x -> y -> T t
        -- and use that to check the pattern.  Mind you, this is really only
        -- used in CoreLint.
383 384


Edward Z. Yang's avatar
Edward Z. Yang committed
385 386 387
        dcInfix :: Bool,        -- True <=> declared infix
                                -- Used for Template Haskell and 'deriving' only
                                -- The actual fixity is stored elsewhere
388 389

        dcPromoted :: Maybe TyCon    -- The promoted TyCon if this DataCon is promotable
390
                                     -- See Note [Promoted data constructors] in TyCon
391
  }
392
  deriving Data.Typeable.Typeable
393

Edward Z. Yang's avatar
Edward Z. Yang committed
394
data DataConRep
395 396
  = NoDataConRep              -- No wrapper

Edward Z. Yang's avatar
Edward Z. Yang committed
397
  | DCR { dcr_wrap_id :: Id   -- Takes src args, unboxes/flattens,
398 399 400 401
                              -- and constructs the representation

        , dcr_boxer   :: DataConBoxer

Edward Z. Yang's avatar
Edward Z. Yang committed
402
        , dcr_arg_tys :: [Type]  -- Final, representation argument types,
403 404 405 406
                                 -- after unboxing and flattening,
                                 -- and *including* all evidence args

        , dcr_stricts :: [StrictnessMark]  -- 1-1 with dcr_arg_tys
Edward Z. Yang's avatar
Edward Z. Yang committed
407
                -- See also Note [Data-con worker strictness] in MkId.lhs
408 409 410

        , dcr_bangs :: [HsBang]  -- The actual decisions made (including failures)
                                 -- 1-1 with orig_arg_tys
411 412
                                 -- See Note [Bangs on data constructor arguments]

413 414 415
    }
-- Algebraic data types always have a worker, and
-- may or may not have a wrapper, depending on whether
Edward Z. Yang's avatar
Edward Z. Yang committed
416
-- the wrapper does anything.
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
--
-- Data types have a worker with no unfolding
-- Newtypes just have a worker, which has a compulsory unfolding (just a cast)

-- _Neither_ the worker _nor_ the wrapper take the dcStupidTheta dicts as arguments

-- The wrapper (if it exists) takes dcOrigArgTys as its arguments
-- The worker takes dataConRepArgTys as its arguments
-- If the worker is absent, dataConRepArgTys is the same as dcOrigArgTys

-- The 'NoDataConRep' case is important
-- Not only is this efficient,
-- but it also ensures that the wrapper is replaced
-- by the worker (because it *is* the worker)
-- even when there are no args. E.g. in
Edward Z. Yang's avatar
Edward Z. Yang committed
432
--              f (:) x
433 434 435 436 437 438
-- the (:) *is* the worker.
-- This is really important in rule matching,
-- (We could match on the wrappers,
-- but that makes it less likely that rules will match
-- when we bring bits of unfoldings together.)

439 440 441
-------------------------
-- HsBang describes what the *programmer* wrote
-- This info is retained in the DataCon.dcStrictMarks field
Edward Z. Yang's avatar
Edward Z. Yang committed
442
data HsBang
443 444 445 446 447
  = HsUserBang   -- The user's source-code request
       (Maybe Bool)       -- Just True    {-# UNPACK #-}
                          -- Just False   {-# NOUNPACK #-}
                          -- Nothing      no pragma
       Bool               -- True <=> '!' specified
448

Edward Z. Yang's avatar
Edward Z. Yang committed
449
  | HsNoBang              -- Lazy field
450
                          -- HsUserBang Nothing False means the same as HsNoBang
451 452 453 454

  | HsUnpack              -- Definite commitment: this field is strict and unboxed
       (Maybe Coercion)   --    co :: arg-ty ~ product-ty

455
  | HsStrict              -- Definite commitment: this field is strict but not unboxed
456 457 458
  deriving (Data.Data, Data.Typeable)

-------------------------
Edward Z. Yang's avatar
Edward Z. Yang committed
459
-- StrictnessMark is internal only, used to indicate strictness
460
-- of the DataCon *worker* fields
Edward Z. Yang's avatar
Edward Z. Yang committed
461
data StrictnessMark = MarkedStrict | NotMarkedStrict
462

Austin Seipp's avatar
Austin Seipp committed
463
{-
464 465
Note [Data con representation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
466
The dcRepType field contains the type of the representation of a contructor
467 468
This may differ from the type of the contructor *Id* (built
by MkId.mkDataConId) for two reasons:
Edward Z. Yang's avatar
Edward Z. Yang committed
469 470
        a) the constructor Id may be overloaded, but the dictionary isn't stored
           e.g.    data Eq a => T a = MkT a a
471

Edward Z. Yang's avatar
Edward Z. Yang committed
472
        b) the constructor may store an unboxed version of a strict field.
473 474

Here's an example illustrating both:
Edward Z. Yang's avatar
Edward Z. Yang committed
475
        data Ord a => T a = MkT Int! a
476
Here
Edward Z. Yang's avatar
Edward Z. Yang committed
477
        T :: Ord a => Int -> a -> T a
478
but the rep type is
Edward Z. Yang's avatar
Edward Z. Yang committed
479
        Trep :: Int# -> a -> T a
480 481
Actually, the unboxed part isn't implemented yet!

482 483 484 485 486
Note [Bangs on data constructor arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
  data T = MkT !Int {-# UNPACK #-} !Int Bool
Its dcArgBangs field records the *users* specifications, in this case
487 488 489
    [ HsUserBang Nothing True
    , HsUserBang (Just True) True
    , HsNoBang]
490 491 492 493 494 495 496 497 498 499 500 501 502
See the declaration of HsBang in BasicTypes

The dcr_bangs field of the dcRep field records the *actual, decided*
representation of the data constructor.  Without -O this might be
    [HsStrict, HsStrict, HsNoBang]
With -O it might be
    [HsStrict, HsUnpack, HsNoBang]
With -funbox-small-strict-fields it might be
    [HsUnpack, HsUnpack, HsNoBang]

For imported data types, the dcArgBangs field is just the same as the
dcr_bangs field; we don't know what the user originally said.

503

Austin Seipp's avatar
Austin Seipp committed
504 505
************************************************************************
*                                                                      *
506
\subsection{Instances}
Austin Seipp's avatar
Austin Seipp committed
507 508 509
*                                                                      *
************************************************************************
-}
510

511 512 513 514 515 516
instance Eq DataCon where
    a == b = getUnique a == getUnique b
    a /= b = getUnique a /= getUnique b

instance Ord DataCon where
    a <= b = getUnique a <= getUnique b
Edward Z. Yang's avatar
Edward Z. Yang committed
517
    a <  b = getUnique a <  getUnique b
518
    a >= b = getUnique a >= getUnique b
Edward Z. Yang's avatar
Edward Z. Yang committed
519
    a >  b = getUnique a > getUnique b
520 521 522 523 524 525 526 527 528 529 530
    compare a b = getUnique a `compare` getUnique b

instance Uniquable DataCon where
    getUnique = dcUnique

instance NamedThing DataCon where
    getName = dcName

instance Outputable DataCon where
    ppr con = ppr (dataConName con)

531 532 533 534
instance OutputableBndr DataCon where
    pprInfixOcc con = pprInfixName (dataConName con)
    pprPrefixOcc con = pprPrefixName (dataConName con)

535 536 537 538 539
instance Data.Data DataCon where
    -- don't traverse?
    toConstr _   = abstractConstr "DataCon"
    gunfold _ _  = error "gunfold"
    dataTypeOf _ = mkNoRepType "DataCon"
540 541

instance Outputable HsBang where
542 543 544 545 546 547 548 549 550 551
    ppr HsNoBang               = empty
    ppr (HsUserBang prag bang) = pp_unpk prag <+> ppWhen bang (char '!')
    ppr (HsUnpack Nothing)     = ptext (sLit "Unpk")
    ppr (HsUnpack (Just co))   = ptext (sLit "Unpk") <> parens (ppr co)
    ppr HsStrict               = ptext (sLit "SrictNotUnpacked")

pp_unpk :: Maybe Bool -> SDoc
pp_unpk Nothing      = empty
pp_unpk (Just True)  = ptext (sLit "{-# UNPACK #-}")
pp_unpk (Just False) = ptext (sLit "{-# NOUNPACK #-}")
552 553 554 555 556 557 558

instance Outputable StrictnessMark where
  ppr MarkedStrict     = ptext (sLit "!")
  ppr NotMarkedStrict  = empty


eqHsBang :: HsBang -> HsBang -> Bool
559
eqHsBang HsNoBang             HsNoBang             = True
560
eqHsBang HsStrict             HsStrict             = True
561
eqHsBang (HsUserBang u1 b1)   (HsUserBang u2 b2)   = u1==u2 && b1==b2
562 563 564 565 566
eqHsBang (HsUnpack Nothing)   (HsUnpack Nothing)   = True
eqHsBang (HsUnpack (Just c1)) (HsUnpack (Just c2)) = eqType (coercionType c1) (coercionType c2)
eqHsBang _ _ = False

isBanged :: HsBang -> Bool
567 568 569
isBanged HsNoBang                  = False
isBanged (HsUserBang Nothing bang) = bang
isBanged _                         = True
570 571 572 573

isMarkedStrict :: StrictnessMark -> Bool
isMarkedStrict NotMarkedStrict = False
isMarkedStrict _               = True   -- All others are strict
574

Austin Seipp's avatar
Austin Seipp committed
575 576 577
{-
************************************************************************
*                                                                      *
578
\subsection{Construction}
Austin Seipp's avatar
Austin Seipp committed
579 580 581
*                                                                      *
************************************************************************
-}
582

batterseapower's avatar
batterseapower committed
583
-- | Build a new data constructor
Edward Z. Yang's avatar
Edward Z. Yang committed
584 585 586 587 588 589 590 591 592 593 594 595 596 597
mkDataCon :: Name
          -> Bool               -- ^ Is the constructor declared infix?
          -> [HsBang]           -- ^ Strictness annotations written in the source file
          -> [FieldLabel]       -- ^ Field labels for the constructor, if it is a record,
                                --   otherwise empty
          -> [TyVar]            -- ^ Universally quantified type variables
          -> [TyVar]            -- ^ Existentially quantified type variables
          -> [(TyVar,Type)]     -- ^ GADT equalities
          -> ThetaType          -- ^ Theta-type occuring before the arguments proper
          -> [Type]             -- ^ Original argument types
          -> Type               -- ^ Original result type
          -> TyCon              -- ^ Representation type constructor
          -> ThetaType          -- ^ The "stupid theta", context of the data declaration
                                --   e.g. @data Eq a => T a ...@
598
          -> Id                 -- ^ Worker Id
Edward Z. Yang's avatar
Edward Z. Yang committed
599 600
          -> DataConRep         -- ^ Representation
          -> DataCon
601 602
  -- Can get the tag from the TyCon

603
mkDataCon name declared_infix
Edward Z. Yang's avatar
Edward Z. Yang committed
604 605 606 607 608 609 610
          arg_stricts   -- Must match orig_arg_tys 1-1
          fields
          univ_tvs ex_tvs
          eq_spec theta
          orig_arg_tys orig_res_ty rep_tycon
          stupid_theta work_id rep
-- Warning: mkDataCon is not a good place to check invariants.
611
-- If the programmer writes the wrong result type in the decl, thus:
Edward Z. Yang's avatar
Edward Z. Yang committed
612
--      data T a where { MkT :: S }
613 614 615 616 617
-- then it's possible that the univ_tvs may hit an assertion failure
-- if you pull on univ_tvs.  This case is checked by checkValidDataCon,
-- so the error is detected properly... it's just that asaertions here
-- are a little dodgy.

618
  = con
619
  where
620
    is_vanilla = null ex_tvs && null eq_spec && null theta
Edward Z. Yang's avatar
Edward Z. Yang committed
621 622 623 624 625 626 627 628 629 630 631 632
    con = MkData {dcName = name, dcUnique = nameUnique name,
                  dcVanilla = is_vanilla, dcInfix = declared_infix,
                  dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
                  dcEqSpec = eq_spec,
                  dcOtherTheta = theta,
                  dcStupidTheta = stupid_theta,
                  dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
                  dcRepTyCon = rep_tycon,
                  dcArgBangs = arg_stricts,
                  dcFields = fields, dcTag = tag, dcRepType = rep_ty,
                  dcWorkId = work_id,
                  dcRep = rep,
633 634
                  dcSourceArity = length orig_arg_tys,
                  dcRepArity = length rep_arg_tys,
635
                  dcPromoted = mb_promoted }
636

Edward Z. Yang's avatar
Edward Z. Yang committed
637 638 639
        -- The 'arg_stricts' passed to mkDataCon are simply those for the
        -- source-language arguments.  We add extra ones for the
        -- dictionary arguments right here.
640

641
    tag = assoc "mkDataCon" (tyConDataCons rep_tycon `zip` [fIRST_TAG..]) con
642
    rep_arg_tys = dataConRepArgTys con
Edward Z. Yang's avatar
Edward Z. Yang committed
643 644 645
    rep_ty = mkForAllTys univ_tvs $ mkForAllTys ex_tvs $
             mkFunTys rep_arg_tys $
             mkTyConApp rep_tycon (mkTyVarTys univ_tvs)
646

647
    mb_promoted   -- See Note [Promoted data constructors] in TyCon
648 649 650
      | isJust (promotableTyCon_maybe rep_tycon)
          -- The TyCon is promotable only if all its datacons
          -- are, so the promoteType for prom_kind should succeed
651
      = Just (mkPromotedDataCon con name (getUnique name) prom_kind roles)
Edward Z. Yang's avatar
Edward Z. Yang committed
652 653
      | otherwise
      = Nothing
654
    prom_kind = promoteType (dataConUserType con)
655 656
    roles = map (const Nominal)          (univ_tvs ++ ex_tvs) ++
            map (const Representational) orig_arg_tys
657

658
eqSpecPreds :: [(TyVar,Type)] -> ThetaType
659
eqSpecPreds spec = [ mkEqPred (mkTyVarTy tv) ty | (tv,ty) <- spec ]
660

Austin Seipp's avatar
Austin Seipp committed
661
{-
Simon Peyton Jones's avatar
Simon Peyton Jones committed
662 663 664 665 666 667 668 669
Note [Unpack equality predicates]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we have a GADT with a contructor C :: (a~[b]) => b -> T a
we definitely want that equality predicate *unboxed* so that it
takes no space at all.  This is easily done: just give it
an UNPACK pragma. The rest of the unpack/repack code does the
heavy lifting.  This one line makes every GADT take a word less
space for each equality predicate, so it's pretty important!
Austin Seipp's avatar
Austin Seipp committed
670
-}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
671

batterseapower's avatar
batterseapower committed
672
-- | The 'Name' of the 'DataCon', giving it a unique, rooted identification
673 674 675
dataConName :: DataCon -> Name
dataConName = dcName

batterseapower's avatar
batterseapower committed
676
-- | The tag used for ordering 'DataCon's
677 678 679
dataConTag :: DataCon -> ConTag
dataConTag  = dcTag

batterseapower's avatar
batterseapower committed
680
-- | The type constructor that we are building via this data constructor
681
dataConTyCon :: DataCon -> TyCon
682
dataConTyCon = dcRepTyCon
683

684 685 686 687
-- | The original type constructor used in the definition of this data
-- constructor.  In case of a data family instance, that will be the family
-- type constructor.
dataConOrigTyCon :: DataCon -> TyCon
Edward Z. Yang's avatar
Edward Z. Yang committed
688
dataConOrigTyCon dc
689 690 691
  | Just (tc, _) <- tyConFamInst_maybe (dcRepTyCon dc) = tc
  | otherwise                                          = dcRepTyCon dc

batterseapower's avatar
batterseapower committed
692 693
-- | The representation type of the data constructor, i.e. the sort
-- type that will represent values of this type at runtime
694 695
dataConRepType :: DataCon -> Type
dataConRepType = dcRepType
696

batterseapower's avatar
batterseapower committed
697
-- | Should the 'DataCon' be presented infix?
698 699 700
dataConIsInfix :: DataCon -> Bool
dataConIsInfix = dcInfix

batterseapower's avatar
batterseapower committed
701
-- | The universally-quantified type variables of the constructor
702 703 704
dataConUnivTyVars :: DataCon -> [TyVar]
dataConUnivTyVars = dcUnivTyVars

batterseapower's avatar
batterseapower committed
705
-- | The existentially-quantified type variables of the constructor
706 707 708
dataConExTyVars :: DataCon -> [TyVar]
dataConExTyVars = dcExTyVars

batterseapower's avatar
batterseapower committed
709
-- | Both the universal and existentiatial type variables of the constructor
710 711 712 713
dataConAllTyVars :: DataCon -> [TyVar]
dataConAllTyVars (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs })
  = univ_tvs ++ ex_tvs

batterseapower's avatar
batterseapower committed
714 715
-- | Equalities derived from the result type of the data constructor, as written
-- by the programmer in any GADT declaration
716 717 718
dataConEqSpec :: DataCon -> [(TyVar,Type)]
dataConEqSpec = dcEqSpec

719 720
-- | The *full* constraints on the constructor type
dataConTheta :: DataCon -> ThetaType
Edward Z. Yang's avatar
Edward Z. Yang committed
721
dataConTheta (MkData { dcEqSpec = eq_spec, dcOtherTheta = theta })
722
  = eqSpecPreds eq_spec ++ theta
723

batterseapower's avatar
batterseapower committed
724 725 726 727
-- | Get the Id of the 'DataCon' worker: a function that is the "actual"
-- constructor and has no top level binding in the program. The type may
-- be different from the obvious one written in the source program. Panics
-- if there is no such 'Id' for this 'DataCon'
728
dataConWorkId :: DataCon -> Id
729
dataConWorkId dc = dcWorkId dc
730

batterseapower's avatar
batterseapower committed
731 732
-- | Get the Id of the 'DataCon' wrapper: a function that wraps the "actual"
-- constructor so it has the type visible in the source program: c.f. 'dataConWorkId'.
Edward Z. Yang's avatar
Edward Z. Yang committed
733
-- Returns Nothing if there is no wrapper, which occurs for an algebraic data constructor
batterseapower's avatar
batterseapower committed
734
-- and also for a newtype (whose constructor is inlined compulsorily)
735
dataConWrapId_maybe :: DataCon -> Maybe Id
736 737 738
dataConWrapId_maybe dc = case dcRep dc of
                           NoDataConRep -> Nothing
                           DCR { dcr_wrap_id = wrap_id } -> Just wrap_id
739

batterseapower's avatar
batterseapower committed
740 741 742
-- | Returns an Id which looks like the Haskell-source constructor by using
-- the wrapper if it exists (see 'dataConWrapId_maybe') and failing over to
-- the worker (see 'dataConWorkId')
743
dataConWrapId :: DataCon -> Id
744 745 746
dataConWrapId dc = case dcRep dc of
                     NoDataConRep-> dcWorkId dc    -- worker=wrapper
                     DCR { dcr_wrap_id = wrap_id } -> wrap_id
747

batterseapower's avatar
batterseapower committed
748 749
-- | Find all the 'Id's implicitly brought into scope by the data constructor. Currently,
-- the union of the 'dataConWorkId' and the 'dataConWrapId'
750
dataConImplicitIds :: DataCon -> [Id]
751 752 753 754
dataConImplicitIds (MkData { dcWorkId = work, dcRep = rep})
  = case rep of
       NoDataConRep               -> [work]
       DCR { dcr_wrap_id = wrap } -> [wrap,work]
755

batterseapower's avatar
batterseapower committed
756
-- | The labels for the fields of this particular 'DataCon'
757 758 759
dataConFieldLabels :: DataCon -> [FieldLabel]
dataConFieldLabels = dcFields

batterseapower's avatar
batterseapower committed
760
-- | Extract the type for any given labelled field of the 'DataCon'
761
dataConFieldType :: DataCon -> FieldLabel -> Type
762 763 764 765
dataConFieldType con label
  = case lookup label (dcFields con `zip` dcOrigArgTys con) of
      Just ty -> ty
      Nothing -> pprPanic "dataConFieldType" (ppr con <+> ppr label)
766

batterseapower's avatar
batterseapower committed
767 768
-- | The strictness markings decided on by the compiler.  Does not include those for
-- existential dictionaries.  The list is in one-to-one correspondence with the arity of the 'DataCon'
769
dataConStrictMarks :: DataCon -> [HsBang]
770
dataConStrictMarks = dcArgBangs
771

batterseapower's avatar
batterseapower committed
772
-- | Source-level arity of the data constructor
773
dataConSourceArity :: DataCon -> Arity
774
dataConSourceArity (MkData { dcSourceArity = arity }) = arity
775

Edward Z. Yang's avatar
Edward Z. Yang committed
776
-- | Gives the number of actual fields in the /representation/ of the
batterseapower's avatar
batterseapower committed
777 778
-- data constructor. This may be more than appear in the source code;
-- the extra ones are the existentially quantified dictionaries
779
dataConRepArity :: DataCon -> Arity
780 781
dataConRepArity (MkData { dcRepArity = arity }) = arity

782

783 784 785 786 787
-- | The number of fields in the /representation/ of the constructor
-- AFTER taking into account the unpacking of any unboxed tuple fields
dataConRepRepArity :: DataCon -> RepArity
dataConRepRepArity dc = typeRepArity (dataConRepArity dc) (dataConRepType dc)

batterseapower's avatar
batterseapower committed
788 789
-- | Return whether there are any argument types for this 'DataCon's original source type
isNullarySrcDataCon :: DataCon -> Bool
790
isNullarySrcDataCon dc = null (dcOrigArgTys dc)
batterseapower's avatar
batterseapower committed
791 792 793

-- | Return whether there are any argument types for this 'DataCon's runtime representation type
isNullaryRepDataCon :: DataCon -> Bool
794
isNullaryRepDataCon dc = dataConRepArity dc == 0
795

796
dataConRepStrictness :: DataCon -> [StrictnessMark]
batterseapower's avatar
batterseapower committed
797 798
-- ^ Give the demands on the arguments of a
-- Core constructor application (Con dc args)
799 800 801 802 803 804 805 806 807 808 809
dataConRepStrictness dc = case dcRep dc of
                            NoDataConRep -> [NotMarkedStrict | _ <- dataConRepArgTys dc]
                            DCR { dcr_stricts = strs } -> strs

dataConRepBangs :: DataCon -> [HsBang]
dataConRepBangs dc = case dcRep dc of
                       NoDataConRep -> dcArgBangs dc
                       DCR { dcr_bangs = bangs } -> bangs

dataConBoxer :: DataCon -> Maybe DataConBoxer
dataConBoxer (MkData { dcRep = DCR { dcr_boxer = boxer } }) = Just boxer
Edward Z. Yang's avatar
Edward Z. Yang committed
810
dataConBoxer _ = Nothing
811

batterseapower's avatar
batterseapower committed
812 813 814 815 816 817 818 819 820 821
-- | The \"signature\" of the 'DataCon' returns, in order:
--
-- 1) The result of 'dataConAllTyVars',
--
-- 2) All the 'ThetaType's relating to the 'DataCon' (coercion, dictionary, implicit
--    parameter - whatever)
--
-- 3) The type arguments to the constructor
--
-- 4) The /original/ result type of the 'DataCon'
822
dataConSig :: DataCon -> ([TyVar], ThetaType, [Type], Type)
Edward Z. Yang's avatar
Edward Z. Yang committed
823 824 825
dataConSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
                    dcEqSpec = eq_spec, dcOtherTheta  = theta,
                    dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
826
  = (univ_tvs ++ ex_tvs, eqSpecPreds eq_spec ++ theta, arg_tys, res_ty)
827

batterseapower's avatar
batterseapower committed
828 829 830 831 832 833 834 835 836 837
-- | The \"full signature\" of the 'DataCon' returns, in order:
--
-- 1) The result of 'dataConUnivTyVars'
--
-- 2) The result of 'dataConExTyVars'
--
-- 3) The result of 'dataConEqSpec'
--
-- 4) The result of 'dataConDictTheta'
--
Edward Z. Yang's avatar
Edward Z. Yang committed
838
-- 5) The original argument types to the 'DataCon' (i.e. before
839
--    any change of the representation of the type)
batterseapower's avatar
batterseapower committed
840 841
--
-- 6) The original result type of the 'DataCon'
Edward Z. Yang's avatar
Edward Z. Yang committed
842 843 844 845 846
dataConFullSig :: DataCon
               -> ([TyVar], [TyVar], [(TyVar,Type)], ThetaType, [Type], Type)
dataConFullSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs,
                        dcEqSpec = eq_spec, dcOtherTheta = theta,
                        dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
847
  = (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, res_ty)
848 849 850

dataConOrigResTy :: DataCon -> Type
dataConOrigResTy dc = dcOrigResTy dc
851

batterseapower's avatar
batterseapower committed
852 853 854
-- | The \"stupid theta\" of the 'DataCon', such as @data Eq a@ in:
--
-- > data Eq a => T a = ...
855 856 857
dataConStupidTheta :: DataCon -> ThetaType
dataConStupidTheta dc = dcStupidTheta dc

858
dataConUserType :: DataCon -> Type
batterseapower's avatar
batterseapower committed
859 860 861 862 863 864 865
-- ^ The user-declared type of the data constructor
-- in the nice-to-read form:
--
-- > T :: forall a b. a -> b -> T [a]
--
-- rather than:
--
866
-- > T :: forall a c. forall b. (c~[a]) => a -> b -> T c
batterseapower's avatar
batterseapower committed
867
--
868 869
-- NB: If the constructor is part of a data instance, the result type
-- mentions the family tycon, not the internal one.
Edward Z. Yang's avatar
Edward Z. Yang committed
870 871 872 873
dataConUserType  (MkData { dcUnivTyVars = univ_tvs,
                           dcExTyVars = ex_tvs, dcEqSpec = eq_spec,
                           dcOtherTheta = theta, dcOrigArgTys = arg_tys,
                           dcOrigResTy = res_ty })
874
  = mkForAllTys ((univ_tvs `minusList` map fst eq_spec) ++ ex_tvs) $
batterseapower's avatar
batterseapower committed
875
    mkFunTys theta $
876
    mkFunTys arg_tys $
877
    res_ty
878

batterseapower's avatar
batterseapower committed
879 880 881 882
-- | Finds the instantiated types of the arguments required to construct a 'DataCon' representation
-- NB: these INCLUDE any dictionary args
--     but EXCLUDE the data-declaration context, which is discarded
-- It's all post-flattening etc; this is a representation type
Edward Z. Yang's avatar
Edward Z. Yang committed
883 884 885 886 887
dataConInstArgTys :: DataCon    -- ^ A datacon with no existentials or equality constraints
                                -- However, it can have a dcTheta (notably it can be a
                                -- class dictionary, with superclasses)
                  -> [Type]     -- ^ Instantiated at these types
                  -> [Type]
888
dataConInstArgTys dc@(MkData {dcUnivTyVars = univ_tvs, dcEqSpec = eq_spec,
Edward Z. Yang's avatar
Edward Z. Yang committed
889
                              dcExTyVars = ex_tvs}) inst_tys
890 891 892
 = ASSERT2( length univ_tvs == length inst_tys
          , ptext (sLit "dataConInstArgTys") <+> ppr dc $$ ppr univ_tvs $$ ppr inst_tys)
   ASSERT2( null ex_tvs && null eq_spec, ppr dc )
893
   map (substTyWith univ_tvs inst_tys) (dataConRepArgTys dc)
894

895 896
-- | Returns just the instantiated /value/ argument types of a 'DataCon',
-- (excluding dictionary args)
Edward Z. Yang's avatar
Edward Z. Yang committed
897 898 899 900 901
dataConInstOrigArgTys
        :: DataCon      -- Works for any DataCon
        -> [Type]       -- Includes existential tyvar args, but NOT
                        -- equality constraints or dicts
        -> [Type]
902 903
-- For vanilla datacons, it's all quite straightforward
-- But for the call in MatchCon, we really do want just the value args
904
dataConInstOrigArgTys dc@(MkData {dcOrigArgTys = arg_tys,
Edward Z. Yang's avatar
Edward Z. Yang committed
905 906
                                  dcUnivTyVars = univ_tvs,
                                  dcExTyVars = ex_tvs}) inst_tys
907
  = ASSERT2( length tyvars == length inst_tys
Ian Lynagh's avatar
Ian Lynagh committed
908
          , ptext (sLit "dataConInstOrigArgTys") <+> ppr dc $$ ppr tyvars $$ ppr inst_tys )
909 910 911
    map (substTyWith tyvars inst_tys) arg_tys
  where
    tyvars = univ_tvs ++ ex_tvs
912

batterseapower's avatar
batterseapower committed
913 914
-- | Returns the argument types of the wrapper, excluding all dictionary arguments
-- and without substituting for any type variables
915 916 917
dataConOrigArgTys :: DataCon -> [Type]
dataConOrigArgTys dc = dcOrigArgTys dc

Edward Z. Yang's avatar
Edward Z. Yang committed
918
-- | Returns the arg types of the worker, including *all* evidence, after any
batterseapower's avatar
batterseapower committed
919
-- flattening has been done and without substituting for any type variables
920
dataConRepArgTys :: DataCon -> [Type]
Edward Z. Yang's avatar
Edward Z. Yang committed
921
dataConRepArgTys (MkData { dcRep = rep
922 923
                         , dcEqSpec = eq_spec
                         , dcOtherTheta = theta
Edward Z. Yang's avatar
Edward Z. Yang committed
924
                         , dcOrigArgTys = orig_arg_tys })
925 926 927
  = case rep of
      NoDataConRep -> ASSERT( null eq_spec ) theta ++ orig_arg_tys
      DCR { dcr_arg_tys = arg_tys } -> arg_tys
928

batterseapower's avatar
batterseapower committed
929 930
-- | The string @package:module.name@ identifying a constructor, which is attached
-- to its info table and used by the GHCi debugger and the heap profiler
931
dataConIdentity :: DataCon -> [Word8]
batterseapower's avatar
batterseapower committed
932
-- We want this string to be UTF-8, so we get the bytes directly from the FastStrings.
933
dataConIdentity dc = bytesFS (packageKeyFS (modulePackageKey mod)) ++
934 935 936
                  fromIntegral (ord ':') : bytesFS (moduleNameFS (moduleName mod)) ++
                  fromIntegral (ord '.') : bytesFS (occNameFS (nameOccName name))
  where name = dataConName dc
937
        mod  = ASSERT( isExternalName name ) nameModule name
938

939 940
isTupleDataCon :: DataCon -> Bool
isTupleDataCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc
Edward Z. Yang's avatar
Edward Z. Yang committed
941

942
isUnboxedTupleCon :: DataCon -> Bool
943
isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc
944

batterseapower's avatar
batterseapower committed
945
-- | Vanilla 'DataCon's are those that are nice boring Haskell 98 constructors
946 947
isVanillaDataCon :: DataCon -> Bool
isVanillaDataCon dc = dcVanilla dc
948

949 950
classDataCon :: Class -> DataCon
classDataCon clas = case tyConDataCons (classTyCon clas) of
Edward Z. Yang's avatar
Edward Z. Yang committed
951 952
                      (dict_constr:no_more) -> ASSERT( null no_more ) dict_constr
                      [] -> panic "classDataCon"