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