DataCon.lhs 11.5 KB
Newer Older
1
2
3
%
% (c) The GRASP/AQUA Project, Glasgow University, 1998
%
4
\section[DataCon]{@DataCon@: Data Constructors}
5
6
7
8
9
10
11

\begin{code}
module DataCon (
	DataCon,
	ConTag, fIRST_TAG,
	mkDataCon,
	dataConType, dataConSig, dataConName, dataConTag,
12
	dataConOrigArgTys, dataConArgTys, dataConRawArgTys, dataConTyCon,
13
14
15
16
17
18
19
20
21
22
23
24
	dataConFieldLabels, dataConStrictMarks, dataConSourceArity,
	dataConNumFields, dataConNumInstArgs, dataConId,
	isNullaryDataCon, isTupleCon, isUnboxedTupleCon,
	isExistentialDataCon
    ) where

#include "HsVersions.h"

import CmdLineOpts	( opt_DictsStrict )
import TysPrim
import Type		( Type, ThetaType, TauType,
			  mkSigmaTy, mkFunTys, mkTyConApp, 
25
26
			  mkTyVarTys, mkDictTy, substTy,
			  splitAlgTyConApp_maybe
27
			)
28
import PprType
29
30
31
import TyCon		( TyCon, tyConDataCons, isDataTyCon,
			  isTupleTyCon, isUnboxedTupleTyCon )
import Class		( classTyCon )
32
import Name		( Name, NamedThing(..), nameUnique, isLocallyDefinedName )
33
34
35
36
37
38
import Var		( TyVar, Id )
import VarEnv
import FieldLabel	( FieldLabel )
import BasicTypes	( StrictnessMark(..), Arity )
import Outputable
import Unique		( Unique, Uniquable(..) )
39
40
41
import CmdLineOpts	( opt_UnboxStrictFields )
import UniqSet
import Maybe
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import Util		( assoc )
\end{code}


%************************************************************************
%*									*
\subsection{Data constructors}
%*									*
%************************************************************************

\begin{code}
data DataCon
  = MkData {			-- Used for data constructors only;
				-- there *is* no constructor for a newtype
	dcName   :: Name,
	dcUnique :: Unique, 		-- Cached from Name
	dcTag    :: ConTag,
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

	-- Running example:
	--
	--	data Eq a => T a = forall b. Ord b => MkT a [b]

	dcType   :: Type,	-- Type of the constructor 
				-- 	forall ab . Ord b => a -> [b] -> MkT a
				-- (this is *not* of the constructor Id: 
				--  see notes after this data type declaration)

	-- The next six fields express the type of the constructor, in pieces
	-- e.g.
	--
	--	dcTyVars   = [a]
	-- 	dcTheta    = [Eq a]
	--	dcExTyVars = [b]
	--	dcExTheta  = [Ord b]
76
	--	dcOrigArgTys   = [a,List b]
77
	--	dcTyCon    = T
78
79
80
81
82
83
84

	dcTyVars :: [TyVar], 		-- Type vars and context for the data type decl
	dcTheta  ::  ThetaType,

	dcExTyVars :: [TyVar], 		-- Ditto for the context of the constructor, 
	dcExTheta  :: ThetaType,	-- the existentially quantified stuff
					
85
86
87
88
	dcOrigArgTys :: [Type],		-- Original argument types
					-- (before unboxing and flattening of
					--  strict fields)
	dcRepArgTys :: [Type],		-- Constructor Argument types
89
90
	dcTyCon  :: TyCon,		-- Result tycon 

91
	-- Now the strictness annotations and field labels of the constructor
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
	dcUserStricts :: [StrictnessMark], 
		-- Strictness annotations, as placed on the data type defn,
		-- in the same order as the argument types;
		-- length = dataConNumFields dataCon

	dcRealStricts :: [StrictnessMark],
		-- Strictness annotations as deduced by the compiler.  May
		-- include some MarkedUnboxed fields that are MarkedStrict
		-- in dcUserStricts.
		-- length = dataConNumFields dataCon

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

108
109
110
111
112
	-- Finally, the curried function that corresponds to the constructor
	-- 	mkT :: forall a b. (Eq a, Ord b) => a -> [b] -> T a
	--	mkT = /\ab. \deq dord p qs. Con MkT [a, b, dord, p, qs]
	-- This unfolding is built in MkId.mkDataConId

113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
	dcId :: Id			-- The corresponding Id
  }

type ConTag = Int

fIRST_TAG :: ConTag
fIRST_TAG =  1	-- Tags allocated from here for real constructors
\end{code}

The dcType field contains the type of the representation of a contructor
This may differ from the type of the contructor *Id* (built
by MkId.mkDataConId) for two reasons:
	a) the constructor Id may be overloaded, but the dictionary isn't stored
	   e.g.    data Eq a => T a = MkT a a

	b) the constructor may store an unboxed version of a strict field.

Here's an example illustrating both:
	data Ord a => T a = MkT Int! a
