Move some flags from the Makefile into module pragmas
[ghc-hetmet.git] / compiler / utils / Encoding.hs
1 {-# OPTIONS_GHC -O #-}
2 -- We always optimise this, otherwise performance of a non-optimised
3 -- compiler is severely affected
4
5 -- -----------------------------------------------------------------------------
6 --
7 -- (c) The University of Glasgow, 1997-2006
8 --
9 -- Character encodings 
10 --
11 -- -----------------------------------------------------------------------------
12
13 module Encoding ( 
14         -- * UTF-8
15         utf8DecodeChar#,
16         utf8PrevChar,
17         utf8CharStart,
18         utf8DecodeChar,
19         utf8DecodeString,
20         utf8EncodeChar,
21         utf8EncodeString,
22         utf8EncodedLength,
23         countUTF8Chars,
24
25         -- * Z-encoding
26         zEncodeString,
27         zDecodeString
28   ) where
29
30 #include "HsVersions.h"
31 import Foreign
32 import Data.Char        ( ord, chr, isDigit, digitToInt, intToDigit,
33                           isHexDigit )
34 import Numeric          ( showIntAtBase )
35 import Data.Bits
36 import GHC.Ptr          ( Ptr(..) )
37 import GHC.Base
38
39 -- -----------------------------------------------------------------------------
40 -- UTF-8
41
42 -- We can't write the decoder as efficiently as we'd like without
43 -- resorting to unboxed extensions, unfortunately.  I tried to write
44 -- an IO version of this function, but GHC can't eliminate boxed
45 -- results from an IO-returning function.
46 --
47 -- We assume we can ignore overflow when parsing a multibyte character here.
48 -- To make this safe, we add extra sentinel bytes to unparsed UTF-8 sequences
49 -- before decoding them (see StringBuffer.hs).
50
51 {-# INLINE utf8DecodeChar# #-}
52 utf8DecodeChar# :: Addr# -> (# Char#, Addr# #)
53 utf8DecodeChar# a# =
54   let ch0 = word2Int# (indexWord8OffAddr# a# 0#) in
55   case () of 
56     _ | ch0 <=# 0x7F# -> (# chr# ch0, a# `plusAddr#` 1# #)
57
58       | ch0 >=# 0xC0# && ch0 <=# 0xDF# ->
59         let ch1 = word2Int# (indexWord8OffAddr# a# 1#) in
60         if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else
61         (# chr# (((ch0 -# 0xC0#) `uncheckedIShiftL#` 6#) +#
62                   (ch1 -# 0x80#)),
63            a# `plusAddr#` 2# #)
64
65       | ch0 >=# 0xE0# && ch0 <=# 0xEF# ->
66         let ch1 = word2Int# (indexWord8OffAddr# a# 1#) in
67         if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else
68         let ch2 = word2Int# (indexWord8OffAddr# a# 2#) in
69         if ch2 <# 0x80# || ch2 >=# 0xC0# then fail 2# else
70         (# chr# (((ch0 -# 0xE0#) `uncheckedIShiftL#` 12#) +#
71                  ((ch1 -# 0x80#) `uncheckedIShiftL#` 6#)  +#
72                   (ch2 -# 0x80#)),
73            a# `plusAddr#` 3# #)
74
75      | ch0 >=# 0xF0# && ch0 <=# 0xF8# ->
76         let ch1 = word2Int# (indexWord8OffAddr# a# 1#) in
77         if ch1 <# 0x80# || ch1 >=# 0xC0# then fail 1# else
78         let ch2 = word2Int# (indexWord8OffAddr# a# 2#) in
79         if ch2 <# 0x80# || ch2 >=# 0xC0# then fail 2# else
80         let ch3 = word2Int# (indexWord8OffAddr# a# 3#) in
81         if ch3 <# 0x80# || ch3 >=# 0xC0# then fail 3# else
82         (# chr# (((ch0 -# 0xF0#) `uncheckedIShiftL#` 18#) +#
83                  ((ch1 -# 0x80#) `uncheckedIShiftL#` 12#) +#
84                  ((ch2 -# 0x80#) `uncheckedIShiftL#` 6#)  +#
85                   (ch3 -# 0x80#)),
86            a# `plusAddr#` 4# #)
87
88       | otherwise -> fail 1#
89   where
90         -- all invalid sequences end up here:
91         fail n = (# '\0'#, a# `plusAddr#` n #)
92         -- '\xFFFD' would be the usual replacement character, but
93         -- that's a valid symbol in Haskell, so will result in a
94         -- confusing parse error later on.  Instead we use '\0' which
95         -- will signal a lexer error immediately.
96
97 utf8DecodeChar :: Ptr Word8 -> (Char, Ptr Word8)
98 utf8DecodeChar (Ptr a#) = 
99   case utf8DecodeChar# a# of (# c#, b# #) -> ( C# c#, Ptr b# )
100
101 -- UTF-8 is cleverly designed so that we can always figure out where
102 -- the start of the current character is, given any position in a
103 -- stream.  This function finds the start of the previous character,
104 -- assuming there *is* a previous character.
105 utf8PrevChar :: Ptr Word8 -> IO (Ptr Word8)
106 utf8PrevChar p = utf8CharStart (p `plusPtr` (-1))
107
108 utf8CharStart :: Ptr Word8 -> IO (Ptr Word8)
109 utf8CharStart p = go p
110  where go p = do w <- peek p
111                  if w >= 0x80 && w < 0xC0
112                         then go (p `plusPtr` (-1))
113                         else return p
114
115 utf8DecodeString :: Ptr Word8 -> Int -> IO [Char]
116 STRICT2(utf8DecodeString)
117 utf8DecodeString (Ptr a#) (I# len#)
118   = unpack a#
119   where
120     end# = addr2Int# (a# `plusAddr#` len#)
121
122     unpack p#
123         | addr2Int# p# >=# end# = return []
124         | otherwise  =
125         case utf8DecodeChar# p# of
126            (# c#, q# #) -> do
127                 chs <- unpack q#
128                 return (C# c# : chs)
129
130 countUTF8Chars :: Ptr Word8 -> Int -> IO Int
131 countUTF8Chars ptr bytes = go ptr 0
132   where
133         end = ptr `plusPtr` bytes
134
135         STRICT2(go)
136         go ptr n 
137            | ptr >= end = return n
138            | otherwise  = do
139                 case utf8DecodeChar# (unPtr ptr) of
140                   (# _, a #) -> go (Ptr a) (n+1)
141
142 unPtr :: Ptr a -> Addr#
143 unPtr (Ptr a) = a
144
145 utf8EncodeChar :: Char -> Ptr Word8 -> IO (Ptr Word8)
146 utf8EncodeChar c ptr =
147   let x = ord c in
148   case () of
149     _ | x > 0 && x <= 0x007f -> do
150           poke ptr (fromIntegral x)
151           return (ptr `plusPtr` 1)
152         -- NB. '\0' is encoded as '\xC0\x80', not '\0'.  This is so that we
153         -- can have 0-terminated UTF-8 strings (see GHC.Base.unpackCStringUtf8).
154       | x <= 0x07ff -> do
155           poke ptr (fromIntegral (0xC0 .|. ((x `shiftR` 6) .&. 0x1F)))
156           pokeElemOff ptr 1 (fromIntegral (0x80 .|. (x .&. 0x3F)))
157           return (ptr `plusPtr` 2)
158       | x <= 0xffff -> do
159           poke ptr (fromIntegral (0xE0 .|. (x `shiftR` 12) .&. 0x0F))
160           pokeElemOff ptr 1 (fromIntegral (0x80 .|. (x `shiftR` 6) .&. 0x3F))
161           pokeElemOff ptr 2 (fromIntegral (0x80 .|. (x .&. 0x3F)))
162           return (ptr `plusPtr` 3)
163       | otherwise -> do
164           poke ptr (fromIntegral (0xF0 .|. (x `shiftR` 18)))
165           pokeElemOff ptr 1 (fromIntegral (0x80 .|. ((x `shiftR` 12) .&. 0x3F)))
166           pokeElemOff ptr 2 (fromIntegral (0x80 .|. ((x `shiftR` 6) .&. 0x3F)))
167           pokeElemOff ptr 3 (fromIntegral (0x80 .|. (x .&. 0x3F)))
168           return (ptr `plusPtr` 4)
169
170 utf8EncodeString :: Ptr Word8 -> String -> IO ()
171 utf8EncodeString ptr str = go ptr str
172   where STRICT2(go)
173         go _   []     = return ()
174         go ptr (c:cs) = do
175           ptr' <- utf8EncodeChar c ptr
176           go ptr' cs
177
178 utf8EncodedLength :: String -> Int
179 utf8EncodedLength str = go 0 str
180   where STRICT2(go)
181         go n [] = n
182         go n (c:cs)
183           | ord c > 0 && ord c <= 0x007f = go (n+1) cs
184           | ord c <= 0x07ff = go (n+2) cs
185           | ord c <= 0xffff = go (n+3) cs       
186           | otherwise       = go (n+4) cs       
187
188 -- -----------------------------------------------------------------------------
189 -- The Z-encoding
190
191 {-
192 This is the main name-encoding and decoding function.  It encodes any
193 string into a string that is acceptable as a C name.  This is done
194 right before we emit a symbol name into the compiled C or asm code.
195 Z-encoding of strings is cached in the FastString interface, so we
196 never encode the same string more than once.
197
198 The basic encoding scheme is this.  
199
200 * Tuples (,,,) are coded as Z3T
201
202 * Alphabetic characters (upper and lower) and digits
203         all translate to themselves; 
204         except 'Z', which translates to 'ZZ'
205         and    'z', which translates to 'zz'
206   We need both so that we can preserve the variable/tycon distinction
207
208 * Most other printable characters translate to 'zx' or 'Zx' for some
209         alphabetic character x
210
211 * The others translate as 'znnnU' where 'nnn' is the decimal number
212         of the character
213
214         Before          After
215         --------------------------
216         Trak            Trak
217         foo_wib         foozuwib
218         >               zg
219         >1              zg1
220         foo#            foozh
221         foo##           foozhzh
222         foo##1          foozhzh1
223         fooZ            fooZZ   
224         :+              ZCzp
225         ()              Z0T     0-tuple
226         (,,,,)          Z5T     5-tuple  
227         (# #)           Z1H     unboxed 1-tuple (note the space)
228         (#,,,,#)        Z5H     unboxed 5-tuple
229                 (NB: There is no Z1T nor Z0H.)
230 -}
231
232 type UserString = String        -- As the user typed it
233 type EncodedString = String     -- Encoded form
234
235
236 zEncodeString :: UserString -> EncodedString
237 zEncodeString cs = case maybe_tuple cs of
238                 Just n  -> n            -- Tuples go to Z2T etc
239                 Nothing -> go cs
240           where
241                 go []     = []
242                 go (c:cs) = encode_ch c ++ go cs
243
244 unencodedChar :: Char -> Bool   -- True for chars that don't need encoding
245 unencodedChar 'Z' = False
246 unencodedChar 'z' = False
247 unencodedChar c   =  c >= 'a' && c <= 'z'
248                   || c >= 'A' && c <= 'Z'
249                   || c >= '0' && c <= '9'
250
251 encode_ch :: Char -> EncodedString
252 encode_ch c | unencodedChar c = [c]     -- Common case first
253
254 -- Constructors
255 encode_ch '('  = "ZL"   -- Needed for things like (,), and (->)
256 encode_ch ')'  = "ZR"   -- For symmetry with (
257 encode_ch '['  = "ZM"
258 encode_ch ']'  = "ZN"
259 encode_ch ':'  = "ZC"
260 encode_ch 'Z'  = "ZZ"
261
262 -- Variables
263 encode_ch 'z'  = "zz"
264 encode_ch '&'  = "za"
265 encode_ch '|'  = "zb"
266 encode_ch '^'  = "zc"
267 encode_ch '$'  = "zd"
268 encode_ch '='  = "ze"
269 encode_ch '>'  = "zg"
270 encode_ch '#'  = "zh"
271 encode_ch '.'  = "zi"
272 encode_ch '<'  = "zl"
273 encode_ch '-'  = "zm"
274 encode_ch '!'  = "zn"
275 encode_ch '+'  = "zp"
276 encode_ch '\'' = "zq"
277 encode_ch '\\' = "zr"
278 encode_ch '/'  = "zs"
279 encode_ch '*'  = "zt"
280 encode_ch '_'  = "zu"
281 encode_ch '%'  = "zv"
282 encode_ch c    = 'z' : if isDigit (head hex_str) then hex_str
283                                                  else '0':hex_str
284   where hex_str = showHex (ord c) "U"
285   -- ToDo: we could improve the encoding here in various ways.
286   -- eg. strings of unicode characters come out as 'z1234Uz5678U', we
287   -- could remove the 'U' in the middle (the 'z' works as a separator).
288
289         showHex = showIntAtBase 16 intToDigit
290         -- needed because prior to GHC 6.2, Numeric.showHex added a "0x" prefix
291
292 zDecodeString :: EncodedString -> UserString
293 zDecodeString [] = []
294 zDecodeString ('Z' : d : rest) 
295   | isDigit d = decode_tuple   d rest
296   | otherwise = decode_upper   d : zDecodeString rest
297 zDecodeString ('z' : d : rest)
298   | isDigit d = decode_num_esc d rest
299   | otherwise = decode_lower   d : zDecodeString rest
300 zDecodeString (c   : rest) = c : zDecodeString rest
301
302 decode_upper, decode_lower :: Char -> Char
303
304 decode_upper 'L' = '('
305 decode_upper 'R' = ')'
306 decode_upper 'M' = '['
307 decode_upper 'N' = ']'
308 decode_upper 'C' = ':'
309 decode_upper 'Z' = 'Z'
310 decode_upper ch  = {-pprTrace "decode_upper" (char ch)-} ch
311                 
312 decode_lower 'z' = 'z'
313 decode_lower 'a' = '&'
314 decode_lower 'b' = '|'
315 decode_lower 'c' = '^'
316 decode_lower 'd' = '$'
317 decode_lower 'e' = '='
318 decode_lower 'g' = '>'
319 decode_lower 'h' = '#'
320 decode_lower 'i' = '.'
321 decode_lower 'l' = '<'
322 decode_lower 'm' = '-'
323 decode_lower 'n' = '!'
324 decode_lower 'p' = '+'
325 decode_lower 'q' = '\''
326 decode_lower 'r' = '\\'
327 decode_lower 's' = '/'
328 decode_lower 't' = '*'
329 decode_lower 'u' = '_'
330 decode_lower 'v' = '%'
331 decode_lower ch  = {-pprTrace "decode_lower" (char ch)-} ch
332
333 -- Characters not having a specific code are coded as z224U (in hex)
334 decode_num_esc :: Char -> EncodedString -> UserString
335 decode_num_esc d rest
336   = go (digitToInt d) rest
337   where
338     go n (c : rest) | isHexDigit c = go (16*n + digitToInt c) rest
339     go n ('U' : rest)           = chr n : zDecodeString rest
340     go n other = error ("decode_num_esc: " ++ show n ++  ' ':other)
341
342 decode_tuple :: Char -> EncodedString -> UserString
343 decode_tuple d rest
344   = go (digitToInt d) rest
345   where
346         -- NB. recurse back to zDecodeString after decoding the tuple, because
347         -- the tuple might be embedded in a longer name.
348     go n (c : rest) | isDigit c = go (10*n + digitToInt c) rest
349     go 0 ('T':rest)     = "()" ++ zDecodeString rest
350     go n ('T':rest)     = '(' : replicate (n-1) ',' ++ ")" ++ zDecodeString rest
351     go 1 ('H':rest)     = "(# #)" ++ zDecodeString rest
352     go n ('H':rest)     = '(' : '#' : replicate (n-1) ',' ++ "#)" ++ zDecodeString rest
353     go n other = error ("decode_tuple: " ++ show n ++ ' ':other)
354
355 {-
356 Tuples are encoded as
357         Z3T or Z3H
358 for 3-tuples or unboxed 3-tuples respectively.  No other encoding starts 
359         Z<digit>
360
361 * "(# #)" is the tycon for an unboxed 1-tuple (not 0-tuple)
362   There are no unboxed 0-tuples.  
363
364 * "()" is the tycon for a boxed 0-tuple.
365   There are no boxed 1-tuples.
366 -}
367
368 maybe_tuple :: UserString -> Maybe EncodedString
369
370 maybe_tuple "(# #)" = Just("Z1H")
371 maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of
372                                  (n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H")
373                                  _                  -> Nothing
374 maybe_tuple "()" = Just("Z0T")
375 maybe_tuple ('(' : cs)       = case count_commas (0::Int) cs of
376                                  (n, ')' : _) -> Just ('Z' : shows (n+1) "T")
377                                  _            -> Nothing
378 maybe_tuple _                = Nothing
379
380 count_commas :: Int -> String -> (Int, String)
381 count_commas n (',' : cs) = count_commas (n+1) cs
382 count_commas n cs         = (n,cs)