2 \documentstyle[a4wide,grasp]{article}
4 \renewcommand{\textfraction}{0.1}
5 \renewcommand{\floatpagefraction}{0.9}
6 \renewcommand{\dblfloatpagefraction}{0.9}
9 \renewcommand{\today}{November 1997}
13 \title{The GHC Prelude and Libraries}
14 \author{Simon L Peyton Jones \and Simon Marlow \and Will Partain}
22 \section[ghc-prelude]{The GHC prelude and libraries}
24 This document describes GHC's prelude and libraries. The basic story is that of
25 the Haskell 1.4 Report and Libraries document (which we do not reproduce here),
26 but this document describes in addition:
28 \item GHC's additional non-standard libraries and types, such as
29 state transformers, packed strings, foreign objects, stable
32 \item GHC's primitive types and operations. The standard Haskell
33 functions are implemented on top of these, and it is sometimes
34 useful to use them directly.
36 \item The organisation of these libraries into directories.
37 \item Short description of programmer interface to the non-standard,
38 `built-in' libraries provided in addition to the standard
39 prelude and libraries.
42 In addition to the GHC prelude libraries, GHC comes with a number of
43 system libraries, which are presented in Section \ref{syslibs}.
45 \subsection{Prelude library organisation}
47 {\em Probably only of interest to implementors...}
49 The prelude libraries are organised into the following three groups,
50 each of which is kept in a separate sub-directory of GHC's source
53 \item[@lib/required/@] These are the libraries {\em required} by the
54 Haskell definition. All are defined by the Haskell Report, or by the
55 Haskell Libraries Report.
56 They currently comprise:
58 \item @Array@: monolithic arrays.
59 \item @Char@: more functions on characters.
60 \item @Complex@: interface defining complex number type and functions
62 \item @CPUTime@: get the CPU time used by the program.
63 \item @Directory@: basic functions for accessing the file system.
64 \item @Ix@: the @Ix@ class of indexing operations.
65 \item @IO@: additional input/output functions.
66 \item @List@: more functions on lists.
67 \item @Locale@: localisation functions.
68 \item @Maybe@: more functions on @Maybe@ types.
69 \item @Monad@: functions on monads.
70 \item @Numeric@: operations for reading and showing number values.
71 \item @Prelude@: standard prelude interface.
72 \item @Random@: pseudo-random number generator.
73 \item @Ratio@: functions on rational numbers.
74 \item @System@: basic operating-system interface functions.
75 \item @Time@: operations on time.
78 \item[@lib/glaExts@] Extension libraries, currently comprising:
80 \item @Addr@: primitive pointer type.
81 \item @Bits@: a class of bitwise operations.
82 \item @ByteArray@: operations over immutable chunks of (heap allocated) bytes.
83 \item @CCall@: classes @CCallable@ and @CReturnable@ for calling C.
84 \item @Foreign@: types and operations for GHC's foreign-language
86 \item @GlaExts@: interface for extensions that are only implemented in
87 GHC: namely unboxed types and primitive operations.
88 \item @IOExts@: extensions to the @IO@ library.
89 \item @Int@: 8, 16, 32 and 64-bit integers with bit operations.
90 \item @LazyST@: a lazy version of the @ST@ monad.
91 \item @MutableArray@: operations over mutable arrays.
92 \item @ST@: the state transformer monad, @STRef@s and @STArray@s.
93 \item @Word@: 8, 16, 32 and 64-bit naturals with bit operations.
96 \item[@lib/concurrent@] GHC extension libraries to support Concurrent Haskell, currently comprising:
98 \item @Concurrent@: main library.
99 \item @Parallel@: stuff for multi-processor parallelism.
107 \item[@lib/ghc@] These libraries are the pieces on which all the
108 others are built. They aren't typically imported by Joe Programmer,
109 but there's nothing to stop you doing so if you want. In general, the
110 modules prefixed by @Prel@ are pieces that go towards building
114 \item @GHC@: this ``library'' brings into scope all the primitive
115 types and operations, such as @Int#@, @+#@, @encodeFloat#@, etc etc.
116 It is unique in that there is no Haskell source code for it. Details
117 in Section \ref{sect:ghc}.
119 \item @PrelBase@: defines the basic types and classes without which
120 very few Haskell programs can work. The classes are: @Eq@, @Ord@,
121 @Enum@, @Bounded@, @Num@, @Show@, @Eval@, @Monad@, @MonadZero@,
122 @MonadPlus@. The types are: list, @Bool@, @Char@, @Ordering@,
123 @String@, @Int@, @Integer@.
125 \item @PrelMaybe@: defines the @Maybe@ type.
127 \item @PrelEither@: defines the @Either@ type.
129 \item @PrelTup@: defines tuples and their instances.
131 \item @PrelList@: defines most of the list operations required by
132 @Prelude@. (A few are in @PrelBase@, to avoid gratuitous mutual
133 recursion between modules.)
135 \item @PrelNum@ defines: the numeric classes beyond @Num@, namely
136 @Real@, @Integral@, @Fractional@, @Floating@, @RealFrac@, @RealFloat@;
137 instances for appropriate classes for @Int@ and @Integer@; the types
138 @Float@, @Double@, and @Ratio@ and their instances.
140 \item @PrelRead@: the @Read@ class and all its instances. It's kept
141 separate because many programs don't use @Read@ at all, so we don't
142 even want to link in its code. (If the prelude libraries are built by
143 splitting the object files, this is all a non-issue)
145 \item @ConcBase@: substrate stuff for Concurrent Haskell.
147 \item @IOBase@: substrate stuff for the main I/O libraries.
148 \item @IOHandle@: large blob of code for doing I/O on handles.
149 \item @PrelIO@: the remaining small pieces to produce the I/O stuff
152 \item @STBase@: substrate stuff for @ST@.
153 \item @ArrBase@: substrate stuff for @Array@.
155 \item @GHCerr@: error reporting code, called from code that the
156 compiler plants in compiled programs.
158 \item @GHCmain@: the definition of @mainIO@, which is what {\em
159 really} gets called by the runtime system. @mainIO@ in turn
162 \item @PackBase@: low-level packing/unpacking operations.
164 \item @Error@: the definition of @error@, placed in its own module
165 with a hand-written @.hi-boot@ file in order to break recursive
166 dependencies in the libraries (everything needs @error@, but the
167 definition of @error@ itself needs a few things...).
171 The @...Base@ modules generally export representation information that
172 is hidden from the public interface. For example the module @STBase@
173 exports the type @ST@ including its representation, whereas the module
174 @ST@ exports @ST@ abstractly.
176 None of these modules are involved in any mutual recursion, with the
177 sole exception that many modules import @Error.error@.
179 \subsection[ghc-libs-ghc]{The module @GHC@: really primitive stuff}
182 This section defines all the types which are primitive in Glasgow
183 Haskell, and the operations provided for them.
185 A primitive type is one which cannot be defined in Haskell, and which
186 is therefore built into the language and compiler. Primitive types
187 are always unboxed; that is, a value of primitive type cannot be
190 Primitive values are often represented by a simple bit-pattern, such
191 as @Int#@, @Float#@, @Double#@. But this is not necessarily the case:
192 a primitive value might be represented by a pointer to a
193 heap-allocated object. Examples include @Array#@, the type of
194 primitive arrays. You might think this odd: doesn't being
195 heap-allocated mean that it has a box? No, it does not. A primitive
196 array is heap-allocated because it is too big a value to fit in a
197 register, and would be too expensive to copy around; in a sense, it is
198 accidental that it is represented by a pointer. If a pointer
199 represents a primitive value, then it really does point to that value:
200 no unevaluated thunks, no indirections...nothing can be at the other
201 end of the pointer than the primitive value.
203 This section also describes a few non-primitive types, which are needed
204 to express the result types of some primitive operations.
206 \subsubsection{Character and numeric types}
208 There are the following obvious primitive types:
211 type Int# -- see also Word# and Addr#, later
215 If you really want to know their exact equivalents in C, see
216 @ghc/includes/StgTypes.lh@ in the GHC source tree.
218 Literals for these types may be written as follows:
223 'a'# a Char#; for weird characters, use '\o<octal>'#
224 "a"# an Addr# (a `char *')
227 \subsubsubsection{Comparison operations}
229 {>,>=,==,/=,<,<=}# :: Int# -> Int# -> Bool
231 {gt,ge,eq,ne,lt,le}Char# :: Char# -> Char# -> Bool
232 -- ditto for Word#, Float#, Double#, and Addr#
235 \subsubsubsection{Unboxed-character operations}
237 ord# :: Char# -> Int#
238 chr# :: Int# -> Char#
242 \subsubsubsection{Unboxed-@Int@ operations}
244 {+,-,*,quotInt,remInt}# :: Int# -> Int# -> Int#
245 negateInt# :: Int# -> Int#
247 iShiftL#, iShiftRA#, iShiftRL# :: Int# -> Int# -> Int#
248 -- shift left, right arithmetic, right logical
251 {\bf Note:} No error/overflow checking!
253 \subsubsubsection{Unboxed-@Double@ and @Float@ operations}
255 {plus,minus,times,divide}Double# :: Double# -> Double# -> Double#
256 negateDouble# :: Double# -> Double#
258 float2Int# :: Double# -> Int# -- just a cast, no checking!
259 int2Double# :: Int# -> Double#
261 expDouble# :: Double# -> Double#
262 logDouble# :: Double# -> Double#
263 sqrtDouble# :: Double# -> Double#
264 sinDouble# :: Double# -> Double#
265 cosDouble# :: Double# -> Double#
266 tanDouble# :: Double# -> Double#
267 asinDouble# :: Double# -> Double#
268 acosDouble# :: Double# -> Double#
269 atanDouble# :: Double# -> Double#
270 sinhDouble# :: Double# -> Double#
271 coshDouble# :: Double# -> Double#
272 tanhDouble# :: Double# -> Double#
273 powerDouble# :: Double# -> Double# -> Double#
276 There's an exactly-matching set of unboxed-@Float@ ops; replace
277 @Double#@ with @Float#@ in the list above. There are two
278 coercion functions for @Float#@/@Double#@:
280 float2Double# :: Float# -> Double#
281 double2Float# :: Double# -> Float#
284 The primitive versions of @encodeDouble@/@decodeDouble@:
286 encodeDouble# :: Int# -> Int# -> ByteArray# -- Integer mantissa
287 -> Int# -- Int exponent
290 decodeDouble# :: Double# -> PrelNum.ReturnIntAndGMP
293 (And the same for @Float#@s.)
295 \subsubsection{Operations on/for @Integers@ (interface to GMP)}
296 \label{sect:horrid-Integer-pairing-types}
298 We implement @Integers@ (arbitrary-precision integers) using the GNU
299 multiple-precision (GMP) package (version 1.3.2).
301 {\bf Note:} some of this might change when we upgrade to using GMP~2.x.
303 The data type for @Integer@ must mirror that for @MP_INT@ in @gmp.h@
304 (see @gmp.info@ in \tr{ghc/includes/runtime/gmp}). It comes out as:
306 data Integer = J# Int# Int# ByteArray#
309 So, @Integer@ is really just a ``pairing'' type for a particular
310 collection of primitive types.
312 The operations in the GMP return other combinations of
313 GMP-plus-something, so we need ``pairing'' types for those, too:
315 data Return2GMPs = Return2GMPs Int# Int# ByteArray# Int# Int# ByteArray#
316 data ReturnIntAndGMP = ReturnIntAndGMP Int# Int# Int# ByteArray#
318 -- ????? something to return a string of bytes (in the heap?)
321 The primitive ops to support @Integers@ use the ``pieces'' of the
322 representation, and are as follows:
324 negateInteger# :: Int# -> Int# -> ByteArray# -> Integer
326 {plus,minus,times}Integer# :: Int# -> Int# -> ByteArray#
327 -> Int# -> Int# -> ByteArray#
330 cmpInteger# :: Int# -> Int# -> ByteArray#
331 -> Int# -> Int# -> ByteArray#
332 -> Int# -- -1 for <; 0 for ==; +1 for >
334 divModInteger#, quotRemInteger#
335 :: Int# -> Int# -> ByteArray#
336 -> Int# -> Int# -> ByteArray#
337 -> PrelNum.Return2GMPs
339 integer2Int# :: Int# -> Int# -> ByteArray# -> Int#
341 int2Integer# :: Int# -> Integer -- NB: no error-checking on these two!
342 word2Integer# :: Word# -> Integer
344 addr2Integer# :: Addr# -> Integer
345 -- the Addr# is taken to be a `char *' string
346 -- to be converted into an Integer.
350 \subsubsection{Words and addresses}
352 A @Word#@ is used for bit-twiddling operations. It is the same size as
353 an @Int#@, but has no sign nor any arithmetic operations.
355 type Word# -- Same size/etc as Int# but *unsigned*
356 type Addr# -- A pointer from outside the "Haskell world" (from C, probably);
357 -- described under "arrays"
360 @Word#@s and @Addr#@s have the usual comparison operations.
361 Other unboxed-@Word@ ops (bit-twiddling and coercions):
363 and#, or#, xor# :: Word# -> Word# -> Word#
366 quotWord#, remWord# :: Word# -> Word# -> Word#
367 -- word (i.e. unsigned) versions are different from int
368 -- versions, so we have to provide these explicitly.
370 not# :: Word# -> Word#
372 shiftL#, shiftRA#, shiftRL# :: Word# -> Int# -> Word#
373 -- shift left, right arithmetic, right logical
375 int2Word# :: Int# -> Word# -- just a cast, really
376 word2Int# :: Word# -> Int#
379 Unboxed-@Addr@ ops (C casts, really):
381 int2Addr# :: Int# -> Addr#
382 addr2Int# :: Addr# -> Int#
385 The casts between @Int#@, @Word#@ and @Addr#@ correspond to null
386 operations at the machine level, but are required to keep the Haskell
389 Operations for indexing off of C pointers (@Addr#@s) to snatch values
390 are listed under ``arrays''.
392 \subsubsection{Arrays}
394 The type @Array# elt@ is the type of primitive, unboxed arrays of
395 values of type @elt@.
401 @Array#@ is more primitive than a Haskell array --- indeed, the
402 Haskell @Array@ interface is implemented using @Array#@ --- in that an
403 @Array#@ is indexed only by @Int#@s, starting at zero. It is also
404 more primitive by virtue of being unboxed. That doesn't mean that it
405 isn't a heap-allocated object --- of course, it is. Rather, being
406 unboxed means that it is represented by a pointer to the array itself,
407 and not to a thunk which will evaluate to the array (or to bottom).
408 The components of an @Array#@ are themselves boxed.
410 The type @ByteArray#@ is similar to @Array#@, except that it contains
411 just a string of (non-pointer) bytes.
417 Arrays of these types are useful when a Haskell program wishes to
418 construct a value to pass to a C procedure. It is also possible to
419 use them to build (say) arrays of unboxed characters for internal use
420 in a Haskell program. Given these uses, @ByteArray#@ is deliberately
421 a bit vague about the type of its components. Operations are provided
422 to extract values of type @Char#@, @Int#@, @Float#@, @Double#@, and
423 @Addr#@ from arbitrary offsets within a @ByteArray#@. (For type
424 @Foo#@, the $i$th offset gets you the $i$th @Foo#@, not the @Foo#@ at
425 byte-position $i$. Mumble.) (If you want a @Word#@, grab an @Int#@,
428 Lastly, we have static byte-arrays, of type @Addr#@ [mentioned
429 previously]. (Remember the duality between arrays and pointers in C.)
430 Arrays of this types are represented by a pointer to an array in the
431 world outside Haskell, so this pointer is not followed by the garbage
432 collector. In other respects they are just like @ByteArray#@. They
433 are only needed in order to pass values from C to Haskell.
435 \subsubsubsection{Reading and writing.}
437 Primitive arrays are linear, and indexed starting at zero.
439 The size and indices of a @ByteArray#@, @Addr#@, and
440 @MutableByteArray#@ are all in bytes. It's up to the program to
441 calculate the correct byte offset from the start of the array. This
442 allows a @ByteArray#@ to contain a mixture of values of different
443 type, which is often needed when preparing data for and unpicking
444 results from C. (Umm... not true of indices... WDP 95/09)
446 {\em Should we provide some @sizeOfDouble#@ constants?}
448 Out-of-range errors on indexing should be caught by the code which
449 uses the primitive operation; the primitive operations themselves do
450 {\em not} check for out-of-range indexes. The intention is that the
451 primitive ops compile to one machine instruction or thereabouts.
453 We use the terms ``reading'' and ``writing'' to refer to accessing
454 {\em mutable} arrays (see Section~\ref{sect:mutable}), and
455 ``indexing'' to refer to reading a value from an {\em immutable}
458 Immutable byte arrays are straightforward to index (all indices in bytes):
460 indexCharArray# :: ByteArray# -> Int# -> Char#
461 indexIntArray# :: ByteArray# -> Int# -> Int#
462 indexAddrArray# :: ByteArray# -> Int# -> Addr#
463 indexFloatArray# :: ByteArray# -> Int# -> Float#
464 indexDoubleArray# :: ByteArray# -> Int# -> Double#
466 indexCharOffAddr# :: Addr# -> Int# -> Char#
467 indexIntOffAddr# :: Addr# -> Int# -> Int#
468 indexFloatOffAddr# :: Addr# -> Int# -> Float#
469 indexDoubleOffAddr# :: Addr# -> Int# -> Double#
470 indexAddrOffAddr# :: Addr# -> Int# -> Addr#
471 -- Get an Addr# from an Addr# offset
473 \index{indexCharArray# function}
474 \index{indexIntArray# function}
475 \index{indexAddrArray# function}
476 \index{indexFloatArray# function}
477 \index{indexDoubleArray# function}
478 \index{indexCharOffAddr# function}
479 \index{indexIntOffAddr# function}
480 \index{indexFloatOffAddr# function}
481 \index{indexDoubleOffAddr# function}
482 \index{indexAddrOffAddr# function}
484 The last of these, @indexAddrOffAddr#@, extracts an @Addr#@ using an offset
485 from another @Addr#@, thereby providing the ability to follow a chain of
488 Something a bit more interesting goes on when indexing arrays of boxed
489 objects, because the result is simply the boxed object. So presumably
490 it should be entered --- we never usually return an unevaluated
491 object! This is a pain: primitive ops aren't supposed to do
492 complicated things like enter objects. The current solution is to
493 return a lifted value, but I don't like it!
495 indexArray# :: Array# elt -> Int# -> PrelBase.Lift elt -- Yuk!
499 \subsubsection{The state type}
502 The primitive type @State#@ represents the state of a state transformer.
503 It is parameterised on the desired type of state, which serves to keep
504 states from distinct threads distinct from one another. But the {\em only}
505 effect of this parameterisation is in the type system: all values of type
506 @State#@ are represented in the same way. Indeed, they are all
507 represented by nothing at all! The code generator ``knows'' to generate no
508 code, and allocate no registers etc, for primitive states.
514 The type @GHC.RealWorld@ is truly opaque: there are no values defined
515 of this type, and no operations over it. It is ``primitive'' in that
516 sense---but it is {\em not unboxed!} Its only role in life is to be
517 the type which distinguishes the @IO@ state transformer.
522 \subsubsubsection{State of the world}
524 A single, primitive, value of type @State# RealWorld@ is provided.
526 realWorld# :: State# GHC.RealWorld
528 \index{realWorld# state object}
530 (Note: in the compiler, not a @PrimOp@; just a mucho magic
531 @Id@. Exported from @GHC@, though).
533 \subsubsection{State pairing types}
534 \label{sect:horrid-pairing-types}
536 This subsection defines some types which, while they aren't quite
537 primitive because we can define them in Haskell, are very nearly so.
538 They define constructors which pair a primitive state with a value of
539 each primitive type. They are required to express the result type of
540 the primitive operations in the state monad.
542 data StateAndPtr# s elt = StateAndPtr# (State# s) elt
544 data StateAndChar# s = StateAndChar# (State# s) Char#
545 data StateAndInt# s = StateAndInt# (State# s) Int#
546 data StateAndWord# s = StateAndWord# (State# s) Word#
547 data StateAndFloat# s = StateAndFloat# (State# s) Float#
548 data StateAndDouble# s = StateAndDouble# (State# s) Double#
549 data StateAndAddr# s = StateAndAddr# (State# s) Addr#
551 data StateAndStablePtr# s a = StateAndStablePtr# (State# s) (StablePtr# a)
552 data StateAndForeignObj# s = StateAndForeignObj# (State# s) ForeignObj#
553 data StateAndSynchVar# s a = StateAndSynchVar# (State# s) (SynchVar# a)
555 data StateAndArray# s elt = StateAndArray# (State# s) (Array# elt)
556 data StateAndMutableArray# s elt = StateAndMutableArray# (State# s) (MutableArray# s elt)
557 data StateAndByteArray# s = StateAndByteArray# (State# s) ByteArray#
558 data StateAndMutableByteArray# s = StateAndMutableByteArray# (State# s) (MutableByteArray# s)
563 \subsubsection{Mutable arrays}
565 \index{Mutable arrays}
567 Corresponding to @Array#@ and @ByteArray#@, we have the types of
568 mutable versions of each. In each case, the representation is a
569 pointer to a suitable block of (mutable) heap-allocated storage.
571 type MutableArray# s elt
572 type MutableByteArray# s
575 \subsubsubsection{Allocation}
576 \index{Mutable arrays, allocation}
577 \index{Allocation, of mutable arrays}
579 Mutable arrays can be allocated. Only pointer-arrays are initialised;
580 arrays of non-pointers are filled in by ``user code'' rather than by
581 the array-allocation primitive. Reason: only the pointer case has to
582 worry about GC striking with a partly-initialised array.
585 newArray# :: Int# -> elt -> State# s -> StateAndMutableArray# s elt
587 newCharArray# :: Int# -> State# s -> StateAndMutableByteArray# s
588 newIntArray# :: Int# -> State# s -> StateAndMutableByteArray# s
589 newAddrArray# :: Int# -> State# s -> StateAndMutableByteArray# s
590 newFloatArray# :: Int# -> State# s -> StateAndMutableByteArray# s
591 newDoubleArray# :: Int# -> State# s -> StateAndMutableByteArray# s
594 The size of a @ByteArray#@ is given in bytes.
596 \subsubsubsection{Reading and writing}
598 %OLD: Remember, offsets in a @MutableByteArray#@ are in bytes.
600 readArray# :: MutableArray# s elt -> Int# -> State# s -> StateAndPtr# s elt
601 readCharArray# :: MutableByteArray# s -> Int# -> State# s -> StateAndChar# s
602 readIntArray# :: MutableByteArray# s -> Int# -> State# s -> StateAndInt# s
603 readAddrArray# :: MutableByteArray# s -> Int# -> State# s -> StateAndAddr# s
604 readFloatArray# :: MutableByteArray# s -> Int# -> State# s -> StateAndFloat# s
605 readDoubleArray# :: MutableByteArray# s -> Int# -> State# s -> StateAndDouble# s
607 writeArray# :: MutableArray# s elt -> Int# -> elt -> State# s -> State# s
608 writeCharArray# :: MutableByteArray# s -> Int# -> Char# -> State# s -> State# s
609 writeIntArray# :: MutableByteArray# s -> Int# -> Int# -> State# s -> State# s
610 writeAddrArray# :: MutableByteArray# s -> Int# -> Addr# -> State# s -> State# s
611 writeFloatArray# :: MutableByteArray# s -> Int# -> Float# -> State# s -> State# s
612 writeDoubleArray# :: MutableByteArray# s -> Int# -> Double# -> State# s -> State# s
616 \subsubsubsection{Equality.}
618 One can take ``equality'' of mutable arrays. What is compared is the
619 {\em name} or reference to the mutable array, not its contents.
621 sameMutableArray# :: MutableArray# s elt -> MutableArray# s elt -> Bool
622 sameMutableByteArray# :: MutableByteArray# s -> MutableByteArray# s -> Bool
626 \subsubsubsection{Freezing mutable arrays}
628 Only unsafe-freeze has a primitive. (Safe freeze is done directly in Haskell
629 by copying the array and then using @unsafeFreeze@.)
631 unsafeFreezeArray# :: MutableArray# s elt -> State# s -> StateAndArray# s elt
632 unsafeFreezeByteArray# :: MutableByteArray# s -> State# s -> StateAndByteArray# s
636 \subsubsection{Stable pointers}
637 \index{Stable pointers}
639 A stable pointer is a name for a Haskell object which can be passed to
640 the external world. It is ``stable'' in the sense that the name does
641 not change when the Haskell garbage collector runs --- in contrast to
642 the address of the object which may well change.
644 The stable pointer type is parameterised by the type of the thing
650 A stable pointer is represented by an index into the (static)
651 @StablePointerTable@. The Haskell garbage collector treats the
652 @StablePointerTable@ as a source of roots for GC.
654 The @makeStablePointer@ function converts a value into a stable
655 pointer. It is part of the @IO@ monad, because we want to be sure
656 we don't allocate one twice by accident, and then only free one of the
659 makeStablePointer# :: a -> State# RealWorld -> StateAndStablePtr# RealWorld a
660 freeStablePointer# :: StablePtr# a -> State# RealWorld -> State# RealWorld
661 deRefStablePointer# :: StablePtr# a -> State# RealWorld -> StateAndPtr RealWorld a
664 There is also a C procedure @FreeStablePtr@ which frees a stable pointer.
666 %{\em Andy's comment.} {\bf Errors:} The following is not strictly true: the current
667 %implementation is not as polymorphic as claimed. The reason for this
668 %is that the C programmer will have to use a different entry-routine
669 %for each type of stable pointer. At present, we only supply a very
670 %limited number (3) of these routines. It might be possible to
671 %increase the range of these routines by providing general purpose
672 %entry points to apply stable pointers to (stable pointers to)
673 %arguments and to enter (stable pointers to) boxed primitive values.
674 %{\em End of Andy's comment.}
677 % Rewritten and updated for MallocPtr++ -- 4/96 SOF
679 \subsubsection{Foreign objects}
680 \index{Foreign objects}
681 \index{ForeignObj type}
683 A @ForeignObj#@ is a reference to an object outside the Haskell world
684 (i.e., from the C world, or a reference to an object on another
685 machine completely.), where the Haskell world has been told ``Let me
686 know when you're finished with this ...''.
692 GHC provides two primitives on @ForeignObj#@:
696 :: Addr# -- foreign reference
697 -> Addr# -- pointer to finalisation routine
698 -> StateAndForeignObj# RealWorld ForeignObj#
700 :: ForeignObj# -- foreign object
706 The module @Foreign@ (Section \ref{sec:foreign-obj}) provides a more
707 programmer-friendly interface to foreign objects.
709 \subsubsection{Synchronizing variables (M-vars)}
710 \index{Synchronising variables (M-vars)}
713 Synchronising variables are the primitive type used to implement
714 Concurrent Haskell's MVars (see the Concurrent Haskell paper for
715 the operational behaviour of these operations).
718 type SynchVar# s elt -- primitive
720 newSynchVar#:: State# s -> StateAndSynchVar# s elt
721 takeMVar# :: SynchVar# s elt -> State# s -> StateAndPtr# s elt
722 putMVar# :: SynchVar# s elt -> State# s -> State# s
725 \subsubsection{@spark#@ primitive operation (for parallel execution)}
727 {\em ToDo: say something} It's used in the unfolding for @par@.
729 \subsubsection{The @errorIO#@ primitive operation}
731 The @errorIO#@ primitive takes an argument much like @IO@. It aborts
732 execution of the current program, and continues instead by performing
733 the given @IO@-like value on the current state of the world.
736 errorIO# :: (State# RealWorld# -> a -> a
739 %------------------------------------------------------------
740 \subsection{GHC/Hugs Extension Libraries}
742 \subsubsection{@LazyST@}
743 \index{LazyST module}
745 This library provides support for both {\em lazy\/} and {\em strict\/}
746 state threads. In addition to the monad {\tt ST}, it also provides
747 mutable variables {\tt STRef} and mutable arrays {\tt STArray}. As
748 the name suggests, the monad {\tt ST} instance is {\em lazy\/}.
751 module LazyST( module LazyST, module Monad ) where
754 data ST s a -- abstract type
755 runST :: forall a. (forall s. ST s a) -> a
756 returnST :: a -> ST s a
757 thenLazyST :: ST s a -> (a -> ST s b) -> ST s b
758 thenStrictST :: ST s a -> (a -> ST s b) -> ST s b
759 fixST :: (a -> ST s a) -> ST s a
760 unsafeInterleaveST :: ST s a -> ST s a
761 instance Functor (ST s)
762 instance Monad (ST s)
764 data STRef s a -- mutable variables in state thread s
765 -- containing values of type a.
766 newSTRef :: a -> ST s (STRef s a)
767 readSTRef :: STRef s a -> ST s a
768 writeSTRef :: STRef s a -> a -> ST s ()
769 instance Eq (STRef s a)
771 data STArray s ix elt -- mutable arrays in state thread s
772 -- indexed by values of type ix
773 -- containing values of type a.
774 newSTArray :: Ix ix => (ix,ix) -> elt -> ST s (STArray s ix elt)
775 boundsSTArray :: Ix ix => STArray s ix elt -> (ix, ix)
776 readSTArray :: Ix ix => STArray s ix elt -> ix -> ST s elt
777 writeSTArray :: Ix ix => STArray s ix elt -> ix -> elt -> ST s ()
778 thawSTArray :: Ix ix => Array ix elt -> ST s (STArray s ix elt)
779 freezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
780 unsafeFreezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
781 instance Eq (STArray s ix elt)
788 GHC also supports ByteArrays --- these aren't supported by Hugs yet.
790 The operations {\tt freezeSTArray} and {\tt thawSTArray} convert mutable
791 arrays to and from immutable arrays. Semantically, they are identical
792 to copying the array and they are usually implemented that way. The
793 operation {\tt unsafeFreezeSTArray} is a faster version of
794 {\tt freezeSTArray} which omits the copying step. It's a safe substitute for
795 {\tt freezeSTArray} if you don't modify the mutable array after freezing it.
796 \item In the current version of Hugs, the {\tt runST} operation,
797 used to specify encapsulation, is implemented as a language construct,
798 and {\tt runST} is treated as a keyword. We plan to change this to match
801 \item The only difference between the lazy and strict instances of the
802 {\tt ST} monad is in their bind operators. The monadic bind operators
803 {\tt thenLazyST} and {\tt thenStrictST} are provided so that you can
804 import {\tt LazyST} (say) and still use the strict instance in those
805 places where it matters. GHC also allows you to write {\tt LazyST.>>=}
806 and {\tt ST.>>=} but this is not supported by Hugs yet.
819 This library is identical to {\tt LazyST} except that the {\tt ST} monad
820 instance is {\em strict\/}. Most programmers use the {\em strict\/} instance
821 to avoid the space leaks associated with the {\em lazy\/} instance.
826 \subsubsection{@IOExts@}
827 \index{IOExts module}
831 This library provides the following extensions to the IO monad:
833 \item The operations {\tt fixIO}, {\tt unsafePerformIO} and {\tt
835 \item References (aka mutable variables) and mutable arrays (but no form of
837 \item {\tt performGC} triggers an immediate garbage collection
838 \item When called, {\tt trace} prints the string in its first argument, and then
839 returns the second argument as its result. The {\tt trace} function is not
840 referentially transparent, and should only be used for debugging, or for
841 monitoring execution.
849 fixIO :: (a -> IO a) -> IO a
850 unsafePerformIO :: IO a -> a
851 unsafeInterleaveIO :: IO a -> IO a
853 data IORef a -- mutable variables containing values of type a
854 newIORef :: a -> IO (IORef a)
855 readIORef :: IORef a -> IO a
856 writeIORef :: IORef a -> a -> IO ()
857 instance Eq (IORef a)
859 data IOArray ix elt -- mutable arrays indexed by values of type ix
860 -- containing values of type a.
861 newIOArray :: Ix ix => (ix,ix) -> elt -> IO (IOArray ix elt)
862 boundsIOArray :: Ix ix => IOArray ix elt -> (ix, ix)
863 readIOArray :: Ix ix => IOArray ix elt -> ix -> IO elt
864 writeIOArray :: Ix ix => IOArray ix elt -> ix -> elt -> IO ()
865 freezeIOArray :: Ix ix => IOArray ix elt -> IO (Array ix elt)
866 instance Eq (IOArray ix elt)
868 trace :: String -> a -> a
878 \subsubsection{@Bits@}
883 This library defines bitwise operations for signed and unsigned ints.
887 infixl 8 `shift`, `rotate`
893 (.&.), (.|.), xor :: a -> a -> a
895 shift :: a -> Int -> a
896 rotate :: a -> Int -> a
898 setBit :: a -> Int -> a
899 clearBit :: a -> Int -> a
900 complementBit :: a -> Int -> a
901 testBit :: a -> Int -> Bool
903 isSigned :: a -> Bool
905 shiftL, shiftR :: Bits a => a -> Int -> a
906 rotateL, rotateR :: Bits a => a -> Int -> a
907 shiftL a i = shift a i
908 shiftR a i = shift a (-i)
909 rotateL a i = rotate a i
910 rotateR a i = rotate a (-i)
916 \item {\tt bitSize} and {\tt isSigned} are like {\tt floatRadix} and {\tt floatDigits}
917 -- they return parameters of the {\em type\/} of their argument rather than
918 of the particular argument they are applied to. {\tt bitSize} returns
919 the number of bits in the type (or {\tt Nothing} for unbounded types); and
920 {\tt isSigned} returns whether the type is signed or not.
921 \item {\tt shift} performs sign extension.
922 That is, right shifts fill the top bits with 1 if the number is negative
923 and with 0 otherwise.
924 (Since unsigned types are always positive, the top bit is always filled with
927 Bits are numbered from 0 with bit 0 being the least significant bit.
928 \item {\tt shift x i} and {\tt rotate x i} shift to the left if {\tt i} is
929 positive and to the right otherwise.
930 \item {\tt bit i} is the value with the i'th bit set.
937 \subsubsection{@Word@}
942 This library provides unsigned integers of various sizes.
943 The types supported are as follows:
945 \begin{tabular}{|l|l|}
946 type & number of bits \\
956 For each type {\it W\/} above, we provide the following functions and
957 instances. The type {\it I\/} refers to the signed integer type of the
961 data W -- Unsigned Ints
977 word8ToWord32 :: Word8 -> Word32
978 word32ToWord8 :: Word32 -> Word8
979 word16ToWord32 :: Word16 -> Word32
980 word32ToWord16 :: Word32 -> Word16
982 word8ToInt :: Word8 -> Int
983 intToWord8 :: Int -> Word8
984 word16ToInt :: Word16 -> Int
985 intToWord16 :: Int -> Word16
986 word32ToInt :: Word32 -> Int
987 intToWord32 :: Int -> Word32
993 \item All arithmetic is performed modulo 2\verb+^+n
995 One non-obvious consequequence of this is that {\tt negate}
996 should {\em not\/} raise an error on negative arguments.
997 \item The coercion {\tt wToI} converts an unsigned n-bit value to the
998 signed n-bit value with the same representation. For example,
999 {\tt word8ToInt8 0xff = -1}.
1000 Likewise, {\tt iToW} converts signed n-bit values to the
1001 corresponding unsigned n-bit value.
1002 \item ToDo: complete the set of coercion functions.
1003 \item Use {\tt Prelude.fromIntegral :: (Integral a, Num b) => a -> b} to
1004 coerce between different sizes or to preserve sign when converting
1005 between values of the same size.
1006 \item It would be very natural to add a type a type {\tt Natural} providing
1007 an unbounded size unsigned integer --- just as {\tt Integer} provides
1008 unbounded size signed integers. We do not do that yet since there is
1009 no demand for it. Doing so would require {\tt Bits.bitSize} to return
1011 \item The {\tt Enum} instances stop when they reach their upper or lower
1012 bound --- they don't overflow the way the {\tt Int} and {\tt Float}
1014 \item It would be useful to provide a function (or a family of functions?)
1015 which coerced between any two Word types (without going through
1020 Hugs only provides {\tt Eq}, {\tt Ord}, {\tt Read} and {\tt Show}
1021 instances for {\tt Word64} at the moment.
1026 \subsubsection{@Int@}
1031 This library provides signed integers of various sizes. The types
1032 supported are as follows:
1034 \begin{tabular}{|l|l|l|}
1035 type & number of bits \\
1045 For each type {\it I\/} above, we provide the following instances.
1048 data I -- Signed Ints
1049 iToInt :: I -> Int -- not provided for Int64
1050 intToi :: Int -> I -- not provided for Int64
1066 int8ToInt :: Int8 -> Int
1067 intToInt8 :: Int -> Int8
1068 int16ToInt :: Int16 -> Int
1069 intToInt16 :: Int -> Int16
1070 int32ToInt :: Int32 -> Int
1071 intToInt32 :: Int -> Int32
1076 \item Hugs does not provide {\tt Int64} at the moment.
1077 \item ToDo: complete the set of coercion functions.
1084 \subsubsection{@Addr@}
1089 This library provides machine addresses and is primarily intended for
1090 use in creating foreign function interfaces using GreenCard.
1094 data Addr -- Address type
1098 plusAddr :: Addr -> Int -> Addr
1100 -- read value out of _immutable_ memory
1101 indexCharOffAddr :: Addr -> Int -> Char
1102 indexIntOffAddr :: Addr -> Int -> Int -- should we drop this?
1103 indexAddrOffAddr :: Addr -> Int -> Addr
1104 indexFloatOffAddr :: Addr -> Int -> Float
1105 indexDoubleOffAddr :: Addr -> Int -> Double
1106 indexWord8OffAddr :: Addr -> Int -> Word8
1107 indexWord16OffAddr :: Addr -> Int -> Word16
1108 indexWord32OffAddr :: Addr -> Int -> Word32
1109 indexWord64OffAddr :: Addr -> Int -> Word64
1110 indexInt8OffAddr :: Addr -> Int -> Int8
1111 indexInt16OffAddr :: Addr -> Int -> Int16
1112 indexInt32OffAddr :: Addr -> Int -> Int32
1113 indexInt64OffAddr :: Addr -> Int -> Int64
1115 -- read value out of mutable memory
1116 readCharOffAddr :: Addr -> Int -> IO Char
1117 readIntOffAddr :: Addr -> Int -> IO Int -- should we drop this?
1118 readAddrOffAddr :: Addr -> Int -> IO Addr
1119 readFloatOffAddr :: Addr -> Int -> IO Float
1120 readDoubleOffAddr :: Addr -> Int -> IO Double
1121 readWord8OffAddr :: Addr -> Int -> IO Word8
1122 readWord16OffAddr :: Addr -> Int -> IO Word16
1123 readWord32OffAddr :: Addr -> Int -> IO Word32
1124 readWord64OffAddr :: Addr -> Int -> IO Word64
1125 readInt8OffAddr :: Addr -> Int -> IO Int8
1126 readInt16OffAddr :: Addr -> Int -> IO Int16
1127 readInt32OffAddr :: Addr -> Int -> IO Int32
1128 readInt64OffAddr :: Addr -> Int -> IO Int64
1130 -- write value into mutable memory
1131 writeCharOffAddr :: Addr -> Int -> Char -> IO ()
1132 writeIntOffAddr :: Addr -> Int -> Int -> IO () -- should we drop this?
1133 writeAddrOffAddr :: Addr -> Int -> Addr -> IO ()
1134 writeFloatOffAddr :: Addr -> Int -> Float -> IO ()
1135 writeDoubleOffAddr :: Addr -> Int -> Double -> IO ()
1136 writeWord8OffAddr :: Addr -> Int -> Word8 -> IO ()
1137 writeWord16OffAddr :: Addr -> Int -> Word16 -> IO ()
1138 writeWord32OffAddr :: Addr -> Int -> Word32 -> IO ()
1139 writeWord64OffAddr :: Addr -> Int -> Word64 -> IO ()
1140 writeInt8OffAddr :: Addr -> Int -> Int8 -> IO ()
1141 writeInt16OffAddr :: Addr -> Int -> Int16 -> IO ()
1142 writeInt32OffAddr :: Addr -> Int -> Int32 -> IO ()
1143 writeInt64OffAddr :: Addr -> Int -> Int64 -> IO ()
1147 Hugs and GHC provide {\tt Addr} and {\tt nullAddr} but do not provide
1148 any of the index, read or write functions. They can be implemented
1149 using GreenCard if required.
1154 \subsubsection{@Concurrent@}
1155 \index{Concurrent module}
1159 This library provides the Concurrent Haskell extensions.
1161 We are grateful to the Glasgow Haskell Project for allowing us to
1162 redistribute their implementation of this module.
1165 module Concurrent where
1167 data ThreadId -- thread identifiers
1168 instance Eq ThreadId
1170 forkIO :: IO () -> IO ThreadId
1171 killThread :: ThreadId -> IO ()
1173 data MVar a -- Synchronisation variables
1174 newEmptyMVar :: IO (MVar a)
1175 newMVar :: a -> IO (MVar a)
1176 takeMVar :: MVar a -> IO a
1177 putMVar :: MVar a -> a -> IO ()
1178 swapMVar :: MVar a -> a -> IO a
1179 readMVar :: MVar a -> IO a
1180 instance Eq (MVar a)
1182 data Chan a -- channels
1183 newChan :: IO (Chan a)
1184 writeChan :: Chan a -> a -> IO ()
1185 readChan :: Chan a -> IO a
1186 dupChan :: Chan a -> IO (Chan a)
1187 unReadChan :: Chan a -> a -> IO ()
1188 readChanContents :: Chan a -> IO [a]
1189 writeList2Chan :: Chan a -> [a] -> IO ()
1191 data CVar a -- one element channels
1192 newCVar :: IO (CVar a)
1193 putCVar :: CVar a -> a -> IO ()
1194 getCVar :: CVar a -> IO a
1196 data QSem -- General/quantity semaphores
1197 newQSem :: Int -> IO QSem
1198 waitQSem :: QSem -> IO ()
1199 signalQSem :: QSem -> IO ()
1201 data QSemN -- General/quantity semaphores
1202 newQSemN :: Int -> IO QSemN
1203 waitQSemN :: QSemN -> Int -> IO ()
1204 signalQSemN :: QSemN -> Int -> IO ()
1206 type SampleVar a -- Sample variables
1207 newEmptySampleVar:: IO (SampleVar a)
1208 newSampleVar :: a -> IO (SampleVar a)
1209 emptySampleVar :: SampleVar a -> IO ()
1210 readSampleVar :: SampleVar a -> IO a
1211 writeSampleVar :: SampleVar a -> a -> IO ()
1218 GHC uses preemptive multitasking:
1219 Context switches can occur at any time, except if you call a C
1220 function (like \verb"getchar") that blocks waiting for input.
1222 Hugs uses cooperative multitasking:
1223 Context switches only occur when you use one of the primitives
1224 defined in this module. This means that programs such as:
1227 main = forkIO (write 'a') >> write 'b'
1228 where write c = putChar c >> write c
1232 will print either {\tt aaaaaaaaaaaaaa...} or {\tt bbbbbbbbbbbb...},
1233 instead of some random interleaving of {\tt a}s and {\tt b}s.
1235 In practice, cooperative multitasking is sufficient for writing
1236 simple graphical user interfaces.
1237 \item Hugs does not provide the functions {\tt mergeIO} or {\tt nmergeIO} since these
1238 require preemptive multitasking.
1239 \item {\tt killThread} has not been implemented yet on either system.
1240 The plan is that {\tt killThread} will raise an IO exception in the
1241 killed thread which it can catch --- perhaps allowing it to kill its
1242 children before exiting.
1243 \item The {\tt Ord} instance for {\tt ThreadId}s provides an arbitrary total ordering
1244 which might be used to build an ordered binary tree, say.
1251 \subsubsection{@Pretty@}
1252 \index{Pretty module}
1256 This library contains Simon Peyton Jones' implementation of John
1257 Hughes's pretty printer combinators.
1264 data Doc -- the Document datatype
1266 -- The primitive Doc values
1268 text :: String -> Doc
1271 integer :: Integer -> Doc
1272 float :: Float -> Doc
1273 double :: Double -> Doc
1274 rational :: Rational -> Doc
1275 semi, comma, colon, space, equals :: Doc
1276 lparen, rparen, lbrack, rbrack, lbrace, rbrace :: Doc
1277 parens, brackets, braces :: Doc -> Doc
1278 quotes, doubleQuotes :: Doc -> Doc
1280 -- Combining Doc values
1281 (<>) :: Doc -> Doc -> Doc -- Beside
1282 hcat :: [Doc] -> Doc -- List version of <>
1283 (<+>) :: Doc -> Doc -> Doc -- Beside, separated by space
1284 hsep :: [Doc] -> Doc -- List version of <+>
1285 ($$) :: Doc -> Doc -> Doc -- Above; if there is no
1286 -- overlap it "dovetails" the two
1287 vcat :: [Doc] -> Doc -- List version of $$
1288 cat :: [Doc] -> Doc -- Either hcat or vcat
1289 sep :: [Doc] -> Doc -- Either hsep or vcat
1290 fcat :: [Doc] -> Doc -- ``Paragraph fill'' version of cat
1291 fsep :: [Doc] -> Doc -- ``Paragraph fill'' version of sep
1292 nest :: Int -> Doc -> Doc -- Nested
1293 hang :: Doc -> Int -> Doc -> Doc
1294 punctuate :: Doc -> [Doc] -> [Doc]
1295 -- punctuate p [d1, ... dn] = [d1 <> p, d2 <> p, ... dn-1 <> p, dn]
1297 -- Displaying Doc values
1299 render :: Doc -> String -- Uses default style
1300 renderStyle :: Style -> Doc -> String
1301 data Style = Style { lineLength :: Int, -- In chars
1302 ribbonsPerLine :: Float, -- Ratio of ribbon length
1306 data Mode = PageMode -- Normal
1307 | ZigZagMode -- With zig-zag cuts
1308 | LeftMode -- No indentation, infinitely long lines
1309 | OneLineMode -- All on one line
1312 \subsection{GHC-only Extension Libraries}
1314 If you rely on the implicit @import Prelude@ that GHC normally does
1315 for you, and if you don't use any weird flags (notably
1316 @-fglasgow-exts@), and if you don't import the Glasgow extensions
1317 interface, @GlaExts@, then GHC should work {\em exactly} as the
1318 Haskell report says, and the full user namespaces should be available
1321 If you mess about with @import Prelude@... innocent hiding, e.g.,
1324 import Prelude hiding ( fromIntegral )
1327 should work just fine.
1329 % this should work now?? -- SDM
1331 %There are some things you can do that will make GHC crash, e.g.,
1332 %hiding a standard class:
1334 %import Prelude hiding ( Eq(..) )
1339 If you turn on @-fglasgow-exts@, the compiler will recognise and parse
1340 unboxed values properly. To get at the primitive operations described
1341 herein, import the relevant interfaces.
1343 \subsubsection{The @GlaExts@ interface}
1344 \index{GlaExts interface (GHC extensions)}
1346 The @GlaExts@ interface provides access to extensions that only GHC
1347 implements. These currently are: unboxed types, including the
1348 representations of the primitive types (Int, Float, etc.), and the
1349 GHC primitive operations (@+#@, @==#@, etc.).
1351 This module used to provide access to all the Glasgow extensions, but
1352 these have since been moved into separate libraries for compatibility
1353 with Hugs (version 2.09: in fact, you can still get at this stuff via
1354 @GlaExts@ for compatibility, but this facility will likely be removed
1358 -- the representation of some basic types:
1359 data Char = C# Char#
1361 data Addr = A# Addr#
1362 data Word = W# Word#
1363 data Float = F# Float#
1364 data Double = D# Double#
1365 data Integer = J# Int# Int# ByteArray#
1367 module GHC -- all primops and primitive types.
1370 \subsubsection[sec:mutable-array]{The @MutableArray@ interface}
1371 \index{MutableArray interface (GHC extensions)}
1373 The @MutableArray@ interface defines a general set of operations over
1374 mutable arrays (@MutableArray@) and mutable chunks of memory
1375 (@MutableByteArray@):
1378 data MutableArray s ix elt -- abstract
1379 data MutableByteArray s ix -- abstract
1380 -- instance of : CCallable
1382 newArray :: Ix ix => (ix,ix) -> elt -> ST s (MutableArray s ix elt)
1383 newCharArray :: Ix ix => (ix,ix) -> ST s (MutableByteArray s ix)
1384 newAddrArray :: Ix ix => (ix,ix) -> ST s (MutableByteArray s ix)
1385 newIntArray :: Ix ix => (ix,ix) -> ST s (MutableByteArray s ix)
1386 newFloatArray :: Ix ix => (ix,ix) -> ST s (MutableByteArray s ix)
1387 newDoubleArray :: Ix ix => (ix,ix) -> ST s (MutableByteArray s ix)
1389 boundsOfArray :: Ix ix => MutableArray s ix elt -> (ix, ix)
1390 boundsOfByteArray :: Ix ix => MutableByteArray s ix -> (ix, ix)
1393 readArray :: Ix ix => MutableArray s ix elt -> ix -> ST s elt
1395 readCharArray :: Ix ix => MutableByteArray s ix -> ix -> ST s Char
1396 readIntArray :: Ix ix => MutableByteArray s ix -> ix -> ST s Int
1397 readAddrArray :: Ix ix => MutableByteArray s ix -> ix -> ST s Addr
1398 readFloatArray :: Ix ix => MutableByteArray s ix -> ix -> ST s Float
1399 readDoubleArray :: Ix ix => MutableByteArray s ix -> ix -> ST s Double
1401 writeArray :: Ix ix => MutableArray s ix elt -> ix -> elt -> ST s ()
1402 writeCharArray :: Ix ix => MutableByteArray s ix -> ix -> Char -> ST s ()
1403 writeIntArray :: Ix ix => MutableByteArray s ix -> ix -> Int -> ST s ()
1404 writeAddrArray :: Ix ix => MutableByteArray s ix -> ix -> Addr -> ST s ()
1405 writeFloatArray :: Ix ix => MutableByteArray s ix -> ix -> Float -> ST s ()
1406 writeDoubleArray :: Ix ix => MutableByteArray s ix -> ix -> Double -> ST s ()
1408 freezeArray :: Ix ix => MutableArray s ix elt -> ST s (Array ix elt)
1409 freezeCharArray :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
1410 freezeIntArray :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
1411 freezeAddrArray :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
1412 freezeFloatArray :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
1413 freezeDoubleArray :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
1415 unsafeFreezeArray :: Ix ix => MutableArray s ix elt -> ST s (Array ix elt)
1416 unsafeFreezeByteArray :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
1417 thawArray :: Ix ix => Array ix elt -> ST s (MutableArray s ix elt)
1420 \subsubsection[sec:byte-array]{The @ByteArray@ interface}
1421 \index{ByteArray interface (GHC extensions)}
1423 @ByteArray@s are chunks of immutable Haskell heap:
1426 data ByteArray ix -- abstract
1427 -- instance of: CCallable
1429 indexCharArray :: Ix ix => ByteArray ix -> ix -> Char
1430 indexIntArray :: Ix ix => ByteArray ix -> ix -> Int
1431 indexAddrArray :: Ix ix => ByteArray ix -> ix -> Addr
1432 indexFloatArray :: Ix ix => ByteArray ix -> ix -> Float
1433 indexDoubleArray :: Ix ix => ByteArray ix -> ix -> Double
1435 indexCharOffAddr :: Addr -> Int -> Char
1436 indexIntOffAddr :: Addr -> Int -> Int
1437 indexAddrOffAddr :: Addr -> Int -> Addr
1438 indexFloatOffAddr :: Addr -> Int -> Float
1439 indexDoubleOffAddr :: Addr -> Int -> Double
1442 \subsubsection{Stable pointers}
1444 Nothing exciting here, just simple boxing up.
1446 data StablePtr a = StablePtr (StablePtr# a)
1448 makeStablePointer :: a -> StablePtr a
1449 freeStablePointer :: StablePtr a -> IO ()
1452 \subsubsection{Foreign objects}
1453 \label{sec:foreign-obj}
1454 \index{Foreign objects}
1456 This module provides the @ForeignObj@ type and wrappers around the
1457 primitive operations on foreign objects.
1460 data ForeignObj = ForeignObj ForeignObj#
1463 :: Addr -- object to be boxed up as a ForeignObj
1464 -> Addr -- finaliser
1468 :: ForeignObj -- previously created foreign object
1469 -> Addr -- new value
1473 \index{ForeignObj type}
1474 \index{makeForeignObj function}
1475 \index{writeForeignObj function}
1477 A typical use of @ForeignObj@ is in constructing Haskell bindings
1478 to external libraries. A good example is that of writing a binding to
1479 an image-processing library (which was actually the main motivation
1480 for implementing @ForeignObj@'s precursor, @MallocPtr#@). The
1481 images manipulated are not stored in the Haskell heap, either because
1482 the library insist on allocating them internally or we (sensibly)
1483 decide to spare the GC from having to heave heavy images around.
1486 data Image = Image ForeignObj
1489 The @ForeignObj@ type is then used to refer to the externally
1490 allocated image, and to acheive some type safety, the Haskell binding
1491 defines the @Image@ data type. So, a value of type @ForeignObj@ is
1492 used to ``box'' up an external reference into a Haskell heap object
1493 that we can then indirectly reference:
1496 createImage :: (Int,Int) -> IO Image
1499 So far, this looks just like an @Addr@ type, but @ForeignObj@ offers a
1500 bit more, namely that we can specify a {\em finalisation routine} to
1501 invoke when the @ForeignObj@ is discarded by the GC. The garbage
1502 collector invokes the finalisation routine associated with the
1503 @ForeignObj@, saying `` Thanks, I'm through with this now..'' For the
1504 image-processing library, the finalisation routine could for the
1505 images free up memory allocated for them. The finalisation routine has
1506 currently to be written in C (the finalisation routine can in turn
1507 call on @FreeStablePtr@ to deallocate a stable pointer).
1509 Associating a finalisation routine with an external object is done by
1510 calling @makeForeignObj@. {\bf Note:} the foreign object value and
1511 its finaliser are contained in the @ForeignObj@, so there's no danger
1512 of an aggressive optimiser somehow separating the two (with the result
1513 that the foreign reference would not be freed).
1515 (Implementation: a linked list of all @ForeignObj#@s is maintained to
1516 allow the garbage collector to detect when a @ForeignObj#@ becomes
1519 Like @Array@, @ForeignObj#@s are represented by heap objects.
1521 Upon controlled termination of the Haskell program, all @ForeignObjs@
1522 are freed, invoking their respective finalisers before terminating.
1524 \subsubsection{The @CCall@ module}
1526 The @CCall@ module defines the classes @CCallable@ and @CReturnable@,
1527 along with instances for the primitive types (@Int@, @Int#@, @Float@,
1528 @Float#@ etc.) GHC knows to import this module if you use @_ccall_@,
1529 but if you need to define your own instances of these classes, you
1530 will need to import @CCall@ explicitly.
1532 More information on how to use @_ccall_@ can be found in Section
1533 \ref{glasgow-ccalls}.
1535 \begin{onlystandalone}
1537 \end{onlystandalone}