doc updates in System.IO
[ghc-base.git] / GHC / IO / Handle / Types.hs
1 {-# OPTIONS_GHC  -XNoImplicitPrelude -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 data Handle 
91   = FileHandle                          -- A normal handle to a file
92         FilePath                        -- the file (used for error messages
93                                         -- only)
94         !(MVar Handle__)
95
96   | DuplexHandle                        -- A handle to a read/write stream
97         FilePath                        -- file for a FIFO, otherwise some
98                                         --   descriptive string (used for error
99                                         --   messages only)
100         !(MVar Handle__)                -- The read side
101         !(MVar Handle__)                -- The write side
102
103   deriving Typeable
104
105 -- NOTES:
106 --    * A 'FileHandle' is seekable.  A 'DuplexHandle' may or may not be
107 --      seekable.
108
109 instance Eq Handle where
110  (FileHandle _ h1)     == (FileHandle _ h2)     = h1 == h2
111  (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
112  _ == _ = False 
113
114 data Handle__
115   = forall dev enc_state dec_state . (IODevice dev, BufferedIO dev, Typeable dev) =>
116     Handle__ {
117       haDevice      :: !dev,
118       haType        :: HandleType,           -- type (read/write/append etc.)
119       haByteBuffer  :: !(IORef (Buffer Word8)),
120       haBufferMode  :: BufferMode,
121       haLastDecode  :: !(IORef (dec_state, Buffer Word8)),
122       haCharBuffer  :: !(IORef (Buffer CharBufElem)), -- the current buffer
123       haBuffers     :: !(IORef (BufferList CharBufElem)),  -- spare buffers
124       haEncoder     :: Maybe (TextEncoder enc_state),
125       haDecoder     :: Maybe (TextDecoder dec_state),
126       haCodec       :: Maybe TextEncoding,
127       haInputNL     :: Newline,
128       haOutputNL    :: Newline,
129       haOtherSide   :: Maybe (MVar Handle__) -- ptr to the write side of a 
130                                              -- duplex handle.
131     }
132     deriving Typeable
133
134 -- we keep a few spare buffers around in a handle to avoid allocating
135 -- a new one for each hPutStr.  These buffers are *guaranteed* to be the
136 -- same size as the main buffer.
137 data BufferList e
138   = BufferListNil 
139   | BufferListCons (RawBuffer e) (BufferList e)
140
141 --  Internally, we classify handles as being one
142 --  of the following:
143
144 data HandleType
145  = ClosedHandle
146  | SemiClosedHandle
147  | ReadHandle
148  | WriteHandle
149  | AppendHandle
150  | ReadWriteHandle
151
152 isReadableHandleType :: HandleType -> Bool
153 isReadableHandleType ReadHandle         = True
154 isReadableHandleType ReadWriteHandle    = True
155 isReadableHandleType _                  = False
156
157 isWritableHandleType :: HandleType -> Bool
158 isWritableHandleType AppendHandle    = True
159 isWritableHandleType WriteHandle     = True
160 isWritableHandleType ReadWriteHandle = True
161 isWritableHandleType _               = False
162
163 isReadWriteHandleType :: HandleType -> Bool
164 isReadWriteHandleType ReadWriteHandle{} = True
165 isReadWriteHandleType _                 = False
166
167 -- INVARIANTS on Handles:
168 --
169 --   * A handle *always* has a buffer, even if it is only 1 character long
170 --     (an unbuffered handle needs a 1 character buffer in order to support
171 --      hLookAhead and hIsEOF).
172 --   * In a read Handle, the byte buffer is always empty (we decode when reading)
173 --   * In a wriite Handle, the Char buffer is always empty (we encode when writing)
174 --
175 checkHandleInvariants :: Handle__ -> IO ()
176 #ifdef DEBUG
177 checkHandleInvariants h_ = do
178  bbuf <- readIORef (haByteBuffer h_)
179  checkBuffer bbuf
180  cbuf <- readIORef (haCharBuffer h_)
181  checkBuffer cbuf
182 #else
183 checkHandleInvariants _ = return ()
184 #endif
185
186 -- ---------------------------------------------------------------------------
187 -- Buffering modes
188
189 -- | Three kinds of buffering are supported: line-buffering, 
190 -- block-buffering or no-buffering.  These modes have the following
191 -- effects. For output, items are written out, or /flushed/,
192 -- from the internal buffer according to the buffer mode:
193 --
194 --  * /line-buffering/: the entire output buffer is flushed
195 --    whenever a newline is output, the buffer overflows, 
196 --    a 'System.IO.hFlush' is issued, or the handle is closed.
197 --
198 --  * /block-buffering/: the entire buffer is written out whenever it
199 --    overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
200 --
201 --  * /no-buffering/: output is written immediately, and never stored
202 --    in the buffer.
203 --
204 -- An implementation is free to flush the buffer more frequently,
205 -- but not less frequently, than specified above.
206 -- The output buffer is emptied as soon as it has been written out.
207 --
208 -- Similarly, input occurs according to the buffer mode for the handle:
209 --
210 --  * /line-buffering/: when the buffer for the handle is not empty,
211 --    the next item is obtained from the buffer; otherwise, when the
212 --    buffer is empty, characters up to and including the next newline
213 --    character are read into the buffer.  No characters are available
214 --    until the newline character is available or the buffer is full.
215 --
216 --  * /block-buffering/: when the buffer for the handle becomes empty,
217 --    the next block of data is read into the buffer.
218 --
219 --  * /no-buffering/: the next input item is read and returned.
220 --    The 'System.IO.hLookAhead' operation implies that even a no-buffered
221 --    handle may require a one-character buffer.
222 --
223 -- The default buffering mode when a handle is opened is
224 -- implementation-dependent and may depend on the file system object
225 -- which is attached to that handle.
226 -- For most implementations, physical files will normally be block-buffered 
227 -- and terminals will normally be line-buffered.
228
229 data BufferMode  
230  = NoBuffering  -- ^ buffering is disabled if possible.
231  | LineBuffering
232                 -- ^ line-buffering should be enabled if possible.
233  | BlockBuffering (Maybe Int)
234                 -- ^ block-buffering should be enabled if possible.
235                 -- The size of the buffer is @n@ items if the argument
236                 -- is 'Just' @n@ and is otherwise implementation-dependent.
237    deriving (Eq, Ord, Read, Show)
238
239 {-
240 [note Buffering Implementation]
241
242 Each Handle has two buffers: a byte buffer (haByteBuffer) and a Char
243 buffer (haCharBuffer).  
244
245 [note Buffered Reading]
246
247 For read Handles, bytes are read into the byte buffer, and immediately
248 decoded into the Char buffer (see
249 GHC.IO.Handle.Internals.readTextDevice).  The only way there might be
250 some data left in the byte buffer is if there is a partial multi-byte
251 character sequence that cannot be decoded into a full character.
252
253 Note that the buffering mode (haBufferMode) makes no difference when
254 reading data into a Handle.  When reading, we can always just read all
255 the data there is available without blocking, decode it into the Char
256 buffer, and then provide it immediately to the caller.
257
258 [note Buffered Writing]
259
260 Characters are written into the Char buffer by e.g. hPutStr.  When the
261 buffer is full, we call writeTextDevice, which encodes the Char buffer
262 into the byte buffer, and then immediately writes it all out to the
263 underlying device.  The Char buffer will always be empty afterward.
264 This might require multiple decoding/writing cycles.
265
266 [note Buffer Sizing]
267
268 Since the buffer mode makes no difference when reading, we can just
269 use the default buffer size for both the byte and the Char buffer.
270 Ineed, we must have room for at least one Char in the Char buffer,
271 because we have to implement hLookAhead, which requires caching a Char
272 in the Handle.  Furthermore, when doing newline translation, we need
273 room for at least two Chars in the read buffer, so we can spot the
274 \r\n sequence.
275
276 For writing, however, when the buffer mode is NoBuffering, we use a
277 1-element Char buffer to force flushing of the buffer after each Char
278 is read.
279
280 [note Buffer Flushing]
281
282 ** Flushing the Char buffer
283
284 We must be able to flush the Char buffer, in order to implement
285 hSetEncoding, and things like hGetBuf which want to read raw bytes.
286
287 Flushing the Char buffer on a write Handle is easy: just call
288 writeTextDevice to encode and write the date.
289
290 Flushing the Char buffer on a read Handle involves rewinding the byte
291 buffer to the point representing the next Char in the Char buffer.
292 This is done by
293
294  - remembering the state of the byte buffer *before* the last decode
295
296  - re-decoding the bytes that represent the chars already read from the
297    Char buffer.  This gives us the point in the byte buffer that
298    represents the *next* Char to be read.
299
300 In order for this to work, after readTextHandle we must NOT MODIFY THE
301 CONTENTS OF THE BYTE OR CHAR BUFFERS, except to remove characters from
302 the Char buffer.
303
304 ** Flushing the byte buffer
305
306 The byte buffer can be flushed if the Char buffer has already been
307 flushed (see above).  For a read Handle, flushing the byte buffer
308 means seeking the device back by the number of bytes in the buffer,
309 and hence it is only possible on a seekable Handle.
310
311 -}
312
313 -- ---------------------------------------------------------------------------
314 -- Newline translation
315
316 -- | The representation of a newline in the external file or stream.
317 data Newline = LF    -- ^ '\n'
318              | CRLF  -- ^ '\r\n'
319              deriving Eq
320
321 -- | Specifies the translation, if any, of newline characters between
322 -- internal Strings and the external file or stream.  Haskell Strings
323 -- are assumed to represent newlines with the '\n' character; the
324 -- newline mode specifies how to translate '\n' on output, and what to
325 -- translate into '\n' on input.
326 data NewlineMode 
327   = NewlineMode { inputNL :: Newline,
328                     -- ^ the representation of newlines on input
329                   outputNL :: Newline
330                     -- ^ the representation of newlines on output
331                  }
332              deriving Eq
333
334 -- | The native newline representation for the current platform: 'LF'
335 -- on Unix systems, 'CRLF' on Windows.
336 nativeNewline :: Newline
337 #ifdef mingw32_HOST_OS
338 nativeNewline = CRLF
339 #else
340 nativeNewline = LF
341 #endif
342
343 -- | Map '\r\n' into '\n' on input, and '\n' to the native newline
344 -- represetnation on output.  This mode can be used on any platform, and
345 -- works with text files using any newline convention.  The downside is
346 -- that @readFile >>= writeFile@ might yield a different file.
347 -- 
348 -- > universalNewlineMode  = NewlineMode { inputNL  = CRLF, 
349 -- >                                       outputNL = nativeNewline }
350 --
351 universalNewlineMode :: NewlineMode
352 universalNewlineMode  = NewlineMode { inputNL  = CRLF, 
353                                       outputNL = nativeNewline }
354
355 -- | Use the native newline representation on both input and output
356 -- 
357 -- > nativeNewlineMode  = NewlineMode { inputNL  = nativeNewline
358 -- >                                    outputNL = nativeNewline }
359 --
360 nativeNewlineMode    :: NewlineMode
361 nativeNewlineMode     = NewlineMode { inputNL  = nativeNewline, 
362                                       outputNL = nativeNewline }
363
364 -- | Do no newline translation at all.
365 -- 
366 -- > noNewlineTranslation  = NewlineMode { inputNL  = LF, outputNL = LF }
367 --
368 noNewlineTranslation :: NewlineMode
369 noNewlineTranslation  = NewlineMode { inputNL  = LF, outputNL = LF }
370
371 -- ---------------------------------------------------------------------------
372 -- Show instance for Handles
373
374 -- handle types are 'show'n when printing error msgs, so
375 -- we provide a more user-friendly Show instance for it
376 -- than the derived one.
377
378 instance Show HandleType where
379   showsPrec _ t =
380     case t of
381       ClosedHandle      -> showString "closed"
382       SemiClosedHandle  -> showString "semi-closed"
383       ReadHandle        -> showString "readable"
384       WriteHandle       -> showString "writable"
385       AppendHandle      -> showString "writable (append)"
386       ReadWriteHandle   -> showString "read-writable"
387
388 instance Show Handle where 
389   showsPrec _ (FileHandle   file _)   = showHandle file
390   showsPrec _ (DuplexHandle file _ _) = showHandle file
391
392 showHandle :: FilePath -> String -> String
393 showHandle file = showString "{handle: " . showString file . showString "}"