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