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