[project @ 1997-03-24 04:42:42 by sof]
[ghc-hetmet.git] / ghc / docs / users_guide / glasgow_exts.lit
1 %************************************************************************
2 %*                                                                      *
3 \section[glasgow-exts]{Glasgow extensions to Haskell}
4 \index{Haskell, Glasgow extensions}
5 \index{extensions, Glasgow Haskell}
6 %*                                                                      *
7 %************************************************************************
8
9 As with all known Haskell systems, GHC implements some extensions to
10 the language.
11 To use them, you'll need to give
12 a \tr{-fglasgow-exts}%
13 \index{-fglasgow-exts option} option.
14
15 Virtually all of the Glasgow extensions serve to give you access to the
16 underlying facilities with which we implement Haskell.  Thus, you can
17 get at the Raw Iron, if you are willing to write some non-standard
18 code at a more primitive level.  You need not be ``stuck'' on
19 performance because of the implementation costs of Haskell's
20 ``high-level'' features---you can always code ``under'' them.  In an
21 extreme case, you can write all your time-critical code in C, and then
22 just glue it together with Haskell!
23
24 Executive summary of our extensions:
25 \begin{description}
26 \item[Unboxed types and primitive operations:] You can get right down
27 to the raw machine types and operations; included in this are
28 ``primitive arrays'' (direct access to Big Wads of Bytes).
29 Please see \Sectionref{glasgow-unboxed} and following.
30
31 \item[Calling out to C:] Just what it sounds like.  We provide {\em
32 lots} of rope that you can dangle around your neck.
33 Please see \Sectionref{glasgow-ccalls}.
34
35 \item[Low-level monadic I/O:] Monadic I/O is now standard with Haskell~1.3;
36 you can still get access to the system at a lower level (the ``PrimIO'' level).
37
38 \item[``HBC-ish'' extensions:] Extensions implemented because people said,
39 ``HBC does Y.  Could you teach GHC to do the same?''  Please see
40 \Sectionref{glasgow-hbc-exts} for a quick list.
41 \end{description}
42
43 Before you get too carried away working at the lowest level (e.g.,
44 sloshing \tr{MutableByteArray#}s around your program), you may wish to
45 check if there are system libraries that provide a ``Haskellised
46 veneer'' over the features you want.  See \Sectionref{syslibs}.
47
48 The definitive guide for many of the low-level facilities in GHC is
49 the ``state interface document'' (distributed in
50 \tr{ghc/docs/state-interface.dvi}).  We do not repeat its details here.
51
52 %Pieter Hartel led an interesting comparison-of-many-compilers (and
53 %many languages) in which GHC got to show off its extensions.  We did
54 %very well!  For the full details, check out
55 %\tr{pub/computer-systems/functional/packages/pseudoknot.tar.Z} on \tr{ftp.fwi.uva.nl}.
56 %Good clean fun!
57
58 %************************************************************************
59 %*                                                                      *
60 \subsection[glasgow-unboxed]{Unboxed types}
61 \index{Unboxed types (Glasgow extension)}
62 %*                                                                      *
63 %************************************************************************
64
65 These types correspond to the ``raw machine'' types you would use in
66 C: \tr{Int#} (long int), \tr{Double#} (double),
67 \tr{Addr#} (void *), etc.  The {\em primitive
68 operations} (PrimOps) on these types are what you might expect; e.g.,
69 \tr{(+#)} is addition on \tr{Int#}s, and is the machine-addition that
70 we all know and love---usually one instruction.
71
72 A numerically-intensive program using unboxed types can go a {\em lot}
73 faster than its ``standard'' counterpart---we saw a threefold speedup
74 on one example.
75
76 Please see the very first part of the ``state interface document''
77 (distributed in \tr{ghc/docs/state-interface.dvi}) for the details of
78 unboxed types and the operations on them.
79
80 %************************************************************************
81 %*                                                                      *
82 \subsection[glasgow-ST-monad]{Primitive state-transformer monad}
83 \index{state transformers (Glasgow extensions)}
84 %*                                                                      *
85 %************************************************************************
86
87 This monad underlies our implementation of arrays, mutable and immutable,
88 and our implementation of I/O, including ``C calls''.
89
90 You probably won't use the monad directly, but you might use all those
91 other things!
92
93 The ``state interface document'' defines the state-related types in
94 sections~1.4 and~1.5, and the monad itself in section~2.1.
95
96 %************************************************************************
97 %*                                                                      *
98 \subsection[glasgow-prim-arrays]{Primitive arrays, mutable and otherwise}
99 \index{primitive arrays (Glasgow extension)}
100 \index{arrays, primitive (Glasgow extension)}
101 %*                                                                      *
102 %************************************************************************
103
104 GHC knows about quite a few flavours of Large Swathes of Bytes.
105
106 First, GHC distinguishes between primitive arrays of (boxed) Haskell
107 objects (type \tr{Array# obj}) and primitive arrays of bytes (type
108 \tr{ByteArray#}).
109
110 Second, it distinguishes between...
111 \begin{description}
112 \item[Immutable:]
113 Arrays that do not change (as with ``standard'' Haskell arrays); you
114 can only read from them.  Obviously, they do not need the care and
115 attention of the state-transformer monad.
116
117 \item[Mutable:]
118 Arrays that may be changed or ``mutated.''  All the operations on them
119 live within the state-transformer monad and the updates happen {\em
120 in-place}.
121
122 \item[``Static'' (in C land):]
123 A C~routine may pass an \tr{Addr#} pointer back into Haskell land.
124 There are then primitive operations with which you may merrily grab
125 values over in C land, by indexing off the ``static'' pointer.
126
127 \item[``Stable'' pointers:]
128 If, for some reason, you wish to hand a Haskell pointer (i.e., {\em
129 not} an unboxed value) to a C~routine, you first make the pointer
130 ``stable,'' so that the garbage collector won't forget that it exists.
131 That is, GHC provides a safe way to pass Haskell pointers to C.
132
133 Please see \Sectionref{glasgow-stablePtrs} for more details.
134
135 \item[``Foreign objects'':]
136 A ``foreign object'' is a safe way to pass an external object (a
137 C~allocated pointer, say) to Haskell and have Haskell do the Right
138 Thing when it no longer references the object.  So, for example, C
139 could pass a large bitmap over to Haskell and say ``please free this
140 memory when you're done with it.'' 
141
142 Please see \Sectionref{glasgow-foreignObjs} for more details.
143 \end{description}
144
145 See sections~1.4 and~1.6 of the ``state interface document'' for the
146 details of all these ``primitive array'' types and the operations on
147 them.
148
149
150 %************************************************************************
151 %*                                                                      *
152 \subsection[own-mainPrimIO]{Using your own @mainPrimIO@}
153 \index{mainPrimIO, rolling your own}
154 %*                                                                      *
155 %************************************************************************
156
157 Normally, the GHC runtime system begins things by called an internal
158 function @mainPrimIO :: PrimIO ()@ which, in turn, fires up
159 your @Main.main@.
160
161 To subvert the above process, you need only provide a
162 @mainPrimIO :: PrimIO ()@ of your own (in a module named \tr{GHCmain}).
163
164 Here's a little example, stolen from Alastair Reid:
165 \begin{verbatim}
166 module GHCmain ( mainPrimIO ) where
167
168 import PreludeGlaST
169
170 mainPrimIO :: PrimIO ()
171 mainPrimIO = do
172          sleep 5
173          _ccall_ printf "%d\n" (14::Int)
174
175 sleep :: Int -> PrimIO ()
176 sleep t = _ccall_ sleep t
177 \end{verbatim}
178
179 %************************************************************************
180 %*                                                                      *
181 \subsection[glasgow-ccalls]{Calling~C directly from Haskell}
182 \index{C calls (Glasgow extension)}
183 \index{_ccall_ (Glasgow extension)}
184 \index{_casm_ (Glasgow extension)}
185 %*                                                                      *
186 %************************************************************************
187
188 %Besides using a \tr{-fglasgow-exts} flag, your modules need to include...
189 %\begin{verbatim}
190 %import PreludePrimIO
191 %\end{verbatim}
192
193 GOOD ADVICE: Because this stuff is not Entirely Stable as far as names
194 and things go, you would be well-advised to keep your C-callery
195 corraled in a few modules, rather than sprinkled all over your code.
196 It will then be quite easy to update later on.
197
198 WARNING AS OF 2.02: Yes, the \tr{_ccall_} stuff probably {\em will
199 change}, to something better, of course!  We are still at the
200 musing-about-it stage, however...
201
202 %************************************************************************
203 %*                                                                      *
204 \subsubsection[ccall-intro]{\tr{_ccall_} and \tr{_casm_}: an introduction}
205 %*                                                                      *
206 %************************************************************************
207
208 The simplest way to use a simple C function
209 \begin{verbatim}
210 double fooC( FILE *in, char c, int i, double d, unsigned int u )
211 \end{verbatim}
212 is to provide a Haskell wrapper:
213 \begin{verbatim}
214 fooH :: Char -> Int -> Double -> Word -> PrimIO Double
215 fooH c i d w = _ccall_ fooC (``stdin''::Addr) c i d w
216 \end{verbatim}
217 The function @fooH@ will unbox all of its arguments, call the C
218 function \tr{fooC} and box the corresponding arguments.
219
220 So, if you want to do C-calling, you have to confront the underlying
221 I/O system (at the ``PrimIO'' level).
222
223 %The code in \tr{ghc/lib/glaExts/*.lhs} is not too obtuse.
224 %That code, plus \tr{lib/prelude/Builtin.hs}, give examples
225 %of its use.  The latter includes the implementations of \tr{error} and
226 %\tr{trace}.
227
228 One of the annoyances about \tr{_ccall_}s is when the C types don't quite
229 match the Haskell compiler's ideas.  For this, the \tr{_casm_} variant
230 may be just the ticket (NB: {\em no chance} of such code going through
231 a native-code generator):
232 \begin{verbatim}
233 oldGetEnv name
234   = _casm_ ``%r = getenv((char *) %0);'' name >>= \ litstring@(A# str#) ->
235     return (
236         if (litstring == ``NULL'') then
237             Left ("Fail:oldGetEnv:"++name)
238         else
239             Right (unpackCString# str#)
240     )
241 \end{verbatim}
242
243 The first literal-literal argument to a \tr{_casm_} is like a
244 \tr{printf} format: \tr{%r} is replaced with the ``result,''
245 \tr{%0}--\tr{%n-1} are replaced with the 1st--nth arguments.  As you
246 can see above, it is an easy way to do simple C~casting.  Everything
247 said about \tr{_ccall_} goes for \tr{_casm_} as well.
248
249 %************************************************************************
250 %*                                                                      *
251 \subsubsection[glasgow-foreign-headers]{Using function headers}
252 \index{C calls---function headers}
253 %*                                                                      *
254 %************************************************************************
255
256 When generating C (using the \tr{-fvia-C} directive), one can assist
257 the C compiler in detecting type errors by using the \tr{-#include}
258 directive to provide \tr{.h} files containing function headers.
259
260 For example,
261 \begin{verbatim}
262 typedef unsigned long *StgForeignObj;
263 typedef long StgInt;
264
265 void          initialiseEFS (StgInt size);
266 StgInt        terminateEFS (void);
267 StgForeignObj emptyEFS(void);
268 StgForeignObj updateEFS (StgForeignObj a, StgInt i, StgInt x);
269 StgInt        lookupEFS (StgForeignObj a, StgInt i);
270 \end{verbatim}
271
272 You can find appropriate definitions for \tr{StgInt},
273 \tr{StgForeignObj}, etc using \tr{gcc} on your architecture by
274 consulting \tr{ghc/includes/StgTypes.lh}.  The following table
275 summarises the relationship between Haskell types and C types.
276
277 \begin{tabular}{ll}
278 C type name      & Haskell Type \\ \hline
279 %-----           & ---------------     
280 \tr{StgChar}          & \tr{Char#}\\               
281 \tr{StgInt}           & \tr{Int#}\\                
282 \tr{StgWord}          & \tr{Word#}\\               
283 \tr{StgAddr}          & \tr{Addr#}\\               
284 \tr{StgFloat}         & \tr{Float#}\\              
285 \tr{StgDouble}        & \tr{Double#}\\             
286                             
287 \tr{StgArray}         & \tr{Array#}\\              
288 \tr{StgByteArray}     & \tr{ByteArray#}\\          
289 \tr{StgArray}         & \tr{MutableArray#}\\       
290 \tr{StgByteArray}     & \tr{MutableByteArray#}\\   
291                                     
292 \tr{StgStablePtr}     & \tr{StablePtr#}\\          
293 \tr{StgForeignObj}    & \tr{ForeignObj#}
294 \end{tabular}
295
296 Note that this approach is only {\em essential\/} for returning
297 \tr{float}s (or if \tr{sizeof(int) != sizeof(int *)} on your
298 architecture) but is a Good Thing for anyone who cares about writing
299 solid code.  You're crazy not to do it.
300
301 %************************************************************************
302 %*                                                                      *
303 \subsubsection[glasgow-stablePtrs]{Subverting automatic unboxing with ``stable pointers''}
304 \index{stable pointers (Glasgow extension)}
305 %*                                                                      *
306 %************************************************************************
307
308 The arguments of a \tr{_ccall_} are automatically unboxed before the
309 call.  There are two reasons why this is usually the Right Thing to do:
310 \begin{itemize}
311 \item
312 C is a strict language: it would be excessively tedious to pass
313 unevaluated arguments and require the C programmer to force their
314 evaluation before using them.
315
316 \item Boxed values are stored on the Haskell heap and may be moved
317 within the heap if a garbage collection occurs---that is, pointers
318 to boxed objects are not {\em stable\/}.
319 \end{itemize}
320
321 It is possible to subvert the unboxing process by creating a ``stable
322 pointer'' to a value and passing the stable pointer instead.  For example, to
323 pass/return an integer lazily to C functions \tr{storeC} and
324 \tr{fetchC}, one might write:
325 \begin{verbatim}
326 storeH :: Int -> PrimIO ()
327 storeH x = makeStablePtr x              >>= \ stable_x ->
328            _ccall_ storeC stable_x
329
330 fetchH :: PrimIO Int
331 fetchH x = _ccall_ fetchC               >>= \ stable_x ->
332            deRefStablePtr stable_x      >>= \ x ->
333            freeStablePtr stable_x       >>
334            return x
335 \end{verbatim}
336
337 The garbage collector will refrain from throwing a stable pointer away
338 until you explicitly call one of the following from C or Haskell.
339 \begin{verbatim}
340 void freeStablePointer( StgStablePtr stablePtrToToss )
341 freeStablePtr :: StablePtr a -> PrimIO ()
342 \end{verbatim}
343
344 As with the use of \tr{free} in C programs, GREAT CARE SHOULD BE
345 EXERCISED to ensure these functions are called at the right time: too
346 early and you get dangling references (and, if you're lucky, an error
347 message from the runtime system); too late and you get space leaks.
348
349 %Doesn't work in ghc-0.23 - best to just keep quiet about them.
350 %
351 %And to force evaluation of the argument within \tr{fooC}, one would
352 %call one of the following C functions (according to type of argument).
353 %
354 %\begin{verbatim}
355 %void     performIO  ( StgStablePtr stableIndex /* StablePtr s (PrimIO ()) */ );
356 %StgInt   enterInt   ( StgStablePtr stableIndex /* StablePtr s Int */ );
357 %StgFloat enterFloat ( StgStablePtr stableIndex /* StablePtr s Float */ );
358 %\end{verbatim}
359 %
360 %ToDo ADR: test these functions!
361 %
362 %Note Bene: \tr{_ccall_GC_} must be used if any of these functions are used.
363
364
365 %************************************************************************
366 %*                                                                      *
367 \subsubsection[glasgow-foreignObjs]{Pointing outside the Haskell heap}
368 \index{foreign objects (Glasgow extension)}
369 %*                                                                      *
370 %************************************************************************
371
372 There are two types that \tr{ghc} programs can use to reference
373 (heap-allocated) objects outside the Haskell world: \tr{Addr} and
374 \tr{ForeignObj}.
375
376 If you use \tr{Addr}, it is up to you to the programmer to arrange
377 allocation and deallocation of the objects.
378
379 If you use \tr{ForeignObj}, \tr{ghc}'s garbage collector will
380 call the user-supplied C function
381 \begin{verbatim}
382 void freeForeignObj( StgForeignObj garbageMallocPtr )
383 \end{verbatim}
384 when the Haskell world can no longer access the object.  Since
385 \tr{ForeignObj}s only get released when a garbage collection occurs,
386 we provide ways of triggering a garbage collection from within C and
387 from within Haskell.
388 \begin{verbatim}
389 void StgPerformGarbageCollection()
390 performGC :: PrimIO ()
391 \end{verbatim}
392
393 %************************************************************************
394 %*                                                                      *
395 \subsubsection[glasgow-avoiding-monads]{Avoiding monads}
396 \index{C calls to `pure C'}
397 \index{unsafePerformPrimIO (PreludeGlaST)}
398 %*                                                                      *
399 %************************************************************************
400
401 The \tr{_ccall_} construct is part of the \tr{PrimIO} monad because 9
402 out of 10 uses will be to call imperative functions with side effects
403 such as \tr{printf}.  Use of the monad ensures that these operations
404 happen in a predictable order in spite of laziness and compiler
405 optimisations.
406
407 There are three situations where one might like to use
408 @unsafePerformPrimIO@ to avoid the monad:
409 \begin{itemize}
410 \item
411 Calling a function with no side-effects:
412 \begin{verbatim}
413 atan2d :: Double -> Double -> Double
414 atan2d y x = unsafePerformPrimIO (_ccall_ atan2d y x)
415
416 sincosd :: Double -> (Double, Double)
417 sincosd x = unsafePerformPrimIO $
418         newDoubleArray (0, 1)           >>= \ da ->
419         _casm_ ``sincosd( %0, &((double *)%1[0]), &((double *)%1[1]) );'' x da
420                                         >>
421         readDoubleArray da 0            >>= \ s ->
422         readDoubleArray da 1            >>= \ c ->
423         return (s, c)
424 \end{verbatim}
425
426 \item Calling a set of functions which have side-effects but which can
427 be used in a purely functional manner.
428
429 For example, an imperative implementation of a purely functional
430 lookup-table might be accessed using the following functions.
431
432 \begin{verbatim}
433 empty :: EFS x
434 update :: EFS x -> Int -> x -> EFS x
435 lookup :: EFS a -> Int -> a
436
437 empty = unsafePerformPrimIO (_ccall_ emptyEFS)
438
439 update a i x = unsafePerformPrimIO $
440         makeStablePtr x         >>= \ stable_x ->
441         _ccall_ updateEFS a i stable_x
442
443 lookup a i = unsafePerformPrimIO $
444         _ccall_ lookupEFS a i   >>= \ stable_x ->
445         deRefStablePtr stable_x
446 \end{verbatim}
447
448 You will almost always want to use \tr{ForeignObj}s with this.
449
450 \item Calling a side-effecting function even though the results will
451 be unpredictable.  For example the \tr{trace} function is defined by:
452
453 \begin{verbatim}
454 trace :: String -> a -> a
455 trace string expr
456   = unsafePerformPrimIO (
457         ((_ccall_ PreTraceHook sTDERR{-msg-}):: PrimIO ())  >>
458         fputs sTDERR string                                 >>
459         ((_ccall_ PostTraceHook sTDERR{-msg-}):: PrimIO ()) >>
460         returnPrimIO expr )
461   where
462     sTDERR = (``stderr'' :: Addr)
463 \end{verbatim}
464
465 (This kind of use is not highly recommended --- it is only really
466 useful in debugging code.)
467 \end{itemize}
468
469 %************************************************************************
470 %*                                                                      *
471 \subsubsection[ccall-gotchas]{C-calling ``gotchas'' checklist}
472 \index{C call dangers}
473 %*                                                                      *
474 %************************************************************************
475
476 And some advice, too.
477
478 \begin{itemize}
479 \item
480 \tr{_ccall_} is part of the \tr{PrimIO} monad --- not the 1.3 \tr{IO} Monad.
481 Use the function 
482 \begin{verbatim}
483 primIOToIO :: PrimIO a -> IO a
484 \end{verbatim}
485 to promote a \tr{_ccall_} to the \tr{IO} monad.
486
487 \item
488 For modules that use \tr{_ccall_}s, etc., compile with \tr{-fvia-C}.\index{-fvia-C option}
489 You don't have to, but you should.
490
491 Also, use the \tr{-#include "prototypes.h"} flag (hack) to inform the
492 C compiler of the fully-prototyped types of all the C functions you
493 call.  (\Sectionref{glasgow-foreign-headers} says more about this...)
494
495 This scheme is the {\em only} way that you will get {\em any}
496 typechecking of your \tr{_ccall_}s.  (It shouldn't be that way,
497 but...)
498
499 \item
500 Try to avoid \tr{_ccall_}s to C~functions that take \tr{float}
501 arguments or return \tr{float} results.  Reason: if you do, you will
502 become entangled in (ANSI?) C's rules for when arguments/results are
503 promoted to \tr{doubles}.  It's a nightmare and just not worth it.
504 Use \tr{doubles} if possible.
505
506 If you do use \tr{floats}, check and re-check that the right thing is
507 happening.  Perhaps compile with \tr{-keep-hc-file-too} and look at
508 the intermediate C (\tr{.hc} file).
509
510 \item
511 The compiler uses two non-standard type-classes when
512 type-checking the arguments and results of \tr{_ccall_}: the arguments
513 (respectively result) of \tr{_ccall_} must be instances of the class
514 \tr{CCallable} (respectively \tr{CReturnable}).  (Neither class
515 defines any methods --- their only function is to keep the
516 type-checker happy.)
517
518 The type checker must be able to figure out just which of the
519 C-callable/returnable types is being used.  If it can't, you have to
520 add type signatures. For example,
521 \begin{verbatim}
522 f x = _ccall_ foo x
523 \end{verbatim}
524 is not good enough, because the compiler can't work out what type @x@ is, nor 
525 what type the @_ccall_@ returns.  You have to write, say:
526 \begin{verbatim}
527 f :: Int -> PrimIO Double
528 f x = _ccall_ foo x
529 \end{verbatim}
530
531 This table summarises the standard instances of these classes.
532
533 % ToDo: check this table against implementation!
534
535 \begin{tabular}{llll}
536 Type                &CCallable&CReturnable & Which is probably... \\ \hline
537 %------            ----------  ------------    -------------
538 \tr{Char}              & Yes  & Yes   & \tr{unsigned char} \\
539 \tr{Int}               & Yes  & Yes   & \tr{long int} \\
540 \tr{Word}              & Yes  & Yes   & \tr{unsigned long int} \\
541 \tr{Addr}              & Yes  & Yes   & \tr{char *} \\
542 \tr{Float}             & Yes  & Yes   & \tr{float} \\
543 \tr{Double}            & Yes  & Yes   & \tr{double} \\
544 \tr{()}                & No   & Yes   & \tr{void} \\
545 \tr{[Char]}            & Yes  & No    & \tr{char *} (null-terminated) \\
546                                       
547 \tr{Array}             & Yes  & No    & \tr{unsigned long *}\\
548 \tr{ByteArray}         & Yes  & No    & \tr{unsigned long *}\\
549 \tr{MutableArray}      & Yes  & No    & \tr{unsigned long *}\\
550 \tr{MutableByteArray}  & Yes  & No    & \tr{unsigned long *}\\
551                                        
552 \tr{State}             & Yes  & Yes   & nothing!\\
553                                        
554 \tr{StablePtr}         & Yes  & Yes   & \tr{unsigned long *}\\
555 \tr{ForeignObjs}       & Yes  & Yes   & see later\\
556 \end{tabular}
557
558 The brave and careful programmer can add their own instances of these
559 classes for the following types:
560 \begin{itemize}
561 \item
562 A {\em boxed-primitive} type may be made an instance of both
563 \tr{CCallable} and \tr{CReturnable}.  
564
565 A boxed primitive type is any data type with a
566 single unary constructor with a single primitive argument.  For
567 example, the following are all boxed primitive types:
568
569 \begin{verbatim}
570 Int
571 Double
572 data XDisplay = XDisplay Addr#
573 data EFS a = EFS# ForeignObj#
574 \end{verbatim}
575
576 \begin{verbatim}
577 instance CCallable   (EFS a)
578 instance CReturnable (EFS a)
579 \end{verbatim}
580
581 \item Any datatype with a single nullary constructor may be made an
582 instance of \tr{CReturnable}.  For example:
583
584 \begin{verbatim}
585 data MyVoid = MyVoid
586 instance CReturnable MyVoid
587 \end{verbatim}
588
589 \item As at version 2.02, \tr{String} (i.e., \tr{[Char]}) is still
590 not a \tr{CReturnable} type.
591
592 Also, the now-builtin type \tr{PackedString} is neither
593 \tr{CCallable} nor \tr{CReturnable}.  (But there are functions in
594 the PackedString interface to let you get at the necessary bits...)
595 \end{itemize}
596
597 \item
598 The code-generator will complain if you attempt to use \tr{%r}
599 in a \tr{_casm_} whose result type is \tr{PrimIO ()}; or if you don't
600 use \tr{%r} {\em precisely\/} once for any other result type.  These
601 messages are supposed to be helpful and catch bugs---please tell us
602 if they wreck your life.
603
604 \item
605 If you call out to C code which may trigger the Haskell garbage
606 collector (examples of this later...), then you must use the
607 \tr{_ccall_GC_} or \tr{_casm_GC_} variant of C-calls.  (This does not
608 work with the native code generator - use \tr{\fvia-C}.) This stuff is
609 hairy with a capital H!
610 \end{itemize}
611
612 %************************************************************************
613 %*                                                                      *
614 %\subsubsection[ccall-good-practice]{C-calling ``good practice'' checklist}
615 %*                                                                      *
616 %************************************************************************
617
618 %************************************************************************
619 %*                                                                      *
620 \subsubsection[glasgow-prim-interface]{Access to the \tr{PrimIO} monad}
621 \index{PrimIO monad (Glasgow extension)}
622 \index{I/O, primitive (Glasgow extension)}
623 %*                                                                      *
624 %************************************************************************
625
626 The \tr{IO} monad (new in Haskell~1.3) catches errors and passes them
627 along.  It is built on top of the \tr{ST} state-transformer monad.
628
629 A related (and inter-operable-with) monad is the \tr{PrimIO} monad
630 (NB: the level at which @_ccall_@s work...), where you handle errors
631 yourself.
632
633 Should you wish to use the \tr{PrimIO} monad directly, you can import
634 \tr{PreludeGlaST}.  It makes available the usual monadic stuff (@>>=@,
635 @>>@, @return@, etc.), as well as these functions:
636 \begin{verbatim}
637 -- for backward compatibility:
638 returnPrimIO    :: a -> PrimIO a
639 thenPrimIO      :: PrimIO a -> (a -> PrimIO b) -> PrimIO b
640 seqPrimIO       :: PrimIO a -> PrimIO b -> PrimIO b
641
642 -- still useful:
643 fixPrimIO       :: (a -> PrimIO a) -> PrimIO a
644 forkPrimIO      :: PrimIO a -> PrimIO a
645 listPrimIO      :: [PrimIO a] -> PrimIO [a]
646 mapAndUnzipPrimIO :: (a -> PrimIO (b,c)) -> [a] -> PrimIO ([b],[c])
647 mapPrimIO       :: (a -> PrimIO b) -> [a] -> PrimIO [b]
648
649 unsafePerformPrimIO     :: PrimIO a -> a
650 unsafeInterleavePrimIO  :: PrimIO a -> PrimIO a
651   -- and they are not called "unsafe" for nothing!
652
653 -- to convert back and forth between IO and PrimIO
654 ioToPrimIO :: IO     a -> PrimIO a
655 primIOToIO :: PrimIO a -> IO     a
656 \end{verbatim}
657
658
659 %************************************************************************
660 %*                                                                      *
661 \subsection[glasgow-hbc-exts]{``HBC-ish'' extensions implemented by GHC}
662 \index{HBC-like Glasgow extensions}
663 \index{extensions, HBC-like}
664 %*                                                                      *
665 %************************************************************************
666
667 \begin{description}
668 %-------------------------------------------------------------------
669 \item[@fromInt@ method in class @Num@:]
670 It's there.  Converts from an \tr{Int} to the type.
671
672 %-------------------------------------------------------------------
673 \item[@toInt@ method in class @Integral@:]
674 Converts from type type to an \tr{Int}.
675
676 %-------------------------------------------------------------------
677 \item[Overlapping instance declarations:]
678 \index{overlapping instances}
679 \index{instances, overlapping}
680
681 In \tr{instance <context> => Class (T x1 ... xn)}, the \tr{xi}s can be
682 {\em types}, rather than just {\em type variables}.
683
684 Thus, you can have an instance \tr{instance Foo [Char]}, as well as
685 the more general \tr{instance Foo [a]}; the former will be used in
686 preference to the latter, where applicable.
687
688 As Lennart says, ``This is a dubious feature and should not be used
689 carelessly.''
690
691 See also: \tr{SPECIALIZE instance} pragmas, in \Sectionref{faster}.
692
693 %-------------------------------------------------------------------
694 % \item[Signal-handling I/O request:]
695 % \index{signal handling (extension)}
696 % \index{SigAction I/O request}
697 % The Haskell-1.2 I/O request \tr{SigAction n act} installs a signal handler for signal
698 % \tr{n :: Int}.  The number is the usual UNIX signal number.  The action
699 % is of this type:
700 % \begin{verbatim}
701 % data SigAct
702 %   = SAIgnore
703 %   | SADefault
704 %   | SACatch Dialogue
705 % \end{verbatim}
706
707 % The corresponding continuation-style I/O function is the unsurprising:
708 % \begin{verbatim}
709 % sigAction :: Int -> SigAct -> FailCont -> SuccCont -> Dialogue
710 % \end{verbatim}
711
712 % When a signal handler is installed with \tr{SACatch}, receipt of the
713 % signal causes the current top-level computation to be abandoned, and
714 % the specified dialogue to be executed instead.  The abandoned
715 % computation may leave some partially evaluated expressions in a
716 % non-resumable state.  If you believe that your top-level computation
717 % and your signal handling dialogue may share subexpressions, you should
718 % execute your program with the \tr{-N} RTS option, to prevent
719 % black-holing.
720
721 % The \tr{-N} option is not available with concurrent/parallel programs,
722 % so great care should be taken to avoid shared subexpressions between
723 % the top-level computation and any signal handlers when using threads.
724
725 %-------------------------------------------------------------------
726 %\item[Simple time-out mechanism, in ``monadic I/O'':]
727 %\index{time-outs (extension)}
728 %
729 %This function is available: 
730 %\begin{verbatim} 
731 %timeoutIO :: Int -> IO Void -> IO (IO Void) 
732 %\end{verbatim} 
733 %
734 %Wait that many seconds, then abandon the current computation and
735 %perform the given I/O operation (second argument).  Uses the
736 %signal-handling, so it returns the previous signal-handler (in case
737 %you want to re-install it).  As above, you may need to execute your
738 %program with the RTS flag \tr{-N}, to prevent black-holing.
739 %
740 \end{description}
741
742 %************************************************************************
743 %*                                                                      *
744 %\subsection[glasgow-compiler-namespace]{Fiddlings the compiler's built-in namespaces}
745 %*                                                                      *
746 %************************************************************************
747
748 %This is really only used for compiling the prelude.  It's turgid and
749 %will probably change.
750
751 % \begin{description}
752 % \item[\tr{-no-implicit-prelude}:]
753 % \index{-no-implicit-prelude option}
754
755 % ???? (Tells the parser not to read \tr{Prelude.hi}).
756
757 % \item[\tr{-fhide-builtin-names}:]
758 % \index{-fhide-builtin-names option}
759 % This hides {\em all} Prelude names built-in to the compiler.
760
761 % \item[\tr{-fmin-builtin-names}:]
762 % \index{-fmin-builtin-names option}
763 % This hides all but a few of the Prelude names that are built-in to the
764 % compiler.  @:@ (cons) is an example of one that would remain visible.
765
766 % \item[\tr{-fhide-builtin-instances}:]
767 % \index{-fhide-builtin-instances option}
768 % This suppresses the compiler's own ideas about what instances already
769 % exist (e.g., \tr{instance Eq Int}).
770
771 % This flag is used when actually compiling the various instance
772 % declarations in the Prelude.
773 % \end{description}