Here
	T :: Ord a => Int -> a -> T a
but the rep type is
	Trep :: Int# -> a -> T a
Actually, the unboxed part isn't implemented yet!


\begin{code}
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
    a <	 b = getUnique a <  getUnique b
    a >= b = getUnique a >= getUnique b
    a >	 b = getUnique a > getUnique b
    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)

instance Show DataCon where
    showsPrec p con = showsPrecSDoc p (ppr con)
\end{code}

\begin{code}
mkDataCon :: Name
	  -> [StrictnessMark] -> [FieldLabel]
	  -> [TyVar] -> ThetaType
	  -> [TyVar] -> ThetaType
	  -> [TauType] -> TyCon
	  -> Id
	  -> DataCon
  -- Can get the tag from the TyCon

174
175
mkDataCon name arg_stricts fields tyvars theta ex_tyvars ex_theta orig_arg_tys tycon id
  = ASSERT(length arg_stricts == length orig_arg_tys)
176
177
178
179
180
181
	-- The 'stricts' passed to mkDataCon are simply those for the
	-- source-language arguments.  We add extra ones for the
	-- dictionary arguments right here.
    con
  where
    con = MkData {dcName = name, dcUnique = nameUnique name,
182
183
184
	  	  dcTyVars = tyvars, dcTheta = theta, 
		  dcOrigArgTys = orig_arg_tys, 
		  dcRepArgTys = rep_arg_tys,
185
	     	  dcExTyVars = ex_tyvars, dcExTheta = ex_theta,
186
187
		  dcRealStricts = all_stricts, dcUserStricts = user_stricts,
		  dcFields = fields, dcTag = tag, dcTyCon = tycon, dcType = ty,
188
189
		  dcId = id}

190
191
192
    (real_arg_stricts, strict_arg_tyss) 
	= unzip (zipWith (unbox_strict_arg_ty tycon) arg_stricts orig_arg_tys)
    rep_arg_tys = concat strict_arg_tyss
193
194
	
    ex_dict_stricts = map mk_dict_strict_mark ex_theta
195
	-- Add a strictness flag for the existential dictionary arguments
196
197
    all_stricts     = ex_dict_stricts ++ real_arg_stricts
    user_stricts    = ex_dict_stricts ++ arg_stricts
198
199
200
201

    tag = assoc "mkDataCon" (tyConDataCons tycon `zip` [fIRST_TAG..]) con
    ty  = mkSigmaTy (tyvars ++ ex_tyvars) 
	            ex_theta
202
203
	            (mkFunTys rep_arg_tys 
			(mkTyConApp tycon (mkTyVarTys tyvars)))
204
205
206

mk_dict_strict_mark (clas,tys)
  | opt_DictsStrict &&
207
208
	-- Don't mark newtype things as strict!
    isDataTyCon (classTyCon clas) = MarkedStrict
209
  | otherwise		          = NotMarkedStrict
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258

-- We attempt to unbox/unpack a strict field when either:
--   (i)  The tycon is imported, and the field is marked '! !', or
--   (ii) The tycon is defined in this module, the field is marked '!', 
--	  and the -funbox-strict-fields flag is on.
--
-- This ensures that if we compile some modules with -funbox-strict-fields and
-- some without, the compiler doesn't get confused about the constructor
-- representations.

unbox_strict_arg_ty :: TyCon -> StrictnessMark -> Type -> (StrictnessMark, [Type])
unbox_strict_arg_ty tycon NotMarkedStrict ty 
  = (NotMarkedStrict, [ty])
unbox_strict_arg_ty tycon MarkedStrict ty 
  | not opt_UnboxStrictFields
  || not (isLocallyDefinedName (getName tycon)) = (MarkedStrict, [ty])
unbox_strict_arg_ty tycon marked_unboxed ty
  -- MarkedUnboxed || (MarkedStrict && opt_UnboxStrictFields && not imported)
  = case splitAlgTyConApp_maybe ty of
	Just (tycon,_,[])
	   -> panic (showSDoc (hcat [
			text "unbox_strict_arg_ty: constructors for ",
			ppr tycon,
			text " not available."
		     ]))
	Just (tycon,ty_args,[con]) 
	   -> case maybe_unpack_fields emptyUniqSet 
		     (zip (dataConOrigArgTys con ty_args) 
			  (dcUserStricts con))
	      of 
		 Nothing  -> (MarkedStrict, [ty])
	         Just tys -> (MarkedUnboxed con tys, tys)
	_ -> (MarkedStrict, [ty])

-- bail out if we encounter the same tycon twice.  This avoids problems like
--
--   data A = !B
--   data B = !A
--
-- where no useful unpacking can be done.

maybe_unpack_field :: UniqSet TyCon -> Type -> StrictnessMark -> Maybe [Type]
maybe_unpack_field set ty NotMarkedStrict
  = Just [ty]
maybe_unpack_field set ty MarkedStrict | not opt_UnboxStrictFields
  = Just [ty]
