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