fix Hugs implementation of openTempFile
[ghc-base.git] / System / IO.hs
1 {-# OPTIONS_GHC -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     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
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
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 Data.Bits
165 import Data.List
166 import Data.Maybe
167 import Foreign.C.Error
168 import Foreign.C.String
169 import System.Posix.Internals
170
171 #ifdef __GLASGOW_HASKELL__
172 import GHC.Exception    as ExceptionBase hiding (catch)
173 #endif
174 #ifdef __HUGS__
175 import Hugs.Exception   as ExceptionBase
176 #endif
177
178 #ifdef __GLASGOW_HASKELL__
179 import GHC.Base
180 import GHC.IOBase       -- Together these four Prelude modules define
181 import GHC.Handle       -- all the stuff exported by IO for the GHC version
182 import GHC.IO
183 import GHC.Exception
184 import GHC.Num
185 import GHC.Read
186 import GHC.Show
187 #endif
188
189 #ifdef __HUGS__
190 import Hugs.IO
191 import Hugs.IOExts
192 import Hugs.IORef
193 import Hugs.Prelude     ( throw, Exception(NonTermination) )
194 import Control.Exception ( bracket )
195 import System.IO.Unsafe ( unsafeInterleaveIO )
196 #endif
197
198 #ifdef __NHC__
199 import IO
200   ( Handle ()
201   , HandlePosn ()
202   , IOMode (ReadMode,WriteMode,AppendMode,ReadWriteMode)
203   , BufferMode (NoBuffering,LineBuffering,BlockBuffering)
204   , SeekMode (AbsoluteSeek,RelativeSeek,SeekFromEnd)
205   , stdin, stdout, stderr
206   , openFile                  -- :: FilePath -> IOMode -> IO Handle
207   , hClose                    -- :: Handle -> IO ()
208   , hFileSize                 -- :: Handle -> IO Integer
209   , hIsEOF                    -- :: Handle -> IO Bool
210   , isEOF                     -- :: IO Bool
211   , hSetBuffering             -- :: Handle -> BufferMode -> IO ()
212   , hGetBuffering             -- :: Handle -> IO BufferMode
213   , hFlush                    -- :: Handle -> IO ()
214   , hGetPosn                  -- :: Handle -> IO HandlePosn
215   , hSetPosn                  -- :: HandlePosn -> IO ()
216   , hSeek                     -- :: Handle -> SeekMode -> Integer -> IO ()
217   , hWaitForInput             -- :: Handle -> Int -> IO Bool
218   , hGetChar                  -- :: Handle -> IO Char
219   , hGetLine                  -- :: Handle -> IO [Char]
220   , hLookAhead                -- :: Handle -> IO Char
221   , hGetContents              -- :: Handle -> IO [Char]
222   , hPutChar                  -- :: Handle -> Char -> IO ()
223   , hPutStr                   -- :: Handle -> [Char] -> IO ()
224   , hPutStrLn                 -- :: Handle -> [Char] -> IO ()
225   , hPrint                    -- :: Handle -> [Char] -> IO ()
226   , hReady                    -- :: Handle -> [Char] -> IO ()
227   , hIsOpen, hIsClosed        -- :: Handle -> IO Bool
228   , hIsReadable, hIsWritable  -- :: Handle -> IO Bool
229   , hIsSeekable               -- :: Handle -> IO Bool
230   , bracket
231
232   , IO ()
233   , FilePath                  -- :: String
234   )
235 import NHC.IOExtras (fixIO, hPutBuf, hGetBuf)
236 import NHC.FFI (Ptr)
237 #endif
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 writeFile :: FilePath -> String -> IO ()
313 writeFile f txt = withFile f WriteMode (\ hdl -> hPutStr hdl txt)
314
315 -- | The computation 'appendFile' @file str@ function appends the string @str@,
316 -- to the file @file@.
317 --
318 -- Note that 'writeFile' and 'appendFile' write a literal string
319 -- to a file.  To write a value of any printable type, as with 'print',
320 -- use the 'show' function to convert the value to a string first.
321 --
322 -- > main = appendFile "squares" (show [(x,x*x) | x <- [0,0.1..2]])
323
324 appendFile      :: FilePath -> String -> IO ()
325 appendFile f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt)
326
327 -- | The 'readLn' function combines 'getLine' and 'readIO'.
328
329 readLn          :: Read a => IO a
330 readLn          =  do l <- getLine
331                       r <- readIO l
332                       return r
333
334 -- | The 'readIO' function is similar to 'read' except that it signals
335 -- parse failure to the 'IO' monad instead of terminating the program.
336
337 readIO          :: Read a => String -> IO a
338 readIO s        =  case (do { (x,t) <- reads s ;
339                               ("","") <- lex t ;
340                               return x }) of
341                         [x]    -> return x
342                         []     -> ioError (userError "Prelude.readIO: no parse")
343                         _      -> ioError (userError "Prelude.readIO: ambiguous parse")
344 #endif  /* __GLASGOW_HASKELL__ */
345
346 #ifndef __NHC__
347 -- | Computation 'hReady' @hdl@ indicates whether at least one item is
348 -- available for input from handle @hdl@.
349 -- 
350 -- This operation may fail with:
351 --
352 --  * 'System.IO.Error.isEOFError' if the end of file has been reached.
353
354 hReady          :: Handle -> IO Bool
355 hReady h        =  hWaitForInput h 0
356
357 -- | The same as 'hPutStr', but adds a newline character.
358
359 hPutStrLn       :: Handle -> String -> IO ()
360 hPutStrLn hndl str = do
361  hPutStr  hndl str
362  hPutChar hndl '\n'
363
364 -- | Computation 'hPrint' @hdl t@ writes the string representation of @t@
365 -- given by the 'shows' function to the file or channel managed by @hdl@
366 -- and appends a newline.
367 --
368 -- This operation may fail with:
369 --
370 --  * 'System.IO.Error.isFullError' if the device is full; or
371 --
372 --  * 'System.IO.Error.isPermissionError' if another system resource limit would be exceeded.
373
374 hPrint          :: Show a => Handle -> a -> IO ()
375 hPrint hdl      =  hPutStrLn hdl . show
376 #endif /* !__NHC__ */
377
378 -- | @'withFile' name mode act@ opens a file using 'openFile' and passes
379 -- the resulting handle to the computation @act@.  The handle will be
380 -- closed on exit from 'withFile', whether by normal termination or by
381 -- raising an exception.
382 withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
383 withFile name mode = bracket (openFile name mode) hClose
384
385 -- | @'withBinaryFile' name mode act@ opens a file using 'openBinaryFile'
386 -- and passes the resulting handle to the computation @act@.  The handle
387 -- will be closed on exit from 'withBinaryFile', whether by normal
388 -- termination or by raising an exception.
389 withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r
390 withBinaryFile name mode = bracket (openBinaryFile name mode) hClose
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 -- | The function creates a temporary file in ReadWrite mode.
416 -- The created file isn\'t deleted automatically, so you need to delete it manually.
417 openTempFile :: FilePath   -- ^ Directory in which to create the file
418              -> String     -- ^ File name template. If the template is \"foo.ext\" then
419                            -- the create file will be \"fooXXX.ext\" where XXX is some
420                            -- random number.
421              -> IO (FilePath, Handle)
422 openTempFile tmp_dir template = openTempFile' "openTempFile" tmp_dir template False
423
424 -- | Like 'openTempFile', but opens the file in binary mode. See 'openBinaryFile' for more comments.
425 openBinaryTempFile :: FilePath -> String -> IO (FilePath, Handle)
426 openBinaryTempFile tmp_dir template = openTempFile' "openBinaryTempFile" tmp_dir template True
427
428 openTempFile' :: String -> FilePath -> String -> Bool -> IO (FilePath, Handle)
429 openTempFile' loc tmp_dir template binary = do
430   pid <- c_getpid
431   findTempName pid
432   where
433     -- We split off the last extension, so we can use .foo.ext files
434     -- for temporary files (hidden on Unix OSes). Unfortunately we're
435     -- below filepath in the hierarchy here.
436     (prefix,suffix) = case break (== '.') $ reverse template of
437                           (rev_suffix, rev_prefix) ->
438                               (reverse rev_prefix, reverse rev_suffix)
439
440     oflags1 = rw_flags .|. o_EXCL
441
442     binary_flags
443       | binary    = o_BINARY
444       | otherwise = 0
445
446     oflags = oflags1 .|. binary_flags
447
448     findTempName x = do
449       fd <- withCString filepath $ \ f ->
450               c_open f oflags 0o666
451       if fd < 0 
452        then do
453          errno <- getErrno
454          if errno == eEXIST
455            then findTempName (x+1)
456            else ioError (errnoToIOError loc errno Nothing (Just tmp_dir))
457        else do
458          -- XXX We want to tell fdToHandle what the filepath is,
459          -- as any exceptions etc will only be able to report the
460          -- fd currently
461          h <- fdToHandle fd
462                 `ExceptionBase.catchException` \e -> do c_close fd; throw e
463          return (filepath, h)
464       where
465         filename        = prefix ++ show x ++ suffix
466         filepath        = tmp_dir ++ [pathSeparator] ++ filename
467 #if __HUGS__
468         fdToHandle fd   = openFd (fromIntegral fd) False ReadWriteMode binary
469 #endif
470
471 -- XXX Should use filepath library
472 pathSeparator :: Char
473 #ifdef mingw32_HOST_OS
474 pathSeparator = '\\'
475 #else
476 pathSeparator = '/'
477 #endif
478
479 -- XXX Copied from GHC.Handle
480 std_flags    = o_NONBLOCK   .|. o_NOCTTY
481 output_flags = std_flags    .|. o_CREAT
482 read_flags   = std_flags    .|. o_RDONLY
483 write_flags  = output_flags .|. o_WRONLY
484 rw_flags     = output_flags .|. o_RDWR
485 append_flags = write_flags  .|. o_APPEND
486
487 -- $locking
488 -- Implementations should enforce as far as possible, at least locally to the
489 -- Haskell process, multiple-reader single-writer locking on files.
490 -- That is, /there may either be many handles on the same file which manage
491 -- input, or just one handle on the file which manages output/.  If any
492 -- open or semi-closed handle is managing a file for output, no new
493 -- handle can be allocated for that file.  If any open or semi-closed
494 -- handle is managing a file for input, new handles can only be allocated
495 -- if they do not manage output.  Whether two files are the same is
496 -- implementation-dependent, but they should normally be the same if they
497 -- have the same absolute path name and neither has been renamed, for
498 -- example.
499 --
500 -- /Warning/: the 'readFile' operation holds a semi-closed handle on
501 -- the file until the entire contents of the file have been consumed.
502 -- It follows that an attempt to write to a file (using 'writeFile', for
503 -- example) that was earlier opened by 'readFile' will usually result in
504 -- failure with 'System.IO.Error.isAlreadyInUseError'.
505
506 -- -----------------------------------------------------------------------------
507 -- Utils
508
509 #ifdef __GLASGOW_HASKELL__
510 -- Copied here to avoid recursive dependency with Control.Exception
511 bracket 
512         :: IO a         -- ^ computation to run first (\"acquire resource\")
513         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
514         -> (a -> IO c)  -- ^ computation to run in-between
515         -> IO c         -- returns the value from the in-between computation
516 bracket before after thing =
517   block (do
518     a <- before 
519     r <- catchException
520            (unblock (thing a))
521            (\e -> do { after a; throw e })
522     after a
523     return r
524  )
525 #endif