maybe_unpack_field set ty strict
  = case splitAlgTyConApp_maybe ty of
	Just (tycon,ty_args,[con])
259
		-- loop breaker
260
	   | tycon `elementOfUniqSet` set -> Nothing
261
262
263
		-- don't unpack constructors with existential tyvars
	   | not (null ex_tyvars) -> Nothing
		-- ok, let's do it
264
265
266
267
268
	   | otherwise ->
		let set' = addOneToUniqSet set tycon in
		maybe_unpack_fields set' 
		    (zip (dataConOrigArgTys con ty_args)
			 (dcUserStricts con))
269
	   where (_, _, ex_tyvars, _, _, _) = dataConSig con
270
271
272
273
	_ -> Just [ty]

maybe_unpack_fields :: UniqSet TyCon -> [(Type,StrictnessMark)] -> Maybe [Type]
maybe_unpack_fields set tys
274
275
  | all isJust unpacked_fields = Just (concat (catMaybes unpacked_fields))
  | otherwise = Nothing
276
  where unpacked_fields = map (\(ty,str) -> maybe_unpack_field set ty str) tys
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
\end{code}


\begin{code}
dataConName :: DataCon -> Name
dataConName = dcName

dataConTag :: DataCon -> ConTag
dataConTag  = dcTag

dataConTyCon :: DataCon -> TyCon
dataConTyCon = dcTyCon

dataConType :: DataCon -> Type
dataConType = dcType

dataConId :: DataCon -> Id
dataConId = dcId


dataConFieldLabels :: DataCon -> [FieldLabel]
dataConFieldLabels = dcFields

dataConStrictMarks :: DataCon -> [StrictnessMark]
301
dataConStrictMarks = dcRealStricts
302
303

dataConRawArgTys :: DataCon -> [TauType] -- a function of convenience
304
dataConRawArgTys = dcRepArgTys
305
306
307

dataConSourceArity :: DataCon -> Arity
	-- Source-level arity of the data constructor
308
dataConSourceArity dc = length (dcOrigArgTys dc)
309
310
311
312
313
314
315

dataConSig :: DataCon -> ([TyVar], ThetaType, 
			  [TyVar], ThetaType, 
			  [TauType], TyCon)

dataConSig (MkData {dcTyVars = tyvars, dcTheta = theta,
		     dcExTyVars = ex_tyvars, dcExTheta = ex_theta,
316
		     dcOrigArgTys = arg_tys, dcTyCon = tycon})
317
318
  = (tyvars, theta, ex_tyvars, ex_theta, arg_tys, tycon)

319
dataConArgTys, dataConOrigArgTys :: DataCon 
320
321
322
323
324
325
	      -> [Type] 	-- Instantiated at these types
				-- NB: these INCLUDE the existentially quantified arg types
	      -> [Type]		-- Needs arguments of these types
				-- NB: these INCLUDE the existentially quantified dict args
				--     but EXCLUDE the data-decl context which is discarded

326
327
328
329
330
331
dataConArgTys (MkData {dcRepArgTys = arg_tys, dcTyVars = tyvars, 
		       dcExTyVars = ex_tyvars, dcExTheta = ex_theta}) inst_tys
 = map (substTy (zipVarEnv (tyvars ++ ex_tyvars) inst_tys)) 
       ([mkDictTy cls tys | (cls,tys) <- ex_theta] ++ arg_tys)

dataConOrigArgTys (MkData {dcOrigArgTys = arg_tys, dcTyVars = tyvars, 
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
		       dcExTyVars = ex_tyvars, dcExTheta = ex_theta}) inst_tys
 = map (substTy (zipVarEnv (tyvars ++ ex_tyvars) inst_tys)) 
       ([mkDictTy cls tys | (cls,tys) <- ex_theta] ++ arg_tys)
\end{code}

dataConNumFields gives the number of actual fields in the
{\em representation} of the data constructor.  This may be more than appear
in the source code; the extra ones are the existentially quantified
dictionaries

\begin{code}
-- Number of type-instantiation arguments
-- All the remaining arguments of the DataCon are (notionally)
-- stored in the DataCon, and are matched in a case expression
dataConNumInstArgs (MkData {dcTyVars = tyvars}) = length tyvars

348
dataConNumFields (MkData {dcExTheta = theta, dcRepArgTys = arg_tys})
349
350
351
352
353
354
355
356
357
358
359
360
361
362
  = length theta + length arg_tys

isNullaryDataCon con
  = dataConNumFields con == 0 -- function of convenience

isTupleCon :: DataCon -> Bool
isTupleCon (MkData {dcTyCon = tc}) = isTupleTyCon tc
	
isUnboxedTupleCon :: DataCon -> Bool
isUnboxedTupleCon (MkData {dcTyCon = tc}) = isUnboxedTupleTyCon tc

isExistentialDataCon :: DataCon -> Bool
isExistentialDataCon (MkData {dcExTyVars = tvs}) = not (null tvs)
\end{code}