89180d08a1b643065e1f0e8365ac7e86c4fb989a
[ghc-hetmet.git] / ghc / docs / users_guide / libraries.vsgml
1
2 % $Id: libraries.vsgml,v 1.2 1998/08/25 18:07:57 sof Exp $
3 %
4 % GHC Prelude and Libraries.
5 %
6
7 <sect>The GHC prelude and libraries
8 <label id="ghc-prelude">
9 <p>
10
11 This document describes GHC's prelude and libraries.  The basic story is that of
12 the Haskell 1.4 Report and Libraries document (which we do not reproduce here),
13 but this document describes in addition:
14
15 <itemize>
16
17 <item>  GHC's additional non-standard libraries and types, such as
18         state transformers, packed strings, foreign objects, stable
19         pointers, and so on.
20
21 <item>  GHC's primitive types and operations.  The standard Haskell
22         functions are implemented on top of these, and it is sometimes
23         useful to use them directly.
24
25 <item>  The organisation of these libraries into directories.
26
27 <item> Short description of programmer interface to the non-standard
28        libraries provided in addition to the standard prelude.
29 </itemize>
30
31 A number of the libraries that provide access to GHC's language
32 extensions are shared by Hugs, and are described in the <htmlurl
33 name="GHC/Hugs Extension Libraries" url="libs.html"> document.
34
35 <sect1>Prelude extensions
36 <label id="ghc-prelude-exts">
37 <p>
38
39 GHC's prelude contains the following non-standard extensions:
40
41 <descrip>
42
43 <tag>@fromInt@ method in class @Num@:</tag> It's there.  Converts from
44 an @Int@ to the type.
45
46 <tag>@toInt@ method in class @Integral@:</tag> Converts from type type
47 to an @Int@.
48
49 </descrip>
50
51 GHC also internally uses a number of modules that begin with the
52 string @Prel@: for this reason, we don't recommend that you use any
53 module names beginning with @Prel@ in your own programs.  The @Prel@
54 modules are always available: in fact, you can get access to several
55 extensions this way (for some you might need to give the
56 @-fglasgow-exts@<nidx>-fglasgow-exts option</nidx> flag).
57
58 <sect1>The module @PrelGHC@: really primitive stuff
59 <label id="ghc-libs-ghc">
60 <p>
61
62 This section defines all the types which are primitive in Glasgow
63 Haskell, and the operations provided for them.
64
65 A primitive type is one which cannot be defined in Haskell, and which
66 is therefore built into the language and compiler.  Primitive types
67 are always unboxed; that is, a value of primitive type cannot be
68 bottom.
69
70 Primitive values are often represented by a simple bit-pattern, such
71 as @Int#@, @Float#@, @Double#@.  But this is not necessarily the case:
72 a primitive value might be represented by a pointer to a
73 heap-allocated object.  Examples include @Array#@, the type of
74 primitive arrays.  You might think this odd: doesn't being
75 heap-allocated mean that it has a box?  No, it does not.  A primitive
76 array is heap-allocated because it is too big a value to fit in a
77 register, and would be too expensive to copy around; in a sense, it is
78 accidental that it is represented by a pointer.  If a pointer
79 represents a primitive value, then it really does point to that value:
80 no unevaluated thunks, no indirections...nothing can be at the other
81 end of the pointer than the primitive value.
82
83 This section also describes a few non-primitive types, which are needed 
84 to express the result types of some primitive operations.
85
86 <sect2>Character and numeric types
87 <p>
88 <nidx>character types, primitive</nidx>
89 <nidx>numeric types, primitive</nidx>
90 <nidx>integer types, primitive</nidx>
91 <nidx>floating point types, primitive</nidx>
92
93 There are the following obvious primitive types:
94
95 <tscreen><verb>
96 type Char#
97 type Int#       -- see also Word# and Addr#, later
98 type Float#
99 type Double#
100 </verb></tscreen>
101 <ncdx>Char#</ncdx>
102 <ncdx>Int#</ncdx>
103 <ncdx>Float#</ncdx>
104 <ncdx>Double#</ncdx>
105
106 If you really want to know their exact equivalents in C, see
107 @ghc/includes/StgTypes.lh@ in the GHC source tree.
108
109 Literals for these types may be written as follows:
110
111 <tscreen><verb>
112 1#              an Int#
113 1.2#            a Float#
114 1.34##          a Double#
115 'a'#            a Char#; for weird characters, use '\o<octal>'#
116 "a"#            an Addr# (a `char *')
117 </verb></tscreen>
118 <nidx>literals, primitive</nidx>
119 <nidx>constants, primitive</nidx>
120 <nidx>numbers, primitive</nidx>
121
122 <sect2> Comparison operations
123 <p>
124 <nidx>comparisons, primitive</nidx>
125 <nidx>operators, comparison</nidx>
126
127 <tscreen><verb>
128 {>,>=,==,/=,<,<=}# :: Int# -> Int# -> Bool
129
130 {gt,ge,eq,ne,lt,le}Char# :: Char# -> Char# -> Bool
131     -- ditto for Word# and Addr#
132 </verb></tscreen>
133 <ncdx>>#</ncdx>
134 <ncdx>>=#</ncdx>
135 <ncdx>==#</ncdx>
136 <ncdx>/=#</ncdx>
137 <ncdx><#</ncdx>
138 <ncdx><=#</ncdx>
139 <ncdx>gt{Char,Word,Addr}#</ncdx>
140 <ncdx>ge{Char,Word,Addr}#</ncdx>
141 <ncdx>eq{Char,Word,Addr}#</ncdx>
142 <ncdx>ne{Char,Word,Addr}#</ncdx>
143 <ncdx>lt{Char,Word,Addr}#</ncdx>
144 <ncdx>le{Char,Word,Addr}#</ncdx>
145
146 <sect2> Primitive-character operations
147 <p>
148 <nidx>characters, primitive</nidx>
149 <nidx>operators, primitive character</nidx>
150
151 <tscreen><verb>
152 ord# :: Char# -> Int#
153 chr# :: Int# -> Char#
154 </verb></tscreen>
155 <ncdx>ord#</ncdx>
156 <ncdx>chr#</ncdx>
157
158
159 <sect2> Primitive-@Int@ operations
160 <p>
161 <nidx>integers, primitive</nidx>
162 <nidx>operators, primitive integer</nidx>
163
164 <tscreen><verb>
165 {+,-,*,quotInt,remInt}# :: Int# -> Int# -> Int#
166 negateInt# :: Int# -> Int#
167
168 iShiftL#, iShiftRA#, iShiftRL# :: Int# -> Int# -> Int#
169         -- shift left, right arithmetic, right logical
170 </verb></tscreen>
171 <ncdx>+#</ncdx>
172 <ncdx>-#</ncdx>
173 <ncdx>*#</ncdx>
174 <ncdx>quotInt#</ncdx>
175 <ncdx>remInt#</ncdx>
176 <ncdx>iShiftL#</ncdx>
177 <ncdx>iShiftRA#</ncdx>
178 <ncdx>iShiftRL#</ncdx>
179 <nidx>shift operations, integer</nidx>
180
181 <bf>Note:</bf> No error/overflow checking!
182
183 <sect2> Primitive-@Double@ and @Float@ operations
184 <p>
185 <nidx>floating point numbers, primitive</nidx>
186 <nidx>operators, primitive floating point</nidx>
187
188 <tscreen><verb>
189 {+,-,*,/}##         :: Double# -> Double# -> Double#
190 {<,<=,==,/=,>=,>}## :: Double# -> Double# -> Bool
191 negateDouble#       :: Double# -> Double#
192 double2Int#         :: Double# -> Int#
193 int2Double#         :: Int#    -> Double#
194
195 {plus,minux,times,divide}Float# :: Float# -> Float# -> Float#
196 {gt,ge,eq,ne,lt,le}Float# :: Float# -> Float# -> Bool
197 negateFloat#        :: Float# -> Float#
198 float2Int#          :: Float# -> Int#
199 int2Float#          :: Int#   -> Float#
200 </verb></tscreen>
201
202 <ncdx>+##</ncdx>
203 <ncdx>-##</ncdx>
204 <ncdx>*##</ncdx>
205 <ncdx>/##</ncdx>
206 <ncdx><##</ncdx>
207 <ncdx><=##</ncdx>
208 <ncdx>==##</ncdx>
209 <ncdx>=/##</ncdx>
210 <ncdx>>=##</ncdx>
211 <ncdx>>##</ncdx>
212 <ncdx>negateDouble#</ncdx>
213 <ncdx>double2Int#</ncdx>
214 <ncdx>int2Double#</ncdx>
215
216 <ncdx>plusFloat#</ncdx>
217 <ncdx>minusFloat#</ncdx>
218 <ncdx>timesFloat#</ncdx>
219 <ncdx>divideFloat#</ncdx>
220 <ncdx>gtFloat#</ncdx>
221 <ncdx>geFloat#</ncdx>
222 <ncdx>eqFloat#</ncdx>
223 <ncdx>neFloat#</ncdx>
224 <ncdx>ltFloat#</ncdx>
225 <ncdx>leFloat#</ncdx>
226 <ncdx>negateFloat#</ncdx>
227 <ncdx>float2Int#</ncdx>
228 <ncdx>int2Float#</ncdx>
229
230 And a full complement of trigonometric functions:
231
232 <tscreen> <verb>
233 expDouble#      :: Double# -> Double#
234 logDouble#      :: Double# -> Double#
235 sqrtDouble#     :: Double# -> Double#
236 sinDouble#      :: Double# -> Double#
237 cosDouble#      :: Double# -> Double#
238 tanDouble#      :: Double# -> Double#
239 asinDouble#     :: Double# -> Double#
240 acosDouble#     :: Double# -> Double#
241 atanDouble#     :: Double# -> Double#
242 sinhDouble#     :: Double# -> Double#
243 coshDouble#     :: Double# -> Double#
244 tanhDouble#     :: Double# -> Double#
245 powerDouble#    :: Double# -> Double# -> Double#
246 </verb></tscreen>
247 <nidx>trigonometric functions, primitive</nidx>
248
249 similarly for @Float#@.
250
251 There are two coercion functions for @Float#@/@Double#@:
252
253 <tscreen><verb>
254 float2Double#   :: Float# -> Double#
255 double2Float#   :: Double# -> Float#
256 </verb></tscreen>
257 <ncdx>float2Double#</ncdx>
258 <ncdx>double2Float#</ncdx>
259
260 The primitive versions of @encodeDouble@/@decodeDouble@:
261
262 <tscreen><verb>
263 encodeDouble#   :: Int# -> Int# -> ByteArray#   -- Integer mantissa
264                 -> Int#                         -- Int exponent
265                 -> Double#
266
267 decodeDouble#   :: Double# -> PrelNum.ReturnIntAndGMP
268 </verb></tscreen>
269 <ncdx>encodeDouble#</ncdx>
270 <ncdx>decodeDouble#</ncdx>
271
272 (And the same for @Float#@s.)
273
274 <sect2>Operations on/for @Integers@ (interface to GMP)
275 <label id="horrid-Integer-pairing-types">
276 <p>
277 <nidx>arbitrary precision integers</nidx>
278 <nidx>Integer, operations on</nidx>
279
280 We implement @Integers@ (arbitrary-precision integers) using the GNU
281 multiple-precision (GMP) package (version 1.3.2).
282
283 <bf>Note:</bf> some of this might change when we upgrade to using
284 GMP~2.x.
285
286 The data type for @Integer@ must mirror that for @MP_INT@ in @gmp.h@
287 (see @gmp.info@ in @ghc/includes/runtime/gmp@).  It comes out as:
288
289 <tscreen><verb>
290 data Integer = J# Int# Int# ByteArray#
291 </verb></tscreen>
292 <nidx>Integer type</nidx>
293
294 So, @Integer@ is really just a ``pairing'' type for a particular
295 collection of primitive types.
296
297 The operations in the GMP return other combinations of
298 GMP-plus-something, so we need ``pairing'' types for those, too:
299
300 <tscreen><verb>
301 data Return2GMPs     = Return2GMPs Int# Int# ByteArray# Int# Int# ByteArray#
302 data ReturnIntAndGMP = ReturnIntAndGMP Int# Int# Int# ByteArray#
303
304 -- ????? something to return a string of bytes (in the heap?)
305 </verb></tscreen>
306 <ncdx>Return2GMPs</ncdx>
307 <ncdx>ReturnIntAndGMP</ncdx>
308
309 The primitive ops to support @Integers@ use the ``pieces'' of the
310 representation, and are as follows:
311
312 <tscreen><verb>
313 negateInteger#  :: Int# -> Int# -> ByteArray# -> Integer
314
315 {plus,minus,times}Integer# :: Int# -> Int# -> ByteArray#
316                            -> Int# -> Int# -> ByteArray#
317                            -> Integer
318
319 cmpInteger# :: Int# -> Int# -> ByteArray#
320             -> Int# -> Int# -> ByteArray#
321             -> Int# -- -1 for <; 0 for ==; +1 for >
322
323 divModInteger#, quotRemInteger#
324         :: Int# -> Int# -> ByteArray#
325         -> Int# -> Int# -> ByteArray#
326         -> PrelNum.Return2GMPs
327
328 integer2Int# :: Int# -> Int# -> ByteArray# -> Int# 
329
330 int2Integer#  :: Int#  -> Integer -- NB: no error-checking on these two!
331 word2Integer# :: Word# -> Integer
332
333 addr2Integer# :: Addr# -> Integer
334         -- the Addr# is taken to be a `char *' string
335         -- to be converted into an Integer.
336 </verb></tscreen>
337 <ncdx>negateInteger#</ncdx>
338 <ncdx>plusInteger#</ncdx>
339 <ncdx>minusInteger#</ncdx>
340 <ncdx>timesInteger#</ncdx>
341 <ncdx>cmpInteger#</ncdx>
342 <ncdx>divModInteger#</ncdx>
343 <ncdx>quotRemInteger#</ncdx>
344 <ncdx>integer2Int#</ncdx>
345 <ncdx>int2Integer#</ncdx>
346 <ncdx>word2Integer#</ncdx>
347 <ncdx>addr2Integer#</ncdx>
348
349 <sect2>Words and addresses
350 <p>
351 <nidx>word, primitive type</nidx>
352 <nidx>address, primitive type</nidx>
353 <nidx>unsigned integer, primitive type</nidx>
354 <nidx>pointer, primitive type</nidx>
355
356 A @Word#@ is used for bit-twiddling operations.  It is the same size as
357 an @Int#@, but has no sign nor any arithmetic operations.
358 <tscreen><verb>
359 type Word#      -- Same size/etc as Int# but *unsigned*
360 type Addr#      -- A pointer from outside the "Haskell world" (from C, probably);
361                 -- described under "arrays"
362
363 </verb></tscreen>
364 <ncdx>Word#</ncdx>
365 <ncdx>Addr#</ncdx>
366
367 @Word#@s and @Addr#@s have the usual comparison operations.
368 Other unboxed-@Word@ ops (bit-twiddling and coercions):
369
370 <tscreen><verb>
371 and#, or#, xor# :: Word# -> Word# -> Word#
372         -- standard bit ops.
373
374 quotWord#, remWord# :: Word# -> Word# -> Word#
375         -- word (i.e. unsigned) versions are different from int
376         -- versions, so we have to provide these explicitly.
377
378 not# :: Word# -> Word#
379
380 shiftL#, shiftRL# :: Word# -> Int# -> Word#
381         -- shift left, right logical
382
383 int2Word#       :: Int#  -> Word# -- just a cast, really
384 word2Int#       :: Word# -> Int#
385 </verb></tscreen>
386 <nidx>bit operations, Word and Addr</nidx>
387 <ncdx>and#</ncdx>
388 <ncdx>or#</ncdx>
389 <ncdx>xor#</ncdx>
390 <ncdx>not#</ncdx>
391 <ncdx>quotWord#</ncdx>
392 <ncdx>remWord#</ncdx>
393 <ncdx>shiftL#</ncdx>
394 <ncdx>shiftRL#</ncdx>
395 <ncdx>int2Word#</ncdx>
396 <ncdx>word2Int#</ncdx>
397
398 Unboxed-@Addr@ ops (C casts, really):
399 <tscreen><verb>
400 int2Addr#       :: Int#  -> Addr#
401 addr2Int#       :: Addr# -> Int#
402 </verb></tscreen>
403 <ncdx>int2Addr#</ncdx>
404 <ncdx>addr2Int#</ncdx>
405
406 The casts between @Int#@, @Word#@ and @Addr#@ correspond to null
407 operations at the machine level, but are required to keep the Haskell
408 type checker happy.
409
410 Operations for indexing off of C pointers (@Addr#@s) to snatch values
411 are listed under ``arrays''.
412
413 <sect2>Arrays
414 <p>
415 <nidx>arrays, primitive</nidx>
416
417 The type @Array# elt@ is the type of primitive, unpointed arrays of
418 values of type @elt@.
419
420 <tscreen><verb>
421 type Array# elt
422 </verb></tscreen>
423 <ncdx>Array#</ncdx>
424
425 @Array#@ is more primitive than a Haskell array --- indeed, the
426 Haskell @Array@ interface is implemented using @Array#@ --- in that an
427 @Array#@ is indexed only by @Int#@s, starting at zero.  It is also
428 more primitive by virtue of being unboxed.  That doesn't mean that it
429 isn't a heap-allocated object - of course, it is.  Rather, being
430 unboxed means that it is represented by a pointer to the array itself,
431 and not to a thunk which will evaluate to the array (or to bottom).
432 The components of an @Array#@ are themselves boxed.
433
434 The type @ByteArray#@ is similar to @Array#@, except that it contains
435 just a string of (non-pointer) bytes.
436
437 <tscreen><verb>
438 type ByteArray#
439 </verb></tscreen>
440 <ncdx>ByteArray#</ncdx>
441
442 Arrays of these types are useful when a Haskell program wishes to
443 construct a value to pass to a C procedure. It is also possible to
444 use them to build (say) arrays of unboxed characters for internal use
445 in a Haskell program.  Given these uses, @ByteArray#@ is deliberately
446 a bit vague about the type of its components.  Operations are provided
447 to extract values of type @Char#@, @Int#@, @Float#@, @Double#@, and
448 @Addr#@ from arbitrary offsets within a @ByteArray#@.  (For type
449 @Foo#@, the $i$th offset gets you the $i$th @Foo#@, not the @Foo#@ at
450 byte-position $i$.  Mumble.)  (If you want a @Word#@, grab an @Int#@,
451 then coerce it.)
452
453 Lastly, we have static byte-arrays, of type @Addr#@ [mentioned
454 previously].  (Remember the duality between arrays and pointers in C.)
455 Arrays of this types are represented by a pointer to an array in the
456 world outside Haskell, so this pointer is not followed by the garbage
457 collector.  In other respects they are just like @ByteArray#@.  They
458 are only needed in order to pass values from C to Haskell.
459
460 <sect2>Reading and writing
461 <p>
462
463 Primitive arrays are linear, and indexed starting at zero.
464
465 The size and indices of a @ByteArray#@, @Addr#@, and
466 @MutableByteArray#@ are all in bytes.  It's up to the program to
467 calculate the correct byte offset from the start of the array.  This
468 allows a @ByteArray#@ to contain a mixture of values of different
469 type, which is often needed when preparing data for and unpicking
470 results from C.  (Umm... not true of indices... WDP 95/09)
471
472 <em>Should we provide some @sizeOfDouble#@ constants?</em>
473
474 Out-of-range errors on indexing should be caught by the code which
475 uses the primitive operation; the primitive operations themselves do
476 <em>not</em> check for out-of-range indexes. The intention is that the
477 primitive ops compile to one machine instruction or thereabouts.
478
479 We use the terms ``reading'' and ``writing'' to refer to accessing
480 <em>mutable</em> arrays (see Section~<ref name="Mutable arrays" id="sect:mutable">), and
481 ``indexing'' to refer to reading a value from an <em>immutable</em>
482 array.
483
484 Immutable byte arrays are straightforward to index (all indices in bytes):
485 <tscreen><verb>
486 indexCharArray#   :: ByteArray# -> Int# -> Char#
487 indexIntArray#    :: ByteArray# -> Int# -> Int#
488 indexAddrArray#   :: ByteArray# -> Int# -> Addr#
489 indexFloatArray#  :: ByteArray# -> Int# -> Float#
490 indexDoubleArray# :: ByteArray# -> Int# -> Double#
491
492 indexCharOffAddr#   :: Addr# -> Int# -> Char#
493 indexIntOffAddr#    :: Addr# -> Int# -> Int#
494 indexFloatOffAddr#  :: Addr# -> Int# -> Float#
495 indexDoubleOffAddr# :: Addr# -> Int# -> Double#
496 indexAddrOffAddr#   :: Addr# -> Int# -> Addr#   
497  -- Get an Addr# from an Addr# offset
498 </verb></tscreen>
499 <ncdx>indexCharArray#</ncdx>
500 <ncdx>indexIntArray#</ncdx>
501 <ncdx>indexAddrArray#</ncdx>
502 <ncdx>indexFloatArray#</ncdx>
503 <ncdx>indexDoubleArray#</ncdx>
504 <ncdx>indexCharOffAddr#</ncdx>
505 <ncdx>indexIntOffAddr#</ncdx>
506 <ncdx>indexFloatOffAddr#</ncdx>
507 <ncdx>indexDoubleOffAddr#</ncdx>
508 <ncdx>indexAddrOffAddr#</ncdx>
509
510 The last of these, @indexAddrOffAddr#@, extracts an @Addr#@ using an offset
511 from another @Addr#@, thereby providing the ability to follow a chain of
512 C pointers.
513
514 Something a bit more interesting goes on when indexing arrays of boxed
515 objects, because the result is simply the boxed object. So presumably
516 it should be entered --- we never usually return an unevaluated
517 object!  This is a pain: primitive ops aren't supposed to do
518 complicated things like enter objects.  The current solution is to
519 return a lifted value, but I don't like it!
520
521 <tscreen><verb>
522 indexArray#       :: Array# elt -> Int# -> PrelBase.Lift elt  -- Yuk!
523 </verb></tscreen>
524 <ncdx>indexArray#</ncdx>
525
526
527 <sect2>The state type
528 <p>
529 <ncdx>state, primitive type</ncdx>
530 <ncdx>State#</ncdx>
531
532 The primitive type @State#@ represents the state of a state
533 transformer.  It is parameterised on the desired type of state, which
534 serves to keep states from distinct threads distinct from one another.
535 But the <em>only</em> effect of this parameterisation is in the type
536 system: all values of type @State#@ are represented in the same way.
537 Indeed, they are all represented by nothing at all!  The code
538 generator ``knows'' to generate no code, and allocate no registers
539 etc, for primitive states.
540
541 <tscreen><verb>
542 type State# s
543 </verb></tscreen>
544
545 The type @GHC.RealWorld@ is truly opaque: there are no values defined
546 of this type, and no operations over it.  It is ``primitive'' in that
547 sense - but it is <em>not unboxed!</em> Its only role in life is to be
548 the type which distinguishes the @IO@ state transformer.
549
550 <tscreen><verb>
551 data RealWorld
552 </verb></tscreen>
553
554 <sect2>State of the world
555 <p>
556
557 A single, primitive, value of type @State# RealWorld@ is provided.
558
559 <tscreen><verb>
560 realWorld# :: State# GHC.RealWorld
561 </verb></tscreen>
562 <nidx>realWorld# state object</nidx>
563
564 (Note: in the compiler, not a @PrimOp@; just a mucho magic
565 @Id@. Exported from @GHC@, though).
566
567 <sect2>State pairing types
568 <p>
569 <label id="horrid-pairing-types">
570
571 This subsection defines some types which, while they aren't quite
572 primitive because we can define them in Haskell, are very nearly so.
573 They define constructors which pair a primitive state with a value of
574 each primitive type.  They are required to express the result type of
575 the primitive operations in the state monad.
576 <tscreen><verb>
577 data StateAndPtr#    s elt = StateAndPtr#    (State# s) elt 
578
579 data StateAndChar#   s     = StateAndChar#   (State# s) Char# 
580 data StateAndInt#    s     = StateAndInt#    (State# s) Int# 
581 data StateAndWord#   s     = StateAndWord#   (State# s) Word#
582 data StateAndFloat#  s     = StateAndFloat#  (State# s) Float# 
583 data StateAndDouble# s     = StateAndDouble# (State# s) Double#  
584 data StateAndAddr#   s     = StateAndAddr#   (State# s) Addr#
585
586 data StateAndStablePtr# s a = StateAndStablePtr#  (State# s) (StablePtr# a)
587 data StateAndForeignObj# s  = StateAndForeignObj# (State# s) ForeignObj#
588 data StateAndSynchVar#  s a = StateAndSynchVar#  (State# s) (SynchVar# a)
589
590 data StateAndArray#            s elt = StateAndArray#        (State# s) (Array# elt) 
591 data StateAndMutableArray#     s elt = StateAndMutableArray# (State# s) (MutableArray# s elt)  
592 data StateAndByteArray#        s = StateAndByteArray#        (State# s) ByteArray# 
593 data StateAndMutableByteArray# s = StateAndMutableByteArray# (State# s) (MutableByteArray# s)
594 </verb></tscreen>
595
596 Hideous.
597
598 <sect2>Mutable arrays
599 <p>
600 <label id="sect:mutable">
601 <nidx>mutable arrays</nidx>
602 <nidx>arrays, mutable</nidx>
603
604 Corresponding to @Array#@ and @ByteArray#@, we have the types of
605 mutable versions of each.  In each case, the representation is a
606 pointer to a suitable block of (mutable) heap-allocated storage.
607
608 <tscreen><verb>
609 type MutableArray# s elt
610 type MutableByteArray# s
611 </verb></tscreen>
612 <ncdx>MutableArray#</ncdx>
613 <ncdx>MutableByteArray#</ncdx>
614
615 <sect3>Allocation
616 <p>
617 <nidx>mutable arrays, allocation</nidx>
618 <nidx>arrays, allocation</nidx>
619 <nidx>allocation, of mutable arrays</nidx>
620
621 Mutable arrays can be allocated. Only pointer-arrays are initialised;
622 arrays of non-pointers are filled in by ``user code'' rather than by
623 the array-allocation primitive.  Reason: only the pointer case has to
624 worry about GC striking with a partly-initialised array.
625
626 <tscreen><verb>
627 newArray#       :: Int# -> elt -> State# s -> StateAndMutableArray# s elt 
628
629 newCharArray#   :: Int# -> State# s -> StateAndMutableByteArray# s 
630 newIntArray#    :: Int# -> State# s -> StateAndMutableByteArray# s 
631 newAddrArray#   :: Int# -> State# s -> StateAndMutableByteArray# s 
632 newFloatArray#  :: Int# -> State# s -> StateAndMutableByteArray# s 
633 newDoubleArray# :: Int# -> State# s -> StateAndMutableByteArray# s 
634 </verb></tscreen>
635 <ncdx>newArray#</ncdx>
636 <ncdx>newCharArray#</ncdx>
637 <ncdx>newIntArray#</ncdx>
638 <ncdx>newAddrArray#</ncdx>
639 <ncdx>newFloatArray#</ncdx>
640 <ncdx>newDoubleArray#</ncdx>
641
642 The size of a @ByteArray#@ is given in bytes.
643
644 <sect3>Reading and writing
645 <p>
646 <nidx>arrays, reading and writing</nidx>
647
648 <tscreen><verb>
649 readArray#       :: MutableArray# s elt -> Int# -> State# s -> StateAndPtr#    s elt
650 readCharArray#   :: MutableByteArray# s -> Int# -> State# s -> StateAndChar#   s
651 readIntArray#    :: MutableByteArray# s -> Int# -> State# s -> StateAndInt#    s
652 readAddrArray#   :: MutableByteArray# s -> Int# -> State# s -> StateAndAddr#   s 
653 readFloatArray#  :: MutableByteArray# s -> Int# -> State# s -> StateAndFloat#  s 
654 readDoubleArray# :: MutableByteArray# s -> Int# -> State# s -> StateAndDouble# s 
655
656 writeArray#       :: MutableArray# s elt -> Int# -> elt     -> State# s -> State# s 
657 writeCharArray#   :: MutableByteArray# s -> Int# -> Char#   -> State# s -> State# s 
658 writeIntArray#    :: MutableByteArray# s -> Int# -> Int#    -> State# s -> State# s 
659 writeAddrArray#   :: MutableByteArray# s -> Int# -> Addr#   -> State# s -> State# s 
660 writeFloatArray#  :: MutableByteArray# s -> Int# -> Float#  -> State# s -> State# s 
661 writeDoubleArray# :: MutableByteArray# s -> Int# -> Double# -> State# s -> State# s 
662 </verb></tscreen>
663 <ncdx>readArray#</ncdx>
664 <ncdx>readCharArray#</ncdx>
665 <ncdx>readIntArray#</ncdx>
666 <ncdx>readAddrArray#</ncdx>
667 <ncdx>readFloatArray#</ncdx>
668 <ncdx>readDoubleArray#</ncdx>
669 <ncdx>writeArray#</ncdx>
670 <ncdx>writeCharArray#</ncdx>
671 <ncdx>writeIntArray#</ncdx>
672 <ncdx>writeAddrArray#</ncdx>
673 <ncdx>writeFloatArray#</ncdx>
674 <ncdx>writeDoubleArray#</ncdx>
675
676
677 <sect3>Equality
678 <p>
679 <nidx>arrays, testing for equality</nidx>
680
681 One can take ``equality'' of mutable arrays.  What is compared is the
682 <em>name</em> or reference to the mutable array, not its contents.
683
684 <tscreen><verb>
685 sameMutableArray#     :: MutableArray# s elt -> MutableArray# s elt -> Bool
686 sameMutableByteArray# :: MutableByteArray# s -> MutableByteArray# s -> Bool
687 </verb></tscreen>
688 <ncdx>sameMutableArray#</ncdx>
689 <ncdx>sameMutableByteArray#</ncdx>
690
691 <sect3>Freezing mutable arrays
692 <p>
693 <nidx>arrays, freezing mutable</nidx>
694 <nidx>freezing mutable arrays</nidx>
695 <nidx>mutable arrays, freezing</nidx>
696
697 Only unsafe-freeze has a primitive.  (Safe freeze is done directly in Haskell 
698 by copying the array and then using @unsafeFreeze@.) 
699
700 <tscreen><verb>
701 unsafeFreezeArray#     :: MutableArray# s elt -> State# s -> StateAndArray#     s elt
702 unsafeFreezeByteArray# :: MutableByteArray# s -> State# s -> StateAndByteArray# s
703 </verb></tscreen>
704 <ncdx>unsafeFreezeArray#</ncdx>
705 <ncdx>unsafeFreezeByteArray#</ncdx>
706
707 <sect2>Stable pointers
708 <p>
709 <nidx>stable pointers</nidx>
710 <nidx>pointers, stable</nidx>
711
712 A stable pointer is a name for a Haskell object which can be passed to
713 the external world.  It is ``stable'' in the sense that the name does
714 not change when the Haskell garbage collector runs --- in contrast to
715 the address of the object which may well change.
716
717 The stable pointer type is parameterised by the type of the thing
718 which is named.
719
720 <tscreen><verb>
721 type StablePtr# a
722 </verb></tscreen>
723 <ncdx>StablePtr#</ncdx>
724
725 A stable pointer is represented by an index into the (static)
726 @StablePointerTable@.  The Haskell garbage collector treats the
727 @StablePointerTable@ as a source of roots for GC.
728
729 The @makeStablePointer@ function converts a value into a stable
730 pointer.  It is part of the @IO@ monad, because we want to be sure
731 we don't allocate one twice by accident, and then only free one of the
732 copies.
733
734 <tscreen><verb>
735 makeStablePointer#  :: a -> State# RealWorld -> StateAndStablePtr# RealWorld a
736 freeStablePointer#  :: StablePtr# a -> State# RealWorld -> State# RealWorld
737 deRefStablePointer# :: StablePtr# a -> State# RealWorld -> StateAndPtr RealWorld a
738 </verb></tscreen>
739 <ncdx>makeStablePointer#</ncdx>
740 <ncdx>freeStablePointer#</ncdx>
741 <ncdx>deRefStablePointer#</ncdx>
742
743 There is also a C procedure @FreeStablePtr@ which frees a stable pointer.
744
745 %<em>Andy's comment.</em> {\bf Errors:} The following is not strictly true: the current
746 %implementation is not as polymorphic as claimed.  The reason for this
747 %is that the C programmer will have to use a different entry-routine
748 %for each type of stable pointer.  At present, we only supply a very
749 %limited number (3) of these routines.  It might be possible to
750 %increase the range of these routines by providing general purpose
751 %entry points to apply stable pointers to (stable pointers to)
752 %arguments and to enter (stable pointers to) boxed primitive values.
753 %<em>End of Andy's comment.</em>
754
755 <sect2>Foreign objects
756 <p>
757 <nidx>Foreign objects</nidx>
758
759 A @ForeignObj#@ is a reference to an object outside the Haskell world
760 (i.e., from the C world, or a reference to an object on another
761 machine completely.), where the Haskell world has been told ``Let me
762 know when you're finished with this ...''.
763
764 <tscreen><verb>
765 type ForeignObj#
766 </verb></tscreen>
767 <ncdx>ForeignObj#</ncdx>
768
769 GHC provides two primitives on @ForeignObj#@:
770
771 <tscreen><verb>
772 makeForeignObj# 
773         :: Addr# -- foreign reference
774         -> Addr# -- pointer to finalisation routine
775         -> StateAndForeignObj# RealWorld ForeignObj#
776 writeForeignObj 
777         :: ForeignObj#        -- foreign object
778         -> Addr#              -- datum
779         -> State# RealWorld
780         -> State# RealWorld
781 </verb></tscreen>
782 <ncdx>makeForeignObj#</ncdx>
783 <ncdx>writeForeignObj#</ncdx>
784
785 The module @Foreign@ (Section <ref name="Foreign objects"
786 id="sec:foreign-obj">) provides a more programmer-friendly interface
787 to foreign objects.
788
789 <sect2>Synchronizing variables (M-vars)
790 <p>
791 <nidx>synchronising variables (M-vars)</nidx>
792 <nidx>M-Vars</nidx>
793
794 Synchronising variables are the primitive type used to implement
795 Concurrent Haskell's MVars (see the Concurrent Haskell paper for
796 the operational behaviour of these operations).
797
798 <tscreen><verb>
799 type SynchVar# s elt    -- primitive
800
801 newSynchVar#:: State# s -> StateAndSynchVar# s elt
802 takeMVar#   :: SynchVar# s elt -> State# s -> StateAndPtr# s elt
803 putMVar#    :: SynchVar# s elt -> State# s -> State# s
804 </verb></tscreen>
805 <ncdx>SynchVar#</ncdx>
806 <ncdx>newSynchVar#</ncdx>
807 <ncdx>takeMVar</ncdx>
808 <ncdx>putMVar</ncdx>
809
810 <sect2>@spark#@ primitive operation (for parallel execution)
811 <p>
812 <nidx>spark primitive operation</nidx>
813
814 <em>ToDo: say something</em>  It's used in the unfolding for @par@.
815
816 <sect2>The @errorIO#@ primitive operation
817 <p>
818 <nidx>errors, primitive</nidx>
819
820 The @errorIO#@ primitive takes an argument much like @IO@.  It aborts
821 execution of the current program, and continues instead by performing
822 the given @IO@-like value on the current state of the world.
823
824 <tscreen><verb>
825 errorIO# :: (State# RealWorld# -> a) -> a
826 </verb></tscreen>
827 <ncdx>errorIO#</ncdx>
828
829 <sect1>GHC/Hugs Extension Libraries
830 <p>
831
832 The extension libraries provided by both GHC and Hugs are described in
833 the <htmlurl name="GHC/Hugs Extension Libraries" url="libs.html">
834 document.
835
836 <sect1>GHC-only Extension Libraries
837 <p>
838 <nidx>libraries, ghc-only</nidx>
839 <nidx>extension libraries, ghc-only</nidx>
840
841 If you rely on the implicit @import Prelude@ that GHC normally does
842 for you, and if you don't use any weird flags (notably
843 @-fglasgow-exts@), and if you don't import the Glasgow extensions
844 interface, @GlaExts@, then GHC should work <em>exactly</em> as the
845 Haskell report says (modulo a few minor issues, see Section <ref
846 id="vs-Haskell-defn" name="Language Non-compliance">).
847
848 If you turn on @-fglasgow-exts@, the compiler will recognise and parse
849 unboxed values properly, and provide access to the various interfaces
850 libraries described here.
851
852 <sect2>The @GlaExts@ interface
853 <p>
854 <nidx>GlaExts interface (GHC extensions)</nidx>
855
856 The @GlaExts@ interface provides access to extensions that only GHC
857 implements.  These currently are: unboxed types, including the
858 representations of the primitive types (Int, Float, etc.), and the
859 GHC primitive operations (@+#@, @==#@, etc.).
860
861 This module used to provide access to all the Glasgow extensions, but
862 these have since been moved into separate libraries for compatibility
863 with Hugs (version 2.09: in fact, you can still get at this stuff via
864 @GlaExts@ for compatibility, but this facility will likely be removed
865 in the future).
866
867 <tscreen><verb>
868 -- the representation of some basic types:
869 data Char    = C# Char#
870 data Int     = I# Int#
871 data Addr    = A# Addr#
872 data Word    = W# Word#
873 data Float   = F# Float#
874 data Double  = D# Double#
875 data Integer = J# Int# Int# ByteArray#
876
877 module GHC  -- all primops and primitive types.
878 </verb></tscreen>
879
880 <sect2>The @MutableArray@ interface
881 <label id="sec:mutable-array">
882 <p>
883 <nidx>MutableArray interface (GHC extensions)</nidx>
884
885 The @MutableArray@ interface defines a general set of operations over
886 mutable arrays (@MutableArray@) and mutable chunks of memory
887 (@MutableByteArray@):
888
889 <tscreen><verb>
890 data MutableArray s ix elt -- abstract
891 data MutableByteArray s ix -- abstract
892                            -- instance of : CCallable
893 -- Creators:
894 newArray           :: Ix ix => (ix,ix) -> elt -> ST s (MutableArray s ix elt)
895 newCharArray       :: Ix ix => (ix,ix) -> ST s (MutableByteArray s ix) 
896 newAddrArray       :: Ix ix => (ix,ix) -> ST s (MutableByteArray s ix) 
897 newIntArray        :: Ix ix => (ix,ix) -> ST s (MutableByteArray s ix) 
898 newFloatArray      :: Ix ix => (ix,ix) -> ST s (MutableByteArray s ix) 
899 newDoubleArray     :: Ix ix => (ix,ix) -> ST s (MutableByteArray s ix) 
900
901 boundsOfArray      :: Ix ix => MutableArray s ix elt -> (ix, ix)  
902 boundsOfByteArray  :: Ix ix => MutableByteArray s ix -> (ix, ix)
903
904
905 readArray          :: Ix ix => MutableArray s ix elt -> ix -> ST s elt 
906
907 readCharArray      :: Ix ix => MutableByteArray s ix -> ix -> ST s Char 
908 readIntArray       :: Ix ix => MutableByteArray s ix -> ix -> ST s Int
909 readAddrArray      :: Ix ix => MutableByteArray s ix -> ix -> ST s Addr
910 readFloatArray     :: Ix ix => MutableByteArray s ix -> ix -> ST s Float
911 readDoubleArray    :: Ix ix => MutableByteArray s ix -> ix -> ST s Double
912
913 writeArray         :: Ix ix => MutableArray s ix elt -> ix -> elt -> ST s () 
914 writeCharArray     :: Ix ix => MutableByteArray s ix -> ix -> Char -> ST s () 
915 writeIntArray      :: Ix ix => MutableByteArray s ix -> ix -> Int  -> ST s () 
916 writeAddrArray     :: Ix ix => MutableByteArray s ix -> ix -> Addr -> ST s () 
917 writeFloatArray    :: Ix ix => MutableByteArray s ix -> ix -> Float -> ST s () 
918 writeDoubleArray   :: Ix ix => MutableByteArray s ix -> ix -> Double -> ST s () 
919
920 freezeArray        :: Ix ix => MutableArray s ix elt -> ST s (Array ix elt)
921 freezeCharArray    :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
922 freezeIntArray     :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
923 freezeAddrArray    :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
924 freezeFloatArray   :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
925 freezeDoubleArray  :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
926
927 unsafeFreezeArray     :: Ix ix => MutableArray s ix elt -> ST s (Array ix elt)  
928 unsafeFreezeByteArray :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
929 thawArray             :: Ix ix => Array ix elt -> ST s (MutableArray s ix elt)
930 </verb></tscreen>
931
932 %ToDo: index these.
933
934 <sect2>The @ByteArray@ interface
935 <label id="sec:byte-array">
936 <p>
937 <nidx>ByteArray interface (GHC extensions)</nidx>
938
939 @ByteArray@s are chunks of immutable Haskell heap:
940
941 <tscreen><verb>
942 data ByteArray ix -- abstract
943                   -- instance of: CCallable
944
945 indexCharArray     :: Ix ix => ByteArray ix -> ix -> Char 
946 indexIntArray      :: Ix ix => ByteArray ix -> ix -> Int
947 indexAddrArray     :: Ix ix => ByteArray ix -> ix -> Addr
948 indexFloatArray    :: Ix ix => ByteArray ix -> ix -> Float
949 indexDoubleArray   :: Ix ix => ByteArray ix -> ix -> Double
950
951 indexCharOffAddr   :: Addr -> Int -> Char
952 indexIntOffAddr    :: Addr -> Int -> Int
953 indexAddrOffAddr   :: Addr -> Int -> Addr
954 indexFloatOffAddr  :: Addr -> Int -> Float
955 indexDoubleOffAddr :: Addr -> Int -> Double
956 </verb></tscreen>
957
958 <sect2>Stable pointers
959 <p>
960
961 Nothing exciting here, just simple boxing up.
962 <tscreen><verb>
963 data StablePtr a = StablePtr (StablePtr# a)
964
965 makeStablePointer :: a -> StablePtr a
966 freeStablePointer :: StablePtr a -> IO ()
967 </verb></tscreen>
968
969 <sect2>Foreign objects
970 <label id="sec:foreign-obj">
971 <p>
972 <nidx>Foreign objects</nidx>
973
974 This module provides the @ForeignObj@ type and wrappers around the
975 primitive operations on foreign objects.
976
977 <tscreen><verb>
978 data ForeignObj = ForeignObj ForeignObj#
979
980 makeForeignObj 
981         :: Addr   -- object to be boxed up as a ForeignObj
982         -> Addr   -- finaliser 
983         -> IO ForeignObj
984
985 writeForeignObj 
986         :: ForeignObj   -- previously created foreign object
987         -> Addr         -- new value
988         -> IO ()
989
990 </verb></tscreen>
991 <ncdx>ForeignObj</ncdx>
992 <ncdx>makeForeignObj</ncdx>
993 <ncdx>writeForeignObj</ncdx>
994
995 A typical use of @ForeignObj@ is in constructing Haskell bindings
996 to external libraries. A good example is that of writing a binding to
997 an image-processing library (which was actually the main motivation
998 for implementing @ForeignObj@'s precursor, @MallocPtr#@). The
999 images manipulated are not stored in the Haskell heap, either because
1000 the library insist on allocating them internally or we (sensibly)
1001 decide to spare the GC from having to heave heavy images around.
1002
1003 <tscreen><verb>
1004 data Image = Image ForeignObj
1005 </verb></tscreen>
1006
1007 The @ForeignObj@ type is then used to refer to the externally
1008 allocated image, and to acheive some type safety, the Haskell binding
1009 defines the @Image@ data type. So, a value of type @ForeignObj@ is
1010 used to ``box'' up an external reference into a Haskell heap object
1011 that we can then indirectly reference:
1012
1013 <tscreen><verb>
1014 createImage :: (Int,Int) -> IO Image
1015 </verb></tscreen>
1016
1017 So far, this looks just like an @Addr@ type, but @ForeignObj@ offers a
1018 bit more, namely that we can specify a <em>finalisation routine</em> to
1019 invoke when the @ForeignObj@ is discarded by the GC. The garbage
1020 collector invokes the finalisation routine associated with the
1021 @ForeignObj@, saying `` Thanks, I'm through with this now..'' For the
1022 image-processing library, the finalisation routine could for the
1023 images free up memory allocated for them. The finalisation routine has
1024 currently to be written in C (the finalisation routine can in turn
1025 call on @FreeStablePtr@ to deallocate a stable pointer).
1026
1027 Associating a finalisation routine with an external object is done by
1028 calling @makeForeignObj@.  {\bf Note:} the foreign object value and
1029 its finaliser are contained in the @ForeignObj@, so there's no danger
1030 of an aggressive optimiser somehow separating the two (with the result
1031 that the foreign reference would not be freed).
1032
1033 (Implementation: a linked list of all @ForeignObj#@s is maintained to
1034  allow the garbage collector to detect when a @ForeignObj#@ becomes
1035  garbage.)
1036
1037 Like @Array@, @ForeignObj#@s are represented by heap objects.
1038
1039 Upon controlled termination of the Haskell program, all @ForeignObjs@
1040 are freed, invoking their respective finalisers before terminating.
1041
1042 <sect2>The @CCall@ module
1043 <p>
1044
1045 The @CCall@ module defines the classes @CCallable@ and @CReturnable@,
1046 along with instances for the primitive types (@Int@, @Int#@, @Float@,
1047 @Float#@ etc.)  GHC knows to import this module if you use @_ccall_@,
1048 but if you need to define your own instances of these classes, you
1049 will need to import @CCall@ explicitly.
1050
1051 More information on how to use @_ccall_@ can be found in Section
1052 <ref name="Calling~C directly from Haskell" id="glasgow-ccalls">.
1053