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