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