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