[project @ 1997-06-05 23:38:01 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 mostly complete interface to OS functionality as
18 specified by {\tt POSIX 1003.1}. Sadly, this library isn't a standard
19 Haskell library...yet.
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
270 \tr{-syslib 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 
791 \tr{-syslib 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 data Fd 
935
936 intToFd :: Int -> Fd -- use with care.
937
938 data FdOption = AppendOnWrite
939               | CloseOnExec
940               | NonBlockingRead
941
942 data ControlCharacter = EndOfFile
943                       | EndOfLine
944                       | Erase
945                       | Interrupt
946                       | Kill
947                       | Quit
948                       | Suspend
949                       | Start
950                       | Stop
951
952 type ErrorCode = Int
953
954 type FileLock = (LockRequest, SeekMode, FileOffset, FileOffset)
955 --                            whence    start       length
956
957 data FlowAction = SuspendOutput | RestartOutput | TransmitStop | TransmitStart
958
959 data Handler = Default | Ignore | Catch (IO ())
960
961 data LockRequest = ReadLock | WriteLock | Unlock
962                  deriving (Eq, Show)
963
964 data OpenMode = ReadOnly | WriteOnly | ReadWrite
965
966 data PathVar = LinkLimit
967              | InputLineLimit
968              | InputQueueLimit
969              | FileNameLimit
970              | PathNameLimit
971              | PipeBufferLimit
972              | SetOwnerAndGroupIsRestricted
973              | FileNamesAreNotTruncated
974
975 data QueueSelector = InputQueue | OutputQueue | BothQueues
976
977 type Signal = Int
978
979 data SysVar = ArgumentLimit
980             | ChildLimit
981             | ClockTick
982             | GroupLimit
983             | OpenFileLimit
984             | PosixVersion
985             | HasSavedIDs
986             | HasJobControl
987
988 data TerminalMode = InterruptOnBreak       -- BRKINT
989                 | MapCRtoLF                -- ICRNL
990                 | IgnoreBreak              -- IGNBRK
991                 | IgnoreCR                 -- IGNCR
992                 | IgnoreParityErrors       -- IGNPAR
993                 | MapLFtoCR                -- INLCR
994                 | CheckParity              -- INPCK
995                 | StripHighBit             -- ISTRIP
996                 | StartStopInput           -- IXOFF
997                 | StartStopOutput          -- IXON
998                 | MarkParityErrors         -- PARMRK
999                 | ProcessOutput            -- OPOST
1000                 | LocalMode                -- CLOCAL
1001                 | ReadEnable               -- CREAD
1002                 | TwoStopBits              -- CSTOPB
1003                 | HangupOnClose            -- HUPCL
1004                 | EnableParity             -- PARENB
1005                 | OddParity                -- PARODD
1006                 | EnableEcho               -- ECHO
1007                 | EchoErase                -- ECHOE
1008                 | EchoKill                 -- ECHOK
1009                 | EchoLF                   -- ECHONL
1010                 | ProcessInput             -- ICANON
1011                 | ExtendedFunctions        -- IEXTEN
1012                 | KeyboardInterrupts       -- ISIG
1013                 | NoFlushOnInterrupt       -- NOFLSH
1014                 | BackgroundWriteInterrupt -- TOSTOP
1015
1016 data TerminalState = Immediately | WhenDrained | WhenFlushed
1017
1018 data ProcessStatus = Exited ExitCode 
1019                    | Terminated Signal 
1020                    | Stopped Signal
1021                    deriving (Eq, Show)
1022 \end{verbatim}
1023
1024 \subsubsection[Process Primitives]{Posix Process Primitives}
1025
1026 \begin{verbatim}
1027 forkProcess :: IO (Maybe ProcessID)
1028 \end{verbatim}
1029
1030 \tr{forkProcess} calls \tr{fork}, returning
1031 \tr{Just pid} to the parent, where \tr{pid} is the
1032 ProcessID of the child, and returning \tr{Nothing} to the
1033 child.
1034
1035 \begin{verbatim}
1036 executeFile :: FilePath                   -- Command
1037             -> Bool                       -- Search PATH?
1038             -> [String]                   -- Arguments
1039             -> Maybe [(String, String)]   -- Environment
1040             -> IO ()
1041 \end{verbatim}
1042
1043 \tr{executeFile cmd args env} calls one of the
1044 \tr{execv*} family, depending on whether or not the current
1045 PATH is to be searched for the command, and whether or not an
1046 environment is provided to supersede the process's current
1047 environment.  The basename (leading directory names suppressed) of
1048 the command is passed to \tr{execv*} as \tr{arg[0]};
1049 the argument list passed to \tr{executeFile} therefore begins 
1050 with \tr{arg[1]}.
1051
1052 \begin{verbatim}
1053 Search PATH?    Supersede environ?      Call
1054 ~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~~      ~~~~~~~
1055 False           False                   execv
1056 False           True                    execve
1057 True            False                   execvp
1058 True            True                    execvpe*
1059 \end{verbatim}
1060
1061 Note that \tr{execvpe} is not provided by the POSIX standard, and must
1062 be written by hand.  Care must be taken to ensure that the search path
1063 is extracted from the original environment, and not from the
1064 environment to be passed on to the new image.
1065
1066 A successful \tr{executeFile} overlays the current process image with 
1067 a new one, so it only returns on failure.
1068 \begin{verbatim}
1069 runProcess :: FilePath                    -- Command
1070            -> [String]                    -- Arguments
1071            -> Maybe [(String, String)]    -- Environment (Nothing -> Inherited)
1072            -> Maybe FilePath              -- Working directory (Nothing -> inherited)
1073            -> Maybe Handle                -- stdin  (Nothing -> inherited)
1074            -> Maybe Handle                -- stdout (Nothing -> inherited)
1075            -> Maybe Handle                -- stderr (Nothing -> inherited)
1076            -> IO ()
1077 \end{verbatim}
1078
1079 \tr{runProcess} is our candidate for the high-level OS-independent
1080 primitive.
1081
1082 \tr{runProcess cmd args env wd inhdl outhdl errhdl} runs \tr{cmd}
1083 (searching the current \tr{PATH}) with arguments \tr{args}.  If
1084 \tr{env} is \tr{Just pairs}, the command is executed with the
1085 environment specified by \tr{pairs} of variables and values;
1086 otherwise, the command is executed with the current environment.  If
1087 \tr{wd} is \tr{Just dir}, the command is executed with working
1088 directory \tr{dir}; otherwise, the command is executed in the current
1089 working directory.  If \tr{{in,out,err}hdl} is \tr{Just handle}, the
1090 command is executed with the \tr{Fd} for \tr{std{in,out,err}}
1091 attached to the specified \tr{handle}; otherwise, the \tr{Fd} for
1092 \tr{std{in,out,err}} is left unchanged.
1093
1094 \begin{verbatim}
1095 getProcessStatus :: Bool              -- Block?
1096                  -> Bool              -- Stopped processes?
1097                  -> ProcessID 
1098                  -> IO (Maybe ProcessStatus)
1099 \end{verbatim}
1100
1101 \tr{getProcessStatus blk stopped pid} calls \tr{waitpid}, returning
1102 \tr{Just tc}, the \tr{ProcessStatus} for process \tr{pid} if it is
1103 available, \tr{Nothing} otherwise.  If \tr{blk} is \tr{False}, then
1104 \tr{WNOHANG} is set in the options for \tr{waitpid}, otherwise not.
1105 If \tr{stopped} is \tr{True}, then \tr{WUNTRACED} is set in the
1106 options for \tr{waitpid}, otherwise not.
1107
1108 \begin{verbatim}
1109 getGroupProcessStatus :: Bool         -- Block?
1110                       -> Bool         -- Stopped processes?
1111                       -> ProcessGroupID 
1112                       -> IO (Maybe (ProcessID, ProcessStatus))
1113 \end{verbatim}
1114
1115 \tr{getGroupProcessStatus blk stopped pgid} calls \tr{waitpid},
1116 returning \tr{Just (pid, tc)}, the \tr{ProcessID} and
1117 \tr{ProcessStatus} for any process in group \tr{pgid} if one is
1118 available, \tr{Nothing} otherwise.  If \tr{blk} is \tr{False}, then
1119 \tr{WNOHANG} is set in the options for \tr{waitpid}, otherwise not.
1120 If \tr{stopped} is \tr{True}, then \tr{WUNTRACED} is set in the
1121 options for \tr{waitpid}, otherwise not.
1122
1123 \begin{verbatim}
1124 getAnyProcessStatus :: Bool           -- Block?
1125                     -> Bool           -- Stopped processes?
1126                     -> IO (Maybe (ProcessID, ProcessStatus))
1127 \end{verbatim}
1128
1129 \tr{getAnyProcessStatus blk stopped} calls \tr{waitpid}, returning
1130 \tr{Just (pid, tc)}, the \tr{ProcessID} and \tr{ProcessStatus} for any
1131 child process if one is available, \tr{Nothing} otherwise.  If
1132 \tr{blk} is \tr{False}, then \tr{WNOHANG} is set in the options for
1133 \tr{waitpid}, otherwise not.  If \tr{stopped} is \tr{True}, then
1134 \tr{WUNTRACED} is set in the options for \tr{waitpid}, otherwise not.
1135
1136 \begin{verbatim}
1137 exitImmediately :: ExitCode -> IO ()
1138 \end{verbatim}
1139
1140 \tr{exitImmediately status} calls \tr{_exit} to terminate the process
1141 with the indicated exit \tr{status}.
1142 The operation never returns.
1143
1144 \begin{verbatim}
1145 getEnvironment :: IO [(String, String)]
1146 \end{verbatim}
1147
1148 \tr{getEnvironment} parses the environment variable mapping provided by
1149 \tr{environ}, returning \tr{(variable, value)} pairs. 
1150 The operation never fails.
1151
1152 \begin{verbatim}
1153 setEnvironment :: [(String, String)] -> IO ()
1154 \end{verbatim}
1155
1156 \tr{setEnvironment} replaces the process environment with the provided
1157 mapping of \tr{(variable, value)} pairs. 
1158
1159 \begin{verbatim}
1160 getEnvVar :: String -> IO String
1161 \end{verbatim}
1162
1163 \tr{getEnvVar var} returns the value associated with variable \tr{var} 
1164 in the current environment (identical functionality provided through
1165 standard Haskell library function @System.getEnv@).
1166
1167 The operation may fail with:
1168
1169 \begin{itemize}
1170 \item[\tr{NoSuchThing}]
1171 The variable has no mapping in the current environment.
1172 \end{itemize}
1173
1174 \begin{verbatim}
1175 setEnvVar :: String -> String -> IO ()
1176 \end{verbatim}
1177
1178 \tr{setEnvVar var val} sets the value associated with variable \tr{var} 
1179 in the current environment to be \tr{val}.  Any previous mapping is 
1180 superseded.
1181
1182 \begin{verbatim}
1183 removeEnvVar :: String -> IO ()
1184 \end{verbatim}
1185
1186 \tr{removeEnvVar var} removes any value associated with variable \tr{var} 
1187 in the current environment.  Deleting a variable for which there is no mapping
1188 does not generate an error.
1189
1190 \begin{verbatim}
1191 nullSignal :: Signal
1192 nullSignal = 0
1193
1194 backgroundRead, sigTTIN        :: Signal
1195 backgroundWrite, sigTTOU       :: Signal
1196 continueProcess, sigCONT       :: Signal
1197 floatingPointException, sigFPE :: Signal
1198 illegalInstruction, sigILL     :: Signal
1199 internalAbort, sigABRT         :: Signal
1200 keyboardSignal, sigINT         :: Signal
1201 keyboardStop, sigTSTP          :: Signal
1202 keyboardTermination, sigQUIT   :: Signal
1203 killProcess, sigKILL           :: Signal
1204 lostConnection, sigHUP         :: Signal
1205 openEndedPipe, sigPIPE         :: Signal
1206 processStatusChanged, sigCHLD  :: Signal
1207 realTimeAlarm, sigALRM         :: Signal
1208 segmentationViolation, sigSEGV :: Signal
1209 softwareStop, sigSTOP          :: Signal
1210 softwareTermination, sigTERM   :: Signal
1211 userDefinedSignal1, sigUSR1    :: Signal
1212 userDefinedSignal2, sigUSR2    :: Signal
1213
1214 signalProcess :: Signal -> ProcessID -> IO ()
1215 \end{verbatim}
1216
1217 \tr{signalProcess int pid} calls \tr{kill} to signal 
1218 process \tr{pid} with interrupt signal \tr{int}.
1219
1220 \begin{verbatim}
1221 raiseSignal :: Signal -> IO ()
1222 \end{verbatim}
1223
1224 \tr{raiseSignal int} calls \tr{kill} to signal the current process
1225 with interrupt signal \tr{int}. 
1226
1227 \begin{verbatim}
1228 signalProcessGroup :: Signal -> ProcessGroupID -> IO ()
1229 \end{verbatim}
1230
1231 \tr{signalProcessGroup int pgid} calls \tr{kill} to signal 
1232 all processes in group \tr{pgid} with interrupt signal \tr{int}.
1233
1234 \begin{verbatim}
1235 setStoppedChildFlag :: Bool -> IO Bool
1236 \end{verbatim}
1237
1238 \tr{setStoppedChildFlag bool} sets a flag which controls whether or
1239 not the \tr{NOCLDSTOP} option will be used the next time a signal
1240 handler is installed for \tr{SIGCHLD}.  If \tr{bool} is \tr{True} (the
1241 default), \tr{NOCLDSTOP} will not be used; otherwise it will be.  The
1242 operation never fails.
1243
1244 \begin{verbatim}
1245 queryStoppedChildFlag :: IO Bool
1246 \end{verbatim}
1247
1248 \tr{queryStoppedChildFlag} queries the flag which
1249 controls whether or not the \tr{NOCLDSTOP} option will be used
1250 the next time a signal handler is installed for \tr{SIGCHLD}.
1251 If \tr{NOCLDSTOP} will be used, it returns \tr{False}; 
1252 otherwise (the default) it returns \tr{True}.  
1253 The operation never fails.
1254
1255 \begin{verbatim}
1256 emptySignalSet :: SignalSet
1257 fullSignalSet  :: SignalSet
1258 addSignal      :: Signal -> SignalSet -> SignalSet
1259 deleteSignal   :: Signal -> SignalSet -> SignalSet
1260 inSignalSet    :: Signal -> SignalSet -> Bool
1261
1262 installHandler :: Signal
1263                -> Handler 
1264                -> Maybe SignalSet       -- other signals to block
1265                -> IO Handler            -- old handler
1266 \end{verbatim}
1267
1268 \tr{installHandler int handler iset} calls \tr{sigaction} to install
1269 an interrupt handler for signal \tr{int}.  If \tr{handler} is
1270 \tr{Default}, \tr{SIG_DFL} is installed; if \tr{handler} is
1271 \tr{Ignore}, \tr{SIG_IGN} is installed; if \tr{handler} is
1272 \tr{Catch action}, a handler is installed which will invoke \tr{action} as a
1273 replacement for \tr{main}.  If \tr{iset} is \tr{Just s}, then the
1274 \tr{sa_mask} of the \tr{sigaction} structure is set to \tr{s};
1275 otherwise it is cleared.  The previously installed signal handler for
1276 \tr{int} is returned.
1277
1278 \begin{verbatim}
1279 getSignalMask :: IO SignalSet
1280 \end{verbatim}
1281
1282 \tr{getSignalMask} calls \tr{sigprocmask} to determine the
1283 set of interrupts which are currently being blocked.
1284
1285 \begin{verbatim}
1286 setSignalMask :: SignalSet -> IO SignalSet
1287 \end{verbatim}
1288
1289 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1290 \tr{SIG_SETMASK} to block all interrupts in \tr{mask}.  The
1291 previous set of blocked interrupts is returned.
1292
1293 \begin{verbatim}
1294 blockSignals :: SignalSet -> IO SignalSet
1295 \end{verbatim}
1296
1297 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1298 \tr{SIG_BLOCK} to add all interrupts in \tr{mask} to the
1299 set of blocked interrupts.  The previous set of blocked interrupts is returned.
1300
1301 \begin{verbatim}
1302 unBlockSignals :: SignalSet -> IO SignalSet
1303 \end{verbatim}
1304
1305 \tr{setSignalMask mask} calls \tr{sigprocmask} with
1306 \tr{SIG_UNBLOCK} to remove all interrupts in \tr{mask} from the
1307 set of blocked interrupts.  The previous set of blocked interrupts is returned.
1308
1309 \begin{verbatim}
1310 getPendingSignals :: IO SignalSet
1311 \end{verbatim}
1312
1313 \tr{getPendingSignals} calls \tr{sigpending} to obtain
1314 the set of interrupts which have been received but are currently blocked.
1315
1316 \begin{verbatim}
1317 awaitSignal :: Maybe SignalSet -> IO ()
1318 \end{verbatim}
1319
1320 \tr{awaitSignal iset} suspends execution until an interrupt is received.
1321 If \tr{iset} is \tr{Just s}, \tr{awaitSignal} calls 
1322 \tr{sigsuspend}, installing \tr{s} as the new signal mask before
1323 suspending execution; otherwise, it calls \tr{pause}.  If successful,
1324 \tr{awaitSignal} does not return.
1325
1326 \begin{verbatim}
1327 scheduleAlarm :: Int -> IO Int
1328 \end{verbatim}
1329
1330 \tr{scheduleAlarm i} calls \tr{alarm} to schedule a real time
1331 alarm at least \tr{i} seconds in the future.
1332
1333 \begin{verbatim}
1334 sleep :: Int -> IO ()
1335 \end{verbatim}
1336
1337 \tr{sleep i} calls \tr{sleep} to suspend execution of the
1338 program until at least \tr{i} seconds have elapsed or a signal is
1339 received.
1340
1341 \subsubsection[Process Environment]{Posix Process Environment}
1342 \index{Posix, process environment}
1343
1344 \begin{verbatim}
1345 getProcessID :: IO ProcessID
1346 \end{verbatim}
1347
1348 \tr{getProcessID} calls \tr{getpid} to obtain the \tr{ProcessID} for
1349 the current process.
1350
1351 \begin{verbatim}
1352 getParentProcessID :: IO ProcessID
1353 \end{verbatim}
1354
1355 \tr{getProcessID} calls \tr{getppid} to obtain the \tr{ProcessID} for
1356 the parent of the current process.
1357
1358 \begin{verbatim}
1359 getRealUserID :: IO UserID
1360 \end{verbatim}
1361
1362 \tr{getRealUserID} calls \tr{getuid} to obtain the real \tr{UserID}
1363 associated with the current process.
1364
1365 \begin{verbatim}
1366 getEffectiveUserID :: IO UserID
1367 \end{verbatim}
1368
1369 \tr{getRealUserID} calls \tr{geteuid} to obtain the effective
1370 \tr{UserID} associated with the current process.
1371
1372 \begin{verbatim}
1373 setUserID :: UserID -> IO ()
1374 \end{verbatim}
1375
1376 \tr{setUserID uid} calls \tr{setuid} to set the real, effective, and
1377 saved set-user-id associated with the current process to \tr{uid}.
1378
1379 \begin{verbatim}
1380 getLoginName :: IO String
1381 \end{verbatim}
1382
1383 \tr{getLoginName} calls \tr{getlogin} to obtain the login name
1384 associated with the current process.
1385
1386 \begin{verbatim}
1387 getRealGroupID :: IO GroupID
1388 \end{verbatim}
1389
1390 \tr{getRealGroupID} calls \tr{getgid} to obtain the real \tr{GroupID}
1391 associated with the current process.
1392
1393 \begin{verbatim}
1394 getEffectiveGroupID :: IO GroupID
1395 \end{verbatim}
1396
1397 \tr{getEffectiveGroupID} calls \tr{getegid} to obtain the effective
1398 \tr{GroupID} associated with the current process.
1399
1400 \begin{verbatim}
1401 setGroupID :: GroupID -> IO ()
1402 \end{verbatim}
1403
1404 \tr{setGroupID gid} calls \tr{setgid} to set the real, effective, and
1405 saved set-group-id associated with the current process to \tr{gid}.
1406
1407 \begin{verbatim}
1408 getGroups :: IO [GroupID]
1409 \end{verbatim}
1410
1411 \tr{getGroups} calls \tr{getgroups} to obtain the list of
1412 supplementary \tr{GroupID}s associated with the current process.
1413
1414 \begin{verbatim}
1415 getEffectiveUserName :: IO String
1416 \end{verbatim}
1417
1418 \tr{getEffectiveUserName} calls \tr{cuserid} to obtain a name
1419 associated with the effective \tr{UserID} of the process.
1420
1421 \begin{verbatim}
1422 getProcessGroupID :: IO ProcessGroupID
1423 \end{verbatim}
1424
1425 \tr{getProcessGroupID} calls \tr{getpgrp} to obtain the
1426 \tr{ProcessGroupID} for the current process.
1427
1428 \begin{verbatim}
1429 createProcessGroup :: ProcessID -> IO ProcessGroupID
1430 \end{verbatim}
1431
1432 \tr{createProcessGroup pid} calls \tr{setpgid} to make
1433 process \tr{pid} a new process group leader.
1434
1435 \begin{verbatim}
1436 joinProcessGroup :: ProcessGroupID -> IO ProcessGroupID
1437 \end{verbatim}
1438
1439 \tr{joinProcessGroup pgid} calls \tr{setpgid} to set the
1440 \tr{ProcessGroupID} of the current process to \tr{pgid}.
1441
1442 \begin{verbatim}
1443 setProcessGroupID :: ProcessID -> ProcessGroupID -> IO ()
1444 \end{verbatim}
1445
1446 \tr{setProcessGroupID pid pgid} calls \tr{setpgid} to set the
1447 \tr{ProcessGroupID} for process \tr{pid} to \tr{pgid}.
1448
1449 \begin{verbatim}
1450 createSession :: IO ProcessGroupID
1451 \end{verbatim}
1452
1453 \tr{createSession} calls \tr{setsid} to create a new session
1454 with the current process as session leader.
1455
1456 \begin{verbatim}
1457 systemName :: SystemID -> String
1458 nodeName :: SystemID -> String
1459 release :: SystemID -> String
1460 version :: SystemID -> String
1461 machine :: SystemID -> String
1462
1463 getSystemID :: IO SystemID
1464 \end{verbatim}
1465
1466 \tr{getSystemID} calls \tr{uname} to obtain information
1467 about the current operating system.
1468
1469 \begin{verbatim}
1470 > epochTime :: IO EpochTime
1471 \end{verbatim}
1472
1473 \tr{epochTime} calls \tr{time} to obtain the number of 
1474 seconds that have elapsed since the epoch (Jan 01 00:00:00 GMT 1970).
1475
1476 \begin{verbatim}
1477 elapsedTime     :: ProcessTimes -> ClockTick
1478 userTime        :: ProcessTimes -> ClockTick
1479 systemTime      :: ProcessTimes -> ClockTick
1480 childUserTime   :: ProcessTimes -> ClockTick
1481 childSystemTime :: ProcessTimes -> ClockTick
1482
1483 getProcessTimes :: IO ProcessTimes
1484 \end{verbatim}
1485
1486 \tr{getProcessTimes} calls \tr{times} to obtain time-accounting
1487 information for the current process and its children.
1488
1489 \begin{verbatim}
1490 getControllingTerminalName :: IO FilePath
1491 \end{verbatim}
1492
1493 \tr{getControllingTerminalName} calls \tr{ctermid} to obtain
1494 a name associated with the controlling terminal for the process.  If a
1495 controlling terminal exists,
1496 \tr{getControllingTerminalName} returns the name of the
1497 controlling terminal.
1498
1499 The operation may fail with:
1500
1501 \begin{itemize}
1502 \item[\tr{NoSuchThing}]
1503 There is no controlling terminal, or its name cannot be determined.
1504 \item[\tr{SystemError}]
1505 Various other causes.
1506 \end{itemize}
1507
1508 \begin{verbatim}
1509 getTerminalName :: Fd -> IO FilePath
1510 \end{verbatim}
1511
1512 \tr{getTerminalName fd} calls \tr{ttyname} to obtain a name associated
1513 with the terminal for \tr{Fd} \tr{fd}. If \tr{fd} is associated
1514 with a terminal, \tr{getTerminalName} returns the name of the
1515 terminal.
1516
1517 The operation may fail with:
1518
1519 \begin{itemize}
1520 \item[\tr{InappropriateType}]
1521 The channel is not associated with a terminal.
1522 \item[\tr{NoSuchThing}]
1523 The channel is associated with a terminal, but it has no name.
1524 \item[\tr{SystemError}]
1525 Various other causes.
1526 \end{itemize}
1527
1528 \begin{verbatim}
1529 queryTerminal :: Fd -> IO Bool
1530 \end{verbatim}
1531
1532 \tr{queryTerminal fd} calls \tr{isatty} to determine whether or
1533 not \tr{Fd} \tr{fd} is associated with a terminal.
1534
1535 \begin{verbatim}
1536 getSysVar :: SysVar -> IO Limit
1537 \end{verbatim}
1538
1539 \tr{getSysVar var} calls \tr{sysconf} to obtain the
1540 dynamic value of the requested configurable system limit or option.
1541 For defined system limits, \tr{getSysVar} returns the associated
1542 value.  For defined system options, the result of \tr{getSysVar}
1543 is undefined, but not failure.
1544
1545 The operation may fail with:
1546
1547 \begin{itemize}
1548 \item[\tr{NoSuchThing}]
1549 The requested system limit or option is undefined.
1550 \end{itemize}
1551
1552 \subsubsection[Files and Directories]{Posix operations on files and directories}
1553 \index{Posix, files and directories}
1554
1555 \begin{verbatim}
1556 openDirStream :: FilePath -> IO DirStream
1557 \end{verbatim}
1558
1559 \tr{openDirStream dir} calls \tr{opendir} to obtain a
1560 directory stream for \tr{dir}.
1561
1562 \begin{verbatim}
1563 readDirStream :: DirStream -> IO String
1564 \end{verbatim}
1565
1566 \tr{readDirStream dp} calls \tr{readdir} to obtain the
1567 next directory entry (\tr{struct dirent}) for the open directory
1568 stream \tr{dp}, and returns the \tr{d_name} member of that
1569 structure.
1570
1571 The operation may fail with:
1572
1573 \begin{itemize}
1574 \item[\tr{EOF}]
1575 End of file has been reached.
1576 \item[\tr{SystemError}]
1577 Various other causes.
1578 \end{itemize}
1579
1580 \begin{verbatim}
1581 rewindDirStream :: DirStream -> IO ()
1582 \end{verbatim}
1583
1584 \tr{rewindDirStream dp} calls \tr{rewinddir} to reposition
1585 the directory stream \tr{dp} at the beginning of the directory.
1586
1587 \begin{verbatim}
1588 closeDirStream :: DirStream -> IO ()
1589 \end{verbatim}
1590
1591 \tr{closeDirStream dp} calls \tr{closedir} to close
1592 the directory stream \tr{dp}.
1593
1594 \begin{verbatim}
1595 getWorkingDirectory :: IO FilePath
1596 \end{verbatim}
1597
1598 \tr{getWorkingDirectory} calls \tr{getcwd} to obtain the name
1599 of the current working directory.
1600
1601 \begin{verbatim}
1602 changeWorkingDirectory :: FilePath -> IO ()
1603 \end{verbatim}
1604
1605 \tr{changeWorkingDirectory dir} calls \tr{chdir} to change
1606 the current working directory to \tr{dir}.
1607
1608 \begin{verbatim}
1609 nullFileMode       :: FileMode       -- ---------
1610 ownerReadMode      :: FileMode       -- r--------
1611 ownerWriteMode     :: FileMode       -- -w-------
1612 ownerExecuteMode   :: FileMode       -- --x------
1613 groupReadMode      :: FileMode       -- ---r-----
1614 groupWriteMode     :: FileMode       -- ----w----
1615 groupExecuteMode   :: FileMode       -- -----x---
1616 otherReadMode      :: FileMode       -- ------r--
1617 otherWriteMode     :: FileMode       -- -------w-
1618 otherExecuteMode   :: FileMode       -- --------x
1619 setUserIDMode      :: FileMode       -- --S------
1620 setGroupIDMode     :: FileMode       -- -----S---
1621                                
1622 stdFileMode        :: FileMode       -- rw-rw-rw-
1623                                
1624 ownerModes         :: FileMode       -- rwx------
1625 groupModes         :: FileMode       -- ---rwx---
1626 otherModes         :: FileMode       -- ------rwx
1627 accessModes        :: FileMode       -- rwxrwxrwx
1628
1629 unionFileModes     :: FileMode -> FileMode -> FileMode
1630 intersectFileModes :: FileMode -> FileMode -> FileMode
1631
1632 stdInput  :: Fd
1633 stdInput  = intToFd 0
1634
1635 stdOutput :: Fd
1636 stdOutput = intToFd 1
1637
1638 stdError  :: Fd
1639 stdError  = intToFd 2
1640
1641 data OpenFileFlags =
1642  OpenFileFlags {
1643     append    :: Bool,
1644     exclusive :: Bool,
1645     noctty    :: Bool,
1646     nonBlock  :: Bool,
1647     trunc     :: Bool
1648  }
1649
1650 openFd :: FilePath
1651        -> OpenMode
1652        -> Maybe FileMode  -- Just x => O_CREAT, Nothing => must exist
1653        -> OpenFileFlags
1654        -> IO Fd
1655 \end{verbatim}
1656
1657 \tr{openFd path acc mode (OpenFileFlags app excl noctty nonblock trunc)} calls
1658 \tr{open} to obtain a \tr{Fd} for the file \tr{path} with access
1659 mode \tr{acc}.  If \tr{mode} is \tr{Just m}, the \tr{O_CREAT} flag is
1660 set and the file's permissions will be based on \tr{m} if it does not
1661 already exist; otherwise, the \tr{O_CREAT} flag is not set.  The
1662 arguments \tr{app}, \tr{excl}, \tr{noctty}, \tr{nonblock}, and
1663 \tr{trunc} control whether or not the flags \tr{O_APPEND},
1664 \tr{O_EXCL}, \tr{O_NOCTTY}, \tr{O_NONBLOCK}, and \tr{O_TRUNC} are set,
1665 respectively.
1666
1667 \begin{verbatim}
1668 createFile :: FilePath -> FileMode -> IO Fd
1669 \end{verbatim}
1670
1671 \tr{createFile path mode} calls \tr{creat} to obtain a \tr{Fd}
1672 for file \tr{path}, which will be created with permissions based on
1673 \tr{mode} if it does not already exist.
1674
1675 \begin{verbatim}
1676 setFileCreationMask :: FileMode -> IO FileMode
1677 \end{verbatim}
1678
1679 \tr{setFileCreationMask mode} calls \tr{umask} to set
1680 the process's file creation mask to \tr{mode}.  The previous file
1681 creation mask is returned.
1682
1683 \begin{verbatim}
1684 createLink :: FilePath -> FilePath -> IO ()
1685 \end{verbatim}
1686
1687 \tr{createLink old new} calls \tr{link} to create a 
1688 new path, \tr{new}, linked to an existing file, \tr{old}.
1689 \begin{verbatim}
1690 createDirectory :: FilePath -> FileMode -> IO ()
1691 \end{verbatim}
1692
1693 \tr{createDirectory dir mode} calls \tr{mkdir} to 
1694 create a new directory, \tr{dir}, with permissions based on
1695 \tr{mode}.
1696
1697 \begin{verbatim}
1698 createNamedPipe :: FilePath -> FileMode -> IO ()
1699 \end{verbatim}
1700
1701 \tr{createNamedPipe fifo mode} calls \tr{mkfifo} to 
1702 create a new named pipe, \tr{fifo}, with permissions based on
1703 \tr{mode}.
1704
1705 \begin{verbatim}
1706 removeLink :: FilePath -> IO ()
1707 \end{verbatim}
1708
1709 \tr{removeLink path} calls \tr{unlink} to remove the link
1710 named \tr{path}.
1711
1712 \begin{verbatim}
1713 removeDirectory :: FilePath -> IO ()
1714 \end{verbatim}
1715
1716 \tr{removeDirectory dir} calls \tr{rmdir} to remove the 
1717 directory named \tr{dir}.
1718
1719 \begin{verbatim}
1720 rename :: FilePath -> FilePath -> IO ()
1721 \end{verbatim}
1722
1723 \tr{rename old new} calls \tr{rename} to rename a 
1724 file or directory from \tr{old} to \tr{new}.
1725
1726 \begin{verbatim}
1727 fileMode          :: FileStatus -> FileMode
1728                    
1729 fileID            :: FileStatus -> FileID
1730 deviceID          :: FileStatus -> DeviceID
1731                    
1732 linkCount         :: FileStatus -> LinkCount
1733                    
1734 fileOwner         :: FileStatus -> UserID
1735 fileGroup         :: FileStatus -> GroupID
1736 fileSize          :: FileStatus -> FileOffset
1737
1738 accessTime        :: FileStatus -> EpochTime
1739 modificationTime  :: FileStatus -> EpochTime
1740 statusChangeTime  :: FileStatus -> EpochTime
1741
1742 isDirectory       :: FileStatus -> Bool
1743 isCharacterDevice :: FileStatus -> Bool
1744 isBlockDevice     :: FileStatus -> Bool
1745 isRegularFile     :: FileStatus -> Bool
1746 isNamedPipe       :: FileStatus -> Bool
1747
1748 getFileStatus     :: FilePath -> IO FileStatus
1749 \end{verbatim}
1750
1751 \tr{getFileStatus path} calls \tr{stat} to get the
1752 \tr{FileStatus} information for the file \tr{path}.
1753
1754 \begin{verbatim}
1755 getFdStatus :: Fd -> IO FileStatus
1756 \end{verbatim}
1757
1758 \tr{getFdStatus fd} calls \tr{fstat} to get the
1759 \tr{FileStatus} information for the file associated with
1760 \tr{Fd} \tr{fd}.
1761
1762 \begin{verbatim}
1763 queryAccess :: FilePath -> Bool -> Bool -> Bool -> IO Bool
1764 \end{verbatim}
1765
1766 \tr{queryAccess path r w x} calls \tr{access} to test the access
1767 permissions for file \tr{path}.  The three arguments, \tr{r}, \tr{w},
1768 and \tr{x} control whether or not \tr{access} is called with
1769 \tr{R_OK}, \tr{W_OK}, and \tr{X_OK} respectively.
1770
1771 \begin{verbatim}
1772 queryFile :: FilePath -> IO Bool
1773 \end{verbatim}
1774
1775 \tr{queryFile path} calls \tr{access} with \tr{F_OK} to test for the
1776 existence for file \tr{path}.
1777
1778 \begin{verbatim}
1779 setFileMode :: FilePath -> FileMode -> IO ()
1780 \end{verbatim}
1781
1782 \tr{setFileMode path mode} calls \tr{chmod} to set the
1783 permission bits associated with file \tr{path} to \tr{mode}.
1784
1785 \begin{verbatim}
1786 setOwnerAndGroup :: FilePath -> UserID -> GroupID -> IO ()
1787 \end{verbatim}
1788
1789 \tr{setOwnerAndGroup path uid gid} calls \tr{chown} to
1790 set the \tr{UserID} and \tr{GroupID} associated with file
1791 \tr{path} to \tr{uid} and \tr{gid}, respectively.
1792
1793 \begin{verbatim}
1794 setFileTimes :: FilePath -> EpochTime -> EpochTime -> IO ()
1795 \end{verbatim}
1796
1797 \tr{setFileTimes path atime mtime} calls \tr{utime} to
1798 set the access and modification times associated with file
1799 \tr{path} to \tr{atime} and \tr{mtime}, respectively.
1800
1801 \begin{verbatim}
1802 touchFile :: FilePath -> IO ()
1803 \end{verbatim}
1804
1805 \tr{touchFile path} calls \tr{utime} to
1806 set the access and modification times associated with file
1807 \tr{path} to the current time.
1808
1809 \begin{verbatim}
1810 getPathVar :: PathVar -> FilePath -> IO Limit
1811 \end{verbatim}
1812
1813 \tr{getPathVar var path} calls \tr{pathconf} to obtain the
1814 dynamic value of the requested configurable file limit or option associated
1815 with file or directory \tr{path}.  For
1816 defined file limits, \tr{getPathVar} returns the associated
1817 value.  For defined file options, the result of \tr{getPathVar}
1818 is undefined, but not failure.
1819 The operation may fail with:
1820 \begin{itemize}
1821 \item[\tr{NoSuchThing}]
1822 The requested file limit or option is undefined.
1823 \item[\tr{SystemError}]
1824 Various other causes.
1825 \end{itemize}
1826
1827
1828 \begin{verbatim}
1829 getFdVar :: PathVar -> Fd -> IO Limit
1830 \end{verbatim}
1831
1832 \tr{getFdVar var fd} calls \tr{fpathconf} to obtain the
1833 dynamic value of the requested configurable file limit or option associated
1834 with the file or directory attached to the open channel \tr{fd}.
1835 For defined file limits, \tr{getFdVar} returns the associated
1836 value.  For defined file options, the result of \tr{getFdVar}
1837 is undefined, but not failure.
1838
1839 The operation may fail with:
1840
1841 \begin{itemize}
1842 \item[\tr{NoSuchThing}]
1843 The requested file limit or option is undefined.
1844 \item[\tr{SystemError}]
1845 Various other causes.
1846 \end{itemize}
1847
1848 \subsubsection[Inut Output]{Posix Input and Output Primitives}
1849 \index{Posix, input/output}
1850
1851 \begin{verbatim}
1852 createPipe :: IO (Fd, Fd)
1853 \end{verbatim}
1854
1855 \tr{createPipe} calls \tr{pipe} to create a pipe and returns a pair of
1856 \tr{Fd}s, the first for writing and the second for reading.
1857
1858 \begin{verbatim}
1859 dup :: Fd -> IO Fd
1860 \end{verbatim}
1861
1862 \tr{dup fd} calls \tr{dup} to duplicate \tr{Fd} \tr{fd} to
1863 another \tr{Fd}.
1864
1865 \begin{verbatim}
1866 dupTo :: Fd -> Fd -> IO ()
1867 \end{verbatim}
1868
1869 \tr{dupTo src dst} calls \tr{dup2} to duplicate \tr{Fd}
1870 \tr{src} to \tr{Fd} \tr{dst}.
1871
1872 \begin{verbatim}
1873 fdClose :: Fd -> IO ()
1874 \end{verbatim}
1875
1876 \tr{fdClose fd} calls \tr{close} to close \tr{Fd} \tr{fd}.
1877
1878 \begin{verbatim}
1879 fdRead :: Fd -> ByteCount -> IO (String, ByteCount)
1880 \end{verbatim}
1881
1882 \tr{fdRead fd nbytes} calls \tr{read} to read at most \tr{nbytes}
1883 bytes from \tr{Fd} \tr{fd}, and returns the result as a string
1884 paired with the number of bytes actually read.
1885
1886 The operation may fail with:
1887
1888 \begin{itemize}
1889 \item[\tr{EOF}]
1890 End of file has been reached.
1891 \item[\tr{SystemError}]
1892 Various other causes.
1893 \end{itemize}
1894
1895 \begin{verbatim}
1896 fdWrite :: Fd -> String -> IO ByteCount
1897 \end{verbatim}
1898
1899 \tr{fdWrite fd s} calls \tr{write} to write
1900 the string \tr{s} to \tr{Fd} \tr{fd} as a
1901 contiguous sequence of bytes.  It returns the number of bytes successfully
1902 written.
1903
1904 \begin{verbatim}
1905 queryFdOption :: FdOption -> Fd -> IO Bool
1906 \end{verbatim}
1907
1908 \tr{getFdOption opt fd} calls \tr{fcntl} to determine whether or
1909 not the flag associated with \tr{FdOption} \tr{opt} is set for
1910 \tr{Fd} \tr{fd}.
1911
1912 \begin{verbatim}
1913 setFdOption :: Fd -> FdOption -> Bool -> IO ()
1914 \end{verbatim}
1915
1916 \tr{setFdOption fd opt val} calls \tr{fcntl} to set the flag
1917 associated with \tr{FdOption} \tr{opt} on \tr{Fd} \tr{fd} to
1918 \tr{val}.
1919
1920 \begin{verbatim}
1921 getLock :: Fd -> FileLock -> IO (Maybe (ProcessID, FileLock))
1922 \end{verbatim}
1923
1924 \tr{getLock fd lock} calls \tr{fcntl} to get the first \tr{FileLock}
1925 for \tr{Fd} \tr{fd} which blocks the \tr{FileLock} \tr{lock}.  If
1926 no such \tr{FileLock} exists, \tr{getLock} returns \tr{Nothing}.
1927 Otherwise, it returns \tr{Just (pid, block)}, where \tr{block} is the
1928 blocking \tr{FileLock} and \tr{pid} is the \tr{ProcessID} of the
1929 process holding the blocking \tr{FileLock}.
1930
1931
1932 \begin{verbatim}
1933 setLock :: Fd -> FileLock -> IO ()
1934 \end{verbatim}
1935
1936 \tr{setLock fd lock} calls \tr{fcntl} with \tr{F_SETLK} to set or
1937 clear a lock segment for \tr{Fd} \tr{fd} as indicated by the
1938 \tr{FileLock} \tr{lock}.  \tr{setLock} does not block, but fails with
1939 \tr{SystemError} if the request cannot be satisfied immediately.
1940
1941 \begin{verbatim}
1942 waitToSetLock :: Fd -> FileLock -> IO ()
1943 \end{verbatim}
1944
1945 \tr{waitToSetLock fd lock} calls \tr{fcntl} with \tr{F_SETLKW} to set
1946 or clear a lock segment for \tr{Fd} \tr{fd} as indicated by the
1947 \tr{FileLock} \tr{lock}. If the request cannot be satisfied
1948 immediately, \tr{waitToSetLock} blocks until the request can be
1949 satisfied.
1950
1951
1952 \begin{verbatim}
1953 fdSeek :: Fd -> SeekMode -> FileOffset -> IO FileOffset
1954 \end{verbatim}
1955
1956 \tr{fdSeek fd whence offset} calls \tr{lseek} to position the
1957 \tr{Fd} \tr{fd} at the given \tr{offset} from the starting location
1958 indicated by \tr{whence}.  It returns the resulting offset from the
1959 start of the file in bytes.
1960
1961 \subsubsection[Device Specific Functions]{Posix, Device- and Class-Specific Functions}
1962 \index{Posix, device and class-specific functions}
1963
1964 \begin{verbatim}
1965 terminalMode    :: TerminalMode -> TerminalAttributes -> Bool
1966 withMode        :: TerminalAttributes -> TerminalMode -> TerminalAttributes
1967 withoutMode     :: TerminalAttributes -> TerminalMode -> TerminalAttributes
1968
1969 bitsPerByte     :: TerminalAttributes -> Int
1970 withBits        :: TerminalAttributes -> Int -> TerminalAttributes
1971
1972 controlChar     :: TerminalAttributes -> ControlCharacter -> Maybe Char
1973 withCC          :: TerminalAttributes
1974                 -> (ControlCharacter, Char)
1975                 -> TerminalAttributes 
1976 withoutCC       :: TerminalAttributes 
1977                 -> ControlCharacter 
1978                 -> TerminalAttributes
1979                   
1980 inputTime       :: TerminalAttributes -> Int
1981 withTime        :: TerminalAttributes -> Int -> TerminalAttributes
1982                   
1983 minInput        :: TerminalAttributes -> Int
1984 withMinInput    :: TerminalAttributes -> Int -> TerminalAttributes
1985                   
1986 inputSpeed      :: TerminalAttributes -> BaudRate
1987 withInputSpeed  :: TerminalAttributes -> BaudRate -> TerminalAttributes
1988                   
1989 outputSpeed     :: TerminalAttributes -> BaudRate
1990 withOutputSpeed :: TerminalAttributes -> BaudRate -> TerminalAttributes
1991
1992 getTerminalAttributes :: Fd -> IO TerminalAttributes
1993 \end{verbatim}
1994
1995 \tr{getTerminalAttributes fd} calls \tr{tcgetattr} to obtain
1996 the \tr{TerminalAttributes} associated with \tr{Fd} \tr{fd}.
1997
1998 \begin{verbatim}
1999 setTerminalAttributes :: Fd
2000                       -> TerminalAttributes 
2001                       -> TerminalState
2002                       -> IO ()
2003 \end{verbatim}
2004
2005 \tr{setTerminalAttributes fd attr ts} calls \tr{tcsetattr} to change
2006 the \tr{TerminalAttributes} associated with \tr{Fd} \tr{fd} to
2007 \tr{attr}, when the terminal is in the state indicated by \tr{ts}.
2008
2009 \begin{verbatim}
2010 sendBreak :: Fd -> Int -> IO ()
2011 \end{verbatim}
2012
2013 \tr{sendBreak fd duration} calls \tr{tcsendbreak} to transmit a
2014 continuous stream of zero-valued bits on \tr{Fd} \tr{fd} for the
2015 specified implementation-dependent \tr{duration}.
2016
2017 \begin{verbatim}
2018 drainOutput :: Fd -> IO ()
2019 \end{verbatim}
2020
2021 \tr{drainOutput fd} calls \tr{tcdrain} to block until all output
2022 written to \tr{Fd} \tr{fd} has been transmitted.
2023
2024 \begin{verbatim}
2025 discardData :: Fd -> QueueSelector -> IO ()
2026 \end{verbatim}
2027
2028 \tr{discardData fd queues} calls \tr{tcflush} to discard
2029 pending input and/or output for \tr{Fd} \tr{fd},
2030 as indicated by the \tr{QueueSelector} \tr{queues}.
2031
2032 \begin{verbatim}
2033 controlFlow :: Fd -> FlowAction -> IO ()
2034 \end{verbatim}
2035
2036 \tr{controlFlow fd action} calls \tr{tcflow} to control the 
2037 flow of data on \tr{Fd} \tr{fd}, as indicated by
2038 \tr{action}.
2039
2040 \begin{verbatim}
2041 getTerminalProcessGroupID :: Fd -> IO ProcessGroupID
2042 \end{verbatim}
2043
2044 \tr{getTerminalProcessGroupID fd} calls \tr{tcgetpgrp} to
2045 obtain the \tr{ProcessGroupID} of the foreground process group 
2046 associated with the terminal attached to \tr{Fd} \tr{fd}.
2047
2048 \begin{verbatim}
2049 setTerminalProcessGroupID :: Fd -> ProcessGroupID -> IO ()
2050 \end{verbatim}
2051
2052 \tr{setTerminalProcessGroupID fd pgid} calls \tr{tcsetpgrp} to
2053 set the \tr{ProcessGroupID} of the foreground process group 
2054 associated with the terminal attached to \tr{Fd} 
2055 \tr{fd} to \tr{pgid}.
2056
2057 \subsubsection[System Database]{Posix System Databases}
2058 \index{Posix, system databases}
2059
2060 \begin{verbatim}
2061 groupName    :: GroupEntry -> String
2062 groupID      :: GroupEntry -> GroupID
2063 groupMembers :: GroupEntry -> [String]
2064
2065 getGroupEntryForID :: GroupID -> IO GroupEntry
2066 \end{verbatim}
2067
2068 \tr{getGroupEntryForID gid} calls \tr{getgrgid} to obtain
2069 the \tr{GroupEntry} information associated with \tr{GroupID}
2070 \tr{gid}.
2071
2072 The operation may fail with:
2073
2074 \begin{itemize}
2075 \item[\tr{NoSuchThing}]
2076 There is no group entry for the GroupID.
2077 \end{itemize}
2078
2079 \begin{verbatim}
2080 getGroupEntryForName :: String -> IO GroupEntry
2081 \end{verbatim}
2082
2083 \tr{getGroupEntryForName name} calls \tr{getgrnam} to obtain
2084 the \tr{GroupEntry} information associated with the group called
2085 \tr{name}.
2086
2087 The operation may fail with:
2088
2089 \begin{itemize}
2090 \item[\tr{NoSuchThing}]
2091 There is no group entry for the name.
2092 \end{itemize}
2093
2094 \begin{verbatim}
2095 userName      :: UserEntry -> String
2096 userID        :: UserEntry -> UserID
2097 userGroupID   :: UserEntry -> GroupID
2098 homeDirectory :: UserEntry -> String
2099 userShell     :: UserEntry -> String
2100
2101 getUserEntryForID :: UserID -> IO UserEntry
2102 \end{verbatim}
2103
2104 \tr{getUserEntryForID gid} calls \tr{getpwuid} to obtain
2105 the \tr{UserEntry} information associated with \tr{UserID}
2106 \tr{uid}.
2107 The operation may fail with:
2108
2109 \begin{itemize}
2110 \item[\tr{NoSuchThing}]
2111 There is no user entry for the UserID.
2112 \end{itemize}
2113
2114 \begin{verbatim}
2115 getUserEntryForName :: String -> IO UserEntry
2116 \end{verbatim}
2117
2118 \tr{getUserEntryForName name} calls \tr{getpwnam} to obtain
2119 the \tr{UserEntry} information associated with the user login
2120 \tr{name}.
2121
2122 The operation may fail with:
2123
2124 \begin{itemize}
2125 \item[\tr{NoSuchThing}]
2126 There is no user entry for the name.
2127 \end{itemize}
2128
2129 \subsubsection[Error reporting and handling]{POSIX Errors}
2130 \index{Posix, errors}
2131
2132 \begin{verbatim}
2133 getErrorCode :: IO ErrorCode
2134 \end{verbatim}
2135
2136 \tr{getErrorCode} returns the current value of the external
2137 variable \tr{errno}.  It never fails.
2138
2139 \begin{verbatim}
2140 setErrorCode :: ErrorCode -> IO ()
2141 \end{verbatim}
2142
2143 \tr{setErrorCode err} sets the external
2144 variable \tr{errno} to \tr{err}.  It never fails.
2145
2146 \begin{verbatim}
2147 noError :: ErrorCode
2148 noError = 0
2149
2150 argumentListTooLong, e2BIG              :: ErrorCode
2151 badFd, eBADF                            :: ErrorCode
2152 brokenPipe, ePIPE                       :: ErrorCode
2153 directoryNotEmpty, eNOTEMPTY            :: ErrorCode
2154 execFormatError, eNOEXEC                :: ErrorCode
2155 fileAlreadyExists, eEXIST               :: ErrorCode
2156 fileTooLarge, eFBIG                     :: ErrorCode
2157 filenameTooLong, eNAMETOOLONG           :: ErrorCode
2158 improperLink, eXDEV                     :: ErrorCode
2159 inappropriateIOControlOperation, eNOTTY :: ErrorCode
2160 inputOutputError, eIO                   :: ErrorCode
2161 interruptedOperation, eINTR             :: ErrorCode
2162 invalidArgument, eINVAL                 :: ErrorCode
2163 invalidSeek, eSPIPE                     :: ErrorCode
2164 isADirectory, eISDIR                    :: ErrorCode
2165 noChildProcess, eCHILD                  :: ErrorCode
2166 noLocksAvailable, eNOLCK                :: ErrorCode
2167 noSpaceLeftOnDevice, eNOSPC             :: ErrorCode
2168 noSuchOperationOnDevice, eNODEV         :: ErrorCode
2169 noSuchDeviceOrAddress, eNXIO            :: ErrorCode
2170 noSuchFileOrDirectory, eNOENT           :: ErrorCode
2171 noSuchProcess, eSRCH                    :: ErrorCode
2172 notADirectory, eNOTDIR                  :: ErrorCode
2173 notEnoughMemory, eNOMEM                 :: ErrorCode
2174 operationNotImplemented, eNOSYS         :: ErrorCode
2175 operationNotPermitted, ePERM            :: ErrorCode
2176 permissionDenied, eACCES                :: ErrorCode
2177 readOnlyFileSystem, eROFS               :: ErrorCode
2178 resourceBusy, eBUSY                     :: ErrorCode
2179 resourceDeadlockAvoided, eDEADLK        :: ErrorCode
2180 resourceTemporarilyUnavailable, eAGAIN  :: ErrorCode
2181 tooManyLinks, eMLINK                    :: ErrorCode
2182 tooManyOpenFiles, eMFILE                :: ErrorCode
2183 tooManyOpenFilesInSystem, eNFILE        :: ErrorCode
2184
2185 \end{verbatim}
2186
2187 %************************************************************************
2188 %*                                                                      *
2189 \subsection[HBC-library]{The HBC system library}
2190 \index{HBC system library}
2191 \index{system library, HBC}
2192 %*                                                                      *
2193 %************************************************************************
2194
2195 This documentation is stolen directly from the HBC distribution.  The
2196 modules that GHC does not support (because they require HBC-specific
2197 extensions) are omitted.
2198
2199 \begin{description}
2200 \item[\tr{Either}:]
2201 \index{Either module (HBC library)}%
2202 A binary sum data type:
2203 \begin{verbatim}
2204 data Either a b = Left a | Right b
2205 \end{verbatim}
2206 The constructor \tr{Left} is typically used for errors; it can be
2207 renamed to \tr{Wrong} on import.
2208
2209 \item[\tr{Maybe}:]
2210 \index{Maybe module (HBC library)}%
2211 A type for failure or success:
2212 \begin{verbatim}
2213 data Maybe a = Nothing | Just a
2214 thenM :: Maybe a -> (a -> Maybe b) -> Maybe b
2215     -- apply a function that may fail
2216 \end{verbatim}
2217
2218 \item[\tr{Option}:]
2219 \index{Option module (HBC library)}%
2220 An alias for \tr{Maybe}:
2221 \begin{verbatim}
2222 data Option a = None | Some a
2223 thenO :: Option a -> (a -> Option b) -> Option b
2224 \end{verbatim}
2225
2226 \item[\tr{ListUtil}:]
2227 \index{ListUtil module (HBC library)}%
2228 Various useful functions involving lists that are missing from the
2229 \tr{Prelude}:
2230 \begin{verbatim}
2231 assoc :: (Eq c) => (a -> b) -> b -> [(c, a)] -> c -> b
2232         -- assoc f d l k looks for k in the association list l, if it
2233         -- is found f is applied to the value, otherwise d is returned.
2234 concatMap :: (a -> [b]) -> [a] -> [b]
2235         -- flattening map (LML's concmap)
2236 unfoldr :: (a -> (b, a)) -> (a -> Bool) -> a -> [b]
2237         -- unfoldr f p x repeatedly applies f to x until (p x) holds.
2238         -- (f x) should give a list element and a new x.
2239 mapAccuml :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
2240         -- mapAccuml f s l maps f over l, but also threads the state s
2241         -- through (LML's mapstate).
2242 union :: (Eq a) => [a] -> [a] -> [a]
2243         -- union of two lists
2244 intersection :: (Eq a) => [a] -> [a] -> [a]
2245         -- intersection of two lists
2246 chopList :: ([a] -> (b, [a])) -> [a] -> [b]
2247         -- LMLs choplist
2248 assocDef :: (Eq a) => [(a, b)] -> b -> a -> b
2249         -- LMLs assocdef
2250 lookup :: (Eq a) => [(a, b)] -> a -> Option b
2251         -- lookup l k looks for the key k in the association list l
2252         -- and returns an optional value
2253 tails :: [a] -> [[a]]
2254         -- return all the tails of a list
2255 rept :: (Integral a) => a -> b -> [b]
2256         -- repeat a value a number of times
2257 groupEq :: (a->a->Bool) -> [a] -> [[a]]
2258         -- group list elements according to an equality predicate
2259 group :: (Eq a) => [a] -> [[a]]
2260         -- group according to} ==
2261 readListLazily :: (Text a) => String -> [a]
2262         -- read a list in a lazy fashion
2263 \end{verbatim}
2264
2265 \item[\tr{Pretty}:]
2266 \index{Pretty module (HBC library)}%
2267 John Hughes's pretty printing library.  
2268 \begin{verbatim}
2269 type Context = (Bool, Int, Int, Int)
2270 type IText = Context -> [String]
2271 text :: String -> IText                 -- just text
2272 (~.) :: IText -> IText -> IText         -- horizontal composition
2273 (^.) :: IText -> IText -> IText         -- vertical composition
2274 separate :: [IText] -> IText            -- separate by spaces
2275 nest :: Int -> IText -> IText           -- indent
2276 pretty :: Int -> Int -> IText -> String -- format it
2277 \end{verbatim}
2278
2279 \item[\tr{QSort}:]
2280 \index{QSort module (HBC library)}%
2281 A sort function using quicksort.
2282 \begin{verbatim}
2283 sortLe :: (a -> a -> Bool) -> [a] -> [a]
2284         -- sort le l  sorts l with le as less than predicate
2285 sort :: (Ord a) => [a] -> [a]
2286         -- sort l  sorts l using the Ord class
2287 \end{verbatim}
2288
2289 \item[\tr{Random}:]
2290 \index{Random module (HBC library)}%
2291 Random numbers.
2292 \begin{verbatim}
2293 randomInts :: Int -> Int -> [Int]
2294         -- given two seeds gives a list of random Int
2295 randomDoubles :: Int -> Int -> [Double]
2296         -- random Double with uniform distribution in (0,1)
2297 normalRandomDoubles :: Int -> Int -> [Double]
2298         -- random Double with normal distribution, mean 0, variance 1
2299 \end{verbatim}
2300
2301 \item[\tr{Trace}:]
2302 Simple tracing.  (Note: This comes with GHC anyway.)
2303 \begin{verbatim}
2304 trace :: String -> a -> a       -- trace x y  prints x and returns y
2305 \end{verbatim}
2306
2307 \item[\tr{Miranda}:]
2308 \index{Miranda module (HBC library)}%
2309 Functions found in the Miranda library.
2310 (Note: Miranda is a registered trade mark of Research Software Ltd.)
2311
2312 \item[\tr{Word}:]
2313 \index{Word module (HBC library)}
2314 Bit manipulation.  (GHC doesn't implement absolutely all of this.
2315 And don't count on @Word@ being 32 bits on a Alpha...)
2316 \begin{verbatim}
2317 class Bits a where
2318     bitAnd :: a -> a -> a       -- bitwise and
2319     bitOr :: a -> a -> a        -- bitwise or
2320     bitXor :: a -> a -> a       -- bitwise xor
2321     bitCompl :: a -> a          -- bitwise negation
2322     bitRsh :: a -> Int -> a     -- bitwise right shift
2323     bitLsh :: a -> Int -> a     -- bitwise left shift
2324     bitSwap :: a -> a           -- swap word halves
2325     bit0 :: a                   -- word with least significant bit set
2326     bitSize :: a -> Int         -- number of bits in a word
2327
2328 data Byte                       -- 8  bit quantity
2329 data Short                      -- 16 bit quantity
2330 data Word                       -- 32 bit quantity
2331
2332 instance Bits Byte, Bits Short, Bits Word
2333 instance Eq Byte, Eq Short, Eq Word
2334 instance Ord Byte, Ord Short, Ord Word
2335 instance Text Byte, Text Short, Text Word
2336 instance Num Byte, Num Short, Num Word
2337 wordToShorts :: Word -> [Short]   -- convert a Word to two Short
2338 wordToBytes :: Word -> [Byte]     -- convert a Word to four Byte
2339 bytesToString :: [Byte] -> String -- convert a list of Byte to a String (bit by bit)
2340 wordToInt :: Word -> Int          -- convert a Word to Int
2341 shortToInt :: Short -> Int        -- convert a Short to Int
2342 byteToInt :: Byte -> Int          -- convert a Byte to Int
2343 \end{verbatim}
2344
2345 \item[\tr{Time}:]
2346 \index{Time module (HBC library)}%
2347 Manipulate time values (a Double with seconds since 1970).
2348 \begin{verbatim}
2349 --               year mon  day  hour min  sec  dec-sec  weekday
2350 data Time = Time Int  Int  Int  Int  Int  Int  Double  Int
2351 dblToTime :: Double -> Time     -- convert a Double to a Time
2352 timeToDbl :: Time -> Double     -- convert a Time to a Double
2353 timeToString :: Time -> String  -- convert a Time to a readable String
2354 \end{verbatim}
2355
2356 \item[\tr{Hash}:]
2357 \index{Hash module (HBC library)}%
2358 Hashing functions.
2359 \begin{verbatim}
2360 class Hashable a where
2361     hash :: a -> Int                            -- hash a value, return an Int
2362 -- instances for all Prelude types
2363 hashToMax :: (Hashable a) => Int -> a -> Int    -- hash into interval [0..x-1]
2364 \end{verbatim}
2365
2366 \item[\tr{NameSupply}:]
2367 \index{NameSupply module (HBC library)}%
2368 Functions to generate unique names (Int).
2369 \begin{verbatim}
2370 type Name = Int
2371 initialNameSupply :: NameSupply
2372         -- The initial name supply (may be different every
2373         -- time the program is run.
2374 splitNameSupply :: NameSupply -> (NameSupply,NameSupply)
2375         -- split the namesupply into two
2376 getName :: NameSupply -> Name
2377         -- get the name associated with a name supply
2378 \end{verbatim}
2379
2380 \item[\tr{Parse}:]
2381 \index{Parse module (HBC library)}%
2382 Higher order functions to build parsers.  With a little care these
2383 combinators can be used to build efficient parsers with good error
2384 messages.
2385 \begin{verbatim}
2386 infixr 8 +.+ , ..+ , +.. 
2387 infix  6 `act` , >>> , `into` , .> 
2388 infixr 4 ||| , ||! , |!! 
2389 data ParseResult a b 
2390 type Parser a b = a -> Int -> ParseResult a b 
2391 (|||) :: Parser a b -> Parser a b -> Parser a b
2392         -- Alternative
2393 (||!) :: Parser a b -> Parser a b -> Parser a b
2394         -- Alternative, but with committed choice
2395 (|!!) :: Parser a b -> Parser a b -> Parser a b
2396         -- Alternative, but with committed choice
2397 (+.+) :: Parser a b -> Parser a c -> Parser a (b,c)
2398         -- Sequence
2399 (..+) :: Parser a b -> Parser a c -> Parser a c
2400         -- Sequence, throw away first part
2401 (+..) :: Parser a b -> Parser a c -> Parser a b
2402         -- Sequence, throw away second part
2403 act   :: Parser a b -> (b->c) -> Parser a c
2404         -- Action
2405 (>>>) :: Parser a (b,c) -> (b->c->d) -> Parser a d
2406         -- Action on two items
2407 (.>) :: Parser a b -> c -> Parse a c
2408         -- Action ignoring value
2409 into :: Parser a b -> (b -> Parser a c) -> Parser a c
2410         -- Use a produced value in a parser.
2411 succeed b :: Parser a b
2412         -- Always succeeds without consuming a token
2413 failP :: Parser a b
2414         -- Always fails.
2415 many :: Parser a b -> Parser a [b]
2416         -- Kleene star
2417 many1 :: Parser a b -> Parser a [b]
2418         -- Kleene plus
2419 count :: Parser a b -> Int -> Parser a [b]
2420         -- Parse an exact number of items
2421 sepBy1 :: Parser a b -> Parser a c -> Parser a [b]
2422         -- Non-empty sequence of items separated by something
2423 sepBy :: Parser a b -> Parser a c -> Parser a [b]
2424         -- Sequence of items separated by something
2425 lit :: (Eq a, Text a) => a -> Parser [a] a
2426         -- Recognise a literal token from a list of tokens
2427 litp :: String -> (a->Bool) -> Parser [a] a
2428         -- Recognise a token with a predicate.
2429         -- The string is a description for error messages.
2430 testp :: String -> (a -> Bool) -> (Parser b a) -> Parser b a
2431         -- Test a semantic value. 
2432 token :: (a -> Either String (b, a)) -> Parser a b
2433         -- General token recogniser.
2434 parse :: Parser a b -> a -> Either ([String], a) [(b, a)]
2435         -- Do a parse.  Return either error (possible tokens and rest
2436         -- of tokens) or all possible parses.
2437 sParse :: (Text a) => (Parser [a] b) -> [a] -> Either String b
2438         -- Simple parse.  Return error message or result.
2439 \end{verbatim}
2440
2441 %%%simpleLex :: String -> [String]              -- A simple (but useful) lexical analyzer
2442
2443 \item[\tr{Native}:]
2444 \index{Native module (HBC library)}%
2445 Functions to convert the primitive types \tr{Int}, \tr{Float}, and \tr{Double} to
2446 their native representation as a list of bytes (\tr{Char}).  If such a list
2447 is read/written to a file it will have the same format as when, e.g.,
2448 C read/writes the same kind of data.
2449 \begin{verbatim}
2450 type Bytes = [Char] -- A byte stream is just a list of characters
2451
2452 class Native a where 
2453     showBytes     :: a -> Bytes -> Bytes
2454         -- prepend the representation of an item the a byte stream
2455     listShowBytes :: [a] -> Bytes -> Bytes
2456         -- prepend the representation of a list of items to a stream
2457         -- (may be more efficient than repeating showBytes).
2458     readBytes     :: Bytes -> Maybe (a, Bytes)
2459         -- get an item from the stream and return the rest,
2460         -- or fail if the stream is to short.
2461     listReadBytes :: Int -> Bytes -> Maybe ([a], Bytes)
2462         -- read n items from a stream.
2463
2464 instance Native Int 
2465 instance Native Float 
2466 instance Native Double 
2467 instance (Native a, Native b) => Native (a,b)
2468         -- juxtaposition of the two items
2469 instance (Native a, Native b, Native c) => Native (a, b, c)
2470         -- juxtaposition of the three items
2471 instance (Native a) => Native [a]
2472         -- an item count in an Int followed by the items
2473
2474 shortIntToBytes :: Int -> Bytes -> Bytes
2475         -- Convert an Int to what corresponds to a short in C.
2476 bytesToShortInt :: Bytes -> Maybe (Int, Bytes)
2477         -- Get a short from a byte stream and convert to an Int.
2478
2479 showB :: (Native a) => a -> Bytes       -- Simple interface to showBytes.
2480 readB :: (Native a) => Bytes -> a       -- Simple interface to readBytes.
2481 \end{verbatim}
2482
2483 \item[\tr{Number}:]
2484 \index{Number module (HBC library)}%
2485 Simple numbers that belong to all numeric classes and behave like
2486 a naive user would expect (except that printing is still ugly).
2487 (NB: GHC does not provide a magic way to use \tr{Numbers} everywhere,
2488 but you should be able to do it with normal \tr{import}ing and
2489 \tr{default}ing.)
2490 \begin{verbatim}
2491 data Number                     -- The type itself.
2492 instance ...                    -- All reasonable instances.
2493 isInteger :: Number -> Bool     -- Test if a Number is an integer.
2494 \end{verbatim}
2495 \end{description}