6a6efa20d45fb80ae8ea218e4b146a02cb8dfdf1
[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     openTempFileWithDefaultPermissions,
163     openBinaryTempFileWithDefaultPermissions,
164
165 #if !defined(__NHC__) && !defined(__HUGS__)
166     -- * Unicode encoding\/decoding
167
168     -- | A text-mode 'Handle' has an associated 'TextEncoding', which
169     -- is used to decode bytes into Unicode characters when reading,
170     -- and encode Unicode characters into bytes when writing.
171     --
172     -- The default 'TextEncoding' is the same as the default encoding
173     -- on your system, which is also available as 'localeEncoding'.
174     -- (GHC note: on Windows, we currently do not support double-byte
175     -- encodings; if the console\'s code page is unsupported, then
176     -- 'localeEncoding' will be 'latin1'.)
177     --
178     -- Encoding and decoding errors are always detected and reported,
179     -- except during lazy I/O ('hGetContents', 'getContents', and
180     -- 'readFile'), where a decoding error merely results in
181     -- termination of the character stream, as with other I/O errors.
182
183     hSetEncoding, 
184     hGetEncoding,
185
186     -- ** Unicode encodings
187     TextEncoding, 
188     latin1,
189     utf8, utf8_bom,
190     utf16, utf16le, utf16be,
191     utf32, utf32le, utf32be, 
192     localeEncoding,
193     mkTextEncoding,
194 #endif
195
196 #if !defined(__NHC__) && !defined(__HUGS__)
197     -- * Newline conversion
198     
199     -- | In Haskell, a newline is always represented by the character
200     -- '\n'.  However, in files and external character streams, a
201     -- newline may be represented by another character sequence, such
202     -- as '\r\n'.
203     --
204     -- A text-mode 'Handle' has an associated 'NewlineMode' that
205     -- specifies how to transate newline characters.  The
206     -- 'NewlineMode' specifies the input and output translation
207     -- separately, so that for instance you can translate '\r\n'
208     -- to '\n' on input, but leave newlines as '\n' on output.
209     --
210     -- The default 'NewlineMode' for a 'Handle' is
211     -- 'nativeNewlineMode', which does no translation on Unix systems,
212     -- but translates '\r\n' to '\n' and back on Windows.
213     --
214     -- Binary-mode 'Handle's do no newline translation at all.
215     --
216     hSetNewlineMode, 
217     Newline(..), nativeNewline, 
218     NewlineMode(..), 
219     noNewlineTranslation, universalNewlineMode, nativeNewlineMode,
220 #endif
221   ) where
222
223 import Control.Exception.Base
224
225 #ifndef __NHC__
226 import Data.Bits
227 import Data.List
228 import Data.Maybe
229 import Foreign.C.Error
230 import Foreign.C.Types
231 import System.Posix.Internals
232 import System.Posix.Types
233 #endif
234
235 #ifdef __GLASGOW_HASKELL__
236 import GHC.Base
237 import GHC.IO hiding ( onException )
238 import GHC.IO.IOMode
239 import GHC.IO.Handle.FD
240 import GHC.IO.Handle
241 import GHC.IORef
242 import GHC.IO.Exception ( userError )
243 import GHC.IO.Encoding
244 import GHC.Num
245 import Text.Read
246 import GHC.Show
247 #endif
248
249 #ifdef __HUGS__
250 import Hugs.IO
251 import Hugs.IOExts
252 import Hugs.IORef
253 import System.IO.Unsafe ( unsafeInterleaveIO )
254 #endif
255
256 #ifdef __NHC__
257 import IO
258   ( Handle ()
259   , HandlePosn ()
260   , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
261   , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
262   , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
263   , stdin, stdout, stderr
264   , openFile                  -- :: FilePath -> IOMode -> IO Handle
265   , hClose                    -- :: Handle -> IO ()
266   , hFileSize                 -- :: Handle -> IO Integer
267   , hIsEOF                    -- :: Handle -> IO Bool
268   , isEOF                     -- :: IO Bool
269   , hSetBuffering             -- :: Handle -> BufferMode -> IO ()
270   , hGetBuffering             -- :: Handle -> IO BufferMode
271   , hFlush                    -- :: Handle -> IO ()
272   , hGetPosn                  -- :: Handle -> IO HandlePosn
273   , hSetPosn                  -- :: HandlePosn -> IO ()
274   , hSeek                     -- :: Handle -> SeekMode -> Integer -> IO ()
275   , hWaitForInput             -- :: Handle -> Int -> IO Bool
276   , hGetChar                  -- :: Handle -> IO Char
277   , hGetLine                  -- :: Handle -> IO [Char]
278   , hLookAhead                -- :: Handle -> IO Char
279   , hGetContents              -- :: Handle -> IO [Char]
280   , hPutChar                  -- :: Handle -> Char -> IO ()
281   , hPutStr                   -- :: Handle -> [Char] -> IO ()
282   , hPutStrLn                 -- :: Handle -> [Char] -> IO ()
283   , hPrint                    -- :: Handle -> [Char] -> IO ()
284   , hReady                    -- :: Handle -> [Char] -> IO ()
285   , hIsOpen, hIsClosed        -- :: Handle -> IO Bool
286   , hIsReadable, hIsWritable  -- :: Handle -> IO Bool
287   , hIsSeekable               -- :: Handle -> IO Bool
288   , bracket
289
290   , IO ()
291   , FilePath                  -- :: String
292   )
293 import NHC.IOExtras (fixIO, hPutBuf, hGetBuf)
294 import NHC.FFI (Ptr)
295 #endif
296
297 -- -----------------------------------------------------------------------------
298 -- Standard IO
299
300 #ifdef __GLASGOW_HASKELL__
301 -- | Write a character to the standard output device
302 -- (same as 'hPutChar' 'stdout').
303
304 putChar         :: Char -> IO ()
305 putChar c       =  hPutChar stdout c
306
307 -- | Write a string to the standard output device
308 -- (same as 'hPutStr' 'stdout').
309
310 putStr          :: String -> IO ()
311 putStr s        =  hPutStr stdout s
312
313 -- | The same as 'putStr', but adds a newline character.
314
315 putStrLn        :: String -> IO ()
316 putStrLn s      =  do putStr s
317                       putChar '\n'
318
319 -- | The 'print' function outputs a value of any printable type to the
320 -- standard output device.
321 -- Printable types are those that are instances of class 'Show'; 'print'
322 -- converts values to strings for output using the 'show' operation and
323 -- adds a newline.
324 --
325 -- For example, a program to print the first 20 integers and their
326 -- powers of 2 could be written as:
327 --
328 -- > main = print ([(n, 2^n) | n <- [0..19]])
329
330 print           :: Show a => a -> IO ()
331 print x         =  putStrLn (show x)
332
333 -- | Read a character from the standard input device
334 -- (same as 'hGetChar' 'stdin').
335
336 getChar         :: IO Char
337 getChar         =  hGetChar stdin
338
339 -- | Read a line from the standard input device
340 -- (same as 'hGetLine' 'stdin').
341
342 getLine         :: IO String
343 getLine         =  hGetLine stdin
344
345 -- | The 'getContents' operation returns all user input as a single string,
346 -- which is read lazily as it is needed
347 -- (same as 'hGetContents' 'stdin').
348
349 getContents     :: IO String
350 getContents     =  hGetContents stdin
351
352 -- | The 'interact' function takes a function of type @String->String@
353 -- as its argument.  The entire input from the standard input device is
354 -- passed to this function as its argument, and the resulting string is
355 -- output on the standard output device.
356
357 interact        ::  (String -> String) -> IO ()
358 interact f      =   do s <- getContents
359                        putStr (f s)
360
361 -- | The 'readFile' function reads a file and
362 -- returns the contents of the file as a string.
363 -- The file is read lazily, on demand, as with 'getContents'.
364
365 readFile        :: FilePath -> IO String
366 readFile name   =  openFile name ReadMode >>= hGetContents
367
368 -- | The computation 'writeFile' @file str@ function writes the string @str@,
369 -- to the file @file@.
370 writeFile :: FilePath -> String -> IO ()
371 writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
372
373 -- | The computation 'appendFile' @file str@ function appends the string @str@,
374 -- to the file @file@.
375 --
376 -- Note that 'writeFile' and 'appendFile' write a literal string
377 -- to a file.  To write a value of any printable type, as with 'print',
378 -- use the 'show' function to convert the value to a string first.
379 --
380 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
381
382 appendFile      :: FilePath -> String -> IO ()
383 appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
384
385 -- | The 'readLn' function combines 'getLine' and 'readIO'.
386
387 readLn          :: Read a => IO a
388 readLn          =  do l <- getLine
389                       r <- readIO l
390                       return r
391
392 -- | The 'readIO' function is similar to 'read' except that it signals
393 -- parse failure to the 'IO' monad instead of terminating the program.
394
395 readIO          :: Read a => String -> IO a
396 readIO s        =  case (do { (x,t) <- reads s ;
397                               ("","") <- lex t ;
398                               return x }) of
399                         [x]    -> return x
400                         []     -> ioError (userError "Prelude.readIO: no parse")
401                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
402 #endif  /* __GLASGOW_HASKELL__ */
403
404 #ifndef __NHC__
405 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
406 -- available for input from handle @hdl@.
407 -- 
408 -- This operation may fail with:
409 --
410 --  * 'System.IO.Error.isEOFError' if the end of file has been reached.
411
412 hReady          :: Handle -> IO Bool
413 hReady h        =  hWaitForInput h 0
414
415 -- | The same as 'hPutStr', but adds a newline character.
416
417 hPutStrLn       :: Handle -> String -> IO ()
418 hPutStrLn hndl str = do
419  hPutStr  hndl str
420  hPutChar hndl '\n'
421
422 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
423 -- given by the 'shows' function to the file or channel managed by @hdl@
424 -- and appends a newline.
425 --
426 -- This operation may fail with:
427 --
428 --  * 'System.IO.Error.isFullError' if the device is full; or
429 --
430 --  * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
431
432 hPrint          :: Show a => Handle -> a -> IO ()
433 hPrint hdl      =  hPutStrLn hdl . show
434 #endif /* !__NHC__ */
435
436 -- | @'withFile' name mode act@ opens a file using 'openFile' and passes
437 -- the resulting handle to the computation @act@.  The handle will be
438 -- closed on exit from 'withFile', whether by normal termination or by
439 -- raising an exception.
440 withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
441 withFile name mode = bracket (openFile name mode) hClose
442
443 -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
444 -- and passes the resulting handle to the computation @act@.  The handle
445 -- will be closed on exit from 'withBinaryFile', whether by normal
446 -- termination or by raising an exception.
447 withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
448 withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
449
450 -- ---------------------------------------------------------------------------
451 -- fixIO
452
453 #if defined(__GLASGOW_HASKELL__) || defined(__HUGS__)
454 fixIO :: (a -> IO a) -> IO a
455 fixIO k = do
456     ref <- newIORef (throw NonTermination)
457     ans <- unsafeInterleaveIO (readIORef ref)
458     result <- k ans
459     writeIORef ref result
460     return result
461
462 -- NOTE: we do our own explicit black holing here, because GHC's lazy
463 -- blackholing isn't enough.  In an infinite loop, GHC may run the IO
464 -- computation a few times before it notices the loop, which is wrong.
465 #endif
466
467 #if defined(__NHC__)
468 -- Assume a unix platform, where text and binary I/O are identical.
469 openBinaryFile = openFile
470 hSetBinaryMode _ _ = return ()
471
472 type CMode = Int
473 #endif
474
475 -- | The function creates a temporary file in ReadWrite mode.
476 -- The created file isn\'t deleted automatically, so you need to delete it manually.
477 --
478 -- The file is creates with permissions such that only the current
479 -- user can read\/write it.
480 --
481 -- With some exceptions (see below), the file will be created securely
482 -- in the sense that an attacker should not be able to cause
483 -- openTempFile to overwrite another file on the filesystem using your
484 -- credentials, by putting symbolic links (on Unix) in the place where
485 -- the temporary file is to be created.  On Unix the @O_CREAT@ and
486 -- @O_EXCL@ flags are used to prevent this attack, but note that
487 -- @O_EXCL@ is sometimes not supported on NFS filesystems, so if you
488 -- rely on this behaviour it is best to use local filesystems only.
489 --
490 openTempFile :: FilePath   -- ^ Directory in which to create the file
491              -> String     -- ^ File name template. If the template is \"foo.ext\" then
492                            -- the created file will be \"fooXXX.ext\" where XXX is some
493                            -- random number.
494              -> IO (FilePath, Handle)
495 openTempFile tmp_dir template
496     = openTempFile' "openTempFile" tmp_dir template False 0o600
497
498 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.
499 openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
500 openBinaryTempFile tmp_dir template
501     = openTempFile' "openBinaryTempFile" tmp_dir template True 0o600
502
503 -- | Like 'openTempFile', but uses the default file permissions
504 openTempFileWithDefaultPermissions :: FilePath -> String
505                                    -> IO (FilePath, Handle)
506 openTempFileWithDefaultPermissions tmp_dir template
507     = openTempFile' "openBinaryTempFile" tmp_dir template False 0o666
508
509 -- | Like 'openBinaryTempFile', but uses the default file permissions
510 openBinaryTempFileWithDefaultPermissions :: FilePath -> String
511                                          -> IO (FilePath, Handle)
512 openBinaryTempFileWithDefaultPermissions tmp_dir template
513     = openTempFile' "openBinaryTempFile" tmp_dir template True 0o666
514
515 openTempFile' :: String -> FilePath -> String -> Bool -> CMode
516               -> IO (FilePath, Handle)
517 openTempFile' loc tmp_dir template binary mode = do
518   pid <- c_getpid
519   findTempName pid
520   where
521     -- We split off the last extension, so we can use .foo.ext files
522     -- for temporary files (hidden on Unix OSes). Unfortunately we're
523     -- below filepath in the hierarchy here.
524     (prefix,suffix) =
525        case break (== '.') $ reverse template of
526          -- First case: template contains no '.'s. Just re-reverse it.
527          (rev_suffix, "")       -> (reverse rev_suffix, "")
528          -- Second case: template contains at least one '.'. Strip the
529          -- dot from the prefix and prepend it to the suffix (if we don't
530          -- do this, the unique number will get added after the '.' and
531          -- thus be part of the extension, which is wrong.)
532          (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
533          -- Otherwise, something is wrong, because (break (== '.')) should
534          -- always return a pair with either the empty string or a string
535          -- beginning with '.' as the second component.
536          _                      -> error "bug in System.IO.openTempFile"
537
538 #ifndef __NHC__
539     oflags1 = rw_flags .|. o_EXCL
540
541     binary_flags
542       | binary    = o_BINARY
543       | otherwise = 0
544
545     oflags = oflags1 .|. binary_flags
546 #endif
547
548 #ifdef __NHC__
549     findTempName x = do h <- openFile filepath ReadWriteMode
550                         return (filepath, h)
551 #else
552     findTempName x = do
553       fd <- withFilePath filepath $ \ f ->
554               c_open f oflags mode
555       if fd < 0
556        then do
557          errno <- getErrno
558          if errno == eEXIST
559            then findTempName (x+1)
560            else ioError (errnoToIOError loc errno Nothing (Just tmp_dir))
561        else do
562          -- XXX We want to tell fdToHandle what the filepath is,
563          -- as any exceptions etc will only be able to report the
564          -- fd currently
565          h <- fdToHandle fd `onException` c_close fd
566          return (filepath, h)
567 #endif
568       where
569         filename        = prefix ++ show x ++ suffix
570         filepath        = tmp_dir `combine` filename
571
572         -- XXX bits copied from System.FilePath, since that's not available here
573         combine a b
574                   | null b = a
575                   | null a = b
576                   | last a == pathSeparator = a ++ b
577                   | otherwise = a ++ [pathSeparator] ++ b
578
579 #if __HUGS__
580         fdToHandle fd   = openFd (fromIntegral fd) False ReadWriteMode binary
581 #endif
582
583 -- XXX Should use filepath library
584 pathSeparator :: Char
585 #ifdef mingw32_HOST_OS
586 pathSeparator = '\\'
587 #else
588 pathSeparator = '/'
589 #endif
590
591 #ifndef __NHC__
592 -- XXX Copied from GHC.Handle
593 std_flags, output_flags, rw_flags :: CInt
594 std_flags    = o_NONBLOCK   .|. o_NOCTTY
595 output_flags = std_flags    .|. o_CREAT
596 rw_flags     = output_flags .|. o_RDWR
597 #endif
598
599 #ifdef __NHC__
600 foreign import ccall "getpid" c_getpid :: IO Int
601 #endif
602
603 -- $locking
604 -- Implementations should enforce as far as possible, at least locally to the
605 -- Haskell process, multiple-reader single-writer locking on files.
606 -- That is, /there may either be many handles on the same file which manage
607 -- input, or just one handle on the file which manages output/.  If any
608 -- open or semi-closed handle is managing a file for output, no new
609 -- handle can be allocated for that file.  If any open or semi-closed
610 -- handle is managing a file for input, new handles can only be allocated
611 -- if they do not manage output.  Whether two files are the same is
612 -- implementation-dependent, but they should normally be the same if they
613 -- have the same absolute path name and neither has been renamed, for
614 -- example.
615 --
616 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
617 -- the file until the entire contents of the file have been consumed.
618 -- It follows that an attempt to write to a file (using 'writeFile', for
619 -- example) that was earlier opened by 'readFile' will usually result in
620 -- failure with 'System.IO.Error.isAlreadyInUseError'.