Improve External Core syntax for newtypes
[ghc-hetmet.git] / utils / ext-core / Encoding.hs
1 module Encoding where
2
3 import Data.Char
4 import Numeric
5
6 -- tjc: TODO: Copied straight out of Encoding.hs.
7 -- Ugh, maybe we can avoid this copy-pasta...
8
9 -- -----------------------------------------------------------------------------
10 -- The Z-encoding
11
12 {-
13 This is the main name-encoding and decoding function.  It encodes any
14 string into a string that is acceptable as a C name.  This is done
15 right before we emit a symbol name into the compiled C or asm code.
16 Z-encoding of strings is cached in the FastString interface, so we
17 never encode the same string more than once.
18
19 The basic encoding scheme is this.  
20
21 * Tuples (,,,) are coded as Z3T
22
23 * Alphabetic characters (upper and lower) and digits
24         all translate to themselves; 
25         except 'Z', which translates to 'ZZ'
26         and    'z', which translates to 'zz'
27   We need both so that we can preserve the variable/tycon distinction
28
29 * Most other printable characters translate to 'zx' or 'Zx' for some
30         alphabetic character x
31
32 * The others translate as 'znnnU' where 'nnn' is the decimal number
33         of the character
34
35         Before          After
36         --------------------------
37         Trak            Trak
38         foo_wib         foozuwib
39         >               zg
40         >1              zg1
41         foo#            foozh
42         foo##           foozhzh
43         foo##1          foozhzh1
44         fooZ            fooZZ   
45         :+              ZCzp
46         ()              Z0T     0-tuple
47         (,,,,)          Z5T     5-tuple  
48         (# #)           Z1H     unboxed 1-tuple (note the space)
49         (#,,,,#)        Z5H     unboxed 5-tuple
50                 (NB: There is no Z1T nor Z0H.)
51 -}
52
53 type UserString = String        -- As the user typed it
54 type EncodedString = String     -- Encoded form
55
56
57 zEncodeString :: UserString -> EncodedString
58 zEncodeString cs = case maybe_tuple cs of
59                 Just n  -> n            -- Tuples go to Z2T etc
60                 Nothing -> go cs
61           where
62                 go []     = []
63                 go (c:cs) = encode_ch c ++ go cs
64
65 unencodedChar :: Char -> Bool   -- True for chars that don't need encoding
66 unencodedChar 'Z' = False
67 unencodedChar 'z' = False
68 unencodedChar c   =  c >= 'a' && c <= 'z'
69                   || c >= 'A' && c <= 'Z'
70                   || c >= '0' && c <= '9'
71
72 encode_ch :: Char -> EncodedString
73 encode_ch c | unencodedChar c = [c]     -- Common case first
74
75 -- Constructors
76 encode_ch '('  = "ZL"   -- Needed for things like (,), and (->)
77 encode_ch ')'  = "ZR"   -- For symmetry with (
78 encode_ch '['  = "ZM"
79 encode_ch ']'  = "ZN"
80 encode_ch ':'  = "ZC"
81 encode_ch 'Z'  = "ZZ"
82
83 -- Variables
84 encode_ch 'z'  = "zz"
85 encode_ch '&'  = "za"
86 encode_ch '|'  = "zb"
87 encode_ch '^'  = "zc"
88 encode_ch '$'  = "zd"
89 encode_ch '='  = "ze"
90 encode_ch '>'  = "zg"
91 encode_ch '#'  = "zh"
92 encode_ch '.'  = "zi"
93 encode_ch '<'  = "zl"
94 encode_ch '-'  = "zm"
95 encode_ch '!'  = "zn"
96 encode_ch '+'  = "zp"
97 encode_ch '\'' = "zq"
98 encode_ch '\\' = "zr"
99 encode_ch '/'  = "zs"
100 encode_ch '*'  = "zt"
101 encode_ch '_'  = "zu"
102 encode_ch '%'  = "zv"
103 encode_ch c    = 'z' : if isDigit (head hex_str) then hex_str
104                                                  else '0':hex_str
105   where hex_str = showHex (ord c) "U"
106   -- ToDo: we could improve the encoding here in various ways.
107   -- eg. strings of unicode characters come out as 'z1234Uz5678U', we
108   -- could remove the 'U' in the middle (the 'z' works as a separator).
109
110         showHex = showIntAtBase 16 intToDigit
111         -- needed because prior to GHC 6.2, Numeric.showHex added a "0x" prefix
112
113 zDecodeString :: EncodedString -> UserString
114 zDecodeString [] = []
115 zDecodeString ('Z' : d : rest) 
116   | isDigit d = decode_tuple   d rest
117   | otherwise = decode_upper   d : zDecodeString rest
118 zDecodeString ('z' : d : rest)
119   | isDigit d = decode_num_esc d rest
120   | otherwise = decode_lower   d : zDecodeString rest
121 zDecodeString (c   : rest) = c : zDecodeString rest
122
123 decode_upper, decode_lower :: Char -> Char
124
125 decode_upper 'L' = '('
126 decode_upper 'R' = ')'
127 decode_upper 'M' = '['
128 decode_upper 'N' = ']'
129 decode_upper 'C' = ':'
130 decode_upper 'Z' = 'Z'
131 decode_upper ch  = {-pprTrace "decode_upper" (char ch)-} ch
132                 
133 decode_lower 'z' = 'z'
134 decode_lower 'a' = '&'
135 decode_lower 'b' = '|'
136 decode_lower 'c' = '^'
137 decode_lower 'd' = '$'
138 decode_lower 'e' = '='
139 decode_lower 'g' = '>'
140 decode_lower 'h' = '#'
141 decode_lower 'i' = '.'
142 decode_lower 'l' = '<'
143 decode_lower 'm' = '-'
144 decode_lower 'n' = '!'
145 decode_lower 'p' = '+'
146 decode_lower 'q' = '\''
147 decode_lower 'r' = '\\'
148 decode_lower 's' = '/'
149 decode_lower 't' = '*'
150 decode_lower 'u' = '_'
151 decode_lower 'v' = '%'
152 decode_lower ch  = {-pprTrace "decode_lower" (char ch)-} ch
153
154 -- Characters not having a specific code are coded as z224U (in hex)
155 decode_num_esc :: Char -> EncodedString -> UserString
156 decode_num_esc d rest
157   = go (digitToInt d) rest
158   where
159     go n (c : rest) | isHexDigit c = go (16*n + digitToInt c) rest
160     go n ('U' : rest)           = chr n : zDecodeString rest
161     go n other = error ("decode_num_esc: " ++ show n ++  ' ':other)
162
163 decode_tuple :: Char -> EncodedString -> UserString
164 decode_tuple d rest
165   = go (digitToInt d) rest
166   where
167         -- NB. recurse back to zDecodeString after decoding the tuple, because
168         -- the tuple might be embedded in a longer name.
169     go n (c : rest) | isDigit c = go (10*n + digitToInt c) rest
170     go 0 ('T':rest)     = "()" ++ zDecodeString rest
171     go n ('T':rest)     = '(' : replicate (n-1) ',' ++ ")" ++ zDecodeString rest
172     go 1 ('H':rest)     = "(# #)" ++ zDecodeString rest
173     go n ('H':rest)     = '(' : '#' : replicate (n-1) ',' ++ "#)" ++ zDecodeString rest
174     go n other = error ("decode_tuple: " ++ show n ++ ' ':other)
175
176 {-
177 Tuples are encoded as
178         Z3T or Z3H
179 for 3-tuples or unboxed 3-tuples respectively.  No other encoding starts 
180         Z<digit>
181
182 * "(# #)" is the tycon for an unboxed 1-tuple (not 0-tuple)
183   There are no unboxed 0-tuples.  
184
185 * "()" is the tycon for a boxed 0-tuple.
186   There are no boxed 1-tuples.
187 -}
188
189 maybe_tuple :: UserString -> Maybe EncodedString
190
191 maybe_tuple "(# #)" = Just("Z1H")
192 maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of
193                                  (n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H")
194                                  _                  -> Nothing
195 maybe_tuple "()" = Just("Z0T")
196 maybe_tuple ('(' : cs)       = case count_commas (0::Int) cs of
197                                  (n, ')' : _) -> Just ('Z' : shows (n+1) "T")
198                                  _            -> Nothing
199 maybe_tuple _                = Nothing
200
201 count_commas :: Int -> String -> (Int, String)
202 count_commas n (',' : cs) = count_commas (n+1) cs
203 count_commas n cs         = (n,cs)
204