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