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