[go: up one dir, main page]

Menu

[390b88]: / ir / pprint.py  Maximize  Restore  History

Download this file

380 lines (319 with data), 7.0 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
'''Pretty-printing of intermediate representation code.
'''
import math
from transf import util
from transf.lib import *
from transf import parse
import box
from box import op as ppOp
from box import kw
from box import lit
from box import sym
from box import commas
from box import Path
#######################################################################
# Int Literals
def _entropy(seq, states):
state_freqs = dict.fromkeys(states, 0)
for state in seq:
state_freqs[state] += 1
entropy = 0
nstates = len(seq)
for freq in state_freqs.itervalues():
prob = float(freq)/nstates
if prob:
entropy -= prob*math.log(prob)
return entropy
@util.Adaptor
def intrepr(term):
'''Represent integers, choosing the most suitable (lowest entropy)
representation.
'''
val = term.value
d = "%d" % abs(val)
x = "%x" % abs(val)
sd = _entropy(d, "0123456789")
sx = _entropy(x, "0123456789abcdef")
if sx < sd:
rep = hex(val)
else:
rep = str(val)
return term.factory.makeStr(rep)
intlit = combine.Composition(intrepr, box.const)
@util.Adaptor
def strrepr(term):
val = term.value
if val[-1:] == '\0':
val = val[:-1]
res = '"'
for c in val:
if c in ('"', '\\'):
res += '\\' + c
elif ord(c) >= 32 and ord(c) < 128:
res += c
elif c == '\n':
res += '\\n'
elif c == '\t':
res += '\\t'
elif c == '\r':
res += '\\r'
else:
res += '\\' + oct(ord(c))
res += '"'
return term.factory.makeStr(res)
strlit = combine.Composition(strrepr, box.const)
parse.Transfs('''
#######################################################################
# Types
ppSign =
Signed -> H([ <kw "signed">, " " ])
| Unsigned -> H([ <kw "unsigned"> , " " ])
| NoSign -> ""
ppSize =
switch id
case 8:
!<kw "char">
case 16:
!H([ <kw "short">, " ", <kw "int"> ])
case 32:
!<kw "int">
case 64:
!H([ <kw "long">, " ", <kw "int"> ])
else
!H([ "int", <strings.tostr> ])
end
ppType =
Void
-> <kw "void">
| Bool
-> <kw "bool">
| Int(size, sign)
-> H([ <ppSign sign>, <ppSize size> ])
| Float(32)
-> <kw "float">
| Float(64)
-> <kw "double">
| Char(8)
-> <kw "char">
| Char(16)
-> <kw "wchar_t">
| Pointer(type)
-> H([ <ppType type>, " ", <ppOp "*"> ])
| Array(type)
-> H([ <ppType type>, "[", "]" ])
| Blob(size)
-> H([ "blob", <strings.tostr size> ])
| _ -> "???"
#######################################################################
# Operator precendence.
#
# See http://www.difranco.net/cop2220/op-prec.htm
precUnaryOp =
Not -> 1
| Neg -> 1
precBinaryOp =
And(Bool) -> 10
| Or(Bool) -> 11
| And(_) -> 7
| Or(_) -> 9
| Xor(_) -> 8
| LShift -> 4
| RShift -> 4
| Plus -> 4 # force parenthesis inside shifts (was 3)
| Minus -> 4 # force parenthesis inside shifts (was 3)
| Mult -> 2
| Div -> 2
| Mod -> 2
| Eq -> 6
| NotEq -> 6
| Lt -> 5
| LtEq -> 5
| Gt -> 5
| GtEq -> 5
precExpr =
Lit(_, _) -> 0
| Sym(_) -> 0
| Cast(_, _) -> 1
| Addr(_) -> 1
| Ref(_) -> 1
| Unary(op, _) -> <precUnaryOp op>
| Binary(op, _, _) -> <precBinaryOp op>
| Cond(_, _, _) -> 13
| Call(_, _) -> 0
#######################################################################
# Expressions
ppUnaryOp =
Not(Bool) -> "!"
| Not(_) -> "~"
| Neg -> "-"
ppBinaryOp =
And(Bool) -> "&&"
| Or(Bool) -> "||"
| And(_) -> "&"
| Or(_) -> "|"
| Xor(_) -> "^"
| LShift -> "<<"
| RShift -> ">>"
| Plus -> "+"
| Minus -> "-"
| Mult -> "*"
| Div -> "/"
| Mod -> "%"
| Eq -> "=="
| NotEq -> "!="
| Lt -> "<"
| LtEq -> "<="
| Gt -> ">"
| GtEq -> ">="
SubExpr(Cmp) =
?[pprec, rest] ;
prec := precExpr rest ;
if Cmp(!prec, !pprec) then
!H([ "(", <exprKern [prec,rest]>, ")" ])
else
exprKern [prec,rest]
end
subExpr = SubExpr(arith.Gt)
subExprEq = SubExpr(arith.Geq)
exprKern =
( [prec,rest] -> rest ) ;
Path((
Lit(Int(_,_), value)
-> <intlit value>
| Lit(Pointer(Char(8)), value)
-> <strlit value>
| Lit(type, value)
-> <lit value>
| Sym(name)
-> <sym name>
| Cast(type, expr)
-> H([ "(", <ppType type>, ")", " ", <subExpr [prec,expr]> ])
| Unary(op, expr)
-> H([ <ppUnaryOp op>, <subExpr [prec,expr]> ])
| Binary(op, lexpr, rexpr)
-> H([ <subExpr [prec,lexpr]>, " ", <ppBinaryOp op>, " ", <subExprEq [prec,rexpr]> ])
| Cond(cond, texpr, fexpr)
-> H([ <subExpr [prec,cond]>, " ", <ppOp "?">, " ", <subExpr [prec,texpr]>, " ", <ppOp ":">, " ", <subExpr [prec,fexpr]> ])
| Call(addr, args)
-> H([ <subExpr [prec,addr]>, "(", <(Map(subExpr [prec,<id>]); commas) args>, ")" ])
| Addr(addr)
-> H([ <ppOp "&">, <subExpr [prec,addr]> ])
| Ref(expr)
-> H([ <ppOp "*">, <subExpr [prec,expr]> ])
))
ppExpr =
exprKern [<precExpr>,<id>]
#######################################################################
# Statements
ppArg =
Arg(type, name)
-> H([ <ppType type>, " ", name ])
ppStmts =
!V( <Map(ppStmt)> )
stmtKern =
Assign(Void, NoExpr, src)
-> H([ <ppExpr src> ])
| Assign(_, dst, src)
-> H([ <ppExpr dst>, " ", <ppOp "=">, " ", <ppExpr src> ])
| If(cond, _, _)
-> H([ <kw "if">, "(", <ppExpr cond>, ")" ])
| While(cond, _)
-> H([ <kw "while">, "(", <ppExpr cond>, ")" ])
| DoWhile(cond, _)
-> H([ <kw "while">, "(", <ppExpr cond>, ")" ])
| Var(type, name, NoExpr)
-> H([ <ppType type>, " ", name ])
| Var(type, name, val)
-> H([ <ppType type>, " ", name, " = ", <ppExpr val> ])
| Function(type, name, args, stmts)
-> H([ <ppType type>, " ", name, "(", <(Map(ppArg);commas) args>, ")" ])
| Label(name)
-> H([ name, ":" ])
| GoTo(label)
-> H([ <kw "goto">, " ", <ppExpr label> ])
| Ret(_, NoExpr)
-> H([ <kw "return"> ])
| Ret(_, value)
-> H([ <kw "return">, " ", <ppExpr value> ])
| NoStmt
-> ""
| Asm(opcode, operands)
-> H([ <kw "asm">, "(", <commas [<lit opcode>, *<Map(ppExpr) operands>]>, ")" ])
ppLabel =
Label
-> D( <stmtKern> )
ppBlock =
Block( stmts )
-> V([
D("{"),
<ppStmts stmts>,
D("}")
])
ppIf =
If(_, true, NoStmt)
-> V([
<stmtKern>,
I( <ppStmt true> )
])
| If(_, true, false)
-> V([
<stmtKern>,
I( <ppStmt true> ),
H([ <kw "else"> ]),
I( <ppStmt false> )
])
ppWhile =
While(_, body)
-> V([
<stmtKern>,
I( <ppStmt body> )
])
ppDoWhile =
DoWhile(_, body)
-> V([
H([ <kw "do"> ]),
I( <ppStmt body> ),
!H([ <stmtKern>, ";" ])
])
ppFunction =
Function(_, _, _, stmts)
-> D(V([
<stmtKern>,
"{",
I(V([ <ppStmts stmts> ])),
"}"
]))
ppDefault =
!H([ <stmtKern>, ";" ])
ppStmt = Path(
switch project.name
case "Label": ppLabel
case "Block": ppBlock
case "If": ppIf
case "While": ppWhile
case "DoWhile": ppDoWhile
case "Function": ppFunction
else ppDefault
end
)
module = Path((
Module(stmts)
-> V([
I( <ppStmts stmts> )
])
))
''')
#######################################################################
# Test
if __name__ == '__main__':
from aterm.factory import factory
import sys
def run(fp):
term = factory.readFromTextFile(fp)
boxes = module(term)
sys.stdout.write(box.stringify(boxes))
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
run(open(arg, "rb"))
else:
run(sys.stdin)