[project @ 1999-05-11 16:33:06 by keithw]
[ghc-hetmet.git] / ghc / compiler / prelude / TysWiredIn.lhs
1 %
2 % (c) The GRASP Project, Glasgow University, 1994-1998
3 %
4 \section[TysWiredIn]{Wired-in knowledge about {\em non-primitive} types}
5
6 This module is about types that can be defined in Haskell, but which
7 must be wired into the compiler nonetheless.
8
9 This module tracks the ``state interface'' document, ``GHC prelude:
10 types and operations.''
11
12 \begin{code}
13 module TysWiredIn (
14         addrDataCon,
15         addrTy,
16         addrTyCon,
17         boolTy,
18         boolTyCon,
19         charDataCon,
20         charTy,
21         charTyCon,
22         consDataCon,
23         doubleDataCon,
24         doubleTy,
25         isDoubleTy,
26         doubleTyCon,
27         falseDataCon,
28         floatDataCon,
29         floatTy,
30         isFloatTy,
31         floatTyCon,
32
33         intDataCon,
34         intTy,
35         intTyCon,
36         isIntTy,
37         inIntRange,
38
39         integerTy,
40         integerTyCon,
41         smallIntegerDataCon,
42         largeIntegerDataCon,
43         isIntegerTy,
44
45         listTyCon,
46
47         mkListTy,
48         nilDataCon,
49
50         -- tuples
51         mkTupleTy,
52         tupleTyCon, tupleCon, unitTyCon, unitDataCon, pairTyCon, pairDataCon,
53
54         -- unboxed tuples
55         mkUnboxedTupleTy,
56         unboxedTupleTyCon, unboxedTupleCon, 
57         unboxedPairTyCon, unboxedPairDataCon,
58
59         stablePtrTyCon,
60         stringTy,
61         trueDataCon,
62         unitTy,
63         voidTy,
64         wordDataCon,
65         wordTy,
66         wordTyCon,
67
68         isFFIArgumentTy,  -- :: Type -> Bool
69         isFFIResultTy,    -- :: Type -> Bool
70         isFFIExternalTy,  -- :: Type -> Bool
71         isAddrTy,         -- :: Type -> Bool
72
73     ) where
74
75 #include "HsVersions.h"
76
77 import {-# SOURCE #-} MkId( mkDataConId )
78
79 -- friends:
80 import PrelMods
81 import TysPrim
82
83 -- others:
84 import Constants        ( mAX_TUPLE_SIZE )
85 import Module           ( Module )
86 import Name             ( mkWiredInTyConName, mkWiredInIdName, mkSrcOccFS, dataName )
87 import DataCon          ( DataCon, mkDataCon )
88 import Var              ( TyVar, tyVarKind )
89 import TyCon            ( TyCon, ArgVrcs, mkAlgTyCon, mkSynTyCon, mkTupleTyCon )
90 import BasicTypes       ( Arity, NewOrData(..), 
91                           RecFlag(..), StrictnessMark(..) )
92 import Type             ( Type, mkTyConTy, mkTyConApp, mkSigmaTy, mkTyVarTys, 
93                           mkArrowKinds, boxedTypeKind, unboxedTypeKind,
94                           mkFunTy, mkFunTys, isUnLiftedType,
95                           splitTyConApp_maybe, splitAlgTyConApp_maybe,
96                           ThetaType, TauType )
97 import PrimRep          ( PrimRep(..) )
98 import Unique
99 import CmdLineOpts      ( opt_GlasgowExts )
100 import Util             ( assoc )
101 import Panic            ( panic )
102 import Array
103
104 alpha_tyvar       = [alphaTyVar]
105 alpha_ty          = [alphaTy]
106 alpha_beta_tyvars = [alphaTyVar, betaTyVar]
107
108 pcRecDataTyCon, pcNonRecDataTyCon, pcNonRecNewTyCon
109         :: Unique{-TyConKey-} -> Module -> FAST_STRING
110         -> [TyVar] -> ArgVrcs -> [DataCon] -> TyCon
111
112 pcRecDataTyCon    = pcTyCon DataType Recursive
113 pcNonRecDataTyCon = pcTyCon DataType NonRecursive
114 pcNonRecNewTyCon  = pcTyCon NewType  NonRecursive
115
116 pcTyCon new_or_data is_rec key mod str tyvars argvrcs cons
117   = tycon
118   where
119     tycon = mkAlgTyCon name kind 
120                 tyvars 
121                 []              -- No context
122                 argvrcs
123                 cons
124                 []              -- No derivings
125                 Nothing         -- Not a dictionary
126                 new_or_data
127                 is_rec
128
129     name = mkWiredInTyConName key mod str tycon
130     kind = mkArrowKinds (map tyVarKind tyvars) boxedTypeKind
131
132 pcSynTyCon key mod str kind arity tyvars expansion argvrcs  -- this fun never used!
133   = tycon
134   where
135     tycon = mkSynTyCon name kind arity tyvars expansion argvrcs
136     name  = mkWiredInTyConName key mod str tycon
137
138 pcDataCon :: Unique{-DataConKey-} -> Module -> FAST_STRING
139           -> [TyVar] -> ThetaType -> [TauType] -> TyCon -> DataCon
140 pcDataCon key mod str tyvars context arg_tys tycon
141   = data_con
142   where
143     data_con = mkDataCon name 
144                 [ NotMarkedStrict | a <- arg_tys ]
145                 [ {- no labelled fields -} ]
146                 tyvars context [] [] arg_tys tycon id
147     name = mkWiredInIdName key mod (mkSrcOccFS dataName str) id
148     id   = mkDataConId data_con
149 \end{code}
150
151 %************************************************************************
152 %*                                                                      *
153 \subsection[TysWiredIn-tuples]{The tuple types}
154 %*                                                                      *
155 %************************************************************************
156
157 \begin{code}
158 tupleTyCon :: Arity -> TyCon
159 tupleTyCon i | i > mAX_TUPLE_SIZE = fst (mk_tuple i)    -- Build one specially
160              | otherwise          = tupleTyConArr!i
161
162 tupleCon :: Arity -> DataCon
163 tupleCon i | i > mAX_TUPLE_SIZE = snd (mk_tuple i)      -- Build one specially
164            | otherwise          = tupleConArr!i
165
166 tupleTyCons :: [TyCon]
167 tupleTyCons = elems tupleTyConArr
168
169 tupleTyConArr :: Array Int TyCon
170 tupleTyConArr = array (0,mAX_TUPLE_SIZE) ([0..] `zip` map fst tuples)
171
172 tupleConArr :: Array Int DataCon
173 tupleConArr = array (0,mAX_TUPLE_SIZE) ([0..] `zip` map snd tuples)
174
175 tuples :: [(TyCon,DataCon)]
176 tuples = [mk_tuple i | i <- [0..mAX_TUPLE_SIZE]]
177
178 mk_tuple :: Int -> (TyCon,DataCon)
179 mk_tuple arity = (tycon, tuple_con)
180   where
181         tycon   = mkTupleTyCon tc_name tc_kind arity tyvars tuple_con True
182         tc_name = mkWiredInTyConName tc_uniq mod_name name_str tycon
183         tc_kind = mkArrowKinds (map tyVarKind tyvars) boxedTypeKind
184
185         tuple_con = pcDataCon dc_uniq mod_name name_str tyvars [] tyvar_tys tycon
186         tyvars    = take arity alphaTyVars
187         tyvar_tys = mkTyVarTys tyvars
188         (mod_name, name_str) = mkTupNameStr arity
189         tc_uniq   = mkTupleTyConUnique   arity
190         dc_uniq   = mkTupleDataConUnique arity
191
192 unitTyCon = tupleTyCon 0
193 pairTyCon = tupleTyCon 2
194
195 unitDataCon = tupleCon 0
196 pairDataCon = tupleCon 2
197 \end{code}
198
199 %************************************************************************
200 %*                                                                      *
201 \subsection[TysWiredIn-ubx-tuples]{Unboxed Tuple Types}
202 %*                                                                      *
203 %************************************************************************
204
205 \begin{code}
206 unboxedTupleTyCon :: Arity -> TyCon
207 unboxedTupleTyCon i | i > mAX_TUPLE_SIZE = fst (mk_unboxed_tuple i)
208                     | otherwise          = unboxedTupleTyConArr!i
209
210 unboxedTupleCon :: Arity -> DataCon
211 unboxedTupleCon i | i > mAX_TUPLE_SIZE = snd (mk_unboxed_tuple i)
212                   | otherwise          = unboxedTupleConArr!i
213
214 unboxedTupleTyConArr :: Array Int TyCon
215 unboxedTupleTyConArr = array (0,mAX_TUPLE_SIZE) ([0..] `zip` map fst ubx_tuples)
216
217 unboxedTupleConArr :: Array Int DataCon
218 unboxedTupleConArr = array (0,mAX_TUPLE_SIZE) ([0..] `zip` map snd ubx_tuples)
219
220 ubx_tuples :: [(TyCon,DataCon)]
221 ubx_tuples = [mk_unboxed_tuple i | i <- [0..mAX_TUPLE_SIZE]]
222
223 mk_unboxed_tuple :: Int -> (TyCon,DataCon)
224 mk_unboxed_tuple arity = (tycon, tuple_con)
225   where
226         tycon   = mkTupleTyCon tc_name tc_kind arity tyvars tuple_con False
227         tc_name = mkWiredInTyConName tc_uniq mod_name name_str tycon
228         tc_kind = mkArrowKinds (map tyVarKind tyvars) unboxedTypeKind
229
230         tuple_con = pcDataCon dc_uniq mod_name name_str tyvars [] tyvar_tys tycon
231         tyvars    = take arity openAlphaTyVars
232         tyvar_tys = mkTyVarTys tyvars
233         (mod_name, name_str) = mkUbxTupNameStr arity
234         tc_uniq   = mkUbxTupleTyConUnique   arity
235         dc_uniq   = mkUbxTupleDataConUnique arity
236
237 unboxedPairTyCon   = unboxedTupleTyCon 2
238 unboxedPairDataCon = unboxedTupleCon 2
239 \end{code}
240
241 %************************************************************************
242 %*                                                                      *
243 \subsection[TysWiredIn-boxed-prim]{The ``boxed primitive'' types (@Char@, @Int@, etc)}
244 %*                                                                      *
245 %************************************************************************
246
247 \begin{code}
248 -- The Void type is represented as a data type with no constructors
249 -- It's a built in type (i.e. there's no way to define it in Haskell;
250 --      the nearest would be
251 --
252 --              data Void =             -- No constructors!
253 --
254 -- ) It's boxed; there is only one value of this
255 -- type, namely "void", whose semantics is just bottom.
256 --
257 -- Haskell 98 drops the definition of a Void type, so we just 'simulate'
258 -- voidTy using ().
259 voidTy = unitTy
260 \end{code}
261
262
263 \begin{code}
264 charTy = mkTyConTy charTyCon
265
266 charTyCon = pcNonRecDataTyCon charTyConKey  pREL_BASE  SLIT("Char") [] [] [charDataCon]
267 charDataCon = pcDataCon charDataConKey pREL_BASE SLIT("C#") [] [] [charPrimTy] charTyCon
268
269 stringTy = mkListTy charTy -- convenience only
270 \end{code}
271
272 \begin{code}
273 intTy = mkTyConTy intTyCon 
274
275 intTyCon = pcNonRecDataTyCon intTyConKey pREL_BASE SLIT("Int") [] [] [intDataCon]
276 intDataCon = pcDataCon intDataConKey pREL_BASE SLIT("I#") [] [] [intPrimTy] intTyCon
277
278 isIntTy :: Type -> Bool
279 isIntTy ty
280   = case (splitAlgTyConApp_maybe ty) of
281         Just (tycon, [], _) -> getUnique tycon == intTyConKey
282         _                   -> False
283
284 inIntRange :: Integer -> Bool   -- Tells if an integer lies in the legal range of Ints
285 inIntRange i = (min_int <= i) && (i <= max_int)
286
287 max_int, min_int :: Integer
288 max_int = toInteger maxInt  
289 min_int = toInteger minInt
290
291 \end{code}
292
293 \begin{code}
294
295 wordTy = mkTyConTy wordTyCon
296
297 wordTyCon = pcNonRecDataTyCon wordTyConKey   pREL_ADDR SLIT("Word") [] [] [wordDataCon]
298 wordDataCon = pcDataCon wordDataConKey pREL_ADDR SLIT("W#") [] [] [wordPrimTy] wordTyCon
299 \end{code}
300
301 \begin{code}
302 addrTy = mkTyConTy addrTyCon
303
304 addrTyCon = pcNonRecDataTyCon addrTyConKey   pREL_ADDR SLIT("Addr") [] [] [addrDataCon]
305 addrDataCon = pcDataCon addrDataConKey pREL_ADDR SLIT("A#") [] [] [addrPrimTy] addrTyCon
306
307 isAddrTy :: Type -> Bool
308 isAddrTy ty
309   = case (splitAlgTyConApp_maybe ty) of
310         Just (tycon, [], _) -> getUnique tycon == addrTyConKey
311         _                   -> False
312
313 \end{code}
314
315 \begin{code}
316 floatTy = mkTyConTy floatTyCon
317
318 floatTyCon = pcNonRecDataTyCon floatTyConKey pREL_BASE SLIT("Float") [] [] [floatDataCon]
319 floatDataCon = pcDataCon floatDataConKey pREL_BASE SLIT("F#") [] [] [floatPrimTy] floatTyCon
320
321 isFloatTy :: Type -> Bool
322 isFloatTy ty
323   = case (splitAlgTyConApp_maybe ty) of
324         Just (tycon, [], _) -> getUnique tycon == floatTyConKey
325         _                   -> False
326
327 \end{code}
328
329 \begin{code}
330 doubleTy = mkTyConTy doubleTyCon
331
332 isDoubleTy :: Type -> Bool
333 isDoubleTy ty
334   = case (splitAlgTyConApp_maybe ty) of
335         Just (tycon, [], _) -> getUnique tycon == doubleTyConKey
336         _                   -> False
337
338 doubleTyCon = pcNonRecDataTyCon doubleTyConKey pREL_BASE SLIT("Double") [] [] [doubleDataCon]
339 doubleDataCon = pcDataCon doubleDataConKey pREL_BASE SLIT("D#") [] [] [doublePrimTy] doubleTyCon
340 \end{code}
341
342 \begin{code}
343 stablePtrTyCon
344   = pcNonRecDataTyCon stablePtrTyConKey pREL_STABLE SLIT("StablePtr")
345         alpha_tyvar [(True,False)] [stablePtrDataCon]
346   where
347     stablePtrDataCon
348       = pcDataCon stablePtrDataConKey pREL_STABLE SLIT("StablePtr")
349             alpha_tyvar [] [mkStablePtrPrimTy alphaTy] stablePtrTyCon
350 \end{code}
351
352 \begin{code}
353 foreignObjTyCon
354   = pcNonRecDataTyCon foreignObjTyConKey pREL_IO_BASE SLIT("ForeignObj")
355         [] [] [foreignObjDataCon]
356   where
357     foreignObjDataCon
358       = pcDataCon foreignObjDataConKey pREL_IO_BASE SLIT("ForeignObj")
359             [] [] [foreignObjPrimTy] foreignObjTyCon
360 \end{code}
361
362 %************************************************************************
363 %*                                                                      *
364 \subsection[TysWiredIn-Integer]{@Integer@ and its related ``pairing'' types}
365 %*                                                                      *
366 %************************************************************************
367
368 @Integer@ and its pals are not really primitive.  @Integer@ itself, first:
369 \begin{code}
370 integerTy :: Type
371 integerTy = mkTyConTy integerTyCon
372
373 integerTyCon = pcNonRecDataTyCon integerTyConKey pREL_BASE SLIT("Integer")
374                    [] [] [smallIntegerDataCon, largeIntegerDataCon]
375
376 smallIntegerDataCon = pcDataCon smallIntegerDataConKey pREL_BASE SLIT("S#")
377                 [] [] [intPrimTy] integerTyCon
378 largeIntegerDataCon = pcDataCon largeIntegerDataConKey pREL_BASE SLIT("J#")
379                 [] [] [intPrimTy, byteArrayPrimTy] integerTyCon
380
381
382 isIntegerTy :: Type -> Bool
383 isIntegerTy ty
384   = case (splitAlgTyConApp_maybe ty) of
385         Just (tycon, [], _) -> getUnique tycon == integerTyConKey
386         _                   -> False
387 \end{code}
388
389
390 %************************************************************************
391 %*                                                                      *
392 \subsection[TysWiredIn-ext-type]{External types}
393 %*                                                                      *
394 %************************************************************************
395
396 The compiler's foreign function interface supports the passing of a
397 restricted set of types as arguments and results (the restricting factor
398 being the )
399
400 \begin{code}
401 isFFIArgumentTy :: Type -> Bool
402 isFFIArgumentTy ty =
403   (opt_GlasgowExts && isUnLiftedType ty) || --leave out for now: maybeToBool (maybeBoxedPrimType ty))) ||
404   case (splitAlgTyConApp_maybe ty) of
405     Just (tycon, _, _) -> (getUnique tycon) `elem` primArgTyConKeys
406     _                  -> False
407
408 -- types that can be passed as arguments to "foreign" functions
409 primArgTyConKeys 
410   = [ intTyConKey, int8TyConKey, int16TyConKey, int32TyConKey, int64TyConKey
411     , wordTyConKey, word8TyConKey, word16TyConKey, word32TyConKey, word64TyConKey
412     , floatTyConKey, doubleTyConKey
413     , addrTyConKey, charTyConKey, foreignObjTyConKey
414     , stablePtrTyConKey
415     , byteArrayTyConKey, mutableByteArrayTyConKey
416     ]
417
418 -- types that can be passed from the outside world into Haskell.
419 -- excludes (mutable) byteArrays.
420 isFFIExternalTy :: Type -> Bool
421 isFFIExternalTy ty = 
422   (opt_GlasgowExts && isUnLiftedType ty) || --leave out for now: maybeToBool (maybeBoxedPrimType ty))) ||
423   case (splitAlgTyConApp_maybe ty) of
424     Just (tycon, _, _) -> 
425        let 
426         u_tycon = getUnique tycon
427        in  
428        (u_tycon `elem` primArgTyConKeys) &&
429        not (u_tycon `elem` notLegalExternalTyCons)
430     _                  -> False
431
432
433 isFFIResultTy :: Type -> Bool
434 isFFIResultTy ty =
435    not (isUnLiftedType ty) &&
436    case (splitAlgTyConApp_maybe ty) of
437     Just (tycon, _, _) -> 
438         let
439          u_tycon = getUnique tycon
440         in
441         (u_tycon == getUnique unitTyCon) ||
442         ((u_tycon `elem` primArgTyConKeys) && 
443          not (u_tycon `elem` notLegalExternalTyCons))
444     _                  -> False
445
446 -- it's illegal to return foreign objects and (mutable)
447 -- bytearrays from a _ccall_ / foreign declaration
448 -- (or be passed them as arguments in foreign exported functions).
449 notLegalExternalTyCons =
450   [ foreignObjTyConKey, byteArrayTyConKey, mutableByteArrayTyConKey ]
451     
452 \end{code}
453
454 %************************************************************************
455 %*                                                                      *
456 \subsection[TysWiredIn-Bool]{The @Bool@ type}
457 %*                                                                      *
458 %************************************************************************
459
460 An ordinary enumeration type, but deeply wired in.  There are no
461 magical operations on @Bool@ (just the regular Prelude code).
462
463 {\em BEGIN IDLE SPECULATION BY SIMON}
464
465 This is not the only way to encode @Bool@.  A more obvious coding makes
466 @Bool@ just a boxed up version of @Bool#@, like this:
467 \begin{verbatim}
468 type Bool# = Int#
469 data Bool = MkBool Bool#
470 \end{verbatim}
471
472 Unfortunately, this doesn't correspond to what the Report says @Bool@
473 looks like!  Furthermore, we get slightly less efficient code (I
474 think) with this coding. @gtInt@ would look like this:
475
476 \begin{verbatim}
477 gtInt :: Int -> Int -> Bool
478 gtInt x y = case x of I# x# ->
479             case y of I# y# ->
480             case (gtIntPrim x# y#) of
481                 b# -> MkBool b#
482 \end{verbatim}
483
484 Notice that the result of the @gtIntPrim@ comparison has to be turned
485 into an integer (here called @b#@), and returned in a @MkBool@ box.
486
487 The @if@ expression would compile to this:
488 \begin{verbatim}
489 case (gtInt x y) of
490   MkBool b# -> case b# of { 1# -> e1; 0# -> e2 }
491 \end{verbatim}
492
493 I think this code is a little less efficient than the previous code,
494 but I'm not certain.  At all events, corresponding with the Report is
495 important.  The interesting thing is that the language is expressive
496 enough to describe more than one alternative; and that a type doesn't
497 necessarily need to be a straightforwardly boxed version of its
498 primitive counterpart.
499
500 {\em END IDLE SPECULATION BY SIMON}
501
502 \begin{code}
503 boolTy = mkTyConTy boolTyCon
504
505 boolTyCon = pcTyCon EnumType NonRecursive boolTyConKey 
506                     pREL_BASE SLIT("Bool") [] [] [falseDataCon, trueDataCon]
507
508 falseDataCon = pcDataCon falseDataConKey pREL_BASE SLIT("False") [] [] [] boolTyCon
509 trueDataCon  = pcDataCon trueDataConKey  pREL_BASE SLIT("True")  [] [] [] boolTyCon
510 \end{code}
511
512 %************************************************************************
513 %*                                                                      *
514 \subsection[TysWiredIn-List]{The @List@ type (incl ``build'' magic)}
515 %*                                                                      *
516 %************************************************************************
517
518 Special syntax, deeply wired in, but otherwise an ordinary algebraic
519 data types:
520 \begin{verbatim}
521 data [] a = [] | a : (List a)
522 data () = ()
523 data (,) a b = (,,) a b
524 ...
525 \end{verbatim}
526
527 \begin{code}
528 mkListTy :: Type -> Type
529 mkListTy ty = mkTyConApp listTyCon [ty]
530
531 alphaListTy = mkSigmaTy alpha_tyvar [] (mkTyConApp listTyCon alpha_ty)
532
533 listTyCon = pcRecDataTyCon listTyConKey pREL_BASE SLIT("[]") 
534                         alpha_tyvar [(True,False)] [nilDataCon, consDataCon]
535
536 nilDataCon  = pcDataCon nilDataConKey  pREL_BASE SLIT("[]") alpha_tyvar [] [] listTyCon
537 consDataCon = pcDataCon consDataConKey pREL_BASE SLIT(":")
538                 alpha_tyvar [] [alphaTy, mkTyConApp listTyCon alpha_ty] listTyCon
539 -- Interesting: polymorphic recursion would help here.
540 -- We can't use (mkListTy alphaTy) in the defn of consDataCon, else mkListTy
541 -- gets the over-specific type (Type -> Type)
542 \end{code}
543
544 %************************************************************************
545 %*                                                                      *
546 \subsection[TysWiredIn-Tuples]{The @Tuple@ types}
547 %*                                                                      *
548 %************************************************************************
549
550 The tuple types are definitely magic, because they form an infinite
551 family.
552
553 \begin{itemize}
554 \item
555 They have a special family of type constructors, of type @TyCon@
556 These contain the tycon arity, but don't require a Unique.
557
558 \item
559 They have a special family of constructors, of type
560 @Id@. Again these contain their arity but don't need a Unique.
561
562 \item
563 There should be a magic way of generating the info tables and
564 entry code for all tuples.
565
566 But at the moment we just compile a Haskell source
567 file\srcloc{lib/prelude/...} containing declarations like:
568 \begin{verbatim}
569 data Tuple0             = Tup0
570 data Tuple2  a b        = Tup2  a b
571 data Tuple3  a b c      = Tup3  a b c
572 data Tuple4  a b c d    = Tup4  a b c d
573 ...
574 \end{verbatim}
575 The print-names associated with the magic @Id@s for tuple constructors
576 ``just happen'' to be the same as those generated by these
577 declarations.
578
579 \item
580 The instance environment should have a magic way to know
581 that each tuple type is an instances of classes @Eq@, @Ix@, @Ord@ and
582 so on. \ToDo{Not implemented yet.}
583
584 \item
585 There should also be a way to generate the appropriate code for each
586 of these instances, but (like the info tables and entry code) it is
587 done by enumeration\srcloc{lib/prelude/InTup?.hs}.
588 \end{itemize}
589
590 \begin{code}
591 mkTupleTy :: Int -> [Type] -> Type
592 mkTupleTy arity tys = mkTyConApp (tupleTyCon arity) tys
593
594 mkUnboxedTupleTy :: Int -> [Type] -> Type
595 mkUnboxedTupleTy arity tys = mkTyConApp (unboxedTupleTyCon arity) tys
596
597 unitTy    = mkTupleTy 0 []
598 \end{code}