[project @ 1997-05-18 04:33:03 by sof]
[ghc-hetmet.git] / ghc / docs / users_guide / syslib.lit
1 %************************************************************************
2 %*                                                                      *
3 \section[syslibs]{System libraries}
4 \index{system libraries}
5 \index{libraries, system}
6 %*                                                                      *
7
8 This section gives an overview of the interfaces provided
9 by the different {\em syslibs} that comes bundled with GHC.
10
11 At the moment, there four different collections of system libraries:
12
13 \begin{itemize}
14 \item The GHC system library - collection of interfaces that mainly
15 have grown out of abstractions used to implement GHC itself.
16 \item Parts of the HBC libraries.
17 \item The Posix interface - a quality interface to OS functionality as
18 specified by {\tt POSIX 1003.1}. Sadly, this library hasn't made it
19 into a standard Haskell library.
20 \item The contrib libraries - oodles of numeric codes..
21 \end{itemize}
22
23 If you provide a \tr{-syslib <name>}\index{-syslib <name> option}
24 option on the command line, then the interfaces for that library will
25 come into scope (and may be \tr{import}ed), and the code will be added
26 in at link time. 
27
28
29 %************************************************************************
30 %*                                                                      *
31 \subsection[GHC-library]{The GHC system library}
32 \index{library, GHC}
33 \index{GHC library}
34 %*                                                                      *
35 %************************************************************************
36
37 We have started to put together a ``GHC system library.''
38
39 At the moment, the library is made of generally-useful bits of the
40 compiler itself.
41
42 To use this library, just give a \tr{-syslib ghc}\index{-syslib ghc option}
43 option to GHC, both for compiling and linking.
44
45 %************************************************************************
46 %*                                                                      *
47 \subsubsection[Bag]{The @Bag@ type}
48 \index{Bag module (GHC syslib)}
49 %*                                                                      *
50 %************************************************************************
51
52 A {\em bag} is an unordered collection of elements which may contain
53 duplicates.  To use, \tr{import Bag}.
54
55 \begin{verbatim}
56 data Bag elt    -- abstract
57
58 emptyBag        :: Bag elt
59 unitBag         :: elt -> Bag elt
60
61 consBag         :: elt       -> Bag elt -> Bag elt
62 snocBag         :: Bag elt   -> elt     -> Bag elt
63
64 unionBags       :: Bag elt   -> Bag elt -> Bag elt
65 unionManyBags   :: [Bag elt] -> Bag elt
66
67 isEmptyBag      :: Bag elt   -> Bool
68 elemBag         :: Eq elt => elt -> Bag elt -> Bool
69
70 filterBag       :: (elt -> Bool) -> Bag elt -> Bag elt
71 partitionBag    :: (elt -> Bool) -> Bag elt-> (Bag elt, Bag elt)
72         -- returns the elements that do/don't satisfy the predicate
73
74 concatBag       :: Bag (Bag a) -> Bag a 
75 foldBag         :: (r -> r -> r) -> (a -> r) -> r -> Bag a -> r
76 mapBag          :: (a -> b) -> Bag a -> Bag b
77
78 listToBag       :: [elt] -> Bag elt
79 bagToList       :: Bag elt -> [elt]
80 \end{verbatim}
81
82 %************************************************************************
83 %*                                                                      *
84 \subsubsection[FiniteMap]{The @FiniteMap@ type}
85 \index{FiniteMap module (GHC syslib)}
86 %*                                                                      *
87 %************************************************************************
88
89 What functional programmers call a {\em finite map}, everyone else
90 calls a {\em lookup table}.
91
92 Out code is derived from that in this paper:
93 \begin{display}
94 S Adams
95 "Efficient sets: a balancing act"
96 Journal of functional programming 3(4) Oct 1993, pages 553-562
97 \end{display}
98 Guess what?  The implementation uses balanced trees.
99
100 \begin{verbatim}
101 data FiniteMap key elt  -- abstract
102
103 --      BUILDING
104 emptyFM         :: FiniteMap key elt
105 unitFM          :: key -> elt -> FiniteMap key elt
106 listToFM        :: Ord key => [(key,elt)] -> FiniteMap key elt
107                         -- In the case of duplicates, the last is taken
108
109 --      ADDING AND DELETING
110                    -- Throws away any previous binding
111                    -- In the list case, the items are added starting with the
112                    -- first one in the list
113 addToFM         :: Ord key => FiniteMap key elt -> key -> elt  -> FiniteMap key elt
114 addListToFM     :: Ord key => FiniteMap key elt -> [(key,elt)] -> FiniteMap key elt
115
116                  -- Combines with previous binding
117                  -- In the combining function, the first argument is
118                  -- the "old" element, while the second is the "new" one.
119 addToFM_C       :: Ord key => (elt -> elt -> elt)
120                            -> FiniteMap key elt -> key -> elt  
121                            -> FiniteMap key elt
122 addListToFM_C   :: Ord key => (elt -> elt -> elt)
123                            -> FiniteMap key elt -> [(key,elt)] 
124                            -> FiniteMap key elt
125
126                  -- Deletion doesn't complain if you try to delete something
127                  -- which isn't there
128 delFromFM       :: Ord key => FiniteMap key elt -> key   -> FiniteMap key elt
129 delListFromFM   :: Ord key => FiniteMap key elt -> [key] -> FiniteMap key elt
130
131 --      COMBINING
132                  -- Bindings in right argument shadow those in the left
133 plusFM          :: Ord key => FiniteMap key elt -> FiniteMap key elt
134                            -> FiniteMap key elt
135
136                    -- Combines bindings for the same thing with the given function
137 plusFM_C        :: Ord key => (elt -> elt -> elt) 
138                            -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
139
140 minusFM         :: Ord key => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
141                    -- (minusFM a1 a2) deletes from a1 any bindings which are bound in a2
142
143 intersectFM     :: Ord key => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt 
144 intersectFM_C   :: Ord key => (elt -> elt -> elt)
145                            -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt 
146
147 --      MAPPING, FOLDING, FILTERING
148 foldFM          :: (key -> elt -> a -> a) -> a -> FiniteMap key elt -> a
149 mapFM           :: (key -> elt1 -> elt2) -> FiniteMap key elt1 -> FiniteMap key elt2
150 filterFM        :: Ord key => (key -> elt -> Bool) 
151                            -> FiniteMap key elt -> FiniteMap key elt
152
153 --      INTERROGATING
154 sizeFM          :: FiniteMap key elt -> Int
155 isEmptyFM       :: FiniteMap key elt -> Bool
156
157 elemFM          :: Ord key => key -> FiniteMap key elt -> Bool
158 lookupFM        :: Ord key => FiniteMap key elt -> key -> Maybe elt
159 lookupWithDefaultFM
160                 :: Ord key => FiniteMap key elt -> elt -> key -> elt
161                 -- lookupWithDefaultFM supplies a "default" elt
162                 -- to return for an unmapped key
163
164 --      LISTIFYING
165 fmToList        :: FiniteMap key elt -> [(key,elt)]
166 keysFM          :: FiniteMap key elt -> [key]
167 eltsFM          :: FiniteMap key elt -> [elt]
168 \end{verbatim}
169
170 %************************************************************************
171 %*                                                                      *
172 \subsubsection[ListSetOps]{The @ListSetOps@ type}
173 \index{ListSetOps module (GHC syslib)}
174 %*                                                                      *
175 %************************************************************************
176
177 Just a few set-sounding operations on lists.  If you want sets, use
178 the \tr{Set} module.
179
180 \begin{verbatim}
181 unionLists          :: Eq a => [a] -> [a] -> [a]
182 intersectLists      :: Eq a => [a] -> [a] -> [a]
183 minusList           :: Eq a => [a] -> [a] -> [a]
184 disjointLists       :: Eq a => [a] -> [a] -> Bool
185 intersectingLists   :: Eq a => [a] -> [a] -> Bool
186 \end{verbatim}
187
188 %************************************************************************
189 %*                                                                      *
190 \subsubsection[Maybes]{The @Maybes@ type}
191 \index{Maybes module (GHC syslib)}
192 %*                                                                      *
193 %************************************************************************
194
195 The \tr{Maybe} type is in the Haskell 1.4 prelude. Moreover, the
196 required \tr{Maybe} library provides many useful functions on
197 \tr{Maybe}s. This (pre-1.3) module provides some more:
198
199 An \tr{Either}-like type called \tr{MaybeErr}:
200 \begin{verbatim}
201 data MaybeErr val err = Succeeded val | Failed err
202 \end{verbatim}
203
204 Some operations to do with \tr{Maybe} (some commentary follows):
205 \begin{verbatim}
206 maybeToBool :: Maybe a -> Bool      -- Nothing => False; Just => True
207 allMaybes   :: [Maybe a] -> Maybe [a]
208 firstJust   :: [Maybe a] -> Maybe a
209 findJust    :: (a -> Maybe b) -> [a] -> Maybe b
210
211 assocMaybe  :: Eq a => [(a,b)] -> a -> Maybe b
212 mkLookupFun :: (key -> key -> Bool) -- Equality predicate
213             -> [(key,val)]          -- The assoc list
214             -> (key -> Maybe val)   -- A lookup fun to use
215 mkLookupFunDef :: (key -> key -> Bool)  -- Equality predicate
216                -> [(key,val)]           -- The assoc list
217                -> val                   -- Value to return on failure
218                -> key                   -- The key
219                -> val                   -- The corresponding value
220
221     -- a monad thing
222 thenMaybe   :: Maybe a -> (a -> Maybe b) -> Maybe b
223 returnMaybe :: a -> Maybe a
224 failMaybe   :: Maybe a
225 mapMaybe    :: (a -> Maybe b) -> [a] -> Maybe [b]
226 \end{verbatim}
227
228 NB: @catMaybes@ which used to be here, is now available via the
229 standard @Maybe@ interface (@Maybe@ is an instance of @MonadPlus@).
230
231 @allMaybes@ collects a list of @Justs@ into a single @Just@, returning
232 @Nothing@ if there are any @Nothings@.
233
234 @firstJust@ takes a list of @Maybes@ and returns the
235 first @Just@ if there is one, or @Nothing@ otherwise.
236
237 @assocMaybe@ looks up in an association list, returning
238 @Nothing@ if it fails.
239
240 Now, some operations to do with \tr{MaybeErr} (comments follow):
241 \begin{verbatim}
242     -- a monad thing (surprise, surprise)
243 thenMaB   :: MaybeErr a err -> (a -> MaybeErr b err) -> MaybeErr b err
244 returnMaB :: val -> MaybeErr val err
245 failMaB   :: err -> MaybeErr val err
246
247 listMaybeErrs :: [MaybeErr val err] -> MaybeErr [val] [err]
248 foldlMaybeErrs :: (acc -> input -> MaybeErr acc err)
249                -> acc
250                -> [input]
251                -> MaybeErr acc [err]
252 \end{verbatim}
253
254 @listMaybeErrs@ takes a list of @MaybeErrs@ and, if they all succeed,
255 returns a @Succeeded@ of a list of their values.  If any fail, it
256 returns a @Failed@ of the list of all the errors in the list.
257
258 @foldlMaybeErrs@ works along a list, carrying an accumulator; it
259 applies the given function to the accumulator and the next list item,
260 accumulating any errors that occur.
261
262 %************************************************************************
263 %*                                                                      *
264 \subsubsection[PackedString]{The @PackedString@ type}
265 \index{PackedString module (GHC syslib)}
266 %*                                                                      *
267 %************************************************************************
268
269 You need to \tr{import PackedString} and heave in your \tr{-syslib
270 ghc} to use \tr{PackedString}s.
271
272 The basic type and functions available are:
273 \begin{verbatim}
274 data PackedString -- abstract
275
276 packString          :: [Char] -> PackedString
277 packStringST        :: [Char] -> ST s PackedString
278 packCBytesST        :: Int -> Addr -> ST s PackedString
279 packBytesForCST     :: [Char] -> ST s (ByteArray Int)
280 byteArrayToPS       :: ByteArray Int -> PackedString
281 unsafeByteArrayToPS :: ByteArray a   -> Int -> PackedString
282 psToByteArray       :: PackedString -> ByteArray Int
283 psToByteArrayST     :: PackedString -> ST s (ByteArray Int)
284
285 unpackPS        :: PackedString -> [Char]
286 \end{verbatim}
287
288 We also provide a wad of list-manipulation-like functions:
289 \begin{verbatim}
290 nilPS       :: PackedString
291 consPS      :: Char -> PackedString -> PackedString
292
293 headPS      :: PackedString -> Char
294 tailPS      :: PackedString -> PackedString
295 nullPS      :: PackedString -> Bool
296 appendPS    :: PackedString -> PackedString -> PackedString
297 lengthPS    :: PackedString -> Int
298 indexPS     :: PackedString -> Int -> Char
299             -- 0-origin indexing into the string
300 mapPS       :: (Char -> Char) -> PackedString -> PackedString
301 filterPS    :: (Char -> Bool) -> PackedString -> PackedString
302 foldlPS     :: (a -> Char -> a) -> a -> PackedString -> a
303 foldrPS     :: (Char -> a -> a) -> a -> PackedString -> a
304 takePS      :: Int -> PackedString -> PackedString
305 dropPS      :: Int -> PackedString -> PackedString
306 splitAtPS   :: Int -> PackedString -> (PackedString, PackedString)
307 takeWhilePS :: (Char -> Bool) -> PackedString -> PackedString
308 dropWhilePS :: (Char -> Bool) -> PackedString -> PackedString
309 spanPS      :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
310 breakPS     :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
311 linesPS     :: PackedString -> [PackedString]
312 wordsPS     :: PackedString -> [PackedString]
313 reversePS   :: PackedString -> PackedString
314 concatPS    :: [PackedString] -> PackedString
315 elemPS      :: Char -> PackedString -> Bool
316   -- Perl-style split&join
317 splitPS     :: Char -> PackedString -> [PackedString]
318 splitWithPS :: (Char -> Bool) -> PackedString -> [PackedString]
319 joinPS      :: PackedString -> [PackedString] -> PackedString
320
321 substrPS   :: PackedString -> Int -> Int -> PackedString
322            -- pluck out a piece of a PackedString
323            -- start and end chars you want; both 0-origin-specified
324 \end{verbatim}
325
326 %************************************************************************
327 %*                                                                      *
328 \subsubsection[Pretty]{The @Pretty@ type}
329 \index{Pretty module (GHC syslib)}
330 %*                                                                      *
331 %************************************************************************
332
333 This is the pretty-printer that is currently used in GHC:
334
335 \begin{verbatim}
336 type Pretty
337
338 ppShow          :: Int{-width-} -> Pretty -> [Char]
339
340 pp'SP           :: Pretty -- "comma space"
341 ppComma         :: Pretty -- ,
342 ppEquals        :: Pretty -- =
343 ppLbrack        :: Pretty -- [
344 ppLparen        :: Pretty -- (
345 ppNil           :: Pretty -- nothing
346 ppRparen        :: Pretty -- )
347 ppRbrack        :: Pretty -- ]
348 ppSP            :: Pretty -- space
349 ppSemi          :: Pretty -- ;
350
351 ppChar          :: Char -> Pretty
352 ppDouble        :: Double -> Pretty
353 ppFloat         :: Float -> Pretty
354 ppInt           :: Int -> Pretty
355 ppInteger       :: Integer -> Pretty
356 ppRational      :: Rational -> Pretty
357 ppStr           :: [Char] -> Pretty
358
359 ppAbove         :: Pretty -> Pretty -> Pretty
360 ppAboves        :: [Pretty] -> Pretty
361 ppBeside        :: Pretty -> Pretty -> Pretty
362 ppBesides       :: [Pretty] -> Pretty
363 ppCat           :: [Pretty] -> Pretty
364 ppHang          :: Pretty -> Int -> Pretty -> Pretty
365 ppInterleave    :: Pretty -> [Pretty] -> Pretty -- spacing between
366 ppIntersperse   :: Pretty -> [Pretty] -> Pretty -- no spacing between
367 ppNest          :: Int -> Pretty -> Pretty
368 ppSep           :: [Pretty] -> Pretty
369 \end{verbatim}
370
371 %************************************************************************
372 %*                                                                      *
373 \subsubsection[Set]{The @Set@ type}
374 \index{Set module (GHC syslib)}
375 %*                                                                      *
376 %************************************************************************
377
378 Our implementation of {\em sets} (key property: no duplicates) is just
379 a variant of the \tr{FiniteMap} module.
380
381 \begin{verbatim}
382 data Set        -- abstract
383                 -- instance of: Eq
384
385 emptySet        :: Set a
386 mkSet           :: Ord a => [a]  -> Set a
387 setToList       :: Set a -> [a]
388 unitSet         :: a -> Set a
389 singletonSet    :: a -> Set a  -- deprecated, use unitSet.
390
391 union           :: Ord a => Set a -> Set a -> Set a
392 unionManySets   :: Ord a => [Set a] -> Set a
393 minusSet        :: Ord a => Set a -> Set a -> Set a
394 mapSet          :: Ord a => (b -> a) -> Set b -> Set a
395 intersect       :: Ord a => Set a -> Set a -> Set a
396
397 elementOf       :: Ord a => a -> Set a -> Bool
398 isEmptySet      :: Set a -> Bool
399
400 cardinality     :: Set a -> Int
401
402 \end{verbatim}
403
404 %************************************************************************
405 %*                                                                      *
406 \subsubsection[BitSet]{The @BitSet@ interface}
407 \index{Bitset interface (GHC syslib)}
408 %*                                                                      *
409 %************************************************************************
410
411 Bit sets are a fast implementation of sets of integers ranging from 0
412 to one less than the number of bits in a machine word (typically 31).
413 If any element exceeds the maximum value for a particular machine
414 architecture, the results of these operations are undefined.  You have
415 been warned. 
416
417 \begin{verbatim}
418 data BitSet   -- abstract
419               -- instance of:
420
421 emptyBS       :: BitSet
422 mkBS          :: [Int] -> BitSet
423 unitBS        :: Int -> BitSet
424 unionBS       :: BitSet -> BitSet -> BitSet
425 minusBS       :: BitSet -> BitSet -> BitSet
426 isEmptyBS     :: BitSet -> Bool
427 intersectBS   :: BitSet -> BitSet -> BitSet
428 elementBS     :: Int -> BitSet -> Bool
429 listBS        :: BitSet -> [Int]
430 \end{verbatim}
431
432 %************************************************************************
433 %*                                                                      *
434 \subsubsection[Util]{The @Util@ type}
435 \index{Util module (GHC syslib)}
436 %*                                                                      *
437 %************************************************************************
438
439 Stuff that has been generally useful to use in writing the compiler.
440 Don't be too surprised if this stuff moves/gets-renamed/etc.
441
442 \begin{verbatim}
443 -- general list processing
444 forall          :: (a -> Bool) -> [a] -> Bool
445 exists          :: (a -> Bool) -> [a] -> Bool
446
447 nOfThem         :: Int -> a -> [a]
448 lengthExceeds   :: [a] -> Int -> Bool
449 isSingleton     :: [a] -> Bool
450
451 --paranoid zip'ing (equal length lists)
452 zipEqual        :: [a] -> [b] -> [(a,b)]
453 zipWithEqual    :: String -> (a->b->c) -> [a]->[b]->[c]
454 zipWith3Equal   :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
455 zipWith4Equal   :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
456 -- lazy in second argument
457 zipLazy :: [a] -> [b] -> [(a,b)]
458
459 mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
460 mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
461
462 -- prefix and suffix matching on lists of characters.
463 startsWith :: {-prefix-}String -> String -> Maybe String
464 endsWith   :: {-suffix-}String -> String -> Maybe String
465
466 -- association lists
467 assoc       :: Eq a => String -> [(a, b)] -> a -> b
468
469 -- duplicate handling
470 hasNoDups    :: Eq a => [a] -> Bool
471 equivClasses :: (a -> a -> Ordering) -> [a] -> [[a]]
472 runs         :: (a -> a -> Bool)     -> [a] -> [[a]]
473 removeDups   :: (a -> a -> Ordering) -> [a] -> ([a], [[a]])
474
475 -- sorting (don't complain of no choice...)
476 quicksort          :: (a -> a -> Bool)     -> [a] -> [a]
477 sortLt             :: (a -> a -> Bool)     -> [a] -> [a]
478 stableSortLt       :: (a -> a -> Bool)     -> [a] -> [a]
479 mergesort          :: (a -> a -> _CMP_TAG) -> [a] -> [a]
480 mergeSort          :: Ord a => [a] -> [a]
481 naturalMergeSort   :: Ord a => [a] -> [a]
482 mergeSortLe        :: Ord a => [a] -> [a]
483 naturalMergeSortLe :: Ord a => [a] -> [a]
484
485 -- transitive closures
486 transitiveClosure :: (a -> [a])         -- Successor function
487                   -> (a -> a -> Bool)   -- Equality predicate
488                   -> [a] 
489                   -> [a]                -- The transitive closure
490
491 -- accumulating (Left, Right, Bi-directional)
492 mapAccumL :: (acc -> x -> (acc, y))
493                         -- Function of elt of input list and
494                         -- accumulator, returning new accumulator and
495                         -- elt of result list
496           -> acc        -- Initial accumulator
497           -> [x]        -- Input list
498           -> (acc, [y]) -- Final accumulator and result list
499
500 mapAccumR :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
501
502 mapAccumB :: (accl -> accr -> x -> (accl, accr,y))
503           -> accl -> accr -> [x]
504           -> (accl, accr, [y])
505
506 --list comparison with explicit element comparer.
507 cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
508
509 -- pairs
510 applyToPair :: ((a -> c), (b -> d)) -> (a, b) -> (c, d)
511 applyToFst  :: (a -> c) -> (a, b) -> (c, b)
512 applyToSnd  :: (b -> d) -> (a, b) -> (a, d)
513 foldPair    :: (a->a->a, b->b->b) -> (a, b) -> [(a, b)] -> (a, b)
514 unzipWith   :: (a -> b -> c) -> [(a, b)] -> [c]
515 \end{verbatim}
516
517 %************************************************************************
518 %*                                                                      *
519 \subsection[C-interfaces]{Interfaces to C libraries}
520 \index{C library interfaces}
521 \index{interfaces, C library}
522 %*                                                                      *
523 %************************************************************************
524
525 The GHC system library (\tr{-syslib ghc}) also provides interfaces to
526 several useful C libraries, mostly from the GNU project.
527
528 %************************************************************************
529 %*                                                                      *
530 \subsubsection[Readline]{The @Readline@ interface}
531 \index{Readline library (GHC syslib)}
532 \index{command-line editing library}
533 %*                                                                      *
534 %************************************************************************
535
536 (Darren Moffat supplied the \tr{Readline} interface.)
537
538 The \tr{Readline} module is a straightforward interface to the GNU
539 Readline library.  As such, you will need to look at the GNU
540 documentation (and have a \tr{libreadline.a} file around somewhere...)
541
542 You'll need to link any Readlining program with \tr{-lreadline -ltermcap},
543 besides the usual \tr{-syslib ghc} (and \tr{-fhaskell-1.3}).
544
545 The main function you'll use is:
546 \begin{verbatim}
547 readline :: String{-the prompt-} -> IO String
548 \end{verbatim}
549
550 If you want to mess around with Full Readline G(l)ory, we also
551 provide:
552 \begin{verbatim}
553 rlInitialize, addHistory,
554
555 rlBindKey, rlAddDefun, RlCallbackFunction(..),
556
557 rlGetLineBuffer, rlSetLineBuffer, rlGetPoint, rlSetPoint, rlGetEnd,
558 rlSetEnd, rlGetMark, rlSetMark, rlSetDone, rlPendingInput,
559
560 rlPrompt, rlTerminalName, rlSetReadlineName, rlGetReadlineName
561 \end{verbatim}
562 (All those names are just Haskellised versions of what you
563 will see in the GNU readline documentation.)
564
565 %************************************************************************
566 %*                                                                      *
567 \subsubsection[Regexp]{The @Regexp@ and @MatchPS@ interfaces}
568 \index{Regex library (GHC syslib)}
569 \index{MatchPS library (GHC syslib)}
570 \index{regular-expressions library}
571 %*                                                                      *
572 %************************************************************************
573
574 (Sigbjorn Finne supplied the regular-expressions interface.)
575
576 The \tr{Regex} library provides quite direct interface to the GNU
577 regular-expression library, for doing manipulation on
578 \tr{PackedString}s.  You probably need to see the GNU documentation
579 if you are operating at this level.
580
581 The datatypes and functions that \tr{Regex} provides are:
582 \begin{verbatim}
583 data PatBuffer  # just a bunch of bytes (mutable)
584
585 data REmatch
586  = REmatch (Array Int GroupBounds)  -- for $1, ... $n
587            GroupBounds              -- for $` (everything before match)
588            GroupBounds              -- for $& (entire matched string)
589            GroupBounds              -- for $' (everything after)
590            GroupBounds              -- for $+ (matched by last bracket)
591
592 -- GroupBounds hold the interval where a group
593 -- matched inside a string, e.g.
594 --
595 -- matching "reg(exp)" "a regexp" returns the pair (5,7) for the
596 -- (exp) group. (PackedString indices start from 0)
597
598 type GroupBounds = (Int, Int)
599
600 re_compile_pattern
601         :: PackedString         -- pattern to compile
602         -> Bool                 -- True <=> assume single-line mode
603         -> Bool                 -- True <=> case-insensitive
604         -> PrimIO PatBuffer
605
606 re_match :: PatBuffer           -- compiled regexp
607          -> PackedString        -- string to match
608          -> Int                 -- start position
609          -> Bool                -- True <=> record results in registers
610          -> PrimIO (Maybe REmatch)
611
612 -- Matching on 2 strings is useful when you're dealing with multiple
613 -- buffers, which is something that could prove useful for
614 -- PackedStrings, as we don't want to stuff the contents of a file
615 -- into one massive heap chunk, but load (smaller chunks) on demand.
616
617 re_match2 :: PatBuffer          -- 2-string version
618           -> PackedString
619           -> PackedString
620           -> Int
621           -> Int
622           -> Bool
623           -> PrimIO (Maybe REmatch)
624
625 re_search :: PatBuffer          -- compiled regexp
626           -> PackedString       -- string to search
627           -> Int                -- start index
628           -> Int                -- stop index
629           -> Bool               -- True <=> record results in registers
630           -> PrimIO (Maybe REmatch)
631
632 re_search2 :: PatBuffer         -- Double buffer search
633            -> PackedString
634            -> PackedString
635            -> Int               -- start index
636            -> Int               -- range (?)
637            -> Int               -- stop index
638            -> Bool              -- True <=> results in registers
639            -> PrimIO (Maybe REmatch)
640 \end{verbatim}
641
642 The \tr{MatchPS} module provides Perl-like ``higher-level'' facilities
643 to operate on \tr{PackedStrings}.  The regular expressions in
644 question are in Perl syntax.  The ``flags'' on various functions can
645 include: \tr{i} for case-insensitive, \tr{s} for single-line mode, and
646 \tr{g} for global.  (It's probably worth your time to peruse the
647 source code...)
648
649 \begin{verbatim}
650 matchPS :: PackedString    -- regexp
651         -> PackedString    -- string to match
652         -> [Char]          -- flags
653         -> Maybe REmatch   -- info about what matched and where
654
655 searchPS :: PackedString    -- regexp
656          -> PackedString    -- string to match
657          -> [Char]          -- flags
658          -> Maybe REmatch
659
660 -- Perl-like match-and-substitute:
661 substPS :: PackedString     -- regexp
662         -> PackedString     -- replacement
663         -> [Char]           -- flags
664         -> PackedString     -- string
665         -> PackedString
666
667 -- same as substPS, but no prefix and suffix:
668 replacePS :: PackedString  -- regexp
669           -> PackedString  -- replacement
670           -> [Char]        -- flags
671           -> PackedString  -- string
672           -> PackedString
673
674 match2PS :: PackedString   -- regexp
675          -> PackedString   -- string1 to match
676          -> PackedString   -- string2 to match
677          -> [Char]         -- flags
678          -> Maybe REmatch
679
680 search2PS :: PackedString  -- regexp
681           -> PackedString  -- string to match
682           -> PackedString  -- string to match
683           -> [Char]        -- flags
684           -> Maybe REmatch
685
686 -- functions to pull the matched pieces out of an REmatch:
687
688 getMatchesNo    :: REmatch -> Int
689 getMatchedGroup :: REmatch -> Int -> PackedString -> PackedString
690 getWholeMatch   :: REmatch -> PackedString -> PackedString
691 getLastMatch    :: REmatch -> PackedString -> PackedString
692 getAfterMatch   :: REmatch -> PackedString -> PackedString
693
694 -- (reverse) brute-force string matching;
695 -- Perl equivalent is index/rindex:
696 findPS, rfindPS :: PackedString -> PackedString -> Maybe Int
697
698 -- Equivalent to Perl "chop" (off the last character, if any):
699 chopPS :: PackedString -> PackedString
700
701 -- matchPrefixPS: tries to match as much as possible of strA starting
702 -- from the beginning of strB (handy when matching fancy literals in
703 -- parsers):
704 matchPrefixPS :: PackedString -> PackedString -> Int
705 \end{verbatim}
706
707 %************************************************************************
708 %*                                                                      *
709 \subsubsection[Socket]{Network-interface toolkit---@Socket@ and @SocketPrim@}
710 \index{SocketPrim interface (GHC syslib)}
711 \index{Socket interface (GHC syslib)}
712 \index{network-interface library}
713 \index{sockets library}
714 \index{BSD sockets library}
715 %*                                                                      *
716 %************************************************************************
717
718 (Darren Moffat supplied the network-interface toolkit.)
719
720 Your best bet for documentation is to look at the code---really!--- 
721 normally in \tr{hslibs/ghc/src/{BSD,Socket,SocketPrim}.lhs}.
722
723 The \tr{BSD} module provides functions to get at system-database info;
724 pretty straightforward if you're into this sort of thing:
725 \begin{verbatim}
726 getHostName         :: IO String
727
728 getServiceByName    :: ServiceName -> IO ServiceEntry
729 getServicePortNumber:: ServiceName -> IO PortNumber
730 getServiceEntry     :: IO ServiceEntry
731 setServiceEntry     :: Bool -> IO ()
732 endServiceEntry     :: IO ()
733
734 getProtocolByName   :: ProtocolName -> IO ProtocolEntry
735 getProtocolByNumber :: ProtocolNumber -> IO ProtcolEntry
736 getProtocolNumber   :: ProtocolName -> ProtocolNumber
737 getProtocolEntry    :: IO ProtocolEntry
738 setProtocolEntry    :: Bool -> IO ()
739 endProtocolEntry    :: IO ()
740
741 getHostByName       :: HostName -> IO HostEntry
742 getHostByAddr       :: Family -> HostAddress -> IO HostEntry
743 getHostEntry        :: IO HostEntry
744 setHostEntry        :: Bool -> IO ()
745 endHostEntry        :: IO ()
746 \end{verbatim}
747
748 The \tr{SocketPrim} interface provides quite direct access to the
749 socket facilities in a BSD Unix system, including all the
750 complications.  We hope you don't need to use it!  See the source if
751 needed...
752
753 The \tr{Socket} interface is a ``higher-level'' interface to sockets,
754 and it is what we recommend.  Please tell us if the facilities it
755 offers are inadequate to your task!
756
757 The interface is relatively modest:
758 \begin{verbatim}
759 connectTo       :: Hostname -> PortID -> IO Handle
760 listenOn        :: PortID -> IO Socket
761
762 accept          :: Socket -> IO (Handle, HostName)
763 sendTo          :: Hostname -> PortID -> String -> IO ()
764
765 recvFrom        :: Hostname -> PortID -> IO String
766 socketPort      :: Socket -> IO PortID
767
768 data PortID     -- PortID is a non-abstract type
769   = Service String      -- Service Name eg "ftp"
770   | PortNumber Int      -- User defined Port Number
771   | UnixSocket String   -- Unix family socket in file system
772
773 type Hostname = String
774 \end{verbatim}
775
776 Various examples of networking Haskell code are provided in
777 \tr{ghc/misc/examples/}, notably the \tr{net???/Main.hs} programs.
778
779 %************************************************************************
780 %*                                                                      *
781 \subsection[Posix-library]{The Posix system library}
782 \index{Posix system library}
783 \index{system library, Posix}
784 %*                                                                      *
785 %************************************************************************
786
787 The @Posix@ interface gives you access to the set of OS services
788 standardised by POSIX 1003.1b (or the {\em IEEE Portable Operating System
789 Interface for Computing Environments} - IEEE Std. 1003.1). The
790 interface is accessed by \tr{import Posix} and adding \tr{-syslib
791 posix} on your command-line.
792
793 \subsubsection[Posix-data-types]{Posix data types}
794 \index{Posix, data types}
795
796
797 \begin{verbatim}
798 data ByteCount  -- instances of : Eq Ord Num Real Integral Ix Enum Show
799 \end{verbatim}
800
801 A \tr{ByteCount} is a primitive of type \tr{unsigned}. At a minimum,
802 an conforming implementation must support values in the range
803 \tr{[0, UINT_MAX]}.
804
805 \begin{verbatim}
806 data ClockTick  -- instances of : Eq Ord Num Real Integral Ix Enum Show
807 \end{verbatim}
808
809 A \tr{ClockTick} is a primitive of type \tr{clock_t}, which
810 is used to measure intervals of time in fractions of a second.  The 
811 resolution is determined by \tr{getSysVar ClockTick}.
812
813 \begin{verbatim}
814 data DeviceID  -- instances of : Eq Ord Num Real Integral Ix Enum Show
815 \end{verbatim}
816
817 A \tr{DeviceID} is a primitive of type \tr{dev_t}.  It must
818 be an arithmetic type.
819
820 \begin{verbatim}
821 > data EpochTime -- instances of : Eq Ord Num Real Integral Ix Enum Show
822 \end{verbatim}
823
824 A \tr{EpochTime} is a primitive of type \tr{time_t}, which is
825 used to measure seconds since the Epoch.  At a minimum, the implementation 
826 must support values in the range \tr{[0, INT_MAX]}.
827
828 \begin{verbatim}
829 data FileID -- instances of : Eq Ord Num Real Integral Ix Enum Show
830 \end{verbatim}
831
832 A \tr{FileID} is a primitive of type \tr{ino_t}.  It must
833 be an arithmetic type.
834
835 \begin{verbatim}
836 data FileMode -- instances of : Eq Ord Num Real Integral Ix Enum Show
837 \end{verbatim}
838
839 A \tr{FileMode} is a primitive of type \tr{mode_t}.
840 It must be an arithmetic type.
841
842 \begin{verbatim}
843 data FileOffset -- instances of : Eq Ord Num Real Integral Ix Enum Show
844 \end{verbatim}
845
846 A \tr{FileOffset} is a primitive of type \tr{off_t}.  It must
847 be an arithmetic type.
848
849 \begin{verbatim}
850 data GroupID -- instances of : Eq Ord Num Real Integral Ix Enum Show
851 \end{verbatim}
852
853 A \tr{GroupID} is a primitive of type \tr{gid_t}.  It must
854 be an arithmetic type.
855 \begin{verbatim}
856 data Limit -- instances of : Eq Ord Num Real Integral Ix Enum Show
857 \end{verbatim}
858
859 A \tr{Limit} is a primitive of type \tr{long}.
860 At a minimum, the implementation must support values in the range 
861 \tr{[LONG_MIN, LONG_MAX]}.
862
863 \begin{verbatim}
864 data LinkCount -- instances of : Eq Ord Num Real Integral Ix Enum Show
865 \end{verbatim}
866
867 A \tr{LinkCount} is a primitive of type \tr{nlink_t}.  It must
868 be an arithmetic type.
869
870 \begin{verbatim}
871 data ProcessID -- instances of : Eq Ord Num Real Integral Ix Enum Show
872 type ProcessGroupID = ProcessID
873 \end{verbatim}
874
875 A \tr{ProcessID} is a primitive of type \tr{pid_t}.  It
876 must be a signed arithmetic type.
877 \begin{verbatim}
878 data UserID -- instances of : Eq Ord Num Real Integral Ix Enum Show
879 \end{verbatim}
880
881 A \tr{UserID} is a primitive of type \tr{uid_t}.  It
882 must be an arithmetic type.
883
884 \begin{verbatim}
885 data DirStream
886 \end{verbatim}
887 A \tr{DirStream} is a primitive of type \tr{DIR *}.
888
889 \begin{verbatim}
890 data FileStatus
891 \end{verbatim}
892 A \tr{FileStatus} is a primitive of type \tr{struct stat}.
893
894 \begin{verbatim}
895 data GroupEntry
896 \end{verbatim}
897
898 A \tr{GroupEntry} is a primitive of type \tr{struct group}.
899 \begin{verbatim}
900 data ProcessTimes
901 \end{verbatim}
902
903 \tr{ProcessTimes} is a primitive structure containing a
904 \tr{clock_t} and a \tr{struct tms}.
905
906 \begin{verbatim}
907 data SignalSet
908 \end{verbatim}
909
910 An \tr{SignalSet} is a primitive of type \tr{sigset_t}.
911
912 \begin{verbatim}
913 data SystemID
914 \end{verbatim}
915
916 A \tr{SystemID} is a primitive of type \tr{struct utsname}.
917
918 \begin{verbatim}
919 data TerminalAttributes
920 \end{verbatim}
921 \tr{TerminalAttributes} is a primitive of type \tr{struct termios}.
922
923 \begin{verbatim}
924 data UserEntry
925 \end{verbatim}
926
927 A \tr{UserEntry} is a primitive of type \tr{struct passwd}.
928
929 \begin{verbatim}
930 data BaudRate = B0 | B50 | B75 | B110 | B134 | B150 | B200 | B300 | B600
931               | B1200 | B1800 | B2400 | B4800 | B9600 | B19200 | B38400
932               deriving (Eq, Show)
933
934 type Channel = Int
935
936 data ChannelOption = AppendOnWrite
937                    | CloseOnExec
938                    | NonBlockingRead
939
940 data ControlCharacter = EndOfFile
941                       | EndOfLine
942                       | Erase
943                       | Interrupt
944                       | Kill
945                       | Quit
946                       | Suspend
947                       | Start
948                       | Stop
949
950 type ErrorCode = Int
951
952 type FileLock = (LockRequest, SeekMode, FileOffset, FileOffset)
953 --                            whence    start       length
954
955 data FlowAction = SuspendOutput | RestartOutput | TransmitStop | TransmitStart
956
957 data Handler = Default | Ignore | Catch (IO ())
958
959 data LockRequest = ReadLock | WriteLock | Unlock
960                  deriving (Eq, Show)
961
962 data OpenMode = ReadOnly | WriteOnly | ReadWrite
963
964 data PathVar = LinkLimit
965              | InputLineLimit
966              | InputQueueLimit
967              | FileNameLimit
968              | PathNameLimit
969              | PipeBufferLimit
970              | SetOwnerAndGroupIsRestricted
971              | FileNamesAreNotTruncated
972
973 data QueueSelector = InputQueue | OutputQueue | BothQueues
974
975 type Signal = Int
976
977 data SysVar = ArgumentLimit
978             | ChildLimit
979             | ClockTick
980             | GroupLimit
981             | OpenFileLimit
982             | PosixVersion
983             | HasSavedIDs
984             | HasJobControl
985
986 data TerminalMode = InterruptOnBreak       -- BRKINT
987                 | MapCRtoLF                -- ICRNL
988                 | IgnoreBreak              -- IGNBRK
989                 | IgnoreCR                 -- IGNCR
990                 | IgnoreParityErrors       -- IGNPAR
991                 | MapLFtoCR                -- INLCR
992                 | CheckParity              -- INPCK
993                 | StripHighBit             -- ISTRIP
994                 | StartStopInput           -- IXOFF
995                 | StartStopOutput          -- IXON
996                 | MarkParityErrors         -- PARMRK
997                 | ProcessOutput            -- OPOST
998                 | LocalMode                -- CLOCAL
999                 | ReadEnable               -- CREAD
1000                 | TwoStopBits              -- CSTOPB
1001                 | HangupOnClose            -- HUPCL
1002                 | EnableParity             -- PARENB
1003                 | OddParity                -- PARODD
1004                 | EnableEcho               -- ECHO
1005                 | EchoErase                -- ECHOE
1006                 | EchoKill                 -- ECHOK
1007                 | EchoLF                   -- ECHONL
1008                 | ProcessInput             -- ICANON
1009                 | ExtendedFunctions        -- IEXTEN
1010                 | KeyboardInterrupts       -- ISIG
1011                 | NoFlushOnInterrupt       -- NOFLSH
1012                 | BackgroundWriteInterrupt -- TOSTOP
1013
1014 data TerminalState = Immediately | WhenDrained | WhenFlushed
1015
1016 data ProcessStatus = Exited ExitCode 
1017                    | Terminated Signal 
1018                    | Stopped Signal
1019                    deriving (Eq, Show)
1020 \end{verbatim}
1021
1022 \subsubsection{posix-process-env}{Posix Process Primitives}
1023
1024 \begin{verbatim}
1025 forkProcess :: IO (Maybe ProcessID)
1026 \end{verbatim}
1027
1028 \tr{forkProcess} calls \tr{fork}, returning
1029 \tr{Just pid} to the parent, where <var>pid</var> is the
1030 ProcessID of the child, and returning \tr{Nothing} to the
1031 child.
1032
1033 \begin{verbatim}
1034 executeFile :: FilePath                   -- Command
1035             -> Bool                       -- Search PATH?
1036             -> [String]                   -- Arguments
1037             -> Maybe [(String, String)]   -- Environment
1038             -> IO ()
1039 \end{verbatim}
1040
1041 \tr{executeFile cmd args env} calls one of the
1042 \tr{execv*} family, depending on whether or not the current
1043 PATH is to be searched for the command, and whether or not an
1044 environment is provided to supersede the process's current
1045 environment.  The basename (leading directory names suppressed) of
1046 the command is passed to \tr{execv*} as \tr{arg[0]};
1047 the argument list passed to \tr{executeFile} therefore begins 
1048 with \tr{arg[1]}.
1049
1050 \begin{verbatim}
1051 Search PATH?    Supersede environ?      Call
1052 ~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~~      ~~~~~~~
1053 False           False                   execv
1054 False           True                    execve
1055 True            False                   execvp
1056 True            True                    execvpe*
1057 \end{verbatim}
1058
1059 Note that \tr{execvpe} is not provided by the POSIX standard, and must
1060 be written by hand.  Care must be taken to ensure that the search path
1061 is extracted from the original environment, and not from the
1062 environment to be passed on to the new image.
1063
1064 A successful \tr{executeFile} overlays the current process image with 
1065 a new one, so it only returns on failure.
1066 \begin{verbatim}
1067 runProcess :: FilePath                    -- Command
1068            -> [String]                    -- Arguments
1069            -> Maybe [(String, String)]    -- Environment (Nothing -> Inherited)
1070            -> Maybe FilePath              -- Working directory (Nothing -> inherited)
1071            -> Maybe Handle                -- stdin  (Nothing -> inherited)
1072            -> Maybe Handle                -- stdout (Nothing -> inherited)
1073            -> Maybe Handle                -- stderr (Nothing -> inherited)
1074            -> IO ()
1075 \end{verbatim}
1076
1077 \tr{runProcess} is our candidate for the high-level OS-independent
1078 primitive.
1079
1080 \tr{runProcess cmd args env wd inhdl outhdl errhdl} runs \tr{cmd}
1081 (searching the current \tr{PATH}) with arguments \tr{args}.  If
1082 \tr{env} is \tr{Just pairs}, the command is executed with the
1083 environment specified by \tr{pairs} of variables and values;
1084 otherwise, the command is executed with the current environment.  If
1085 \tr{wd} is \tr{Just dir}, the command is executed with working
1086 directory \tr{dir}; otherwise, the command is executed in the current
1087 working directory.  If \tr{{in,out,err}hdl} is \tr{Just handle}, the
1088 command is executed with the \tr{Channel} for \tr{std{in,out,err}}
1089 attached to the specified \tr{handle}; otherwise, the \tr{Channel} for
1090 \tr{std{in,out,err}} is left unchanged.
1091
1092 \begin{verbatim}
1093 getProcessStatus :: Bool              -- Block?
1094                  -> Bool              -- Stopped processes?
1095                  -> ProcessID 
1096                  -> IO (Maybe ProcessStatus)
1097 \end{verbatim}
1098
1099 \tr{getProcessStatus blk stopped pid} calls \tr{waitpid}, returning
1100 \tr{Just tc}, the \tr{ProcessStatus} for process \tr{pid} if it is
1101 available, \tr{Nothing} otherwise.  If \tr{blk} is \tr{False}, then
1102 \tr{WNOHANG} is set in the options for \tr{waitpid}, otherwise not.
1103 If \tr{stopped} is \tr{True}, then \tr{WUNTRACED} is set in the
1104 options for \tr{waitpid}, otherwise not.
1105
1106 \begin{verbatim}
1107 getGroupProcessStatus :: Bool         -- Block?
1108                       -> Bool         -- Stopped processes?
1109                       -> ProcessGroupID 
1110                       -> IO (Maybe (ProcessID, ProcessStatus))
1111 \end{verbatim}
1112
1113 \tr{getGroupProcessStatus blk stopped pgid} calls \tr{waitpid},
1114 returning \tr{Just (pid, tc)}, the \tr{ProcessID} and
1115 \tr{ProcessStatus} for any process in group \tr{pgid} if one is
1116 available, \tr{Nothing} otherwise.  If \tr{blk} is \tr{False}, then
1117 \tr{WNOHANG} is set in the options for \tr{waitpid}, otherwise not.
1118 If \tr{stopped} is \tr{True}, then \tr{WUNTRACED} is set in the
1119 options for \tr{waitpid}, otherwise not.
1120
1121 \begin{verbatim}
1122 getAnyProcessStatus :: Bool           -- Block?
1123                     -> Bool           -- Stopped processes?
1124                     -> IO (Maybe (ProcessID, ProcessStatus))
1125 \end{verbatim}
1126
1127 \tr{getAnyProcessStatus blk stopped} calls \tr{waitpid}, returning
1128 \tr{Just (pid, tc)}, the \tr{ProcessID} and \tr{ProcessStatus} for any
1129 child process if one is available, \tr{Nothing} otherwise.  If
1130 \tr{blk} is \tr{False}, then \tr{WNOHANG} is set in the options for
1131 \tr{waitpid}, otherwise not.  If \tr{stopped} is \tr{True}, then
1132 \tr{WUNTRACED} is set in the options for \tr{waitpid}, otherwise not.
1133
1134 \begin{verbatim}
1135 exitImmediately :: ExitCode -> IO ()
1136 \end{verbatim}
1137
1138 \tr{exitImmediately status} calls \tr{_exit} to terminate the process
1139 with the indicated exit \tr{status}.
1140 The operation never returns.
1141
1142 \begin{verbatim}
1143 getEnvironment :: IO [(String, String)]
1144 \end{verbatim}
1145
1146 \tr{getEnvironment} parses the environment variable mapping provided by
1147 \tr{environ}, returning \tr{(variable, value)} pairs. 
1148 The operation never fails.
1149
1150 \begin{verbatim}
1151 setEnvironment :: [(String, String)] -> IO ()
1152 \end{verbatim}
1153
1154 \tr{setEnvironment} replaces the process environment with the provided
1155 mapping of \tr{(variable, value)} pairs. 
1156
1157 \begin{verbatim}
1158 getEnvVar :: String -> IO String
1159 \end{verbatim}
1160
1161 \tr{getEnvVar var} returns the value associated with variable \tr{var} 
1162 in the current environment (identical functionality provided through
1163 standard Haskell library function @System.getEnv@).
1164
1165 The operation may fail with:
1166
1167 \begin{itemize}
1168 \item[\tr{NoSuchThing}]
1169 The variable has no mapping in the current environment.
1170 \end{itemize}
1171
1172 \begin{verbatim}
1173 setEnvVar :: String -> String -> IO ()
1174 \end{verbatim}
1175
1176 \tr{setEnvVar var val} sets the value associated with variable \tr{var} 
1177 in the current environment to be \tr{val}.  Any previous mapping is 
1178 superseded.
1179
1180 \begin{verbatim}
1181 removeEnvVar :: String -> IO ()
1182 \end{verbatim}
1183
1184 \tr{removeEnvVar var} removes any value associated with variable \tr{var} 
1185 in the current environment.  Deleting a variable for which there is no mapping
1186 does not generate an error.
1187
1188 \begin{verbatim}
1189 nullSignal :: Signal
1190 nullSignal = 0
1191
1192 backgroundRead, sigTTIN        :: Signal
1193 backgroundWrite, sigTTOU       :: Signal
1194 continueProcess, sigCONT       :: Signal
1195 floatingPointException, sigFPE :: Signal
1196 illegalInstruction, sigILL     :: Signal
1197 internalAbort, sigABRT         :: Signal
1198 keyboardSignal, sigINT         :: Signal
1199 keyboardStop, sigTSTP          :: Signal
1200 keyboardTermination, sigQUIT   :: Signal
1201 killProcess, sigKILL           :: Signal
1202 lostConnection, sigHUP         :: Signal
1203 openEndedPipe, sigPIPE         :: Signal
1204 processStatusChanged, sigCHLD  :: Signal
1205 realTimeAlarm, sigALRM         :: Signal
1206 segmentationViolation, sigSEGV :: Signal
1207 softwareStop, sigSTOP          :: Signal
1208 softwareTermination, sigTERM   :: Signal
1209 userDefinedSignal1, sigUSR1    :: Signal
1210 userDefinedSignal2, sigUSR2    :: Signal
1211
1212 signalProcess :: Signal -> ProcessID -> IO ()
1213 \end{verbatim}
1214
1215 \tr{signalProcess int pid} calls \tr{kill} to signal 
1216 process \tr{pid} with interrupt signal \tr{int}.
1217
1218 \begin{verbatim}
1219 raiseSignal :: Signal -> IO ()
1220 \end{verbatim}
1221
1222 \tr{raiseSignal int} calls \tr{kill} to signal the current process
1223 with interrupt signal \tr{int}. 
1224
1225 \begin{verbatim}
1226 signalProcessGroup :: Signal -> ProcessGroupID -> IO ()
1227 \end{verbatim}
1228
1229 \tr{signalProcessGroup int pgid} calls \tr{kill} to signal 
1230 all processes in group \tr{pgid} with interrupt signal \tr{int}.
1231
1232 \begin{verbatim}
1233 setStoppedChildFlag :: Bool -> IO Bool
1234 \end{verbatim}
1235
1236 \tr{setStoppedChildFlag bool} sets a flag which controls whether or
1237 not the \tr{NOCLDSTOP} option will be used the next time a signal
1238 handler is installed for \tr{SIGCHLD}.  If \tr{bool} is \tr{True} (the
1239 default), \tr{NOCLDSTOP} will not be used; otherwise it will be.  The
1240 operation never fails.
1241
1242 \begin{verbatim}
1243 queryStoppedChildFlag :: IO Bool
1244 \end{verbatim}
1245
1246 \tr{queryStoppedChildFlag} queries the flag which
1247 controls whether or not the \tr{NOCLDSTOP} option will be used
1248 the next time a signal handler is installed for \tr{SIGCHLD}.
1249 If \tr{NOCLDSTOP} will be used, it returns \tr{False}; 
1250 otherwise (the default) it returns \tr{True}.  
1251 The operation never fails.
1252
1253 \begin{verbatim}
1254 emptySignalSet :: SignalSet
1255 fullSignalSet  :: SignalSet
1256 addSignal      :: Signal -> SignalSet -> SignalSet
1257 deleteSignal   :: Signal -> SignalSet -> SignalSet
1258 inSignalSet    :: Signal -> SignalSet -> Bool
1259
1260 installHandler :: Signal
1261                -> Handler 
1262                -> Maybe SignalSet       -- other signals to block
1263                -> IO Handler            -- old handler
1264 \end{verbatim}
1265
1266 \tr{installHandler int handler iset} calls \tr{sigaction} to install
1267 an interrupt handler for signal \tr{int}.  If \tr{handler} is
1268 \tr{Default}, \tr{SIG_DFL} is installed; if \tr{handler} is
1269 \tr{Ignore}, \tr{SIG_IGN} is installed; if \tr{handler} is \tr{Catch
1270 action}, a handler is installed which will invoke \tr{action} as a
1271 replacement for \tr{main}.  If \tr{iset} is \tr{Just s}, then the
1272 \tr{sa_mask} of the \tr{sigaction} structure is set to \tr{s};
1273 otherwise it is cleared.  The previously installed signal handler for
1274 \tr{int} is returned.
1275
1276 \begin{verbatim}
1277 getSignalMask :: IO SignalSet
1278 \end{verbatim}
1279
1280 \tr{getSignalMask} calls \tr{sigprocmask} to determine the
1281 set of interrupts which are currently being blocked.
1282
1283 \begin{verbatim}
1284 setSignalMask :: SignalSet -> IO SignalSet
1285 \end{verbatim}
1286
1287 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1288 \tr{SIG_SETMASK} to block all interrupts in \tr{mask}.  The
1289 previous set of blocked interrupts is returned.
1290
1291 \begin{verbatim}
1292 blockSignals :: SignalSet -> IO SignalSet
1293 \end{verbatim}
1294
1295 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1296 \tr{SIG_BLOCK} to add all interrupts in \tr{mask} to the
1297 set of blocked interrupts.  The previous set of blocked interrupts is returned.
1298
1299 \begin{verbatim}
1300 unBlockSignals :: SignalSet -> IO SignalSet
1301 \end{verbatim}
1302
1303 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1304 \tr{SIG_UNBLOCK} to remove all interrupts in \tr{mask} from the
1305 set of blocked interrupts.  The previous set of blocked interrupts is returned.
1306
1307 \begin{verbatim}
1308 getPendingSignals :: IO SignalSet
1309 \end{verbatim}
1310
1311 \tr{getPendingSignals} calls \tr{sigpending} to obtain
1312 the set of interrupts which have been received but are currently blocked.
1313
1314 \begin{verbatim}
1315 awaitSignal :: Maybe SignalSet -> IO ()
1316 \end{verbatim}
1317
1318 \tr{awaitSignal iset} suspends execution until an interrupt is received.
1319 If \tr{iset} is \tr{Just s}, \tr{awaitSignal} calls 
1320 \tr{sigsuspend}, installing \tr{s} as the new signal mask before
1321 suspending execution; otherwise, it calls \tr{pause}.  If successful,
1322 \tr{awaitSignal} does not return.
1323
1324 \begin{verbatim}
1325 scheduleAlarm :: Int -> IO Int
1326 \end{verbatim}
1327
1328 \tr{scheduleAlarm i} calls \tr{alarm} to schedule a real time
1329 alarm at least \tr{i} seconds in the future.
1330
1331 \begin{verbatim}
1332 sleep :: Int -> IO ()
1333 \end{verbatim}
1334
1335 \tr{sleep i} calls \tr{sleep} to suspend execution of the
1336 program until at least \tr{i} seconds have elapsed or a signal is
1337 received.
1338
1339 \subsubsection[posix-proc-env]{Posix Process Environment}
1340 \index{Posix, process environment}
1341
1342 \begin{verbatim}
1343 getProcessID :: IO ProcessID
1344 \end{verbatim}
1345
1346 \tr{getProcessID} calls \tr{getpid} to obtain the \tr{ProcessID} for
1347 the current process.
1348
1349 \begin{verbatim}
1350 getParentProcessID :: IO ProcessID
1351 \end{verbatim}
1352
1353 \tr{getProcessID} calls \tr{getppid} to obtain the \tr{ProcessID} for
1354 the parent of the current process.
1355
1356 \begin{verbatim}
1357 getRealUserID :: IO UserID
1358 \end{verbatim}
1359
1360 \tr{getRealUserID} calls \tr{getuid} to obtain the real \tr{UserID}
1361 associated with the current process.
1362
1363 \begin{verbatim}
1364 getEffectiveUserID :: IO UserID
1365 \end{verbatim}
1366
1367 \tr{getRealUserID} calls \tr{geteuid} to obtain the effective
1368 \tr{UserID} associated with the current process.
1369
1370 \begin{verbatim}
1371 setUserID :: UserID -> IO ()
1372 \end{verbatim}
1373
1374 \tr{setUserID uid} calls \tr{setuid} to set the real, effective, and
1375 saved set-user-id associated with the current process to \tr{uid}.
1376
1377 \begin{verbatim}
1378 getLoginName :: IO String
1379 \end{verbatim}
1380
1381 \tr{getLoginName} calls \tr{getlogin} to obtain the login name
1382 associated with the current process.
1383
1384 \begin{verbatim}
1385 getRealGroupID :: IO GroupID
1386 \end{verbatim}
1387
1388 \tr{getRealGroupID} calls \tr{getgid} to obtain the real \tr{GroupID}
1389 associated with the current process.
1390
1391 \begin{verbatim}
1392 getEffectiveGroupID :: IO GroupID
1393 \end{verbatim}
1394
1395 \tr{getEffectiveGroupID} calls \tr{getegid} to obtain the effective
1396 \tr{GroupID} associated with the current process.
1397
1398 \begin{verbatim}
1399 setGroupID :: GroupID -> IO ()
1400 \end{verbatim}
1401
1402 \tr{setGroupID gid} calls \tr{setgid} to set the real, effective, and
1403 saved set-group-id associated with the current process to \tr{gid}.
1404
1405 \begin{verbatim}
1406 getGroups :: IO [GroupID]
1407 \end{verbatim}
1408
1409 \tr{getGroups} calls \tr{getgroups} to obtain the list of
1410 supplementary \tr{GroupID}s associated with the current process.
1411
1412 \begin{verbatim}
1413 getEffectiveUserName :: IO String
1414 \end{verbatim}
1415
1416 \tr{getEffectiveUserName} calls \tr{cuserid} to obtain a name
1417 associated with the effective \tr{UserID} of the process.
1418
1419 \begin{verbatim}
1420 getProcessGroupID :: IO ProcessGroupID
1421 \end{verbatim}
1422
1423 \tr{getProcessGroupID} calls \tr{getpgrp} to obtain the
1424 \tr{ProcessGroupID} for the current process.
1425
1426 \begin{verbatim}
1427 createProcessGroup :: ProcessID -> IO ProcessGroupID
1428 \end{verbatim}
1429
1430 \tr{createProcessGroup pid} calls \tr{setpgid} to make
1431 process \tr{pid} a new process group leader.
1432
1433 \begin{verbatim}
1434 joinProcessGroup :: ProcessGroupID -> IO ProcessGroupID
1435 \end{verbatim}
1436
1437 \tr{joinProcessGroup pgid} calls \tr{setpgid} to set the
1438 \tr{ProcessGroupID} of the current process to \tr{pgid}.
1439
1440 \begin{verbatim}
1441 setProcessGroupID :: ProcessID -> ProcessGroupID -> IO ()
1442 \end{verbatim}
1443
1444 \tr{setProcessGroupID pid pgid} calls \tr{setpgid} to set the
1445 \tr{ProcessGroupID} for process \tr{pid} to \tr{pgid}.
1446
1447 \begin{verbatim}
1448 createSession :: IO ProcessGroupID
1449 \end{verbatim}
1450
1451 \tr{createSession} calls \tr{setsid} to create a new session
1452 with the current process as session leader.
1453
1454 \begin{verbatim}
1455 systemName :: SystemID -> String
1456 nodeName :: SystemID -> String
1457 release :: SystemID -> String
1458 version :: SystemID -> String
1459 machine :: SystemID -> String
1460
1461 getSystemID :: IO SystemID
1462 \end{verbatim}
1463
1464 \tr{getSystemID} calls \tr{uname} to obtain information
1465 about the current operating system.
1466
1467 \begin{verbatim}
1468 > epochTime :: IO EpochTime
1469 \end{verbatim}
1470
1471 \tr{epochTime} calls \tr{time} to obtain the number of 
1472 seconds that have elapsed since the epoch (Jan 01 00:00:00 GMT 1970).
1473
1474 \begin{verbatim}
1475 elapsedTime     :: ProcessTimes -> ClockTick
1476 userTime        :: ProcessTimes -> ClockTick
1477 systemTime      :: ProcessTimes -> ClockTick
1478 childUserTime   :: ProcessTimes -> ClockTick
1479 childSystemTime :: ProcessTimes -> ClockTick
1480
1481 getProcessTimes :: IO ProcessTimes
1482 \end{verbatim}
1483
1484 \tr{getProcessTimes} calls \tr{times} to obtain time-accounting
1485 information for the current process and its children.
1486
1487 \begin{verbatim}
1488 getControllingTerminalName :: IO FilePath
1489 \end{verbatim}
1490
1491 \tr{getControllingTerminalName} calls \tr{ctermid} to obtain
1492 a name associated with the controlling terminal for the process.  If a
1493 controlling terminal exists,
1494 \tr{getControllingTerminalName} returns the name of the
1495 controlling terminal.
1496
1497 The operation may fail with:
1498
1499 \begin{itemize}
1500 \item[\tr{NoSuchThing}]
1501 There is no controlling terminal, or its name cannot be determined.
1502 \item[\tr{SystemError}]
1503 Various other causes.
1504 \end{itemize}
1505
1506 \begin{verbatim}
1507 getTerminalName :: Channel -> IO FilePath
1508 \end{verbatim}
1509
1510 \tr{getTerminalName fd} calls \tr{ttyname} to obtain a name associated
1511 with the terminal for \tr{Channel} \tr{fd}. If \tr{fd} is associated
1512 with a terminal, \tr{getTerminalName} returns the name of the
1513 terminal.
1514
1515 The operation may fail with:
1516
1517 \begin{itemize}
1518 \item[\tr{InappropriateType}]
1519 The channel is not associated with a terminal.
1520 \item[\tr{NoSuchThing}]
1521 The channel is associated with a terminal, but it has no name.
1522 \item[\tr{SystemError}]
1523 Various other causes.
1524 \end{itemize}
1525
1526 \begin{verbatim}
1527 queryTerminal :: Channel -> IO Bool
1528 \end{verbatim}
1529
1530 \tr{queryTerminal fd} calls \tr{isatty} to determine whether or
1531 not \tr{Channel} \tr{fd} is associated with a terminal.
1532
1533 \begin{verbatim}
1534 getSysVar :: SysVar -> IO Limit
1535 \end{verbatim}
1536
1537 \tr{getSysVar var} calls \tr{sysconf} to obtain the
1538 dynamic value of the requested configurable system limit or option.
1539 For defined system limits, \tr{getSysVar} returns the associated
1540 value.  For defined system options, the result of \tr{getSysVar}
1541 is undefined, but not failure.
1542
1543 The operation may fail with:
1544
1545 \begin{itemize}
1546 \item[\tr{NoSuchThing}]
1547 The requested system limit or option is undefined.
1548 \end{itemize}
1549
1550 \subsubsection[posix-files-dir]{Files and Directories}
1551 \index{Posix, files and directories}
1552
1553 \begin{verbatim}
1554 openDirStream :: FilePath -> IO DirStream
1555 \end{verbatim}
1556
1557 \tr{openDirStream dir} calls \tr{opendir} to obtain a
1558 directory stream for \tr{dir}.
1559
1560 \begin{verbatim}
1561 readDirStream :: DirStream -> IO String
1562 \end{verbatim}
1563
1564 \tr{readDirStream dp} calls \tr{readdir} to obtain the
1565 next directory entry (\tr{struct dirent}) for the open directory
1566 stream \tr{dp}, and returns the \tr{d_name} member of that
1567 structure.
1568
1569 The operation may fail with:
1570
1571 \begin{itemize}
1572 \item[\tr{EOF}]
1573 End of file has been reached.
1574 \item[\tr{SystemError}]
1575 Various other causes.
1576 \end{itemize}
1577
1578 \begin{verbatim}
1579 rewindDirStream :: DirStream -> IO ()
1580 \end{verbatim}
1581
1582 \tr{rewindDirStream dp} calls \tr{rewinddir} to reposition
1583 the directory stream \tr{dp} at the beginning of the directory.
1584
1585 \begin{verbatim}
1586 closeDirStream :: DirStream -> IO ()
1587 \end{verbatim}
1588
1589 \tr{closeDirStream dp} calls \tr{closedir} to close
1590 the directory stream \tr{dp}.
1591
1592 \begin{verbatim}
1593 getWorkingDirectory :: IO FilePath
1594 \end{verbatim}
1595
1596 \tr{getWorkingDirectory} calls \tr{getcwd} to obtain the name
1597 of the current working directory.
1598
1599 \begin{verbatim}
1600 changeWorkingDirectory :: FilePath -> IO ()
1601 \end{verbatim}
1602
1603 \tr{changeWorkingDirectory dir} calls \tr{chdir} to change
1604 the current working directory to \tr{dir}.
1605
1606 \begin{verbatim}
1607 nullFileMode       :: FileMode       -- ---------
1608 ownerReadMode      :: FileMode       -- r--------
1609 ownerWriteMode     :: FileMode       -- -w-------
1610 ownerExecuteMode   :: FileMode       -- --x------
1611 groupReadMode      :: FileMode       -- ---r-----
1612 groupWriteMode     :: FileMode       -- ----w----
1613 groupExecuteMode   :: FileMode       -- -----x---
1614 otherReadMode      :: FileMode       -- ------r--
1615 otherWriteMode     :: FileMode       -- -------w-
1616 otherExecuteMode   :: FileMode       -- --------x
1617 setUserIDMode      :: FileMode       -- --S------
1618 setGroupIDMode     :: FileMode       -- -----S---
1619                                
1620 stdFileMode        :: FileMode       -- rw-rw-rw-
1621                                
1622 ownerModes         :: FileMode       -- rwx------
1623 groupModes         :: FileMode       -- ---rwx---
1624 otherModes         :: FileMode       -- ------rwx
1625 accessModes        :: FileMode       -- rwxrwxrwx
1626
1627 unionFileModes     :: FileMode -> FileMode -> FileMode
1628 intersectFileModes :: FileMode -> FileMode -> FileMode
1629
1630 stdInput  :: Channel
1631 stdInput  = 0
1632
1633 stdOutput :: Channel
1634 stdOutput = 1
1635
1636 stdError  :: Channel
1637 stdError  = 2
1638
1639 openChannel :: FilePath
1640             -> OpenMode
1641             -> Maybe FileMode  -- Just x => O_CREAT, Nothing => must exist
1642             -> Bool            -- O_APPEND
1643             -> Bool            -- O_EXCL
1644             -> Bool            -- O_NOCTTY
1645             -> Bool            -- O_NONBLOCK
1646             -> Bool            -- O_TRUNC
1647             -> IO Channel
1648 \end{verbatim}
1649
1650 \tr{openChannel path acc mode app excl noctty nonblock trunc} calls
1651 \tr{open} to obtain a \tr{Channel} for the file \tr{path} with access
1652 mode \tr{acc}.  If \tr{mode} is \tr{Just m}, the \tr{O_CREAT} flag is
1653 set and the file's permissions will be based on \tr{m} if it does not
1654 already exist; otherwise, the \tr{O_CREAT} flag is not set.  The
1655 arguments \tr{app}, \tr{excl}, \tr{noctty}, \tr{nonblock}, and
1656 \tr{trunc} control whether or not the flags \tr{O_APPEND},
1657 \tr{O_EXCL}, \tr{O_NOCTTY}, \tr{O_NONBLOCK}, and \tr{O_TRUNC} are set,
1658 respectively.
1659
1660 \begin{verbatim}
1661 createFile :: FilePath -> FileMode -> IO Channel
1662 \end{verbatim}
1663
1664 \tr{createFile path mode} calls \tr{creat} to obtain a \tr{Channel}
1665 for file \tr{path}, which will be created with permissions based on
1666 \tr{mode} if it does not already exist.
1667
1668 \begin{verbatim}
1669 setFileCreationMask :: FileMode -> IO FileMode
1670 \end{verbatim}
1671
1672 \tr{setFileCreationMask mode} calls \tr{umask} to set
1673 the process's file creation mask to \tr{mode}.  The previous file
1674 creation mask is returned.
1675
1676 \begin{verbatim}
1677 createLink :: FilePath -> FilePath -> IO ()
1678 \end{verbatim}
1679
1680 \tr{createLink old new} calls \tr{link} to create a 
1681 new path, \tr{new}, linked to an existing file, \tr{old}.
1682 \begin{verbatim}
1683 createDirectory :: FilePath -> FileMode -> IO ()
1684 \end{verbatim}
1685
1686 \tr{createDirectory dir mode} calls \tr{mkdir} to 
1687 create a new directory, \tr{dir}, with permissions based on
1688 \tr{mode}.
1689
1690 \begin{verbatim}
1691 createNamedPipe :: FilePath -> FileMode -> IO ()
1692 \end{verbatim}
1693
1694 \tr{createNamedPipe fifo mode} calls \tr{mkfifo} to 
1695 create a new named pipe, \tr{fifo}, with permissions based on
1696 \tr{mode}.
1697
1698 \begin{verbatim}
1699 removeLink :: FilePath -> IO ()
1700 \end{verbatim}
1701
1702 \tr{removeLink path} calls \tr{unlink} to remove the link
1703 named \tr{path}.
1704
1705 \begin{verbatim}
1706 removeDirectory :: FilePath -> IO ()
1707 \end{verbatim}
1708
1709 \tr{removeDirectory dir} calls \tr{rmdir} to remove the 
1710 directory named \tr{dir}.
1711
1712 \begin{verbatim}
1713 rename :: FilePath -> FilePath -> IO ()
1714 \end{verbatim}
1715
1716 \tr{rename old new} calls \tr{rename} to rename a 
1717 file or directory from \tr{old} to \tr{new}.
1718
1719 \begin{verbatim}
1720 fileMode          :: FileStatus -> FileMode
1721                    
1722 fileID            :: FileStatus -> FileID
1723 deviceID          :: FileStatus -> DeviceID
1724                    
1725 linkCount         :: FileStatus -> LinkCount
1726                    
1727 fileOwner         :: FileStatus -> UserID
1728 fileGroup         :: FileStatus -> GroupID
1729 fileSize          :: FileStatus -> FileOffset
1730
1731 accessTime        :: FileStatus -> EpochTime
1732 modificationTime  :: FileStatus -> EpochTime
1733 statusChangeTime  :: FileStatus -> EpochTime
1734
1735 isDirectory       :: FileStatus -> Bool
1736 isCharacterDevice :: FileStatus -> Bool
1737 isBlockDevice     :: FileStatus -> Bool
1738 isRegularFile     :: FileStatus -> Bool
1739 isNamedPipe       :: FileStatus -> Bool
1740
1741 getFileStatus     :: FilePath -> IO FileStatus
1742 \end{verbatim}
1743
1744 \tr{getFileStatus path} calls \tr{stat} to get the
1745 \tr{FileStatus} information for the file \tr{path}.
1746
1747 \begin{verbatim}
1748 getChannelStatus :: Channel -> IO FileStatus
1749 \end{verbatim}
1750
1751 \tr{getChannelStatus fd} calls \tr{fstat} to get the
1752 \tr{FileStatus} information for the file associated with
1753 \tr{Channel} \tr{fd}.
1754
1755 \begin{verbatim}
1756 queryAccess :: FilePath -> Bool -> Bool -> Bool -> IO Bool
1757 \end{verbatim}
1758
1759 \tr{queryAccess path r w x} calls \tr{access} to test the access
1760 permissions for file \tr{path}.  The three arguments, \tr{r}, \tr{w},
1761 and \tr{x} control whether or not \tr{access} is called with
1762 \tr{R_OK}, \tr{W_OK}, and \tr{X_OK} respectively.
1763
1764 \begin{verbatim}
1765 queryFile :: FilePath -> IO Bool
1766 \end{verbatim}
1767
1768 \tr{queryFile path} calls \tr{access} with \tr{F_OK} to test for the
1769 existence for file \tr{path}.
1770
1771 \begin{verbatim}
1772 setFileMode :: FilePath -> FileMode -> IO ()
1773 \end{verbatim}
1774
1775 \tr{setFileMode path mode} calls \tr{chmod} to set the
1776 permission bits associated with file \tr{path} to \tr{mode}.
1777
1778 \begin{verbatim}
1779 setOwnerAndGroup :: FilePath -> UserID -> GroupID -> IO ()
1780 \end{verbatim}
1781
1782 \tr{setOwnerAndGroup path uid gid} calls \tr{chown} to
1783 set the \tr{UserID} and \tr{GroupID} associated with file
1784 \tr{path} to \tr{uid} and \tr{gid}, respectively.
1785
1786 \begin{verbatim}
1787 setFileTimes :: FilePath -> EpochTime -> EpochTime -> IO ()
1788 \end{verbatim}
1789
1790 \tr{setFileTimes path atime mtime} calls \tr{utime} to
1791 set the access and modification times associated with file
1792 \tr{path} to \tr{atime} and \tr{mtime}, respectively.
1793
1794 \begin{verbatim}
1795 touchFile :: FilePath -> IO ()
1796 \end{verbatim}
1797
1798 \tr{touchFile path} calls \tr{utime} to
1799 set the access and modification times associated with file
1800 \tr{path} to the current time.
1801
1802 \begin{verbatim}
1803 getPathVar :: PathVar -> FilePath -> IO Limit
1804 \end{verbatim}
1805
1806 \tr{getPathVar var path} calls \tr{pathconf} to obtain the
1807 dynamic value of the requested configurable file limit or option associated
1808 with file or directory \tr{path}.  For
1809 defined file limits, \tr{getPathVar} returns the associated
1810 value.  For defined file options, the result of \tr{getPathVar}
1811 is undefined, but not failure.
1812 The operation may fail with:
1813 \begin{itemize}
1814 \item[\tr{NoSuchThing}]
1815 The requested file limit or option is undefined.
1816 \item[\tr{SystemError}]
1817 Various other causes.
1818 \end{itemize}
1819
1820
1821 \begin{verbatim}
1822 getChannelVar :: PathVar -> Channel -> IO Limit
1823 \end{verbatim}
1824
1825 \tr{getChannelVar var fd} calls \tr{fpathconf} to obtain the
1826 dynamic value of the requested configurable file limit or option associated
1827 with the file or directory attached to the open channel \tr{fd}.
1828 For defined file limits, \tr{getChannelVar} returns the associated
1829 value.  For defined file options, the result of \tr{getChannelVar}
1830 is undefined, but not failure.
1831
1832 The operation may fail with:
1833
1834 \begin{itemize}
1835 \item[\tr{NoSuchThing}]
1836 The requested file limit or option is undefined.
1837 \item[\tr{SystemError}]
1838 Various other causes.
1839 \end{itemize}
1840
1841 \subsubsection[posix-input-output]{Posix Input and Output Primitives}
1842 \index{Posix, input/output}
1843
1844 \begin{verbatim}
1845 createPipe :: IO (Channel, Channel)
1846 \end{verbatim}
1847
1848 \tr{createPipe} calls \tr{pipe} to create a pipe and returns a pair of
1849 \tr{Channels}, the first for writing and the second for reading.
1850
1851 \begin{verbatim}
1852 dupChannel :: Channel -> IO Channel
1853 \end{verbatim}
1854
1855 \tr{dupChannel fd} calls \tr{dup} to duplicate \tr{Channel} \tr{fd} to
1856 another \tr{Channel}.
1857
1858 \begin{verbatim}
1859 dupChannelTo :: Channel -> Channel -> IO ()
1860 \end{verbatim}
1861
1862 \tr{dupChannelTo src dst} calls \tr{dup2} to duplicate \tr{Channel}
1863 \tr{src} to \tr{Channel} \tr{dst}.
1864
1865 \begin{verbatim}
1866 closeChannel :: Channel -> IO ()
1867 \end{verbatim}
1868
1869 \tr{closeChannel fd} calls \tr{close} to close \tr{Channel} \tr{fd}.
1870
1871 \begin{verbatim}
1872 readChannel :: Channel -> ByteCount -> IO (String, ByteCount)
1873 \end{verbatim}
1874
1875 \tr{readChannel fd nbytes} calls \tr{read} to read at most \tr{nbytes}
1876 bytes from \tr{Channel} \tr{fd}, and returns the result as a string
1877 paired with the number of bytes actually read.
1878
1879 The operation may fail with:
1880
1881 \begin{itemize}
1882 \item[\tr{EOF}]
1883 End of file has been reached.
1884 \item[\tr{SystemError}]
1885 Various other causes.
1886 \end{itemize}
1887
1888 \begin{verbatim}
1889 writeChannel :: Channel -> String -> IO ByteCount
1890 \end{verbatim}
1891
1892 \tr{writeChannel fd s} calls \tr{write} to write
1893 the string \tr{s} to \tr{Channel} \tr{fd} as a
1894 contiguous sequence of bytes.  It returns the number of bytes successfully
1895 written.
1896
1897 \begin{verbatim}
1898 queryChannelOption :: ChannelOption -> Channel -> IO Bool
1899 \end{verbatim}
1900
1901 \tr{getChannelOption opt fd} calls \tr{fcntl} to determine whether or
1902 not the flag associated with \tr{ChannelOption} \tr{opt} is set for
1903 \tr{Channel} \tr{fd}.
1904
1905 \begin{verbatim}
1906 setChannelOption :: ChannelOption -> Bool -> Channel -> IO ()
1907 \end{verbatim}
1908
1909 \tr{setChannelOption opt val fd} calls \tr{fcntl} to set the flag
1910 associated with \tr{ChannelOption} \tr{opt} on \tr{Channel} \tr{fd} to
1911 \tr{val}.
1912
1913 \begin{verbatim}
1914 getLock :: Channel -> FileLock -> IO (Maybe (ProcessID, FileLock))
1915 \end{verbatim}
1916
1917 \tr{getLock fd lock} calls \tr{fcntl} to get the first \tr{FileLock}
1918 for \tr{Channel} \tr{fd} which blocks the \tr{FileLock} \tr{lock}.  If
1919 no such \tr{FileLock} exists, \tr{getLock} returns \tr{Nothing}.
1920 Otherwise, it returns \tr{Just (pid, block)}, where \tr{block} is the
1921 blocking \tr{FileLock} and \tr{pid} is the \tr{ProcessID} of the
1922 process holding the blocking \tr{FileLock}.
1923
1924
1925 \begin{verbatim}
1926 setLock :: Channel -> FileLock -> IO ()
1927 \end{verbatim}
1928
1929 \tr{setLock fd lock} calls \tr{fcntl} with \tr{F_SETLK} to set or
1930 clear a lock segment for \tr{Channel} \tr{fd} as indicated by the
1931 \tr{FileLock} \tr{lock}.  \tr{setLock} does not block, but fails with
1932 \tr{SystemError} if the request cannot be satisfied immediately.
1933
1934 \begin{verbatim}
1935 waitToSetLock :: Channel -> FileLock -> IO ()
1936 \end{verbatim}
1937
1938 \tr{waitToSetLock fd lock} calls \tr{fcntl} with \tr{F_SETLKW} to set
1939 or clear a lock segment for \tr{Channel} \tr{fd} as indicated by the
1940 \tr{FileLock} \tr{lock}. If the request cannot be satisfied
1941 immediately, \tr{waitToSetLock} blocks until the request can be
1942 satisfied.
1943
1944
1945 \begin{verbatim}
1946 seekChannel :: Channel -> SeekMode -> FileOffset -> IO FileOffset
1947 \end{verbatim}
1948
1949 \tr{seekChannel fd whence offset} calls \tr{lseek} to position the
1950 \tr{Channel} at the given \tr{offset} from the starting location
1951 indicated by \tr{whence}.  It returns the resulting offset from the
1952 start of the file in bytes.
1953
1954 \subsubsection[posix-device-class]{Posix, Device- and Class-Specific Functions}
1955 \index{Posix, device and class-specific functions}
1956
1957 \begin{verbatim}
1958 terminalMode    :: TerminalMode -> TerminalAttributes -> Bool
1959 withMode        :: TerminalAttributes -> TerminalMode -> TerminalAttributes
1960 withoutMode     :: TerminalAttributes -> TerminalMode -> TerminalAttributes
1961
1962 bitsPerByte     :: TerminalAttributes -> Int
1963 withBits        :: TerminalAttributes -> Int -> TerminalAttributes
1964
1965 controlChar     :: TerminalAttributes -> ControlCharacter -> Maybe Char
1966 withCC          :: TerminalAttributes
1967                 -> (ControlCharacter, Char)
1968                 -> TerminalAttributes 
1969 withoutCC       :: TerminalAttributes 
1970                 -> ControlCharacter 
1971                 -> TerminalAttributes
1972                   
1973 inputTime       :: TerminalAttributes -> Int
1974 withTime        :: TerminalAttributes -> Int -> TerminalAttributes
1975                   
1976 minInput        :: TerminalAttributes -> Int
1977 withMinInput    :: TerminalAttributes -> Int -> TerminalAttributes
1978                   
1979 inputSpeed      :: TerminalAttributes -> BaudRate
1980 withInputSpeed  :: TerminalAttributes -> BaudRate -> TerminalAttributes
1981                   
1982 outputSpeed     :: TerminalAttributes -> BaudRate
1983 withOutputSpeed :: TerminalAttributes -> BaudRate -> TerminalAttributes
1984
1985 getTerminalAttributes :: Channel -> IO TerminalAttributes
1986 \end{verbatim}
1987
1988 \tr{getTerminalAttributes fd} calls \tr{tcgetattr} to obtain
1989 the \tr{TerminalAttributes} associated with \tr{Channel}
1990 \tr{fd}.
1991
1992 \begin{verbatim}
1993 setTerminalAttributes :: Channel 
1994                       -> TerminalAttributes 
1995                       -> TerminalState
1996                       -> IO ()
1997 \end{verbatim}
1998
1999 \tr{setTerminalAttributes fd attr ts} calls \tr{tcsetattr} to change
2000 the \tr{TerminalAttributes} associated with \tr{Channel} \tr{fd} to
2001 \tr{attr}, when the terminal is in the state indicated by \tr{ts}.
2002
2003 \begin{verbatim}
2004 sendBreak :: Channel -> Int -> IO ()
2005 \end{verbatim}
2006
2007 \tr{sendBreak fd duration} calls \tr{tcsendbreak} to transmit a
2008 continuous stream of zero-valued bits on \tr{Channel} \tr{fd} for the
2009 specified implementation-dependent \tr{duration}.
2010
2011 \begin{verbatim}
2012 drainOutput :: Channel -> IO ()
2013 \end{verbatim}
2014
2015 \tr{drainOutput fd} calls \tr{tcdrain} to block until all output
2016 written to \tr{Channel} \tr{fd} has been transmitted.
2017
2018 \begin{verbatim}
2019 discardData :: Channel -> QueueSelector -> IO ()
2020 \end{verbatim}
2021
2022 \tr{discardData fd queues} calls \tr{tcflush} to discard
2023 pending input and/or output for \tr{Channel} \tr{fd},
2024 as indicated by the \tr{QueueSelector} \tr{queues}.
2025
2026 \begin{verbatim}
2027 controlFlow :: Channel -> FlowAction -> IO ()
2028 \end{verbatim}
2029
2030 \tr{controlFlow fd action} calls \tr{tcflow} to control the 
2031 flow of data on \tr{Channel} \tr{fd}, as indicated by
2032 \tr{action}.
2033
2034 \begin{verbatim}
2035 getTerminalProcessGroupID :: Channel -> IO ProcessGroupID
2036 \end{verbatim}
2037
2038 \tr{getTerminalProcessGroupID fd} calls \tr{tcgetpgrp} to
2039 obtain the \tr{ProcessGroupID} of the foreground process group 
2040 associated with the terminal attached to \tr{Channel} 
2041 \tr{fd}.
2042
2043 \begin{verbatim}
2044 setTerminalProcessGroupID :: Channel -> ProcessGroupID -> IO ()
2045 \end{verbatim}
2046
2047 \tr{setTerminalProcessGroupID fd pgid} calls \tr{tcsetpgrp} to
2048 set the \tr{ProcessGroupID} of the foreground process group 
2049 associated with the terminal attached to \tr{Channel} 
2050 \tr{fd} to \tr{pgid}.
2051
2052 \subsubsection[posix-system-db]{Posix System Databases}
2053 \index{Posix, system databases}
2054
2055 \begin{verbatim}
2056 groupName    :: GroupEntry -> String
2057 groupID      :: GroupEntry -> GroupID
2058 groupMembers :: GroupEntry -> [String]
2059
2060 getGroupEntryForID :: GroupID -> IO GroupEntry
2061 \end{verbatim}
2062
2063 \tr{getGroupEntryForID gid} calls \tr{getgrgid} to obtain
2064 the \tr{GroupEntry} information associated with \tr{GroupID}
2065 \tr{gid}.
2066
2067 The operation may fail with:
2068
2069 \begin{itemize}
2070 \item[\tr{NoSuchThing}]
2071 There is no group entry for the GroupID.
2072 \end{itemize}
2073
2074 \begin{verbatim}
2075 getGroupEntryForName :: String -> IO GroupEntry
2076 \end{verbatim}
2077
2078 \tr{getGroupEntryForName name} calls \tr{getgrnam} to obtain
2079 the \tr{GroupEntry} information associated with the group called
2080 \tr{name}.
2081
2082 The operation may fail with:
2083
2084 \begin{itemize}
2085 \item[\tr{NoSuchThing}]
2086 There is no group entry for the name.
2087 \end{itemize}
2088
2089 \begin{verbatim}
2090 userName      :: UserEntry -> String
2091 userID        :: UserEntry -> UserID
2092 userGroupID   :: UserEntry -> GroupID
2093 homeDirectory :: UserEntry -> String
2094 userShell     :: UserEntry -> String
2095
2096 getUserEntryForID :: UserID -> IO UserEntry
2097 \end{verbatim}
2098
2099 \tr{getUserEntryForID gid} calls \tr{getpwuid} to obtain
2100 the \tr{UserEntry} information associated with \tr{UserID}
2101 \tr{uid}.
2102 The operation may fail with:
2103
2104 \begin{itemize}
2105 \item[\tr{NoSuchThing}]
2106 There is no user entry for the UserID.
2107 \end{itemize}
2108
2109 \begin{verbatim}
2110 getUserEntryForName :: String -> IO UserEntry
2111 \end{verbatim}
2112
2113 \tr{getUserEntryForName name} calls \tr{getpwnam} to obtain
2114 the \tr{UserEntry} information associated with the user login
2115 \tr{name}.
2116
2117 The operation may fail with:
2118
2119 \begin{itemize}
2120 \item[\tr{NoSuchThing}]
2121 There is no user entry for the name.
2122 \end{itemize}
2123
2124 \subsubsection[posix-errors]{POSIX Errors}
2125 \index{Posix, errors}
2126
2127 \begin{verbatim}
2128 getErrorCode :: IO ErrorCode
2129 \end{verbatim}
2130
2131 \tr{getErrorCode} returns the current value of the external
2132 variable \tr{errno}.  It never fails.
2133
2134 \begin{verbatim}
2135 setErrorCode :: ErrorCode -> IO ()
2136 \end{verbatim}
2137
2138 \tr{setErrorCode err} sets the external
2139 variable \tr{errno} to \tr{err}.  It never fails.
2140
2141 \begin{verbatim}
2142 noError :: ErrorCode
2143 noError = 0
2144
2145 argumentListTooLong, e2BIG              :: ErrorCode
2146 badChannel, eBADF                       :: ErrorCode
2147 brokenPipe, ePIPE                       :: ErrorCode
2148 directoryNotEmpty, eNOTEMPTY            :: ErrorCode
2149 execFormatError, eNOEXEC                :: ErrorCode
2150 fileAlreadyExists, eEXIST               :: ErrorCode
2151 fileTooLarge, eFBIG                     :: ErrorCode
2152 filenameTooLong, eNAMETOOLONG           :: ErrorCode
2153 improperLink, eXDEV                     :: ErrorCode
2154 inappropriateIOControlOperation, eNOTTY :: ErrorCode
2155 inputOutputError, eIO                   :: ErrorCode
2156 interruptedOperation, eINTR             :: ErrorCode
2157 invalidArgument, eINVAL                 :: ErrorCode
2158 invalidSeek, eSPIPE                     :: ErrorCode
2159 isADirectory, eISDIR                    :: ErrorCode
2160 noChildProcess, eCHILD                  :: ErrorCode
2161 noLocksAvailable, eNOLCK                :: ErrorCode
2162 noSpaceLeftOnDevice, eNOSPC             :: ErrorCode
2163 noSuchOperationOnDevice, eNODEV         :: ErrorCode
2164 noSuchDeviceOrAddress, eNXIO            :: ErrorCode
2165 noSuchFileOrDirectory, eNOENT           :: ErrorCode
2166 noSuchProcess, eSRCH                    :: ErrorCode
2167 notADirectory, eNOTDIR                  :: ErrorCode
2168 notEnoughMemory, eNOMEM                 :: ErrorCode
2169 operationNotImplemented, eNOSYS         :: ErrorCode
2170 operationNotPermitted, ePERM            :: ErrorCode
2171 permissionDenied, eACCES                :: ErrorCode
2172 readOnlyFileSystem, eROFS               :: ErrorCode
2173 resourceBusy, eBUSY                     :: ErrorCode
2174 resourceDeadlockAvoided, eDEADLK        :: ErrorCode
2175 resourceTemporarilyUnavailable, eAGAIN  :: ErrorCode
2176 tooManyLinks, eMLINK                    :: ErrorCode
2177 tooManyOpenFiles, eMFILE                :: ErrorCode
2178 tooManyOpenFilesInSystem, eNFILE        :: ErrorCode
2179
2180 \end{verbatim}
2181
2182 %************************************************************************
2183 %*                                                                      *
2184 \subsection[HBC-library]{The HBC system library}
2185 \index{HBC system library}
2186 \index{system library, HBC}
2187 %*                                                                      *
2188 %************************************************************************
2189
2190 This documentation is stolen directly from the HBC distribution.  The
2191 modules that GHC does not support (because they require HBC-specific
2192 extensions) are omitted.
2193
2194 \begin{description}
2195 \item[\tr{Either}:]
2196 \index{Either module (HBC library)}%
2197 A binary sum data type:
2198 \begin{verbatim}
2199 data Either a b = Left a | Right b
2200 \end{verbatim}
2201 The constructor \tr{Left} is typically used for errors; it can be
2202 renamed to \tr{Wrong} on import.
2203
2204 \item[\tr{Maybe}:]
2205 \index{Maybe module (HBC library)}%
2206 A type for failure or success:
2207 \begin{verbatim}
2208 data Maybe a = Nothing | Just a
2209 thenM :: Maybe a -> (a -> Maybe b) -> Maybe b
2210     -- apply a function that may fail
2211 \end{verbatim}
2212
2213 \item[\tr{Option}:]
2214 \index{Option module (HBC library)}%
2215 An alias for \tr{Maybe}:
2216 \begin{verbatim}
2217 data Option a = None | Some a
2218 thenO :: Option a -> (a -> Option b) -> Option b
2219 \end{verbatim}
2220
2221 \item[\tr{ListUtil}:]
2222 \index{ListUtil module (HBC library)}%
2223 Various useful functions involving lists that are missing from the
2224 \tr{Prelude}:
2225 \begin{verbatim}
2226 assoc :: (Eq c) => (a -> b) -> b -> [(c, a)] -> c -> b
2227         -- assoc f d l k looks for k in the association list l, if it
2228         -- is found f is applied to the value, otherwise d is returned.
2229 concatMap :: (a -> [b]) -> [a] -> [b]
2230         -- flattening map (LML's concmap)
2231 unfoldr :: (a -> (b, a)) -> (a -> Bool) -> a -> [b]
2232         -- unfoldr f p x repeatedly applies f to x until (p x) holds.
2233         -- (f x) should give a list element and a new x.
2234 mapAccuml :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
2235         -- mapAccuml f s l maps f over l, but also threads the state s
2236         -- through (LML's mapstate).
2237 union :: (Eq a) => [a] -> [a] -> [a]
2238         -- union of two lists
2239 intersection :: (Eq a) => [a] -> [a] -> [a]
2240         -- intersection of two lists
2241 chopList :: ([a] -> (b, [a])) -> [a] -> [b]
2242         -- LMLs choplist
2243 assocDef :: (Eq a) => [(a, b)] -> b -> a -> b
2244         -- LMLs assocdef
2245 lookup :: (Eq a) => [(a, b)] -> a -> Option b
2246         -- lookup l k looks for the key k in the association list l
2247         -- and returns an optional value
2248 tails :: [a] -> [[a]]
2249         -- return all the tails of a list
2250 rept :: (Integral a) => a -> b -> [b]
2251         -- repeat a value a number of times
2252 groupEq :: (a->a->Bool) -> [a] -> [[a]]
2253         -- group list elements according to an equality predicate
2254 group :: (Eq a) => [a] -> [[a]]
2255         -- group according to} ==
2256 readListLazily :: (Text a) => String -> [a]
2257         -- read a list in a lazy fashion
2258 \end{verbatim}
2259
2260 \item[\tr{Pretty}:]
2261 \index{Pretty module (HBC library)}%
2262 John Hughes's pretty printing library.  
2263 \begin{verbatim}
2264 type Context = (Bool, Int, Int, Int)
2265 type IText = Context -> [String]
2266 text :: String -> IText                 -- just text
2267 (~.) :: IText -> IText -> IText         -- horizontal composition
2268 (^.) :: IText -> IText -> IText         -- vertical composition
2269 separate :: [IText] -> IText            -- separate by spaces
2270 nest :: Int -> IText -> IText           -- indent
2271 pretty :: Int -> Int -> IText -> String -- format it
2272 \end{verbatim}
2273
2274 \item[\tr{QSort}:]
2275 \index{QSort module (HBC library)}%
2276 A sort function using quicksort.
2277 \begin{verbatim}
2278 sortLe :: (a -> a -> Bool) -> [a] -> [a]
2279         -- sort le l  sorts l with le as less than predicate
2280 sort :: (Ord a) => [a] -> [a]
2281         -- sort l  sorts l using the Ord class
2282 \end{verbatim}
2283
2284 \item[\tr{Random}:]
2285 \index{Random module (HBC library)}%
2286 Random numbers.
2287 \begin{verbatim}
2288 randomInts :: Int -> Int -> [Int]
2289         -- given two seeds gives a list of random Int
2290 randomDoubles :: Int -> Int -> [Double]
2291         -- random Double with uniform distribution in (0,1)
2292 normalRandomDoubles :: Int -> Int -> [Double]
2293         -- random Double with normal distribution, mean 0, variance 1
2294 \end{verbatim}
2295
2296 \item[\tr{Trace}:]
2297 Simple tracing.  (Note: This comes with GHC anyway.)
2298 \begin{verbatim}
2299 trace :: String -> a -> a       -- trace x y  prints x and returns y
2300 \end{verbatim}
2301
2302 \item[\tr{Miranda}:]
2303 \index{Miranda module (HBC library)}%
2304 Functions found in the Miranda library.
2305 (Note: Miranda is a registered trade mark of Research Software Ltd.)
2306
2307 \item[\tr{Word}:]
2308 \index{Word module (HBC library)}
2309 Bit manipulation.  (GHC doesn't implement absolutely all of this.
2310 And don't count on @Word@ being 32 bits on a Alpha...)
2311 \begin{verbatim}
2312 class Bits a where
2313     bitAnd :: a -> a -> a       -- bitwise and
2314     bitOr :: a -> a -> a        -- bitwise or
2315     bitXor :: a -> a -> a       -- bitwise xor
2316     bitCompl :: a -> a          -- bitwise negation
2317     bitRsh :: a -> Int -> a     -- bitwise right shift
2318     bitLsh :: a -> Int -> a     -- bitwise left shift
2319     bitSwap :: a -> a           -- swap word halves
2320     bit0 :: a                   -- word with least significant bit set
2321     bitSize :: a -> Int         -- number of bits in a word
2322
2323 data Byte                       -- 8  bit quantity
2324 data Short                      -- 16 bit quantity
2325 data Word                       -- 32 bit quantity
2326
2327 instance Bits Byte, Bits Short, Bits Word
2328 instance Eq Byte, Eq Short, Eq Word
2329 instance Ord Byte, Ord Short, Ord Word
2330 instance Text Byte, Text Short, Text Word
2331 instance Num Byte, Num Short, Num Word
2332 wordToShorts :: Word -> [Short]   -- convert a Word to two Short
2333 wordToBytes :: Word -> [Byte]     -- convert a Word to four Byte
2334 bytesToString :: [Byte] -> String -- convert a list of Byte to a String (bit by bit)
2335 wordToInt :: Word -> Int          -- convert a Word to Int
2336 shortToInt :: Short -> Int        -- convert a Short to Int
2337 byteToInt :: Byte -> Int          -- convert a Byte to Int
2338 \end{verbatim}
2339
2340 \item[\tr{Time}:]
2341 \index{Time module (HBC library)}%
2342 Manipulate time values (a Double with seconds since 1970).
2343 \begin{verbatim}
2344 --               year mon  day  hour min  sec  dec-sec  weekday
2345 data Time = Time Int  Int  Int  Int  Int  Int  Double  Int
2346 dblToTime :: Double -> Time     -- convert a Double to a Time
2347 timeToDbl :: Time -> Double     -- convert a Time to a Double
2348 timeToString :: Time -> String  -- convert a Time to a readable String
2349 \end{verbatim}
2350
2351 \item[\tr{Hash}:]
2352 \index{Hash module (HBC library)}%
2353 Hashing functions.
2354 \begin{verbatim}
2355 class Hashable a where
2356     hash :: a -> Int                            -- hash a value, return an Int
2357 -- instances for all Prelude types
2358 hashToMax :: (Hashable a) => Int -> a -> Int    -- hash into interval [0..x-1]
2359 \end{verbatim}
2360
2361 \item[\tr{NameSupply}:]
2362 \index{NameSupply module (HBC library)}%
2363 Functions to generate unique names (Int).
2364 \begin{verbatim}
2365 type Name = Int
2366 initialNameSupply :: NameSupply
2367         -- The initial name supply (may be different every
2368         -- time the program is run.
2369 splitNameSupply :: NameSupply -> (NameSupply,NameSupply)
2370         -- split the namesupply into two
2371 getName :: NameSupply -> Name
2372         -- get the name associated with a name supply
2373 \end{verbatim}
2374
2375 \item[\tr{Parse}:]
2376 \index{Parse module (HBC library)}%
2377 Higher order functions to build parsers.  With a little care these
2378 combinators can be used to build efficient parsers with good error
2379 messages.
2380 \begin{verbatim}
2381 infixr 8 +.+ , ..+ , +.. 
2382 infix  6 `act` , >>> , `into` , .> 
2383 infixr 4 ||| , ||! , |!! 
2384 data ParseResult a b 
2385 type Parser a b = a -> Int -> ParseResult a b 
2386 (|||) :: Parser a b -> Parser a b -> Parser a b
2387         -- Alternative
2388 (||!) :: Parser a b -> Parser a b -> Parser a b
2389         -- Alternative, but with committed choice
2390 (|!!) :: Parser a b -> Parser a b -> Parser a b
2391         -- Alternative, but with committed choice
2392 (+.+) :: Parser a b -> Parser a c -> Parser a (b,c)
2393         -- Sequence
2394 (..+) :: Parser a b -> Parser a c -> Parser a c
2395         -- Sequence, throw away first part
2396 (+..) :: Parser a b -> Parser a c -> Parser a b
2397         -- Sequence, throw away second part
2398 act   :: Parser a b -> (b->c) -> Parser a c
2399         -- Action
2400 (>>>) :: Parser a (b,c) -> (b->c->d) -> Parser a d
2401         -- Action on two items
2402 (.>) :: Parser a b -> c -> Parse a c
2403         -- Action ignoring value
2404 into :: Parser a b -> (b -> Parser a c) -> Parser a c
2405         -- Use a produced value in a parser.
2406 succeed b :: Parser a b
2407         -- Always succeeds without consuming a token
2408 failP :: Parser a b
2409         -- Always fails.
2410 many :: Parser a b -> Parser a [b]
2411         -- Kleene star
2412 many1 :: Parser a b -> Parser a [b]
2413         -- Kleene plus
2414 count :: Parser a b -> Int -> Parser a [b]
2415         -- Parse an exact number of items
2416 sepBy1 :: Parser a b -> Parser a c -> Parser a [b]
2417         -- Non-empty sequence of items separated by something
2418 sepBy :: Parser a b -> Parser a c -> Parser a [b]
2419         -- Sequence of items separated by something
2420 lit :: (Eq a, Text a) => a -> Parser [a] a
2421         -- Recognise a literal token from a list of tokens
2422 litp :: String -> (a->Bool) -> Parser [a] a
2423         -- Recognise a token with a predicate.
2424         -- The string is a description for error messages.
2425 testp :: String -> (a -> Bool) -> (Parser b a) -> Parser b a
2426         -- Test a semantic value. 
2427 token :: (a -> Either String (b, a)) -> Parser a b
2428         -- General token recogniser.
2429 parse :: Parser a b -> a -> Either ([String], a) [(b, a)]
2430         -- Do a parse.  Return either error (possible tokens and rest
2431         -- of tokens) or all possible parses.
2432 sParse :: (Text a) => (Parser [a] b) -> [a] -> Either String b
2433         -- Simple parse.  Return error message or result.
2434 \end{verbatim}
2435
2436 %%%simpleLex :: String -> [String]              -- A simple (but useful) lexical analyzer
2437
2438 \item[\tr{Native}:]
2439 \index{Native module (HBC library)}%
2440 Functions to convert the primitive types \tr{Int}, \tr{Float}, and \tr{Double} to
2441 their native representation as a list of bytes (\tr{Char}).  If such a list
2442 is read/written to a file it will have the same format as when, e.g.,
2443 C read/writes the same kind of data.
2444 \begin{verbatim}
2445 type Bytes = [Char] -- A byte stream is just a list of characters
2446
2447 class Native a where 
2448     showBytes     :: a -> Bytes -> Bytes
2449         -- prepend the representation of an item the a byte stream
2450     listShowBytes :: [a] -> Bytes -> Bytes
2451         -- prepend the representation of a list of items to a stream
2452         -- (may be more efficient than repeating showBytes).
2453     readBytes     :: Bytes -> Maybe (a, Bytes)
2454         -- get an item from the stream and return the rest,
2455         -- or fail if the stream is to short.
2456     listReadBytes :: Int -> Bytes -> Maybe ([a], Bytes)
2457         -- read n items from a stream.
2458
2459 instance Native Int 
2460 instance Native Float 
2461 instance Native Double 
2462 instance (Native a, Native b) => Native (a,b)
2463         -- juxtaposition of the two items
2464 instance (Native a, Native b, Native c) => Native (a, b, c)
2465         -- juxtaposition of the three items
2466 instance (Native a) => Native [a]
2467         -- an item count in an Int followed by the items
2468
2469 shortIntToBytes :: Int -> Bytes -> Bytes
2470         -- Convert an Int to what corresponds to a short in C.
2471 bytesToShortInt :: Bytes -> Maybe (Int, Bytes)
2472         -- Get a short from a byte stream and convert to an Int.
2473
2474 showB :: (Native a) => a -> Bytes       -- Simple interface to showBytes.
2475 readB :: (Native a) => Bytes -> a       -- Simple interface to readBytes.
2476 \end{verbatim}
2477
2478 \item[\tr{Number}:]
2479 \index{Number module (HBC library)}%
2480 Simple numbers that belong to all numeric classes and behave like
2481 a naive user would expect (except that printing is still ugly).
2482 (NB: GHC does not provide a magic way to use \tr{Numbers} everywhere,
2483 but you should be able to do it with normal \tr{import}ing and
2484 \tr{default}ing.)
2485 \begin{verbatim}
2486 data Number                     -- The type itself.
2487 instance ...                    -- All reasonable instances.
2488 isInteger :: Number -> Bool     -- Test if a Number is an integer.
2489 \end{verbatim}
2490 \end{description}