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