[project @ 1996-12-19 09:10:02 by simonpj]
[ghc-hetmet.git] / ghc / docs / state_interface / state-interface.verb
1 \documentstyle[a4wide,grasp]{article}
2 \renewcommand{\textfraction}{0.1}
3 \renewcommand{\floatpagefraction}{0.9}
4 \renewcommand{\dblfloatpagefraction}{0.9}
5
6 \sloppy
7 \renewcommand{\today}{July 1996}
8
9 \begin{document}
10
11 \title{The GHC Prelude and Libraries}
12 \author{Simon L Peyton Jones \and Will Partain}
13
14 \maketitle
15 \tableofcontents
16
17 \section{Introduction}
18
19 This document describes GHC's prelude and libraries.  The basic story is that of
20 the Haskell 1.3 Report and Libraries document (which we do not reproduce here),
21 but this document describes in addition:
22 \begin{itemize}
23 \item   GHC's additional non-standard libraries and types, such as state transformers,
24         packed strings, foreign objects, stable pointers, and so on.
25
26 \item   GHC's primitive types and operations.  The standard Haskell functions are implemented
27         on top of these, and it is sometimes useful to use them directly.
28
29 \item   The organsiation of these libraries into directories.
30 \end{itemize}
31
32 \section{Overview}
33
34 The libraries are organised into the following three groups, each of which
35 is kept in a separate sub-directory of GHC's installed @lib/@ directory:
36 \begin{description}
37 \item[@lib/required/@]  These are the libraries {\em required} by the Haskell
38 definition.  All are defined by the Haskell Report, or by the Haskell Libraries Report.
39 They currently comprise:
40 \begin{itemize}
41 \item @Prelude@.
42 \item @List@: more functions on lists.
43 \item @Char@: more functions on characters.
44 \item @Maybe@: more functions on @Maybe@ types.
45 \item @Complex@: functions on complex numbers.
46 \item @Ratio@: functions on rational numbers.
47 \item @Monad@: functions on characters.
48 \item @Ix@: the @Ix@ class of indexing operations.
49 \item @Array@: monolithic arrays.
50 \item @IO@: basic input/output functions.
51 \item @Directory@: basic functions for accessing the file system.
52 \item @System@: basic operating-system interface functions.
53 \end{itemize}
54
55 \item[@lib/glaExts@]  GHC extension libraries, currently comprising:
56 \begin{itemize}
57 \item @PackedString@: functions that manipulate strings packed efficiently, one character per byte.
58 \item @ST@: the state transformer monad.
59 \item @Foreign@: types and operations for GHC's foreign-language interface.
60 \end{itemize}
61
62 \item[@lib/concurrent@] GHC extension libraries to support Concurrent Haskell, currently comprising:
63 \begin{itemize}
64 \item @Concurrent.hs@: main library.
65 \item @Parallel.hs@: stuff for multi-processor parallelism.
66 \item @Channel.hs@
67 \item @ChannelVar.hs@
68 \item @Merge.hs@
69 \item @SampleVar.hs@
70 \item @Semaphore.hs@
71 \end{itemize}
72
73 \item[@lib/ghc@] These libraries are the pieces on which all the others are built.
74 They aren't typically imported by Joe Programmer, but there's nothing to stop you
75 doing so if you want.  In general, the modules prefixed by @Prel@ are pieces that go
76 towards building @Prelude@.
77
78 \begin{itemize}
79 \item @GHC@: this ``library'' brings into scope all the primitive types and operations, such as
80 @Int#@, @+#@,  @encodeFloat#@, etc etc.  It is unique in that there is no Haskell
81 source code for it.  Details in Section \ref{sect:ghc}.
82
83 \item @PrelBase@: defines the basic types and classes without which very few Haskell programs can work.
84 The classes are: @Eq@, @Ord@, @Enum@, @Bounded@, @Num@, @Show@, @Eval@, @Monad@, @MonadZero@, @MonadPlus@.
85 The types are: list, @Bool@, @Char@, @Ordering@, @String@, @Int@, @Integer@, @Maybe@, @Either@.
86
87 \item @PrelTup@: defines tuples and their instances.
88 \item @PrelList@: defines most of the list operations required by @Prelude@.  (A few are in @PrelBase@.
89
90 \item @PrelNum@ defines: the numeric classes beyond @Num@ (namely @Real@, @Integral@, 
91 @Fractional@, @Floating@, @RealFrac@, @RealFloat@; instances for appropriate classes 
92 for @Int@ and @Integer@; the types @Float@, @Double@, and @Ratio@ and their instances.
93
94 \item @PrelRead@: the @Read@ class and all its instances.  It's kept separate because many programs
95 don't use @Read@ at all, so we don't even want to link in its code.
96
97 \item @ConcBase@: substrate stuff for Concurrent Haskell.
98
99 \item @IOBase@: substrate stuff for the main I/O libraries.
100 \item @IOHandle@: large blob of code for doing I/O on handles.
101 \item @PrelIO@: the remaining small pieces to produce the I/O stuff needed by @Prelude@.
102 \item @GHCerr@: error reporting code, called from code that the compiler plants in compiled programs.
103 \item @GHCmain@: the definition of @mainPrimIO@, which is what {\em really} gets
104         called by the runtime system.  @mainPrimIO@ in turn calls @main@.
105 \end{itemize}
106 \end{description}
107
108 \section{The module @GHC@: really primitive stuff}
109 \label{sect:ghc}
110
111 This section defines all the types which are primitive in Glasgow Haskell, and the
112 operations provided for them.
113
114 A primitive type is one which cannot be defined in Haskell, and which
115 is therefore built into the language and compiler.  Primitive types
116 are always unboxed; that is, a value of primitive type cannot be
117 bottom.
118
119 Primitive values are often represented by a simple bit-pattern, such as @Int#@, 
120 @Float#@, @Double#@.  But this is not necessarily the case: a primitive value 
121 might be represented by a pointer to a heap-allocated object.  Examples include 
122 @Array#@, the type of primitive arrays.  You might think this odd: doesn't being 
123 heap-allocated mean that it has a box?  No, it does not.  A primitive array is 
124 heap-allocated because it is too big a value to fit in a register, and would be 
125 too expensive to copy around; in a sense, it is accidental that it is represented 
126 by a pointer.  If a pointer represents a primitive value, then it really does 
127 point to that value: no unevaluated thunks, no indirections...nothing can be at 
128 the other end of the pointer than the primitive value.
129
130 This section also describes a few non-primitive types, which are needed 
131 to express the result types of some primitive operations.
132
133 \subsection{Character and numeric types}
134
135 There are the following obvious primitive types:
136 @
137 type Char#
138 type Int#       -- see also Word# and Addr#, later
139 type Float#
140 type Double#
141 @
142 If you want to know their exact equivalents in C, see
143 @ghc/includes/StgTypes.lh@ in the GHC source.
144
145 Literals for these types may be written as follows:
146 @
147 1#              an Int#
148 1.2#            a Float#
149 1.34##          a Double#
150 'a'#            a Char#; for weird characters, use '\o<octal>'#
151 "a"#            an Addr# (a `char *')
152 @
153
154 \subsubsection{Comparison operations}
155 @
156 {gt,ge,eq,ne,lt,le}Char# :: Char# -> Char# -> Bool
157     -- ditto for Int#, Word#, Float#, Double#, and Addr#
158 @
159
160 \subsubsection{Unboxed-character operations}
161 @
162 ord# :: Char# -> Int#
163 chr# :: Int# -> Char#
164 @
165
166 \subsubsection{Unboxed-@Int@ operations}
167 @
168 {plus,minus,times,quot,div,rem}Int# :: Int# -> Int# -> Int#
169 negateInt# :: Int# -> Int#
170 @
171 NB: No error/overflow checking!
172
173 \subsubsection{Unboxed-@Double@ and @Float@ operations}
174 @
175 {plus,minus,times,divide}Double# :: Double# -> Double# -> Double#
176 negateDouble# :: Double# -> Double#
177
178 float2Int#      :: Double# -> Int#   -- just a cast, no checking!
179 int2Double#     :: Int# -> Double#
180
181 expDouble#      :: Double# -> Double#
182 logDouble#      :: Double# -> Double#
183 sqrtDouble#     :: Double# -> Double#
184 sinDouble#      :: Double# -> Double#
185 cosDouble#      :: Double# -> Double#
186 tanDouble#      :: Double# -> Double#
187 asinDouble#     :: Double# -> Double#
188 acosDouble#     :: Double# -> Double#
189 atanDouble#     :: Double# -> Double#
190 sinhDouble#     :: Double# -> Double#
191 coshDouble#     :: Double# -> Double#
192 tanhDouble#     :: Double# -> Double#
193 powerDouble#    :: Double# -> Double# -> Double#
194 @
195 There's an exactly-matching set of unboxed-@Float@ ops; replace
196 @Double#@ with @Float#@ in the list above.  There are two
197 coercion functions for @Float#@/@Double#@:
198 @
199 float2Double#   :: Float# -> Double#
200 double2Float#   :: Double# -> Float#
201 @
202 The primitive versions of @encodeDouble@/@decodeDouble@:
203 @
204 encodeDouble#   :: Int# -> Int# -> ByteArray#   -- Integer mantissa
205                 -> Int#                         -- Int exponent
206                 -> Double#
207
208 decodeDouble#   :: Double#
209                 -> GHCbase.ReturnIntAndGMP
210 @
211 (And the same for @Float#@s.)
212
213 \subsection{Operations on/for @Integers@ (interface to GMP)}
214 \label{sect:horrid-Integer-pairing-types}
215
216 We implement @Integers@ (arbitrary-precision integers) using the GNU
217 multiple-precision (GMP) package.
218
219 NB: some of this might change if we upgrade to using GMP~2.x.
220
221 The data type for @Integer@ must mirror that for @MP_INT@ in @gmp.h@
222 (see @gmp.info@).  It comes out as:
223 @
224 data Integer = J# Int# Int# ByteArray#
225 @
226 So, @Integer@ is really just a ``pairing'' type for a particular
227 collection of primitive types.
228
229 The operations in the GMP return other combinations of
230 GMP-plus-something, so we need ``pairing'' types for those, too:
231 @
232 data Return2GMPs     = Return2GMPs Int# Int# ByteArray# Int# Int# ByteArray#
233 data ReturnIntAndGMP = ReturnIntAndGMP Int# Int# Int# ByteArray#
234
235 -- ????? something to return a string of bytes (in the heap?)
236 @
237 The primitive ops to support @Integers@ use the ``pieces'' of the
238 representation, and are as follows:
239 @
240 negateInteger#  :: Int# -> Int# -> ByteArray# -> Integer
241
242 {plus,minus,times}Integer# :: Int# -> Int# -> ByteArray#
243                            -> Int# -> Int# -> ByteArray#
244                            -> Integer
245
246 cmpInteger# :: Int# -> Int# -> ByteArray#
247             -> Int# -> Int# -> ByteArray#
248             -> Int# -- -1 for <; 0 for ==; +1 for >
249
250 divModInteger#, quotRemInteger#
251         :: Int# -> Int# -> ByteArray#
252         -> Int# -> Int# -> ByteArray#
253         -> GHCbase.Return2GMPs
254
255 integer2Int# :: Int# -> Int# -> ByteArray#
256              -> Int# 
257
258 int2Integer#  :: Int#  -> Integer -- NB: no error-checking on these two!
259 word2Integer# :: Word# -> Integer
260
261 addr2Integer# :: Addr# -> Integer
262         -- the Addr# is taken to be a `char *' string
263         -- to be converted into an Integer
264 @
265
266
267 \subsection{Words and addresses}
268
269 A @Word#@ is used for bit-twiddling operations.  It is the same size as
270 an @Int#@, but has no sign nor any arithmetic operations.
271 @
272 type Word#      -- Same size/etc as Int# but *unsigned*
273 type Addr#      -- A pointer from outside the "Haskell world" (from C, probably);
274                 -- described under "arrays"
275 @
276 @Word#@s and @Addr#@s have the usual comparison operations.
277 Other unboxed-@Word@ ops (bit-twiddling and coercions):
278 @
279 and#, or# :: Word# -> Word# -> Word#
280
281 not# :: Word# -> Word#
282
283 shiftL#, shiftRA#, shiftRL# :: Word# -> Int# -> Word#
284         -- shift left, right arithmetic, right logical
285
286 iShiftL#, iShiftRA#, iShiftRL# :: Int# -> Int# -> Int#
287         -- same shift ops, but on Int#s
288
289 int2Word#       :: Int#  -> Word# -- just a cast, really
290 word2Int#       :: Word# -> Int#
291 @
292
293 Unboxed-@Addr@ ops (C casts, really):
294 @
295 int2Addr#       :: Int#  -> Addr#
296 addr2Int#       :: Addr# -> Int#
297 @
298 Operations for indexing off of C pointers (@Addr#@s) to snatch values
299 are listed under ``arrays''.
300
301 \subsection{Arrays}
302
303 The type @Array# elt@ is the type of primitive,
304 unboxed arrays of values of type @elt@.  
305 @
306 type Array# elt
307 @
308 @Array#@ is more primitive than a Haskell
309 array --- indeed, Haskell arrays are implemented using @Array#@ ---
310 in that an @Array#@ is indexed only by @Int#@s, starting at zero.  It is also
311 more primitive by virtue of being unboxed.  That doesn't mean that it isn't
312 a heap-allocated object --- of course, it is.  Rather, being unboxed means
313 that it is represented by a pointer to the array itself, and not to a thunk
314 which will evaluate to the array (or to bottom).
315 The components of an @Array#@ are themselves boxed.
316
317 The type @ByteArray#@ is similar to @Array#@, except that it contains
318 just a string of (non-pointer) bytes.
319 @
320 type ByteArray#
321 @
322 Arrays of these types are useful when a Haskell program wishes to
323 construct a value to pass to a C procedure.  It is also possible to
324 use them to build (say) arrays of unboxed characters for internal use
325 in a Haskell program.  Given these uses, @ByteArray#@ is deliberately
326 a bit vague about the type of its components.  Operations are provided
327 to extract values of type @Char#@, @Int#@, @Float#@, @Double#@, and
328 @Addr#@ from arbitrary offsets within a @ByteArray#@.  (For type @Foo#@,
329 the $i$th offset gets you the $i$th @Foo#@, not the @Foo#@ at byte-position $i$.  Mumble.)
330 (If you want a @Word#@, grab an @Int#@, then coerce it.)
331
332 Lastly, we have static byte-arrays, of type @Addr#@ [mentioned
333 previously].  (Remember the duality between arrays and pointers in C.)
334 Arrays of this types are represented by a pointer to an array in the
335 world outside Haskell, so this pointer is not followed by the garbage
336 collector.  In other respects they are just like @ByteArray#@.  They
337 are only needed in order to pass values from C to Haskell.
338
339 \subsubsection{Reading and writing.}
340
341 Primitive arrays are linear, and indexed starting at zero.
342
343 The size and indices of a @ByteArray#@, @Addr#@, and
344 @MutableByteArray#@ are all in bytes.  It's up to the program to
345 calculate the correct byte offset from the start of the array.  This
346 allows a @ByteArray#@ to contain a mixture of values of different
347 type, which is often needed when preparing data for and unpicking
348 results from C.  (Umm... not true of indices... WDP 95/09)
349
350 {\em Should we provide some @sizeOfDouble#@ constants?}
351
352 Out-of-range errors on indexing should be caught by the code which
353 uses the primitive operation; the primitive operations themselves do
354 {\em not} check for out-of-range indexes. The intention is that the
355 primitive ops compile to one machine instruction or thereabouts.
356
357 We use the terms ``reading'' and ``writing'' to refer to accessing {\em mutable} 
358 arrays (see Section~\ref{sect:mutable}), and ``indexing'' 
359 to refer to reading a value from an {\em immutable} 
360 array.
361
362 If you want to read/write a @Word#@, read an @Int#@ and coerce.
363
364 Immutable byte arrays are straightforward to index (all indices in bytes):
365 @
366 indexCharArray#   :: ByteArray# -> Int# -> Char#
367 indexIntArray#    :: ByteArray# -> Int# -> Int#
368 indexAddrArray#   :: ByteArray# -> Int# -> Addr#
369 indexFloatArray#  :: ByteArray# -> Int# -> Float#
370 indexDoubleArray# :: ByteArray# -> Int# -> Double#
371
372 indexCharOffAddr#   :: Addr# -> Int# -> Char#
373 indexIntOffAddr#    :: Addr# -> Int# -> Int#
374 indexFloatOffAddr#  :: Addr# -> Int# -> Float#
375 indexDoubleOffAddr# :: Addr# -> Int# -> Double#
376 indexAddrOffAddr#   :: Addr# -> Int# -> Addr#   -- Get an Addr# from an Addr# offset
377 @
378 The last of these, @indexAddrOffAddr#@, extracts an @Addr#@ using an offset
379 from another @Addr#@, thereby providing the ability to follow a chain of
380 C pointers.
381
382 Something a bit more interesting goes on when indexing arrays of boxed
383 objects, because the result is simply the boxed object. So presumably
384 it should be entered --- we never usually return an unevaluated
385 object!  This is a pain: primitive ops aren't supposed to do
386 complicated things like enter objects.  The current solution is to
387 return a lifted value, but I don't like it!
388 @
389 indexArray#       :: Array# elt -> Int# -> GHCbase.Lift elt  -- Yuk!
390 @
391
392 \subsubsection{The state type}
393
394 The primitive type @State#@ represents the state of a state transformer.
395 It is parameterised on the desired type of state, which serves to keep
396 states from distinct threads distinct from one another.  But the {\em only}
397 effect of this parameterisation is in the type system: all values of type
398 @State#@ are represented in the same way.  Indeed, they are all 
399 represented by nothing at all!  The code generator ``knows'' to generate no 
400 code, and allocate no registers etc, for primitive states.
401 @
402 type State# s
403 @
404
405 The type @GHCbuiltins.RealWorld@ is truly opaque: there are no values defined
406 of this type, and no operations over it.  It is ``primitive'' in that
407 sense---but it is {\em not unboxed!} Its only role in life is to be the type
408 which distinguishes the @PrimIO@ state transformer (see
409 Section~\ref{sect:io-spec}).
410 @
411 data RealWorld
412 @
413
414 \subsubsection{States}
415
416 A single, primitive, value of type @State# RealWorld@ is provided.
417 @
418 realWorld# :: State# GHCbuiltins.RealWorld
419 @
420 (Note: in the compiler, not a @PrimOp@; just a mucho magic @Id@.)
421
422 \subsection{State pairing types}
423 \label{sect:horrid-pairing-types}
424
425 This subsection defines some types which, while they aren't quite primitive 
426 because we can define them in Haskell, are very nearly so.  They define 
427 constructors which pair a primitive state with a value of each primitive type.
428 They are required to express the result type of the primitive operations in the 
429 state monad.
430 @
431 data StateAndPtr#    s elt = StateAndPtr#    (State# s) elt 
432
433 data StateAndChar#   s     = StateAndChar#   (State# s) Char# 
434 data StateAndInt#    s     = StateAndInt#    (State# s) Int# 
435 data StateAndWord#   s     = StateAndWord#   (State# s) Word#
436 data StateAndFloat#  s     = StateAndFloat#  (State# s) Float# 
437 data StateAndDouble# s     = StateAndDouble# (State# s) Double#  
438 data StateAndAddr#   s     = StateAndAddr#   (State# s) Addr#
439
440 data StateAndStablePtr# s a = StateAndStablePtr#  (State# s) (StablePtr# a)
441 data StateAndForeignObj# s  = StateAndForeignObj# (State# s) ForeignObj#
442 data StateAndSynchVar#  s a = StateAndSynchVar#  (State# s) (SynchVar# a)
443
444 data StateAndArray#            s elt = StateAndArray#        (State# s) (Array# elt) 
445 data StateAndMutableArray#     s elt = StateAndMutableArray# (State# s) (MutableArray# s elt)  
446 data StateAndByteArray#        s = StateAndByteArray#        (State# s) ByteArray# 
447 data StateAndMutableByteArray# s = StateAndMutableByteArray# (State# s) (MutableByteArray# s)
448 @
449
450
451 \subsection{Mutable arrays}
452 \label{sect:mutable}
453
454 Corresponding to @Array#@ and @ByteArray#@,
455 we have the types of mutable versions of each.  
456 In each case, the representation is a pointer
457 to a suitable block of (mutable) heap-allocated storage.
458 @
459 type MutableArray# s elt
460 type MutableByteArray# s
461 @
462 \subsubsection{Allocation.}
463
464 Mutable arrays can be allocated.
465 Only pointer-arrays are initialised; arrays of non-pointers are filled
466 in by ``user code'' rather than by the array-allocation primitive.
467 Reason: only the pointer case has to worry about GC striking with a
468 partly-initialised array.
469 @
470 newArray#       :: Int# -> elt -> State# s -> StateAndMutableArray# s elt 
471
472 newCharArray#   :: Int# -> State# s -> StateAndMutableByteArray# s 
473 newIntArray#    :: Int# -> State# s -> StateAndMutableByteArray# s 
474 newAddrArray#   :: Int# -> State# s -> StateAndMutableByteArray# s 
475 newFloatArray#  :: Int# -> State# s -> StateAndMutableByteArray# s 
476 newDoubleArray# :: Int# -> State# s -> StateAndMutableByteArray# s 
477 @
478 The size of a @ByteArray#@ is given in bytes.
479
480 \subsubsection{Reading and writing}
481
482 %OLD: Remember, offsets in a @MutableByteArray#@ are in bytes.
483 @
484 readArray#       :: MutableArray# s elt -> Int# -> State# s -> StateAndPtr#    s elt
485 readCharArray#   :: MutableByteArray# s -> Int# -> State# s -> StateAndChar#   s
486 readIntArray#    :: MutableByteArray# s -> Int# -> State# s -> StateAndInt#    s
487 readAddrArray#   :: MutableByteArray# s -> Int# -> State# s -> StateAndAddr#   s 
488 readFloatArray#  :: MutableByteArray# s -> Int# -> State# s -> StateAndFloat#  s 
489 readDoubleArray# :: MutableByteArray# s -> Int# -> State# s -> StateAndDouble# s 
490
491 writeArray#       :: MutableArray# s elt -> Int# -> elt     -> State# s -> State# s 
492 writeCharArray#   :: MutableByteArray# s -> Int# -> Char#   -> State# s -> State# s 
493 writeIntArray#    :: MutableByteArray# s -> Int# -> Int#    -> State# s -> State# s 
494 writeAddrArray#   :: MutableByteArray# s -> Int# -> Addr#   -> State# s -> State# s 
495 writeFloatArray#  :: MutableByteArray# s -> Int# -> Float#  -> State# s -> State# s 
496 writeDoubleArray# :: MutableByteArray# s -> Int# -> Double# -> State# s -> State# s 
497 @
498
499 \subsubsection{Equality.}
500
501 One can take ``equality'' of mutable arrays.  What is compared is the
502 {\em name} or reference to the mutable array, not its contents.
503 @
504 sameMutableArray#     :: MutableArray# s elt -> MutableArray# s elt -> Bool
505 sameMutableByteArray# :: MutableByteArray# s -> MutableByteArray# s -> Bool
506 @
507
508 \subsubsection{Freezing mutable arrays}
509
510 Only unsafe-freeze has a primitive.  (Safe freeze is done directly in Haskell 
511 by copying the array and then using @unsafeFreeze@.) 
512 @
513 unsafeFreezeArray#     :: MutableArray# s elt -> State# s -> StateAndArray#     s elt
514 unsafeFreezeByteArray# :: MutableByteArray# s -> State# s -> StateAndByteArray# s
515 @
516
517 \subsubsection{Stable pointers}
518
519 {\em Andy's comment.} {\bf Errors:} The following is not strictly true: the current
520 implementation is not as polymorphic as claimed.  The reason for this
521 is that the C programmer will have to use a different entry-routine
522 for each type of stable pointer.  At present, we only supply a very
523 limited number (1) of these routines.  It might be possible to
524 increase the range of these routines by providing general purpose
525 entry points to apply stable pointers to (stable pointers to)
526 arguments and to enter (stable pointers to) boxed primitive values.
527 {\em End of Andy's comment.}
528
529 A stable pointer is a name for a Haskell object which can be passed to the 
530 external world.  It is ``stable'' in the sense that the name does not change when 
531 the Haskell garbage collector runs --- in contrast to the address of the object 
532 which may well change.
533
534 The stable pointer type is parameterised by the type of the thing which is named.
535 @
536 type StablePtr# a
537 @
538 A stable pointer is represented by an index into the (static) 
539 @StablePointerTable@.  The Haskell garbage collector treats the 
540 @StablePointerTable@ as a source of roots for GC.
541
542 The @makeStablePointer@ function converts a value into a stable pointer.
543 It is part of the @PrimIO@ monad, because we want to be sure we don't
544 allocate one twice by accident, and then only free one of the copies.
545 @
546 makeStablePointer#  :: a -> State# RealWorld -> StateAndStablePtr# RealWorld a
547 freeStablePointer#  :: StablePtr# a -> State# RealWorld -> State# RealWorld
548 deRefStablePointer# :: StablePtr# a -> State# RealWorld -> StateAndPtr RealWorld a
549 @
550 There is also a C procedure @FreeStablePtr@ which frees a stable pointer.
551
552 %
553 % Rewritten and updated for MallocPtr++ -- 4/96 SOF
554 %
555 \subsubsection{Foreign objects}
556
557 A @ForeignObj@ is a reference to an object outside the Haskell
558 world (i.e., from the C world, or a reference to an object on another
559 machine completely.), where the Haskell world has been told ``Let me
560 know when you're finished with this ...''.
561
562 The @ForeignObj@ type is just a special @Addr#@ ({\em not} parameterised).
563 @
564 type ForeignObj#
565 @
566
567 A typical use of @ForeignObj@ is in constructing Haskell bindings
568 to external libraries. A good example is that of writing a binding to
569 an image-processing library (which was actually the main motivation
570 for implementing @ForeignObj@'s precursor, @MallocPtr@). The
571 images manipulated are not stored in the Haskell heap, either because
572 the library insist on allocating them internally or we (sensibly)
573 decide to spare the GC from having to heave heavy images around.
574
575 @
576 data Image = Image ForeignObj#
577
578 instance CCallable Image
579 @
580
581 The @ForeignObj#@ type is then used to refer to the externally
582 allocated image, and to acheive some type safety, the Haskell binding
583 defines the @Image@ data type. So, a value of type @ForeignObj#@ is
584 used to ``box'' up an external reference into a Haskell heap object
585 that we can then indirectly reference:
586
587 @
588 createImage :: (Int,Int) -> PrimIO Image
589 @
590
591 So far, this looks just like an @Addr#@ type, but @ForeignObj#@
592 offers a bit more, namely that we can specify a {\em finalisation
593 routine} to invoke when the @ForeignObj#@ is discarded by the
594 GC. The garbage collector invokes the finalisation routine associated
595 with the @ForeignObj#@, saying `` Thanks, I'm through with this
596 now..'' For the image-processing library, the finalisation routine could for
597 the images free up memory allocated for them. The finalisation routine has
598 currently to be written in C (the finalisation routine can in turn call on
599 @FreeStablePtr@ to deallocate a stable pointer.).
600
601 Associating a finalisation routine with an external object is done by 
602 @makeForeignObj#@:
603
604 @
605 makeForeignObj# :: Addr# -- foreign reference
606                 -> Addr# -- pointer to finalisation routine
607                 -> StateAndForeignObj# RealWorld ForeignObj#
608 @
609
610 (Implementation: a linked list of all @ForeignObj#@s is maintained to allow the
611  garbage collector to detect when a @ForeignObj#@ becomes garbage.)
612
613 Like @Array@, @ForeignObj#@s are represented by heap objects.
614
615 {\bf ToDo:} Decide whether @FreeCHeapPointer@ is allowed to call on a
616 stable pointer. (I sincerely hope not since we will still be in the
617 GC at this point.)
618
619 \subsubsection{Synchronizing variables (I-vars, M-vars)}
620
621 ToDo ToDo ToDo
622
623 @
624 type SynchVar# s elt    -- primitive
625
626 newSynchVar#:: State# s -> StateAndSynchVar# s elt
627
628 takeMVar#   :: SynchVar# s elt -> State# s -> StateAndPtr# s elt
629 putMVar#    :: SynchVar# s elt -> State# s -> State# s
630
631 readIVar#   :: SynchVar# s elt -> State# s -> StateAndPtr# s elt
632 writeIVar#  :: SynchVar# s elt -> State# s -> State# s
633 @
634
635 \subsubsection{Controlling the garbage collector}
636
637 The C function {\tt PerformGC\/}, allows the C world to force Haskell
638 to do a garbage collection.  It can only be called while Haskell
639 is performing a C Call.
640
641 Note that this function can be used to define a Haskell IO operation
642 with the same effect:
643 @
644 >       performGCIO :: PrimIO ()
645 >       performGCIO = _ccall_gc_ PerformGC
646 @
647
648 {\bf ToDo:} Is there any need for abnormal/normal termination to force
649 a GC too?  Is there any need for a function that provides finer
650 control over GC: argument = amount of space required; result = amount
651 of space recovered.
652
653 \subsection{@spark#@ primitive operation (for parallel execution)}
654
655 {\em ToDo: say something}  It's used in the unfolding for @par@.
656
657 \subsection{The @errorIO#@ primitive operation}
658
659 The @errorIO#@ primitive takes an argument much like @PrimIO@.  It aborts execution of
660 the current program, and continues instead by performing the given @PrimIO@-like value
661 on the current state of the world.
662 @
663 errorIO# :: (State RealWorld -> ((), State RealWorld)) -> a
664 @
665
666 \subsection{C Calls}
667
668 {\bf ToDo:} current implementation has state variable as second
669 argument not last argument.
670
671 The @ccall#@ primitive can't be given an ordinary type, because it has
672 a variable number of arguments.  The nearest we can get is:
673 @
674 ccall# :: CRoutine -> a1# -> ... -> an# -> State# RealWorld -> StateAndR# RealWorld
675 @
676 where the type variables @a1#@\ldots@an#@ and @r#@ can be instantiated by any
677 primitive type, and @StateAndR#@ is the appropriate pairing type from 
678 Section~\ref{sect:horrid-pairing-types}.  The @CRoutine@ 
679 isn't a proper Haskell type at all; it just reminds us that @ccall#@ needs to 
680 know what C routine to call.
681
682 This notation is really short for a massive family of @ccall#@ primitives, one 
683 for each combination of types.  (Of course, the compiler simply remembers the 
684 types involved, and generates appropriate code when it finally spits out the C.)
685
686 Unlike all the other primitive operators, @ccall#@ is not bound to an in-scope 
687 identifier.  The only way it is possible to generate a @ccall#@ is via the 
688 @_ccall_@ construct.
689
690 All this applies equally to @casm#@:
691 @
692 casm#  :: CAsmString -> a1# -> ... -> an# -> State# RealWorld -> StateAndR# RealWorld
693 @
694
695 %------------------------------------------------------------
696 \section{Library stuff built with the Really Primitive Stuff}
697
698 \subsection{The state transformer monad}
699
700 \subsubsection{Types}
701
702 A state transformer is a function from a state to a pair of a result and a new 
703 state.  
704 @
705 newtype ST s a = ST (State s -> (a, State s))
706 @
707 The @ST@ type is {\em abstract}, so that the programmer cannot see its 
708 representation.  If he could, he could write bad things like:
709 @
710 bad :: ST s a
711 bad = ST $ \ s -> ...(f s)...(g s)...
712 @
713 Here, @s@ is duplicated, which would be bad news.
714
715 A state is represented by a primitive state value, of type @State# s@, 
716 wrapped up in a @State@ constructor.  The reason for boxing it in this
717 way is so that we can be strict or lazy in the state.  (Remember, all 
718 primitive types are unboxed, and hence can't be bottom; but types built
719 with @data@ are all boxed.)
720 @
721 data State s = S# (State# s)
722 @
723
724 \subsubsection{The state transformer combinators}
725
726 Now for the combinators, all of which live inside the @ST@
727 abstraction.  Notice that @returnST@ and @thenST@ are lazy in the
728 state.
729 @
730 returnST :: a -> ST s a
731 returnST a s = (a, s)
732
733 thenST :: ST s a -> (a -> ST s b) -> ST s b
734 thenST m k s = let (r,new_s) = m s
735                in 
736                k r new_s
737
738 fixST :: (a -> ST s a) -> ST s a
739 fixST k s = let ans = k r s
740                 (r,new_s) = ans
741             in
742             ans
743 @
744 The interesting one is, of course, @runST@.  We can't infer its type!
745 (It has a funny name because it must be wired into the compiler.)
746 @
747 -- runST :: forall a. (forall s. ST s a) -> a
748 runST m = case m (S# realWorld#) of
749            (r,_) -> r
750 @
751
752 \subsubsection{Other useful combinators}
753
754 There are various other standard combinators, all defined in terms the
755 fundamental combinators above. The @seqST@ combinator is like
756 @thenST@, except that it discards the result of the first state
757 transformer:
758 @
759 seqST :: ST s a -> ST s b -> ST s b
760 seqST m1 m2 = m1 `thenST` (\_ -> m2)
761 @
762
763 We also have {\em strict} (... in the state...) variants of the
764 then/return combinators (same types as their pals):
765 @
766 returnStrictlyST a s@(S# _) = (a, s)
767
768 thenStrictlyST m k s@(S# _)
769   = case (m s) of { (r, new_s@(S# _)) ->
770     k r new_s }
771
772 seqStrictlyST m k = ... ditto, for seqST ...
773 @
774
775 The combinator @listST@ takes a list of state transformers, and
776 composes them in sequence, returning a list of their results:
777 @
778 listST :: [ST s a] -> ST s [a]
779 listST []     = returnST []
780 listST (m:ms) = m               `thenST` \ r ->
781                 listST ms       `thenST` \ rs ->
782                 returnST (r:rs)
783 @
784 The @mapST@ combinator ``lifts'' a function from a value to state
785 transformers to one which works over a list of values:
786 @
787 mapST :: (a -> ST s b) -> [a] -> ST s [b]
788 mapST f ms = listST (map f ms)
789 @
790 The @mapAndUnzipST@ combinator is similar to @mapST@, except that here the
791 function returns a pair:
792 @
793 mapAndUnzipST :: (a -> ST s (b,c)) -> [a] -> ST s ([b],[c])
794 mapAndUnzipST f (m:ms)
795   = f m                 `thenST` \ ( r1,  r2) ->
796     mapAndUnzipST f ms  `thenST` \ (rs1, rs2) ->
797     returnST (r1:rs1, r2:rs2)
798 @
799
800 \subsubsection{The @PrimIO@ monad}
801 \label{sect:io-spec}
802
803 The @PrimIO@ type is defined in as a state transformer which manipulates the 
804 @RealWorld@.
805 @
806 type PrimIO a = ST RealWorld a      -- Transparent
807 @
808 The @PrimIO@ type is an ordinary type synonym, transparent to the programmer.
809
810 The type @RealWorld@ and value @realWorld#@ do not need to be hidden (although 
811 there is no particular point in exposing them).  Even having a value of type 
812 @realWorld#@ does not compromise safety, since the type @ST@ is hidden. 
813
814 It is type-correct to use @returnST@ in an I/O context, but it is a
815 bit more efficient to use @returnPrimIO@.  The latter is strict in the
816 state, which propagates backwards to all the earlier combinators
817 (provided they are unfolded).  Why is it safe for @returnPrimIO@ to be
818 strict in the state?  Because every context in which an I/O state
819 transformer is used will certainly evaluate the resulting state; it is
820 the state of the real world!
821 @
822 returnPrimIO :: a -> PrimIO a
823 returnPrimIO a s@(S# _) -> (a, s)
824 @
825 We provide strict versions of the other combinators too.
826 @
827 thenPrimIO m k s = case m s of
828                      (r,s) -> k r s
829 @
830 @fixPrimIO@ has to be lazy, though!
831 @
832 fixPrimIO  = fixST
833 @
834 The other combinators are just the same as before, but use the strict
835 @thenPrimIO@ and @returnPrimIO@ for efficiency.
836 @
837 foldrPrimIO f z []     = z
838 foldrPrimIO f z (m:ms) = foldrPrimIO f z ms `thenPrimIO` \ ms' ->
839                          f m ms'
840
841 listPrimIO ms = foldrPrimIO (\ a xs -> a `thenPrimIO` \ x -> returnPrimIO (x : xs))
842                 (returnPrimIO []) ms
843
844 mapPrimIO f ms = listPrimIO (map f ms)
845
846 mapAndUnzipPrimIO f (m:ms)
847   = f m                     `thenPrimIO` \ ( r1,  r2) ->
848     mapAndUnzipPrimIO f ms  `thenPrimIO` \ (rs1, rs2) ->
849     returnPrimIO (r1:rs1, r2:rs2)
850 @
851
852 \subsection{Arrays}
853
854 \subsubsection{Types}
855
856 @
857 data Array      ix elt = Array     (ix,ix) (Array# elt)
858 data ByteArray ix      = ByteArray (ix,ix) ByteArray#
859
860 data MutableArray     s ix elt = MutableArray     (ix,ix) (MutableArray# s elt)
861 data MutableByteArray s ix     = MutableByteArray (ix,ix) (MutableByteArray# s)
862 @
863
864 \subsubsection{Operations on immutable arrays}
865
866 Ordinary array indexing is straightforward.
867 @
868 (!) :: Ix ix => Array ix elt -> ix -> elt
869 @
870 QUESTIONs: should @ByteArray@s be indexed by Ints or ix?  With byte offsets
871 or sized ones? (sized ones [WDP])
872 @
873 indexCharArray   :: Ix ix => ByteArray ix -> ix -> Char
874 indexIntArray    :: Ix ix => ByteArray ix -> ix -> Int
875 indexAddrArray   :: Ix ix => ByteArray ix -> ix -> Addr
876 indexFloatArray  :: Ix ix => ByteArray ix -> ix -> Float
877 indexDoubleArray :: Ix ix => ByteArray ix -> ix -> Double
878 @
879 @Addr@s are indexed straightforwardly by @Int@s.  Unlike the primitive
880 operations, though, the offsets assume that the array consists entirely of the
881 type of value being indexed, and so there's an implicit multiplication by
882 the size of that value.  To access @Addr@s with mixed values requires
883 you to do a DIY job using the primitives.
884 @
885 indexAddrChar :: Addr -> Int -> Char
886 ...etc...
887 indexStaticCharArray   :: Addr -> Int -> Char
888 indexStaticIntArray    :: Addr -> Int -> Int
889 indexStaticFloatArray  :: Addr -> Int -> Float
890 indexStaticDoubleArray :: Addr -> Int -> Double
891 indexStaticArray       :: Addr -> Int -> Addr
892 @
893
894 \subsubsection{Operations on mutable arrays}
895 @
896 newArray     :: Ix ix => (ix,ix) -> elt -> ST s (MutableArray s ix elt)
897 newCharArray :: Ix ix => (ix,ix) -> ST s (MutableByteArray s ix) 
898 ...
899 @
900
901 @
902 readArray   :: Ix ix => MutableArray s ix elt -> ix -> ST s elt 
903 readCharArray   :: Ix ix => MutableByteArray s ix -> ix -> ST s Char 
904 ...
905 @
906
907 @
908 writeArray  :: Ix ix => MutableArray s ix elt -> ix -> elt -> ST s () 
909 writeCharArray  :: Ix ix => MutableByteArray s ix -> ix -> Char -> ST s () 
910 ...
911 @
912
913 @
914 freezeArray :: Ix ix => MutableArray s ix elt -> ST s (Array ix elt)
915 freezeCharArray :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
916 ...
917 @
918
919 We have no need on one-function-per-type for unsafe freezing:
920 @
921 unsafeFreezeArray :: Ix ix => MutableArray s ix elt -> ST s (Array ix elt)  
922 unsafeFreezeByteArray :: Ix ix => MutableByteArray s ix -> ST s (ByteArray ix)
923 @
924
925 Sometimes we want to snaffle the bounds of one of these beasts:
926 @
927 boundsOfArray     :: Ix ix => MutableArray s ix elt -> (ix, ix)  
928 boundsOfByteArray :: Ix ix => MutableByteArray s ix -> (ix, ix)
929 @
930
931 Lastly, ``equality'':
932 @
933 sameMutableArray     :: MutableArray s ix elt -> MutableArray s ix elt -> Bool
934 sameMutableByteArray :: MutableByteArray s ix -> MutableByteArray s ix -> Bool
935 @
936
937
938 \subsection{Variables}
939
940 \subsubsection{Types}
941
942 Mutable variables are (for now anyway) implemented as arrays.  The @MutableVar@ type
943 is opaque, so we can change the implementation later if we want.
944 @
945 type MutableVar s a = MutableArray s Int a
946 @
947
948 \subsubsection{Operations}
949 @
950 newVar   :: a -> ST s (MutableVar s a)
951 readVar  :: MutableVar s a -> ST s a
952 writeVar :: MutableVar s a -> a -> ST s ()
953 sameVar  :: MutableVar s a -> MutableVar s a -> Bool
954 @
955
956 \subsection{Stable pointers}
957
958 Nothing exciting here, just simple boxing up.
959 @
960 data StablePtr a = StablePtr (StablePtr# a)
961
962 makeStablePointer :: a -> StablePtr a
963 freeStablePointer :: StablePtr a -> PrimIO ()
964 @
965
966 \subsection{Foreign objects}
967
968 Again, just boxing up.
969 @
970 data ForeignObj = ForeignObj ForeignObj#
971
972 makeForeignObj :: Addr -> Addr -> PrimIO ForeignObj
973 @
974
975 \subsection{C calls}
976
977 Everything in this section goes for @_casm_@ too.
978
979 {\em ToDo: mention @_ccall_gc_@ and @_casm_gc_@...}
980
981 The @_ccall_@ construct has the following form:
982 $$@_ccall_@~croutine~a_1~\ldots~a_n$$
983 This whole construct has type $@PrimIO@~res$.
984 The rules are these:
985 \begin{itemize}
986 \item
987 The first ``argument'', $croutine$, must be the literal name of a C procedure.
988 It cannot be a Haskell expression which evaluates to a string, etc; it must be 
989 simply the name of the procedure.
990 \item
991 The arguments $a_1, \ldots,a_n$ must be of {\em C-callable} type.
992 \item
993 The whole construct has type $@PrimIO@~ty$, where $ty$ is a {\em C-returnable} type.
994 \end{itemize}
995 A {\em boxed-primitive} type is both C-callable and C-returnable.
996 A boxed primitive type is anything declared by:
997 @
998 data T = C# t
999 @
1000 where @t@ is a primitive type.  Note that
1001 programmer-defined boxed-primitive types are perfectly OK:
1002 @
1003 data Widget = W# Int#
1004 data Screen = S# CHeapPtr#
1005 @
1006
1007 There are other types that can be passed to C (C-callable).  This
1008 table summarises (including the standard boxed-primitive types):
1009 @
1010 Boxed             Type of transferd   Corresp.     Which is
1011 Type              Prim. component     C type       *probably*...
1012 ------            ---------------     ------       -------------
1013 Char              Char#               StgChar       unsigned char
1014 Int               Int#                StgInt        long int
1015 Word              Word#               StgWord       unsigned long int
1016 Addr              Addr#               StgAddr       char *
1017 Float             Float#              StgFloat      float
1018 Double            Double#             StgDouble     double
1019                                        
1020 Array             Array#              StgArray      StgPtr
1021 ByteArray         ByteArray#          StgByteArray  StgPtr
1022 MutableArray      MutableArray#       StgArray      StgPtr
1023 MutableByteArray  MutableByteArray#   StgByteArray  StgPtr
1024                                       
1025 State             State#              nothing!
1026                                       
1027 StablePtr         StablePtr#          StgStablePtr  StgPtr
1028 ForeignObj        ForeignObj#         StgForeignObj StgPtr
1029 @
1030
1031 All of the above are {\em C-returnable} except:
1032 @
1033         Array, ByteArray, MutableArray, MutableByteArray
1034 @
1035
1036 {\bf ToDo:} I'm pretty wary of @Array@ and @MutableArray@ being in
1037 this list, and not too happy about @State@ [WDP].
1038
1039 {\bf ToDo:} Can code generator pass all the primitive types?  Should this be
1040 extended to include {\tt Bool\/} (or any enumeration type?)
1041
1042 The type checker must be able to figure out just which of the C-callable/returnable
1043 types is being used.  If it can't, you have to add type signatures. For example,
1044 @
1045 f x = _ccall_ foo x
1046 @
1047 is not good enough, because the compiler can't work out what type @x@ is, nor 
1048 what type the @_ccall_@ returns.  You have to write, say:
1049 @
1050 f :: Int -> PrimIO Float
1051 f x = _ccall_ foo x
1052 @
1053
1054 \subsubsection{Implementation}
1055
1056 The desugarer unwraps the @_ccall_@ construct by inserting the necessary 
1057 evaluations etc to unbox the arguments.  For example, the body of the definition 
1058 of @f@ above would become:
1059 @
1060         (\ s -> case x of { I# x# -> 
1061                 case s of { S# s# ->
1062                 case ccall# [Int#,Float#] x# s# of { StateAndFloat# f# new_s# ->
1063                 (F# f#, S# new_s#)
1064                 }}})
1065 @
1066 Notice that the state, too, is unboxed.
1067
1068 The code generator must deal specially with primitive objects which
1069 are stored on the heap.
1070
1071 ... details omitted ...
1072
1073 %
1074 %More importantly, it must construct a C Heap Pointer heap-object after
1075 %a @_ccall_@ which returns a @MallocPtr#@.
1076 %
1077
1078 %--------------------------------------------------------
1079 \section{Non-primitive stuff that must be wired into GHC}
1080
1081 @
1082 data Char    = C# Char#
1083 data Int     = I# Int#
1084 data Word    = W# Word#
1085 data Addr    = A# Addr#
1086
1087 data Float   = F# Float#
1088 data Double  = D# Double#
1089 data Integer = J# Int# Int# ByteArray#
1090
1091 -- and the other boxed-primitive types:
1092     Array, ByteArray, MutableArray, MutableByteArray,
1093     StablePtr, ForeignObj
1094
1095 data Bool     = False | True
1096 data Ordering = LT | EQ | GT  -- used in derived comparisons
1097
1098 data List a = [] | a : (List a)
1099 -- tuples...
1100
1101 data Lift a = Lift a    -- used Yukkily as described elsewhere
1102
1103 type String  = [Char]    -- convenience, only
1104 @
1105
1106 %------------------------------------------------------------
1107 \section{Programmer interface(s)}
1108
1109 \subsection{The bog-standard interface}
1110
1111 If you rely on the implicit @import Prelude@ that GHC normally does
1112 for you, and if you don't use any weird flags (notably
1113 @-fglasgow-exts@), and if you don't import one of the fairly-magic
1114 @PreludeGla*@ interfaces, then GHC should work {\em exactly} as the
1115 Haskell report says, and the full user namespaces should be available
1116 to you.
1117
1118 \subsection{If you mess about with @import Prelude@...}
1119
1120 Innocent hiding, e.g.,
1121 @
1122 import Prelude hiding ( fromIntegral )
1123 @
1124 should work just fine.
1125
1126 There are some things you can do that will make GHC crash, e.g.,
1127 hiding a standard class:
1128 @
1129 import Prelude hiding ( Eq(..) )
1130 @
1131 Don't do that.
1132
1133 \subsection{Turning on Glasgow extensions with @-fglasgow-exts@}
1134
1135 If you turn on @-fglasgow-exts@, then all the primitive types and
1136 operations described herein are available.
1137
1138 It is possible that some name conflicts between your code and the
1139 wired-in things might spring to life (though we doubt it...).
1140 Change your names :-)
1141
1142 \end{document}
1143