Export Unicode and newline functionality from System.IO; update Haddock docs
[ghc-base.git] / GHC / IO / Handle / Types.hs
1 {-# OPTIONS_GHC -fno-implicit-prelude -funbox-strict-fields #-}
2 {-# OPTIONS_HADDOCK hide #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.IO.Handle.Types
6 -- Copyright   :  (c) The University of Glasgow, 1994-2009
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  libraries@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable
12 --
13 -- Basic types for the implementation of IO Handles.
14 --
15 -----------------------------------------------------------------------------
16
17 module GHC.IO.Handle.Types (
18       Handle(..), Handle__(..), showHandle,
19       checkHandleInvariants,
20       BufferList(..),
21       HandleType(..),
22       isReadableHandleType, isWritableHandleType, isReadWriteHandleType,
23       BufferMode(..),
24       BufferCodec(..),
25       NewlineMode(..), Newline(..), nativeNewline,
26       universalNewlineMode, noNewlineTranslation, nativeNewlineMode
27   ) where
28
29 #undef DEBUG
30
31 import GHC.Base
32 import GHC.MVar
33 import GHC.IO
34 import GHC.IO.Buffer
35 import GHC.IO.BufferedIO
36 import GHC.IO.Encoding.Types
37 import GHC.IORef
38 import Data.Maybe
39 import GHC.Show
40 import GHC.Read
41 import GHC.Word
42 import GHC.IO.Device
43 import Data.Typeable
44
45 -- ---------------------------------------------------------------------------
46 -- Handle type
47
48 --  A Handle is represented by (a reference to) a record 
49 --  containing the state of the I/O port/device. We record
50 --  the following pieces of info:
51
52 --    * type (read,write,closed etc.)
53 --    * the underlying file descriptor
54 --    * buffering mode 
55 --    * buffer, and spare buffers
56 --    * user-friendly name (usually the
57 --      FilePath used when IO.openFile was called)
58
59 -- Note: when a Handle is garbage collected, we want to flush its buffer
60 -- and close the OS file handle, so as to free up a (precious) resource.
61
62 -- | Haskell defines operations to read and write characters from and to files,
63 -- represented by values of type @Handle@.  Each value of this type is a
64 -- /handle/: a record used by the Haskell run-time system to /manage/ I\/O
65 -- with file system objects.  A handle has at least the following properties:
66 -- 
67 --  * whether it manages input or output or both;
68 --
69 --  * whether it is /open/, /closed/ or /semi-closed/;
70 --
71 --  * whether the object is seekable;
72 --
73 --  * whether buffering is disabled, or enabled on a line or block basis;
74 --
75 --  * a buffer (whose length may be zero).
76 --
77 -- Most handles will also have a current I\/O position indicating where the next
78 -- input or output operation will occur.  A handle is /readable/ if it
79 -- manages only input or both input and output; likewise, it is /writable/ if
80 -- it manages only output or both input and output.  A handle is /open/ when
81 -- first allocated.
82 -- Once it is closed it can no longer be used for either input or output,
83 -- though an implementation cannot re-use its storage while references
84 -- remain to it.  Handles are in the 'Show' and 'Eq' classes.  The string
85 -- produced by showing a handle is system dependent; it should include
86 -- enough information to identify the handle for debugging.  A handle is
87 -- equal according to '==' only to itself; no attempt
88 -- is made to compare the internal state of different handles for equality.
89 --
90 -- GHC note: a 'Handle' will be automatically closed when the garbage
91 -- collector detects that it has become unreferenced by the program.
92 -- However, relying on this behaviour is not generally recommended:
93 -- the garbage collector is unpredictable.  If possible, use explicit
94 -- an explicit 'hClose' to close 'Handle's when they are no longer
95 -- required.  GHC does not currently attempt to free up file
96 -- descriptors when they have run out, it is your responsibility to
97 -- ensure that this doesn't happen.
98
99 data Handle 
100   = FileHandle                          -- A normal handle to a file
101         FilePath                        -- the file (used for error messages
102                                         -- only)
103         !(MVar Handle__)
104
105   | DuplexHandle                        -- A handle to a read/write stream
106         FilePath                        -- file for a FIFO, otherwise some
107                                         --   descriptive string (used for error
108                                         --   messages only)
109         !(MVar Handle__)                -- The read side
110         !(MVar Handle__)                -- The write side
111
112   deriving Typeable
113
114 -- NOTES:
115 --    * A 'FileHandle' is seekable.  A 'DuplexHandle' may or may not be
116 --      seekable.
117
118 instance Eq Handle where
119  (FileHandle _ h1)     == (FileHandle _ h2)     = h1 == h2
120  (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
121  _ == _ = False 
122
123 data Handle__
124   = forall dev enc_state dec_state . (IODevice dev, BufferedIO dev, Typeable dev) =>
125     Handle__ {
126       haDevice      :: !dev,
127       haType        :: HandleType,           -- type (read/write/append etc.)
128       haByteBuffer  :: !(IORef (Buffer Word8)),
129       haBufferMode  :: BufferMode,
130       haLastDecode  :: !(IORef (dec_state, Buffer Word8)),
131       haCharBuffer  :: !(IORef (Buffer CharBufElem)), -- the current buffer
132       haBuffers     :: !(IORef (BufferList CharBufElem)),  -- spare buffers
133       haEncoder     :: Maybe (TextEncoder enc_state),
134       haDecoder     :: Maybe (TextDecoder dec_state),
135       haInputNL     :: Newline,
136       haOutputNL    :: Newline,
137       haOtherSide   :: Maybe (MVar Handle__) -- ptr to the write side of a 
138                                              -- duplex handle.
139     }
140     deriving Typeable
141
142 -- we keep a few spare buffers around in a handle to avoid allocating
143 -- a new one for each hPutStr.  These buffers are *guaranteed* to be the
144 -- same size as the main buffer.
145 data BufferList e
146   = BufferListNil 
147   | BufferListCons (RawBuffer e) (BufferList e)
148
149 --  Internally, we classify handles as being one
150 --  of the following:
151
152 data HandleType
153  = ClosedHandle
154  | SemiClosedHandle
155  | ReadHandle
156  | WriteHandle
157  | AppendHandle
158  | ReadWriteHandle
159
160 isReadableHandleType :: HandleType -> Bool
161 isReadableHandleType ReadHandle         = True
162 isReadableHandleType ReadWriteHandle    = True
163 isReadableHandleType _                  = False
164
165 isWritableHandleType :: HandleType -> Bool
166 isWritableHandleType AppendHandle    = True
167 isWritableHandleType WriteHandle     = True
168 isWritableHandleType ReadWriteHandle = True
169 isWritableHandleType _               = False
170
171 isReadWriteHandleType :: HandleType -> Bool
172 isReadWriteHandleType ReadWriteHandle{} = True
173 isReadWriteHandleType _                 = False
174
175 -- INVARIANTS on Handles:
176 --
177 --   * A handle *always* has a buffer, even if it is only 1 character long
178 --     (an unbuffered handle needs a 1 character buffer in order to support
179 --      hLookAhead and hIsEOF).
180 --   * In a read Handle, the byte buffer is always empty (we decode when reading)
181 --   * In a wriite Handle, the Char buffer is always empty (we encode when writing)
182 --
183 checkHandleInvariants :: Handle__ -> IO ()
184 #ifdef DEBUG
185 checkHandleInvariants h_ = do
186  bbuf <- readIORef (haByteBuffer h_)
187  checkBuffer bbuf
188  cbuf <- readIORef (haCharBuffer h_)
189  checkBuffer cbuf
190 #else
191 checkHandleInvariants _ = return ()
192 #endif
193
194 -- ---------------------------------------------------------------------------
195 -- Buffering modes
196
197 -- | Three kinds of buffering are supported: line-buffering, 
198 -- block-buffering or no-buffering.  These modes have the following
199 -- effects. For output, items are written out, or /flushed/,
200 -- from the internal buffer according to the buffer mode:
201 --
202 --  * /line-buffering/: the entire output buffer is flushed
203 --    whenever a newline is output, the buffer overflows, 
204 --    a 'System.IO.hFlush' is issued, or the handle is closed.
205 --
206 --  * /block-buffering/: the entire buffer is written out whenever it
207 --    overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
208 --
209 --  * /no-buffering/: output is written immediately, and never stored
210 --    in the buffer.
211 --
212 -- An implementation is free to flush the buffer more frequently,
213 -- but not less frequently, than specified above.
214 -- The output buffer is emptied as soon as it has been written out.
215 --
216 -- Similarly, input occurs according to the buffer mode for the handle:
217 --
218 --  * /line-buffering/: when the buffer for the handle is not empty,
219 --    the next item is obtained from the buffer; otherwise, when the
220 --    buffer is empty, characters up to and including the next newline
221 --    character are read into the buffer.  No characters are available
222 --    until the newline character is available or the buffer is full.
223 --
224 --  * /block-buffering/: when the buffer for the handle becomes empty,
225 --    the next block of data is read into the buffer.
226 --
227 --  * /no-buffering/: the next input item is read and returned.
228 --    The 'System.IO.hLookAhead' operation implies that even a no-buffered
229 --    handle may require a one-character buffer.
230 --
231 -- The default buffering mode when a handle is opened is
232 -- implementation-dependent and may depend on the file system object
233 -- which is attached to that handle.
234 -- For most implementations, physical files will normally be block-buffered 
235 -- and terminals will normally be line-buffered.
236
237 data BufferMode  
238  = NoBuffering  -- ^ buffering is disabled if possible.
239  | LineBuffering
240                 -- ^ line-buffering should be enabled if possible.
241  | BlockBuffering (Maybe Int)
242                 -- ^ block-buffering should be enabled if possible.
243                 -- The size of the buffer is @n@ items if the argument
244                 -- is 'Just' @n@ and is otherwise implementation-dependent.
245    deriving (Eq, Ord, Read, Show)
246
247 {-
248 [note Buffering Implementation]
249
250 Each Handle has two buffers: a byte buffer (haByteBuffer) and a Char
251 buffer (haCharBuffer).  
252
253 [note Buffered Reading]
254
255 For read Handles, bytes are read into the byte buffer, and immediately
256 decoded into the Char buffer (see
257 GHC.IO.Handle.Internals.readTextDevice).  The only way there might be
258 some data left in the byte buffer is if there is a partial multi-byte
259 character sequence that cannot be decoded into a full character.
260
261 Note that the buffering mode (haBufferMode) makes no difference when
262 reading data into a Handle.  When reading, we can always just read all
263 the data there is available without blocking, decode it into the Char
264 buffer, and then provide it immediately to the caller.
265
266 [note Buffered Writing]
267
268 Characters are written into the Char buffer by e.g. hPutStr.  When the
269 buffer is full, we call writeTextDevice, which encodes the Char buffer
270 into the byte buffer, and then immediately writes it all out to the
271 underlying device.  The Char buffer will always be empty afterward.
272 This might require multiple decoding/writing cycles.
273
274 [note Buffer Sizing]
275
276 Since the buffer mode makes no difference when reading, we can just
277 use the default buffer size for both the byte and the Char buffer.
278 Ineed, we must have room for at least one Char in the Char buffer,
279 because we have to implement hLookAhead, which requires caching a Char
280 in the Handle.  Furthermore, when doing newline translation, we need
281 room for at least two Chars in the read buffer, so we can spot the
282 \r\n sequence.
283
284 For writing, however, when the buffer mode is NoBuffering, we use a
285 1-element Char buffer to force flushing of the buffer after each Char
286 is read.
287
288 [note Buffer Flushing]
289
290 ** Flushing the Char buffer
291
292 We must be able to flush the Char buffer, in order to implement
293 hSetEncoding, and things like hGetBuf which want to read raw bytes.
294
295 Flushing the Char buffer on a write Handle is easy: just call
296 writeTextDevice to encode and write the date.
297
298 Flushing the Char buffer on a read Handle involves rewinding the byte
299 buffer to the point representing the next Char in the Char buffer.
300 This is done by
301
302  - remembering the state of the byte buffer *before* the last decode
303
304  - re-decoding the bytes that represent the chars already read from the
305    Char buffer.  This gives us the point in the byte buffer that
306    represents the *next* Char to be read.
307
308 In order for this to work, after readTextHandle we must NOT MODIFY THE
309 CONTENTS OF THE BYTE OR CHAR BUFFERS, except to remove characters from
310 the Char buffer.
311
312 ** Flushing the byte buffer
313
314 The byte buffer can be flushed if the Char buffer has already been
315 flushed (see above).  For a read Handle, flushing the byte buffer
316 means seeking the device back by the number of bytes in the buffer,
317 and hence it is only possible on a seekable Handle.
318
319 -}
320
321 -- ---------------------------------------------------------------------------
322 -- Newline translation
323
324 -- | The representation of a newline in the external file or stream.
325 data Newline = LF    -- ^ '\n'
326              | CRLF  -- ^ '\r\n'
327              deriving Eq
328
329 -- | Specifies the translation, if any, of newline characters between
330 -- internal Strings and the external file or stream.  Haskell Strings
331 -- are assumed to represent newlines with the '\n' character; the
332 -- newline mode specifies how to translate '\n' on output, and what to
333 -- translate into '\n' on input.
334 data NewlineMode 
335   = NewlineMode { inputNL :: Newline,
336                     -- ^ the representation of newlines on input
337                   outputNL :: Newline
338                     -- ^ the representation of newlines on output
339                  }
340              deriving Eq
341
342 -- | The native newline representation for the current platform: 'LF'
343 -- on Unix systems, 'CRLF' on Windows.
344 nativeNewline :: Newline
345 #ifdef mingw32_HOST_OS
346 nativeNewline = CRLF
347 #else
348 nativeNewline = LF
349 #endif
350
351 -- | Map '\r\n' into '\n' on input, and '\n' to the native newline
352 -- represetnation on output.  This mode can be used on any platform, and
353 -- works with text files using any newline convention.  The downside is
354 -- that @readFile >>= writeFile@ might yield a different file.
355 -- 
356 -- > universalNewlineMode  = NewlineMode { inputNL  = CRLF, 
357 -- >                                       outputNL = nativeNewline }
358 --
359 universalNewlineMode :: NewlineMode
360 universalNewlineMode  = NewlineMode { inputNL  = CRLF, 
361                                       outputNL = nativeNewline }
362
363 -- | Use the native newline representation on both input and output
364 -- 
365 -- > nativeNewlineMode  = NewlineMode { inputNL  = nativeNewline
366 -- >                                    outputNL = nativeNewline }
367 --
368 nativeNewlineMode    :: NewlineMode
369 nativeNewlineMode     = NewlineMode { inputNL  = nativeNewline, 
370                                       outputNL = nativeNewline }
371
372 -- | Do no newline translation at all.
373 -- 
374 -- > noNewlineTranslation  = NewlineMode { inputNL  = LF, outputNL = LF }
375 --
376 noNewlineTranslation :: NewlineMode
377 noNewlineTranslation  = NewlineMode { inputNL  = LF, outputNL = LF }
378
379 -- ---------------------------------------------------------------------------
380 -- Show instance for Handles
381
382 -- handle types are 'show'n when printing error msgs, so
383 -- we provide a more user-friendly Show instance for it
384 -- than the derived one.
385
386 instance Show HandleType where
387   showsPrec _ t =
388     case t of
389       ClosedHandle      -> showString "closed"
390       SemiClosedHandle  -> showString "semi-closed"
391       ReadHandle        -> showString "readable"
392       WriteHandle       -> showString "writable"
393       AppendHandle      -> showString "writable (append)"
394       ReadWriteHandle   -> showString "read-writable"
395
396 instance Show Handle where 
397   showsPrec _ (FileHandle   file _)   = showHandle file
398   showsPrec _ (DuplexHandle file _ _) = showHandle file
399
400 showHandle :: FilePath -> String -> String
401 showHandle file = showString "{handle: " . showString file . showString "}"