Rewrite of the IO library, including Unicode support
[ghc-base.git] / System / IO.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
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     withFile,
40     openFile,                  -- :: FilePath -> IOMode -> IO Handle
41     IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
42
43     -- ** Closing files
44
45     hClose,                    -- :: Handle -> IO ()
46
47     -- ** Special cases
48
49     -- | These functions are also exported by the "Prelude".
50
51     readFile,                  -- :: FilePath -> IO String
52     writeFile,                 -- :: FilePath -> String -> IO ()
53     appendFile,                -- :: FilePath -> String -> IO ()
54
55     -- ** File locking
56
57     -- $locking
58
59     -- * Operations on handles
60
61     -- ** Determining and changing the size of a file
62
63     hFileSize,                 -- :: Handle -> IO Integer
64 #ifdef __GLASGOW_HASKELL__
65     hSetFileSize,              -- :: Handle -> Integer -> IO ()
66 #endif
67
68     -- ** Detecting the end of input
69
70     hIsEOF,                    -- :: Handle -> IO Bool
71     isEOF,                     -- :: IO Bool
72
73     -- ** Buffering operations
74
75     BufferMode(NoBuffering,LineBuffering,BlockBuffering),
76     hSetBuffering,             -- :: Handle -> BufferMode -> IO ()
77     hGetBuffering,             -- :: Handle -> IO BufferMode
78     hFlush,                    -- :: Handle -> IO ()
79
80     -- ** Repositioning handles
81
82     hGetPosn,                  -- :: Handle -> IO HandlePosn
83     hSetPosn,                  -- :: HandlePosn -> IO ()
84     HandlePosn,                -- abstract, instance of: Eq, Show.
85
86     hSeek,                     -- :: Handle -> SeekMode -> Integer -> IO ()
87     SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
88 #if !defined(__NHC__)
89     hTell,                     -- :: Handle -> IO Integer
90 #endif
91
92     -- ** Handle properties
93
94     hIsOpen, hIsClosed,        -- :: Handle -> IO Bool
95     hIsReadable, hIsWritable,  -- :: Handle -> IO Bool
96     hIsSeekable,               -- :: Handle -> IO Bool
97
98     -- ** Terminal operations (not portable: GHC\/Hugs only)
99
100 #if !defined(__NHC__)
101     hIsTerminalDevice,          -- :: Handle -> IO Bool
102
103     hSetEcho,                   -- :: Handle -> Bool -> IO ()
104     hGetEcho,                   -- :: Handle -> IO Bool
105 #endif
106
107     -- ** Showing handle state (not portable: GHC only)
108
109 #ifdef __GLASGOW_HASKELL__
110     hShow,                      -- :: Handle -> IO String
111 #endif
112
113     -- * Text input and output
114
115     -- ** Text input
116
117     hWaitForInput,             -- :: Handle -> Int -> IO Bool
118     hReady,                    -- :: Handle -> IO Bool
119     hGetChar,                  -- :: Handle -> IO Char
120     hGetLine,                  -- :: Handle -> IO [Char]
121     hLookAhead,                -- :: Handle -> IO Char
122     hGetContents,              -- :: Handle -> IO [Char]
123
124     -- ** Text output
125
126     hPutChar,                  -- :: Handle -> Char -> IO ()
127     hPutStr,                   -- :: Handle -> [Char] -> IO ()
128     hPutStrLn,                 -- :: Handle -> [Char] -> IO ()
129     hPrint,                    -- :: Show a => Handle -> a -> IO ()
130
131     -- ** Special cases for standard input and output
132
133     -- | These functions are also exported by the "Prelude".
134
135     interact,                  -- :: (String -> String) -> IO ()
136     putChar,                   -- :: Char   -> IO ()
137     putStr,                    -- :: String -> IO () 
138     putStrLn,                  -- :: String -> IO ()
139     print,                     -- :: Show a => a -> IO ()
140     getChar,                   -- :: IO Char
141     getLine,                   -- :: IO String
142     getContents,               -- :: IO String
143     readIO,                    -- :: Read a => String -> IO a
144     readLn,                    -- :: Read a => IO a
145
146     -- * Binary input and output
147
148     withBinaryFile,
149     openBinaryFile,            -- :: FilePath -> IOMode -> IO Handle
150     hSetBinaryMode,            -- :: Handle -> Bool -> IO ()
151     hPutBuf,                   -- :: Handle -> Ptr a -> Int -> IO ()
152     hGetBuf,                   -- :: Handle -> Ptr a -> Int -> IO Int
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     openTempFile,
161     openBinaryTempFile,
162   ) where
163
164 import Control.Exception.Base
165
166 #ifndef __NHC__
167 import Data.Bits
168 import Data.List
169 import Data.Maybe
170 import Foreign.C.Error
171 import Foreign.C.String
172 import Foreign.C.Types
173 import System.Posix.Internals
174 #endif
175
176 #ifdef __GLASGOW_HASKELL__
177 import GHC.Base
178 import GHC.IO hiding ( onException )
179 import GHC.IO.IOMode
180 import GHC.IO.Handle.FD
181 import GHC.IO.Handle
182 import GHC.IORef
183 import GHC.IO.Exception ( userError )
184 import GHC.Exception
185 import GHC.Num
186 import Text.Read
187 import GHC.Show
188 #endif
189
190 #ifdef __HUGS__
191 import Hugs.IO
192 import Hugs.IOExts
193 import Hugs.IORef
194 import System.IO.Unsafe ( unsafeInterleaveIO )
195 #endif
196
197 #ifdef __NHC__
198 import IO
199   ( Handle ()
200   , HandlePosn ()
201   , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
202   , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
203   , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
204   , stdin, stdout, stderr
205   , openFile                  -- :: FilePath -> IOMode -> IO Handle
206   , hClose                    -- :: Handle -> IO ()
207   , hFileSize                 -- :: Handle -> IO Integer
208   , hIsEOF                    -- :: Handle -> IO Bool
209   , isEOF                     -- :: IO Bool
210   , hSetBuffering             -- :: Handle -> BufferMode -> IO ()
211   , hGetBuffering             -- :: Handle -> IO BufferMode
212   , hFlush                    -- :: Handle -> IO ()
213   , hGetPosn                  -- :: Handle -> IO HandlePosn
214   , hSetPosn                  -- :: HandlePosn -> IO ()
215   , hSeek                     -- :: Handle -> SeekMode -> Integer -> IO ()
216   , hWaitForInput             -- :: Handle -> Int -> IO Bool
217   , hGetChar                  -- :: Handle -> IO Char
218   , hGetLine                  -- :: Handle -> IO [Char]
219   , hLookAhead                -- :: Handle -> IO Char
220   , hGetContents              -- :: Handle -> IO [Char]
221   , hPutChar                  -- :: Handle -> Char -> IO ()
222   , hPutStr                   -- :: Handle -> [Char] -> IO ()
223   , hPutStrLn                 -- :: Handle -> [Char] -> IO ()
224   , hPrint                    -- :: Handle -> [Char] -> IO ()
225   , hReady                    -- :: Handle -> [Char] -> IO ()
226   , hIsOpen, hIsClosed        -- :: Handle -> IO Bool
227   , hIsReadable, hIsWritable  -- :: Handle -> IO Bool
228   , hIsSeekable               -- :: Handle -> IO Bool
229   , bracket
230
231   , IO ()
232   , FilePath                  -- :: String
233   )
234 import NHC.IOExtras (fixIO, hPutBuf, hGetBuf)
235 import NHC.FFI (Ptr)
236 #endif
237
238 -- -----------------------------------------------------------------------------
239 -- Standard IO
240
241 #ifdef __GLASGOW_HASKELL__
242 -- | Write a character to the standard output device
243 -- (same as 'hPutChar' 'stdout').
244
245 putChar         :: Char -> IO ()
246 putChar c       =  hPutChar stdout c
247
248 -- | Write a string to the standard output device
249 -- (same as 'hPutStr' 'stdout').
250
251 putStr          :: String -> IO ()
252 putStr s        =  hPutStr stdout s
253
254 -- | The same as 'putStr', but adds a newline character.
255
256 putStrLn        :: String -> IO ()
257 putStrLn s      =  do putStr s
258                       putChar '\n'
259
260 -- | The 'print' function outputs a value of any printable type to the
261 -- standard output device.
262 -- Printable types are those that are instances of class 'Show'; 'print'
263 -- converts values to strings for output using the 'show' operation and
264 -- adds a newline.
265 --
266 -- For example, a program to print the first 20 integers and their
267 -- powers of 2 could be written as:
268 --
269 -- > main = print ([(n, 2^n) | n <- [0..19]])
270
271 print           :: Show a => a -> IO ()
272 print x         =  putStrLn (show x)
273
274 -- | Read a character from the standard input device
275 -- (same as 'hGetChar' 'stdin').
276
277 getChar         :: IO Char
278 getChar         =  hGetChar stdin
279
280 -- | Read a line from the standard input device
281 -- (same as 'hGetLine' 'stdin').
282
283 getLine         :: IO String
284 getLine         =  hGetLine stdin
285
286 -- | The 'getContents' operation returns all user input as a single string,
287 -- which is read lazily as it is needed
288 -- (same as 'hGetContents' 'stdin').
289
290 getContents     :: IO String
291 getContents     =  hGetContents stdin
292
293 -- | The 'interact' function takes a function of type @String->String@
294 -- as its argument.  The entire input from the standard input device is
295 -- passed to this function as its argument, and the resulting string is
296 -- output on the standard output device.
297
298 interact        ::  (String -> String) -> IO ()
299 interact f      =   do s <- getContents
300                        putStr (f s)
301
302 -- | The 'readFile' function reads a file and
303 -- returns the contents of the file as a string.
304 -- The file is read lazily, on demand, as with 'getContents'.
305
306 readFile        :: FilePath -> IO String
307 readFile name   =  openFile name ReadMode >>= hGetContents
308
309 -- | The computation 'writeFile' @file str@ function writes the string @str@,
310 -- to the file @file@.
311 writeFile :: FilePath -> String -> IO ()
312 writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
313
314 -- | The computation 'appendFile' @file str@ function appends the string @str@,
315 -- to the file @file@.
316 --
317 -- Note that 'writeFile' and 'appendFile' write a literal string
318 -- to a file.  To write a value of any printable type, as with 'print',
319 -- use the 'show' function to convert the value to a string first.
320 --
321 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
322
323 appendFile      :: FilePath -> String -> IO ()
324 appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
325
326 -- | The 'readLn' function combines 'getLine' and 'readIO'.
327
328 readLn          :: Read a => IO a
329 readLn          =  do l <- getLine
330                       r <- readIO l
331                       return r
332
333 -- | The 'readIO' function is similar to 'read' except that it signals
334 -- parse failure to the 'IO' monad instead of terminating the program.
335
336 readIO          :: Read a => String -> IO a
337 readIO s        =  case (do { (x,t) <- reads s ;
338                               ("","") <- lex t ;
339                               return x }) of
340                         [x]    -> return x
341                         []     -> ioError (userError "Prelude.readIO: no parse")
342                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
343 #endif  /* __GLASGOW_HASKELL__ */
344
345 #ifndef __NHC__
346 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
347 -- available for input from handle @hdl@.
348 -- 
349 -- This operation may fail with:
350 --
351 --  * 'System.IO.Error.isEOFError' if the end of file has been reached.
352
353 hReady          :: Handle -> IO Bool
354 hReady h        =  hWaitForInput h 0
355
356 -- | The same as 'hPutStr', but adds a newline character.
357
358 hPutStrLn       :: Handle -> String -> IO ()
359 hPutStrLn hndl str = do
360  hPutStr  hndl str
361  hPutChar hndl '\n'
362
363 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
364 -- given by the 'shows' function to the file or channel managed by @hdl@
365 -- and appends a newline.
366 --
367 -- This operation may fail with:
368 --
369 --  * 'System.IO.Error.isFullError' if the device is full; or
370 --
371 --  * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
372
373 hPrint          :: Show a => Handle -> a -> IO ()
374 hPrint hdl      =  hPutStrLn hdl . show
375 #endif /* !__NHC__ */
376
377 -- | @'withFile' name mode act@ opens a file using 'openFile' and passes
378 -- the resulting handle to the computation @act@.  The handle will be
379 -- closed on exit from 'withFile', whether by normal termination or by
380 -- raising an exception.
381 withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
382 withFile name mode = bracket (openFile name mode) hClose
383
384 -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
385 -- and passes the resulting handle to the computation @act@.  The handle
386 -- will be closed on exit from 'withBinaryFile', whether by normal
387 -- termination or by raising an exception.
388 withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
389 withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
390
391 -- ---------------------------------------------------------------------------
392 -- fixIO
393
394 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
395 fixIO :: (a -> IO a) -> IO a
396 fixIO k = do
397     ref <- newIORef (throw NonTermination)
398     ans <- unsafeInterleaveIO (readIORef ref)
399     result <- k ans
400     writeIORef ref result
401     return result
402
403 -- NOTE: we do our own explicit black holing here, because GHC's lazy
404 -- blackholing isn't enough.  In an infinite loop, GHC may run the IO
405 -- computation a few times before it notices the loop, which is wrong.
406 #endif
407
408 #if defined(__NHC__)
409 -- Assume a unix platform, where text and binary I/O are identical.
410 openBinaryFile = openFile
411 hSetBinaryMode _ _ = return ()
412 #endif
413
414 -- | The function creates a temporary file in ReadWrite mode.
415 -- The created file isn\'t deleted automatically, so you need to delete it manually.
416 --
417 -- The file is creates with permissions such that only the current
418 -- user can read\/write it.
419 --
420 -- With some exceptions (see below), the file will be created securely
421 -- in the sense that an attacker should not be able to cause
422 -- openTempFile to overwrite another file on the filesystem using your
423 -- credentials, by putting symbolic links (on Unix) in the place where
424 -- the temporary file is to be created.  On Unix the @O_CREAT@ and
425 -- @O_EXCL@ flags are used to prevent this attack, but note that
426 -- @O_EXCL@ is sometimes not supported on NFS filesystems, so if you
427 -- rely on this behaviour it is best to use local filesystems only.
428 --
429 openTempFile :: FilePath   -- ^ Directory in which to create the file
430              -> String     -- ^ File name template. If the template is \"foo.ext\" then
431                            -- the created file will be \"fooXXX.ext\" where XXX is some
432                            -- random number.
433              -> IO (FilePath, Handle)
434 openTempFile tmp_dir template = openTempFile' "openTempFile" tmp_dir template False
435
436 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.
437 openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
438 openBinaryTempFile tmp_dir template = openTempFile' "openBinaryTempFile" tmp_dir template True
439
440 openTempFile' :: String -> FilePath -> String -> Bool -> IO (FilePath, Handle)
441 openTempFile' loc tmp_dir template binary = do
442   pid <- c_getpid
443   findTempName pid
444   where
445     -- We split off the last extension, so we can use .foo.ext files
446     -- for temporary files (hidden on Unix OSes). Unfortunately we're
447     -- below filepath in the hierarchy here.
448     (prefix,suffix) =
449        case break (== '.') $ reverse template of
450          -- First case: template contains no '.'s. Just re-reverse it.
451          (rev_suffix, "")       -> (reverse rev_suffix, "")
452          -- Second case: template contains at least one '.'. Strip the
453          -- dot from the prefix and prepend it to the suffix (if we don't
454          -- do this, the unique number will get added after the '.' and
455          -- thus be part of the extension, which is wrong.)
456          (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
457          -- Otherwise, something is wrong, because (break (== '.')) should
458          -- always return a pair with either the empty string or a string
459          -- beginning with '.' as the second component.
460          _                      -> error "bug in System.IO.openTempFile"
461
462 #ifndef __NHC__
463     oflags1 = rw_flags .|. o_EXCL
464
465     binary_flags
466       | binary    = o_BINARY
467       | otherwise = 0
468
469     oflags = oflags1 .|. binary_flags
470 #endif
471
472 #ifdef __NHC__
473     findTempName x = do h <- openFile filepath ReadWriteMode
474                         return (filepath, h)
475 #else
476     findTempName x = do
477       fd <- withCString filepath $ \ f ->
478               c_open f oflags 0o600
479       if fd < 0
480        then do
481          errno <- getErrno
482          if errno == eEXIST
483            then findTempName (x+1)
484            else ioError (errnoToIOError loc errno Nothing (Just tmp_dir))
485        else do
486          -- XXX We want to tell fdToHandle what the filepath is,
487          -- as any exceptions etc will only be able to report the
488          -- fd currently
489          h <- fdToHandle fd `onException` c_close fd
490          return (filepath, h)
491 #endif
492       where
493         filename        = prefix ++ show x ++ suffix
494         filepath        = tmp_dir `combine` filename
495
496         -- XXX bits copied from System.FilePath, since that's not available here
497         combine a b
498                   | null b = a
499                   | null a = b
500                   | last a == pathSeparator = a ++ b
501                   | otherwise = a ++ [pathSeparator] ++ b
502
503 #if __HUGS__
504         fdToHandle fd   = openFd (fromIntegral fd) False ReadWriteMode binary
505 #endif
506
507 -- XXX Should use filepath library
508 pathSeparator :: Char
509 #ifdef mingw32_HOST_OS
510 pathSeparator = '\\'
511 #else
512 pathSeparator = '/'
513 #endif
514
515 #ifndef __NHC__
516 -- XXX Copied from GHC.Handle
517 std_flags, output_flags, rw_flags :: CInt
518 std_flags    = o_NONBLOCK   .|. o_NOCTTY
519 output_flags = std_flags    .|. o_CREAT
520 rw_flags     = output_flags .|. o_RDWR
521 #endif
522
523 #ifdef __NHC__
524 foreign import ccall "getpid" c_getpid :: IO Int
525 #endif
526
527 -- $locking
528 -- Implementations should enforce as far as possible, at least locally to the
529 -- Haskell process, multiple-reader single-writer locking on files.
530 -- That is, /there may either be many handles on the same file which manage
531 -- input, or just one handle on the file which manages output/.  If any
532 -- open or semi-closed handle is managing a file for output, no new
533 -- handle can be allocated for that file.  If any open or semi-closed
534 -- handle is managing a file for input, new handles can only be allocated
535 -- if they do not manage output.  Whether two files are the same is
536 -- implementation-dependent, but they should normally be the same if they
537 -- have the same absolute path name and neither has been renamed, for
538 -- example.
539 --
540 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
541 -- the file until the entire contents of the file have been consumed.
542 -- It follows that an attempt to write to a file (using 'writeFile', for
543 -- example) that was earlier opened by 'readFile' will usually result in
544 -- failure with 'System.IO.Error.isAlreadyInUseError'.