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