[project @ 2004-12-14 13:31:44 by malcolm]
[ghc-base.git] / System / IO.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module      :  System.IO
5 -- Copyright   :  (c) The University of Glasgow 2001
6 -- License     :  BSD-style (see the file libraries/base/LICENSE)
7 -- 
8 -- Maintainer  :  libraries@haskell.org
9 -- Stability   :  stable
10 -- Portability :  portable
11 --
12 -- The standard IO library.
13 --
14 -----------------------------------------------------------------------------
15
16 module System.IO (
17     -- * The IO monad
18
19     IO,                        -- instance MonadFix
20     fixIO,                     -- :: (a -> IO a) -> IO a
21
22     -- * Files and handles
23
24     FilePath,                  -- :: String
25
26     Handle,             -- abstract, instance of: Eq, Show.
27
28     -- ** Standard handles
29
30     -- | Three handles are allocated during program initialisation,
31     -- and are initially open.
32
33     stdin, stdout, stderr,   -- :: Handle
34
35     -- * Opening and closing files
36
37     -- ** Opening files
38
39     openFile,                  -- :: FilePath -> IOMode -> IO Handle
40     IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
41
42     -- ** Closing files
43
44     hClose,                    -- :: Handle -> IO ()
45
46     -- ** Special cases
47
48     -- | These functions are also exported by the "Prelude".
49
50     readFile,                  -- :: FilePath -> IO String
51     writeFile,                 -- :: FilePath -> String -> IO ()
52     appendFile,                -- :: FilePath -> String -> IO ()
53
54     -- ** File locking
55
56     -- $locking
57
58     -- * Operations on handles
59
60     -- ** Determining the size of a file
61
62     hFileSize,                 -- :: Handle -> IO Integer
63
64     -- ** Detecting the end of input
65
66     hIsEOF,                    -- :: Handle -> IO Bool
67     isEOF,                     -- :: IO Bool
68
69     -- ** Buffering operations
70
71     BufferMode(NoBuffering,LineBuffering,BlockBuffering),
72     hSetBuffering,             -- :: Handle -> BufferMode -> IO ()
73     hGetBuffering,             -- :: Handle -> IO BufferMode
74     hFlush,                    -- :: Handle -> IO ()
75
76     -- ** Repositioning handles
77
78     hGetPosn,                  -- :: Handle -> IO HandlePosn
79     hSetPosn,                  -- :: HandlePosn -> IO ()
80     HandlePosn,                -- abstract, instance of: Eq, Show.
81
82     hSeek,                     -- :: Handle -> SeekMode -> Integer -> IO ()
83     SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
84 #if !defined(__NHC__)
85     hTell,                     -- :: Handle -> IO Integer
86 #endif
87
88     -- ** Handle properties
89
90     hIsOpen, hIsClosed,        -- :: Handle -> IO Bool
91     hIsReadable, hIsWritable,  -- :: Handle -> IO Bool
92     hIsSeekable,               -- :: Handle -> IO Bool
93
94     -- ** Terminal operations
95
96 #if !defined(__NHC__)
97     hIsTerminalDevice,          -- :: Handle -> IO Bool
98
99     hSetEcho,                   -- :: Handle -> Bool -> IO ()
100     hGetEcho,                   -- :: Handle -> IO Bool
101 #endif
102
103     -- ** Showing handle state
104
105 #ifdef __GLASGOW_HASKELL__
106     hShow,                      -- :: Handle -> IO String
107 #endif
108
109     -- * Text input and output
110
111     -- ** Text input
112
113     hWaitForInput,             -- :: Handle -> Int -> IO Bool
114     hReady,                    -- :: Handle -> IO Bool
115     hGetChar,                  -- :: Handle -> IO Char
116     hGetLine,                  -- :: Handle -> IO [Char]
117     hLookAhead,                -- :: Handle -> IO Char
118     hGetContents,              -- :: Handle -> IO [Char]
119
120     -- ** Text output
121
122     hPutChar,                  -- :: Handle -> Char -> IO ()
123     hPutStr,                   -- :: Handle -> [Char] -> IO ()
124     hPutStrLn,                 -- :: Handle -> [Char] -> IO ()
125     hPrint,                    -- :: Show a => Handle -> a -> IO ()
126
127     -- ** Special cases for standard input and output
128
129     -- | These functions are also exported by the "Prelude".
130
131     interact,                  -- :: (String -> String) -> IO ()
132     putChar,                   -- :: Char   -> IO ()
133     putStr,                    -- :: String -> IO () 
134     putStrLn,                  -- :: String -> IO ()
135     print,                     -- :: Show a => a -> IO ()
136     getChar,                   -- :: IO Char
137     getLine,                   -- :: IO String
138     getContents,               -- :: IO String
139     readIO,                    -- :: Read a => String -> IO a
140     readLn,                    -- :: Read a => IO a
141
142     -- * Binary input and output
143
144     openBinaryFile,            -- :: FilePath -> IOMode -> IO Handle
145     hSetBinaryMode,            -- :: Handle -> Bool -> IO ()
146 #if !defined(__NHC__)
147     hPutBuf,                   -- :: Handle -> Ptr a -> Int -> IO ()
148     hGetBuf,                   -- :: Handle -> Ptr a -> Int -> IO Int
149 #endif
150 #if !defined(__NHC__) && !defined(__HUGS__)
151     hPutBufNonBlocking,        -- :: Handle -> Ptr a -> Int -> IO Int
152     hGetBufNonBlocking,        -- :: Handle -> Ptr a -> Int -> IO Int
153 #endif
154
155     module System.IO.Error,
156   ) where
157
158 #ifdef __GLASGOW_HASKELL__
159 import GHC.Base
160 import GHC.IOBase       -- Together these four Prelude modules define
161 import GHC.Handle       -- all the stuff exported by IO for the GHC version
162 import GHC.IO
163 import GHC.ST           ( fixST )
164 import GHC.Exception
165 import GHC.Num
166 import GHC.Read
167 import GHC.Show
168 #endif
169
170 #ifdef __HUGS__
171 import Hugs.IO
172 import Hugs.IOExts
173 import Hugs.IORef
174 import Hugs.Prelude     ( throw, Exception(NonTermination) )
175 import System.IO.Unsafe ( unsafeInterleaveIO )
176 #endif
177
178 #ifdef __NHC__
179 import IO
180   ( Handle ()
181   , HandlePosn ()
182   , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
183   , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
184   , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
185   , stdin, stdout, stderr
186   , openFile                  -- :: FilePath -> IOMode -> IO Handle
187   , hClose                    -- :: Handle -> IO ()
188   , hFileSize                 -- :: Handle -> IO Integer
189   , hIsEOF                    -- :: Handle -> IO Bool
190   , isEOF                     -- :: IO Bool
191   , hSetBuffering             -- :: Handle -> BufferMode -> IO ()
192   , hGetBuffering             -- :: Handle -> IO BufferMode
193   , hFlush                    -- :: Handle -> IO ()
194   , hGetPosn                  -- :: Handle -> IO HandlePosn
195   , hSetPosn                  -- :: HandlePosn -> IO ()
196   , hSeek                     -- :: Handle -> SeekMode -> Integer -> IO ()
197   , hWaitForInput             -- :: Handle -> Int -> IO Bool
198   , hGetChar                  -- :: Handle -> IO Char
199   , hGetLine                  -- :: Handle -> IO [Char]
200   , hLookAhead                -- :: Handle -> IO Char
201   , hGetContents              -- :: Handle -> IO [Char]
202   , hPutChar                  -- :: Handle -> Char -> IO ()
203   , hPutStr                   -- :: Handle -> [Char] -> IO ()
204   , hPutStrLn                 -- :: Handle -> [Char] -> IO ()
205   , hPrint                    -- :: Handle -> [Char] -> IO ()
206   , hReady                    -- :: Handle -> [Char] -> IO ()
207   , hIsOpen, hIsClosed        -- :: Handle -> IO Bool
208   , hIsReadable, hIsWritable  -- :: Handle -> IO Bool
209   , hIsSeekable               -- :: Handle -> IO Bool
210
211   , IO ()
212   , FilePath                  -- :: String
213   )
214 import NHC.IOExtras (fixIO)
215 #endif
216
217 import System.IO.Error (
218     isAlreadyExistsError, isDoesNotExistError,  -- :: IOError -> Bool
219     isAlreadyInUseError, isFullError, 
220     isEOFError, isIllegalOperation, 
221     isPermissionError, isUserError, 
222  
223     ioeGetErrorString,         -- :: IOError -> String
224     ioeGetHandle,              -- :: IOError -> Maybe Handle
225     ioeGetFileName,            -- :: IOError -> Maybe FilePath
226  
227     try,                       -- :: IO a -> IO (Either IOError a)
228  
229     -- re-exports of Prelude names
230     IOError,
231     ioError,                   -- :: IOError -> IO a
232     userError,                 -- :: String  -> IOError
233     catch                      -- :: IO a    -> (IOError -> IO a) -> IO a
234   )
235
236 -- -----------------------------------------------------------------------------
237 -- Standard IO
238
239 #ifdef __GLASGOW_HASKELL__
240 -- | Write a character to the standard output device
241 -- (same as 'hPutChar' 'stdout').
242
243 putChar         :: Char -> IO ()
244 putChar c       =  hPutChar stdout c
245
246 -- | Write a string to the standard output device
247 -- (same as 'hPutStr' 'stdout').
248
249 putStr          :: String -> IO ()
250 putStr s        =  hPutStr stdout s
251
252 -- | The same as 'putStr', but adds a newline character.
253
254 putStrLn        :: String -> IO ()
255 putStrLn s      =  do putStr s
256                       putChar '\n'
257
258 -- | The 'print' function outputs a value of any printable type to the
259 -- standard output device.
260 -- Printable types are those that are instances of class 'Show'; 'print'
261 -- converts values to strings for output using the 'show' operation and
262 -- adds a newline.
263 --
264 -- For example, a program to print the first 20 integers and their
265 -- powers of 2 could be written as:
266 --
267 -- > main = print ([(n, 2^n) | n <- [0..19]])
268
269 print           :: Show a => a -> IO ()
270 print x         =  putStrLn (show x)
271
272 -- | Read a character from the standard input device
273 -- (same as 'hGetChar' 'stdin').
274
275 getChar         :: IO Char
276 getChar         =  hGetChar stdin
277
278 -- | Read a line from the standard input device
279 -- (same as 'hGetLine' 'stdin').
280
281 getLine         :: IO String
282 getLine         =  hGetLine stdin
283
284 -- | The 'getContents' operation returns all user input as a single string,
285 -- which is read lazily as it is needed
286 -- (same as 'hGetContents' 'stdin').
287
288 getContents     :: IO String
289 getContents     =  hGetContents stdin
290
291 -- | The 'interact' function takes a function of type @String->String@
292 -- as its argument.  The entire input from the standard input device is
293 -- passed to this function as its argument, and the resulting string is
294 -- output on the standard output device.
295
296 interact        ::  (String -> String) -> IO ()
297 interact f      =   do s <- getContents
298                        putStr (f s)
299
300 -- | The 'readFile' function reads a file and
301 -- returns the contents of the file as a string.
302 -- The file is read lazily, on demand, as with 'getContents'.
303
304 readFile        :: FilePath -> IO String
305 readFile name   =  openFile name ReadMode >>= hGetContents
306
307 -- | The computation 'writeFile' @file str@ function writes the string @str@,
308 -- to the file @file@.
309
310 writeFile       :: FilePath -> String -> IO ()
311 writeFile name str = do
312     hdl <- openFile name WriteMode
313     hPutStr hdl str
314     hClose hdl
315
316 -- | The computation 'appendFile' @file str@ function appends the string @str@,
317 -- to the file @file@.
318 --
319 -- Note that 'writeFile' and 'appendFile' write a literal string
320 -- to a file.  To write a value of any printable type, as with 'print',
321 -- use the 'show' function to convert the value to a string first.
322 --
323 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
324
325 appendFile      :: FilePath -> String -> IO ()
326 appendFile name str = do
327     hdl <- openFile name AppendMode
328     hPutStr hdl str
329     hClose hdl
330
331 -- | The 'readLn' function combines 'getLine' and 'readIO'.
332
333 readLn          :: Read a => IO a
334 readLn          =  do l <- getLine
335                       r <- readIO l
336                       return r
337
338 -- | The 'readIO' function is similar to 'read' except that it signals
339 -- parse failure to the 'IO' monad instead of terminating the program.
340
341 readIO          :: Read a => String -> IO a
342 readIO s        =  case (do { (x,t) <- reads s ;
343                               ("","") <- lex t ;
344                               return x }) of
345                         [x]    -> return x
346                         []     -> ioError (userError "Prelude.readIO: no parse")
347                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
348 #endif  /* __GLASGOW_HASKELL__ */
349
350 #ifndef __NHC__
351 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
352 -- available for input from handle @hdl@.
353 -- 
354 -- This operation may fail with:
355 --
356 --  * 'isEOFError' if the end of file has been reached.
357
358 hReady          :: Handle -> IO Bool
359 hReady h        =  hWaitForInput h 0
360
361 -- | The same as 'hPutStr', but adds a newline character.
362
363 hPutStrLn       :: Handle -> String -> IO ()
364 hPutStrLn hndl str = do
365  hPutStr  hndl str
366  hPutChar hndl '\n'
367
368 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
369 -- given by the 'shows' function to the file or channel managed by @hdl@
370 -- and appends a newline.
371 --
372 -- This operation may fail with:
373 --
374 --  * 'isFullError' if the device is full; or
375 --
376 --  * 'isPermissionError' if another system resource limit would be exceeded.
377
378 hPrint          :: Show a => Handle -> a -> IO ()
379 hPrint hdl      =  hPutStrLn hdl . show
380 #endif /* !__NHC__ */
381
382 -- ---------------------------------------------------------------------------
383 -- fixIO
384
385 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
386 fixIO :: (a -> IO a) -> IO a
387 fixIO k = do
388     ref <- newIORef (throw NonTermination)
389     ans <- unsafeInterleaveIO (readIORef ref)
390     result <- k ans
391     writeIORef ref result
392     return result
393
394 -- NOTE: we do our own explicit black holing here, because GHC's lazy
395 -- blackholing isn't enough.  In an infinite loop, GHC may run the IO
396 -- computation a few times before it notices the loop, which is wrong.
397 #endif
398
399 #if defined(__NHC__)
400 -- Assume a unix platform, where text and binary I/O are identical.
401 openBinaryFile = openFile
402 hSetBinaryMode _ _ = return ()
403 #endif
404
405 -- $locking
406 -- Implementations should enforce as far as possible, at least locally to the
407 -- Haskell process, multiple-reader single-writer locking on files.
408 -- That is, /there may either be many handles on the same file which manage
409 -- input, or just one handle on the file which manages output/.  If any
410 -- open or semi-closed handle is managing a file for output, no new
411 -- handle can be allocated for that file.  If any open or semi-closed
412 -- handle is managing a file for input, new handles can only be allocated
413 -- if they do not manage output.  Whether two files are the same is
414 -- implementation-dependent, but they should normally be the same if they
415 -- have the same absolute path name and neither has been renamed, for
416 -- example.
417 --
418 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
419 -- the file until the entire contents of the file have been consumed.
420 -- It follows that an attempt to write to a file (using 'writeFile', for
421 -- example) that was earlier opened by 'readFile' will usually result in
422 -- failure with 'isAlreadyInUseError'.