a154908bc9308bfd7fe74a1e856d15d5548fced1
[ghc-hetmet.git] / ghc / docs / users_guide / glasgow_exts.vsgml
1
2 % $Id: glasgow_exts.vsgml,v 1.2 1998/07/20 16:16:34 sof Exp $
3 %
4 % GHC Language Extensions.
5 %
6
7 As with all known Haskell systems, GHC implements some extensions to
8 the language.  To use them, you'll need to give a @-fglasgow-exts@%
9 <nidx>-fglasgow-exts option</nidx> option.
10
11 Virtually all of the Glasgow extensions serve to give you access to
12 the underlying facilities with which we implement Haskell.  Thus, you
13 can get at the Raw Iron, if you are willing to write some non-standard
14 code at a more primitive level.  You need not be ``stuck'' on
15 performance because of the implementation costs of Haskell's
16 ``high-level'' features---you can always code ``under'' them.  In an
17 extreme case, you can write all your time-critical code in C, and then
18 just glue it together with Haskell!
19
20 Executive summary of our extensions:
21
22 <descrip>
23
24 <tag>Unboxed types and primitive operations:</tag> 
25
26 You can get right down to the raw machine types and operations;
27 included in this are ``primitive arrays'' (direct access to Big Wads
28 of Bytes).  Please see Section <ref name="Unboxed types"
29 id="glasgow-unboxed"> and following.
30
31 <tag>Multi-parameter type classes:</tag>
32
33 GHC's type system supports extended type classes with multiple
34 parameters.  Please see Section <ref name="Mult-parameter type
35 classes" id="multi-param-type-classes">.
36
37 <tag>Local universal quantification:</tag>
38
39 GHC's type system supports explicit unversal quantification in
40 constructor fields and function arguments.  This is useful for things
41 like defining @runST@ from the state-thread world amongst other
42 things.  See Section <ref name="Local universal quantification"
43 id="universal-quantification">.
44
45 <tag>Calling out to C:</tag> 
46
47 Just what it sounds like.  We provide <em>lots</em> of rope that you
48 can dangle around your neck.  Please see Section <ref name="Calling~C
49 directly from Haskell" id="glasgow-ccalls">.
50
51 </descrip>
52
53 Before you get too carried away working at the lowest level (e.g.,
54 sloshing @MutableByteArray#@s around your program), you may wish to
55 check if there are system libraries that provide a ``Haskellised
56 veneer'' over the features you want.  See Section <ref name="GHC
57 Prelude and libraries" id="ghc-prelude">.
58
59 %************************************************************************
60 %*                                                                      *
61 <sect1>Unboxed types
62 <label id="glasgow-unboxed">
63 <p>
64 <nidx>Unboxed types (Glasgow extension)</nidx>
65 %*                                                                      *
66 %************************************************************************
67
68 These types correspond to the ``raw machine'' types you would use in
69 C: @Int#@ (long int), @Double#@ (double), @Addr#@ (void *), etc.  The
70 <em>primitive operations</em> (PrimOps) on these types are what you
71 might expect; e.g., @(+#)@ is addition on @Int#@s, and is the
72 machine-addition that we all know and love---usually one instruction.
73
74 A numerically-intensive program using unboxed types can go a <em>lot</em>
75 faster than its ``standard'' counterpart---we saw a threefold speedup
76 on one example.
77
78 Please see Section <ref name="The module PrelGHC: really primitive
79 stuff" id="ghc-libs-ghc"> for the details of unboxed types and the
80 operations on them.
81
82 %************************************************************************
83 %*                                                                      *
84 <sect1>Primitive state-transformer monad
85 <label id="glasgow-ST-monad">
86 <p>
87 <nidx>state transformers (Glasgow extensions)</nidx>
88 <nidx>ST monad (Glasgow extension)</nidx>
89 %*                                                                      *
90 %************************************************************************
91
92 This monad underlies our implementation of arrays, mutable and
93 immutable, and our implementation of I/O, including ``C calls''.
94
95 The @ST@ library, which provides access to the @ST@ monad, is a
96 GHC/Hugs extension library and is described in the separate <htmlurl
97 name="GHC/Hugs Extension Libraries" url="libs.html"> document.
98
99 %************************************************************************
100 %*                                                                      *
101 <sect1>Primitive arrays, mutable and otherwise
102 <label id="glasgow-prim-arrays">
103 <p>
104 <nidx>primitive arrays (Glasgow extension)</nidx>
105 <nidx>arrays, primitive (Glasgow extension)</nidx>
106 %*                                                                      *
107 %************************************************************************
108
109 GHC knows about quite a few flavours of Large Swathes of Bytes.
110
111 First, GHC distinguishes between primitive arrays of (boxed) Haskell
112 objects (type @Array# obj@) and primitive arrays of bytes (type
113 @ByteArray#@).
114
115 Second, it distinguishes between...
116 <descrip>
117 <tag>Immutable:</tag>
118 Arrays that do not change (as with ``standard'' Haskell arrays); you
119 can only read from them.  Obviously, they do not need the care and
120 attention of the state-transformer monad.
121
122 <tag>Mutable:</tag>
123 Arrays that may be changed or ``mutated.''  All the operations on them
124 live within the state-transformer monad and the updates happen
125 <em>in-place</em>.
126
127 <tag>``Static'' (in C land):</tag>
128 A C~routine may pass an @Addr#@ pointer back into Haskell land.  There
129 are then primitive operations with which you may merrily grab values
130 over in C land, by indexing off the ``static'' pointer.
131
132 <tag>``Stable'' pointers:</tag>
133 If, for some reason, you wish to hand a Haskell pointer (i.e.,
134 <em>not</em> an unboxed value) to a C~routine, you first make the
135 pointer ``stable,'' so that the garbage collector won't forget that it
136 exists.  That is, GHC provides a safe way to pass Haskell pointers to
137 C.
138
139 Please see Section <ref name="Subverting automatic unboxing with
140 ``stable pointers''" id="glasgow-stablePtrs"> for more details.
141
142 <tag>``Foreign objects'':</tag>
143 A ``foreign object'' is a safe way to pass an external object (a
144 C~allocated pointer, say) to Haskell and have Haskell do the Right
145 Thing when it no longer references the object.  So, for example, C
146 could pass a large bitmap over to Haskell and say ``please free this
147 memory when you're done with it.'' 
148
149 Please see Section <ref name="Pointing outside the Haskell heap"
150 id="glasgow-foreignObjs"> for more details.
151
152 </descrip>
153
154 The libraries section give more details on all these ``primitive
155 array'' types and the operations on them, Section <ref name="The GHC
156 Prelude and Libraries" id="ghc-prelude">.  Some of these extensions
157 are also supported by Hugs, and the supporting libraries are described
158 in the <htmlurl name="GHC/Hugs Extension Libraries" url="libs.html">
159 document.
160
161 %************************************************************************
162 %*                                                                      *
163 <sect1>Using your own @mainIO@
164 <label id="own-mainIO">
165 <p>
166 <nidx>mainIO, rolling your own</nidx>
167 <nidx>GHCmain, module containing mainIO</nidx>
168 %*                                                                      *
169 %************************************************************************
170
171 Normally, the GHC runtime system begins things by called an internal
172 function 
173
174 <tscreen><verb>
175         mainIO :: IO ()
176 </verb></tscreen>
177
178  which, in turn, fires up your @Main.main@.  The standard
179 definition of @mainIO@ looks like this:
180
181 <tscreen><verb>
182         mainIO = catch Main.main 
183                    (\err -> error ("I/O error: " ++ show err ++ "\n"))
184 </verb></tscreen>
185
186 That is, all it does is run @Main.main@, catching any I/O errors that
187 occur and displaying them on standard error before exiting the
188 program.
189
190 To subvert the above process, you need only provide a @mainIO@ of your
191 own (in a module named @PrelMain@).
192
193 Here's a little example, stolen from Alastair Reid:
194
195 <tscreen><verb>
196 module GHCmain ( mainIO ) where
197
198 import GlaExts
199
200 mainIO :: IO ()
201 mainIO = do
202          _ccall_ sleep 5
203          _ccall_ printf "%d\n" (14::Int)
204 </verb></tscreen>
205
206 %************************************************************************
207 %*                                                                      *
208 <sect1>Calling~C directly from Haskell
209 <label id="glasgow-ccalls">
210 <p>
211 <nidx>C calls (Glasgow extension)</nidx>
212 <nidx>_ccall_ (Glasgow extension)</nidx>
213 <nidx>_casm_ (Glasgow extension)</nidx>
214 %*                                                                      *
215 %************************************************************************
216
217 GOOD ADVICE: Because this stuff is not Entirely Stable as far as names
218 and things go, you would be well-advised to keep your C-callery
219 corraled in a few modules, rather than sprinkled all over your code.
220 It will then be quite easy to update later on.
221
222 WARNING AS OF 2.03: Yes, the @_ccall_@ stuff probably <em>will
223 change</em>, to something better, of course!  One step in that
224 direction is Green Card, a foreign function interface pre-processor
225 for Haskell (``Glasgow'' Haskell in particular) --- check out
226
227 <tscreen><verb>
228 ftp://ftp.dcs.gla.ac.uk/pub/haskell/glasgow/green-card.ANNOUNCE
229 ftp://ftp.dcs.gla.ac.uk/pub/haskell/glasgow/green-card-src.tar.gz
230 </verb></tscreen>
231
232 %************************************************************************
233 %*                                                                      *
234 <sect2>@_ccall_@ and @_casm_@: an introduction
235 <label id="ccall-intro">
236 <p>
237 %*                                                                      *
238 %************************************************************************
239
240 The simplest way to use a simple C function
241
242 <tscreen><verb>
243 double fooC( FILE *in, char c, int i, double d, unsigned int u )
244 </verb></tscreen>
245
246 is to provide a Haskell wrapper:
247
248 <tscreen><verb>
249 fooH :: Char -> Int -> Double -> Word -> IO Double
250 fooH c i d w = _ccall_ fooC (``stdin''::Addr) c i d w
251 </verb></tscreen>
252
253 The function @fooH@ will unbox all of its arguments, call the C
254 function @fooC@ and box the corresponding arguments.
255
256 One of the annoyances about @_ccall_@s is when the C types don't quite
257 match the Haskell compiler's ideas.  For this, the @_casm_@ variant
258 may be just the ticket (NB: <em>no chance</em> of such code going
259 through a native-code generator):
260
261 <tscreen><verb>
262 oldGetEnv name
263   = _casm_ ``%r = getenv((char *) %0);'' name >>= \ litstring@(A# str#) ->
264     return (
265         if (litstring == ``NULL'') then
266             Left ("Fail:oldGetEnv:"++name)
267         else
268             Right (unpackCString# str#)
269     )
270 </verb></tscreen>
271
272 The first literal-literal argument to a @_casm_@ is like a @printf@
273 format: @%r@ is replaced with the ``result,'' @%0@--@%n-1@ are
274 replaced with the 1st--nth arguments.  As you can see above, it is an
275 easy way to do simple C~casting.  Everything said about @_ccall_@ goes
276 for @_casm_@ as well.
277
278 The use of @_casm_@ in your code does pose a problem to the compiler
279 when it comes to generating an interface file for a freshly compiled
280 module. Included in an interface file is the unfolding (if any) of a
281 declaration. However, if a declaration's unfolding happens to contain
282 a @_casm_@, its unfolding will <em/not/ be emitted into the interface
283 file even if it qualifies by all the other criteria. The reason why
284 the compiler prevents this from happening is that unfolding @_casm_@s
285 into an interface file unduly constrains how code that import your
286 module have to be compiled. If an imported declaration is unfolded and
287 it contains a @_casm_@, you now have to be using a compiler backend
288 capable of dealing with it (i.e., the C compiler backend). If you are
289 using the C compiler backend, the unfolded @_casm_@ may still cause you
290 problems since the C code snippet it contains may mention CPP symbols
291 that were in scope when compiling the original module are not when
292 compiling the importing module.
293
294 If you're willing to put up with the drawbacks of doing cross-module
295 inlining of C code (GHC - A Better C Compiler :-), the option
296 @-funfold-casms-in-hi-file@ will turn off the default behaviour.
297 <nidx>-funfold-casms-in-hi-file option</nidx>
298
299 %************************************************************************
300 %*                                                                      *
301 <sect2>Using function headers
302 <label id="glasgow-foreign-headers">
303 <p>
304 <nidx>C calls, function headers</nidx>
305 %*                                                                      *
306 %************************************************************************
307
308 When generating C (using the @-fvia-C@ directive), one can assist the
309 C compiler in detecting type errors by using the @-#include@ directive
310 to provide @.h@ files containing function headers.
311
312 For example,
313
314 <tscreen><verb>
315 typedef unsigned long *StgForeignObj;
316 typedef long StgInt;
317
318 void          initialiseEFS (StgInt size);
319 StgInt        terminateEFS (void);
320 StgForeignObj emptyEFS(void);
321 StgForeignObj updateEFS (StgForeignObj a, StgInt i, StgInt x);
322 StgInt        lookupEFS (StgForeignObj a, StgInt i);
323 </verb></tscreen>
324
325 You can find appropriate definitions for @StgInt@, @StgForeignObj@,
326 etc using @gcc@ on your architecture by consulting
327 @ghc/includes/StgTypes.lh@.  The following table summarises the
328 relationship between Haskell types and C types.
329
330 <tabular ca="ll">
331 <bf>C type name</bf>      | <bf>Haskell Type</bf> @@
332 @@
333 @StgChar@          | @Char#@ @@               
334 @StgInt@           | @Int#@ @@                
335 @StgWord@          | @Word#@ @@               
336 @StgAddr@          | @Addr#@ @@               
337 @StgFloat@         | @Float#@ @@              
338 @StgDouble@        | @Double#@ @@             
339
340 @StgArray@         | @Array#@ @@              
341 @StgByteArray@     | @ByteArray#@ @@          
342 @StgArray@         | @MutableArray#@ @@       
343 @StgByteArray@     | @MutableByteArray#@ @@   
344
345 @StgStablePtr@     | @StablePtr#@ @@
346 @StgForeignObj@    | @ForeignObj#@
347 </tabular>
348
349 Note that this approach is only <em>essential</em> for returning
350 @float@s (or if @sizeof(int) != sizeof(int *)@ on your
351 architecture) but is a Good Thing for anyone who cares about writing
352 solid code.  You're crazy not to do it.
353
354 %************************************************************************
355 %*                                                                      *
356 <sect2>Subverting automatic unboxing with ``stable pointers''
357 <label id="glasgow-stablePtrs">
358 <p>
359 <nidx>stable pointers (Glasgow extension)</nidx>
360 %*                                                                      *
361 %************************************************************************
362
363 The arguments of a @_ccall_@ are automatically unboxed before the
364 call.  There are two reasons why this is usually the Right Thing to
365 do:
366
367 <itemize>
368 <item>
369 C is a strict language: it would be excessively tedious to pass
370 unevaluated arguments and require the C programmer to force their
371 evaluation before using them.
372
373 <item> Boxed values are stored on the Haskell heap and may be moved
374 within the heap if a garbage collection occurs---that is, pointers
375 to boxed objects are not <em>stable</em>.
376 </itemize>
377
378 It is possible to subvert the unboxing process by creating a ``stable
379 pointer'' to a value and passing the stable pointer instead.  For
380 example, to pass/return an integer lazily to C functions @storeC@ and
381 @fetchC@, one might write:
382
383 <tscreen><verb>
384 storeH :: Int -> IO ()
385 storeH x = makeStablePtr x              >>= \ stable_x ->
386            _ccall_ storeC stable_x
387
388 fetchH :: IO Int
389 fetchH x = _ccall_ fetchC               >>= \ stable_x ->
390            deRefStablePtr stable_x      >>= \ x ->
391            freeStablePtr stable_x       >>
392            return x
393 </verb></tscreen>
394
395 The garbage collector will refrain from throwing a stable pointer away
396 until you explicitly call one of the following from C or Haskell.
397
398 <tscreen><verb>
399 void freeStablePointer( StgStablePtr stablePtrToToss )
400 freeStablePtr :: StablePtr a -> IO ()
401 </verb></tscreen>
402
403 As with the use of @free@ in C programs, GREAT CARE SHOULD BE
404 EXERCISED to ensure these functions are called at the right time: too
405 early and you get dangling references (and, if you're lucky, an error
406 message from the runtime system); too late and you get space leaks.
407
408 And to force evaluation of the argument within @fooC@, one would
409 call one of the following C functions (according to type of argument).
410
411 <tscreen><verb>
412 void     performIO  ( StgStablePtr stableIndex /* StablePtr s (IO ()) */ );
413 StgInt   enterInt   ( StgStablePtr stableIndex /* StablePtr s Int */ );
414 StgFloat enterFloat ( StgStablePtr stableIndex /* StablePtr s Float */ );
415 </verb></tscreen>
416
417 <nidx>performIO</nidx>
418 <nidx>enterInt</nidx>
419 <nidx>enterFloat</nidx>
420
421 % ToDo ADR: test these functions!
422
423 Note Bene: @_ccall_GC_@<nidx>_ccall_GC_</nidx> must be used if any of
424 these functions are used.
425
426 %************************************************************************
427 %*                                                                      *
428 <sect2>Pointing outside the Haskell heap
429 <label id="glasgow-foreignObjs">
430 <p>
431 <nidx>foreign objects (Glasgow extension)</nidx>
432 %*                                                                      *
433 %************************************************************************
434
435 There are two types that @ghc@ programs can use to reference
436 (heap-allocated) objects outside the Haskell world: @Addr@ and
437 @ForeignObj@.
438
439 If you use @Addr@, it is up to you to the programmer to arrange
440 allocation and deallocation of the objects.
441
442 If you use @ForeignObj@, @ghc@'s garbage collector will call upon the
443 user-supplied <em>finaliser</em> function to free the object when the
444 Haskell world no longer can access the object.  (An object is
445 associated with a finaliser function when the abstract
446  Haskell type @ForeignObj@ is created). The finaliser function is
447 expressed in C, and is passed as argument the object:
448
449 <tscreen><verb>
450 void foreignFinaliser ( StgForeignObj fo )
451 </verb></tscreen>
452
453 when the Haskell world can no longer access the object.  Since
454 @ForeignObj@s only get released when a garbage collection occurs, we
455 provide ways of triggering a garbage collection from within C and from
456 within Haskell.
457
458 <tscreen><verb>
459 void StgPerformGarbageCollection()
460 performGC :: IO ()
461 </verb></tscreen>
462
463 More information on the programmers' interface to @ForeignObj@ can be
464 found in Section <ref name="Foreign objects" id="sec:foreign-obj">.
465
466 %************************************************************************
467 %*                                                                      *
468 <sect2>Avoiding monads
469 <label id="glasgow-avoiding-monads">
470 <p>
471 <nidx>C calls to `pure C'</nidx>
472 <nidx>unsafePerformIO</nidx>
473 %*                                                                      *
474 %************************************************************************
475
476 The @_ccall_@ construct is part of the @IO@ monad because 9 out of 10
477 uses will be to call imperative functions with side effects such as
478 @printf@.  Use of the monad ensures that these operations happen in a
479 predictable order in spite of laziness and compiler optimisations.
480
481 To avoid having to be in the monad to call a C function, it is
482 possible to use @unsafePerformIO@, which is available from the
483 @IOExts@ module.  There are three situations where one might like to
484 call a C function from outside the IO world:
485
486 <itemize>
487 <item>
488 Calling a function with no side-effects:
489 <tscreen><verb>
490 atan2d :: Double -> Double -> Double
491 atan2d y x = unsafePerformIO (_ccall_ atan2d y x)
492
493 sincosd :: Double -> (Double, Double)
494 sincosd x = unsafePerformIO $ do
495         da <- newDoubleArray (0, 1)
496         _casm_ ``sincosd( %0, &((double *)%1[0]), &((double *)%1[1]) );'' x da
497         s <- readDoubleArray da 0
498         c <- readDoubleArray da 1
499         return (s, c)
500 </verb></tscreen>
501
502 <item> Calling a set of functions which have side-effects but which can
503 be used in a purely functional manner.
504
505 For example, an imperative implementation of a purely functional
506 lookup-table might be accessed using the following functions.
507
508 <tscreen><verb>
509 empty  :: EFS x
510 update :: EFS x -> Int -> x -> EFS x
511 lookup :: EFS a -> Int -> a
512
513 empty = unsafePerformIO (_ccall_ emptyEFS)
514
515 update a i x = unsafePerformIO $
516         makeStablePtr x         >>= \ stable_x ->
517         _ccall_ updateEFS a i stable_x
518
519 lookup a i = unsafePerformIO $
520         _ccall_ lookupEFS a i   >>= \ stable_x ->
521         deRefStablePtr stable_x
522 </verb></tscreen>
523
524 You will almost always want to use @ForeignObj@s with this.
525
526 <item> Calling a side-effecting function even though the results will
527 be unpredictable.  For example the @trace@ function is defined by:
528
529 <tscreen><verb>
530 trace :: String -> a -> a
531 trace string expr
532   = unsafePerformIO (
533         ((_ccall_ PreTraceHook sTDERR{-msg-}):: IO ())  >>
534         fputs sTDERR string                             >>
535         ((_ccall_ PostTraceHook sTDERR{-msg-}):: IO ()) >>
536         return expr )
537   where
538     sTDERR = (``stderr'' :: Addr)
539 </verb></tscreen>
540
541 (This kind of use is not highly recommended --- it is only really
542 useful in debugging code.)
543 </itemize>
544
545 %************************************************************************
546 %*                                                                      *
547 <sect2>C-calling ``gotchas'' checklist
548 <label id="ccall-gotchas">
549 <p>
550 <nidx>C call dangers</nidx>
551 %*                                                                      *
552 %************************************************************************
553
554 And some advice, too.
555
556 <itemize>
557 <item> For modules that use @_ccall_@s, etc., compile with
558 @-fvia-C@.<nidx>-fvia-C option</nidx> You don't have to, but you should.
559
560 Also, use the @-#include "prototypes.h"@ flag (hack) to inform the C
561 compiler of the fully-prototyped types of all the C functions you
562 call.  (Section <ref name="Using function headers"
563 id="glasgow-foreign-headers"> says more about this...)
564
565 This scheme is the <em>only</em> way that you will get <em>any</em>
566 typechecking of your @_ccall_@s.  (It shouldn't be that way,
567 but...)
568
569 <item>
570 Try to avoid @_ccall_@s to C~functions that take @float@
571 arguments or return @float@ results.  Reason: if you do, you will
572 become entangled in (ANSI?) C's rules for when arguments/results are
573 promoted to @doubles@.  It's a nightmare and just not worth it.
574 Use @doubles@ if possible.
575
576 If you do use @floats@, check and re-check that the right thing is
577 happening.  Perhaps compile with @-keep-hc-file-too@ and look at
578 the intermediate C (@.hc@ file).
579
580 <item> The compiler uses two non-standard type-classes when
581 type-checking the arguments and results of @_ccall_@: the arguments
582 (respectively result) of @_ccall_@ must be instances of the class
583 @CCallable@ (respectively @CReturnable@).  Both classes may be
584 imported from the module @CCall@, but this should only be
585 necessary if you want to define a new instance.  (Neither class
586 defines any methods --- their only function is to keep the
587 type-checker happy.)
588
589 The type checker must be able to figure out just which of the
590 C-callable/returnable types is being used.  If it can't, you have to
591 add type signatures. For example,
592
593 <tscreen><verb>
594 f x = _ccall_ foo x
595 </verb></tscreen>
596
597 is not good enough, because the compiler can't work out what type @x@
598 is, nor what type the @_ccall_@ returns.  You have to write, say:
599
600 <tscreen><verb>
601 f :: Int -> IO Double
602 f x = _ccall_ foo x
603 </verb></tscreen>
604
605 This table summarises the standard instances of these classes.
606
607 % ToDo: check this table against implementation!
608
609 <tabular ca="llll">
610 <bf>Type</bf>       |<bf>CCallable</bf>|<bf>CReturnable</bf> | <bf>Which is probably...</bf> @@
611
612 @Char@              | Yes  | Yes   | @unsigned char@ @@
613 @Int@               | Yes  | Yes   | @long int@ @@
614 @Word@              | Yes  | Yes   | @unsigned long int@ @@
615 @Addr@              | Yes  | Yes   | @void *@ @@
616 @Float@             | Yes  | Yes   | @float@ @@
617 @Double@            | Yes  | Yes   | @double@ @@
618 @()@                | No   | Yes   | @void@ @@
619 @[Char]@            | Yes  | No    | @char *@ (null-terminated) @@
620                                       
621 @Array@             | Yes  | No    | @unsigned long *@ @@
622 @ByteArray@         | Yes  | No    | @unsigned long *@ @@
623 @MutableArray@      | Yes  | No    | @unsigned long *@ @@
624 @MutableByteArray@  | Yes  | No    | @unsigned long *@ @@
625                                        
626 @State@             | Yes  | Yes   | nothing!@@
627                                        
628 @StablePtr@         | Yes  | Yes   | @unsigned long *@ @@
629 @ForeignObjs@       | Yes  | Yes   | see later @@
630 </tabular>
631
632 The brave and careful programmer can add their own instances of these
633 classes for the following types:
634
635 <itemize>
636 <item>
637 A <em>boxed-primitive</em> type may be made an instance of both
638 @CCallable@ and @CReturnable@.  
639
640 A boxed primitive type is any data type with a
641 single unary constructor with a single primitive argument.  For
642 example, the following are all boxed primitive types:
643
644 <tscreen><verb>
645 Int
646 Double
647 data XDisplay = XDisplay Addr#
648 data EFS a = EFS# ForeignObj#
649 </verb></tscreen>
650
651 <tscreen><verb>
652 instance CCallable   (EFS a)
653 instance CReturnable (EFS a)
654 </verb></tscreen>
655
656 <item> Any datatype with a single nullary constructor may be made an
657 instance of @CReturnable@.  For example:
658
659 <tscreen><verb>
660 data MyVoid = MyVoid
661 instance CReturnable MyVoid
662 </verb></tscreen>
663
664 <item> As at version 2.09, @String@ (i.e., @[Char]@) is still
665 not a @CReturnable@ type.
666
667 Also, the now-builtin type @PackedString@ is neither
668 @CCallable@ nor @CReturnable@.  (But there are functions in
669 the PackedString interface to let you get at the necessary bits...)
670 </itemize>
671
672 <item> The code-generator will complain if you attempt to use @%r@ in
673 a @_casm_@ whose result type is @IO ()@; or if you don't use @%r@
674 <em>precisely</em> once for any other result type.  These messages are
675 supposed to be helpful and catch bugs---please tell us if they wreck
676 your life.
677
678 <item> If you call out to C code which may trigger the Haskell garbage
679 collector (examples of this later...), then you must use the
680 @_ccall_GC_@<nidx>_ccall_GC_ primitive</nidx> or
681 @_casm_GC_@<nidx>_casm_GC_ primitive</nidx> variant of C-calls.  (This
682 does not work with the native code generator - use @\fvia-C@.) This
683 stuff is hairy with a capital H!  </itemize>
684
685 <sect1> Multi-parameter type classes
686 <label id="multi-param-type-classes">
687 <p>
688
689 (ToDo)
690
691 <sect1> Local universal quantification
692 <label id="universal-quantification">
693 <p>
694
695 (ToDo)