Source

f2pypy / f2pypy / parse_c_expr.py

Full commit
dalke 8a77eb4 











































dalke e719b55 
dalke 8a77eb4 

























































dalke e719b55 
dalke 8a77eb4 
























dalke e719b55 
dalke 8a77eb4 



dalke e719b55 


dalke 8a77eb4 
dalke e719b55 
dalke 8a77eb4 








dalke e719b55 
dalke 8a77eb4 



dalke e719b55 
















dalke 8a77eb4 
























dalke e719b55 
dalke 8a77eb4 


























































































dalke af2de8f 





dalke 8a77eb4 


dalke e719b55 






dalke 8a77eb4 










dalke e719b55 



dalke af2de8f 
dalke a7c2bfd 
dalke af2de8f 



dalke e719b55 




dalke 8a77eb4 
dalke e719b55 
dalke 8a77eb4 












dalke e719b55 











dalke 8a77eb4 
dalke e719b55 




dalke 8a77eb4 
dalke e719b55 


dalke 8a77eb4 

dalke e719b55 




dalke 8a77eb4 














dalke e719b55 




dalke 8a77eb4 






dalke e719b55 
dalke 8a77eb4 




































dalke af2de8f 



dalke 8a77eb4 
dalke e719b55 

dalke 8a77eb4 



dalke 3e7d422 








dalke 8a77eb4 
dalke 3e7d422 






dalke 8a77eb4 

dalke e719b55 
dalke 8a77eb4 
dalke e719b55 
dalke 8a77eb4 












dalke e719b55 
  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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# See http://effbot.org/zone/simple-top-down-parsing.htm

# Note: this is single threaded

import sys
import re
from cStringIO import StringIO

symbol_table = {}

class symbol_base(object):
    value = None
    def __repr__(self):
        if self.value is not None:
            return "%s %r)" % (self.id[:-1], self.value)
            #return "(literal %s)" % self.value
        elif hasattr(self, "third"):
            return "(%s %s %s %s)" % (self.id, self.first, self.second, self.third)
        else:
            return "(%s %s %s)" % (self.id, self.first, self.second)

def symbol(id, bp=0):
    try:
        s = symbol_table[id]
    except KeyError:
        class s(symbol_base):
            pass
        s.__name__ = "symbol-" + id # for debugging
        s.id = id
        s.value = None
        s.lbp = bp
        symbol_table[id] = s
    else:
        s.lbp = max(bp, s.lbp)
    return s

def advance(id=None):
    global token
    if id and token.id != id:
        raise SyntaxError("Expected %r" % id)
    token = next()

def paren_nud(self):
    expr = expression()
    # TODO: Check for empty parens()
    advance(")")
    return expr

def paren_led(self, left): # for use as a function cal
    self.first = left
    self.second = expression()
    advance(")")
    return self

symbol("(").nud = paren_nud
symbol("(").led = paren_led
symbol(")")


def led(self, left):
    self.first = left
    self.second = expression()
    advance(":")
    self.third = expression()
    return self
symbol("?").led = led
symbol(":")
    

# manual configuration

def led(self, left):
    self.first = left
    self.second = expression(10)
    return self
symbol("+").led = led
symbol("-").led = led

# helpers

def infix(id, bp):
    def led(self, left):
        self.first = left
        self.second = expression(bp)
        return self
    symbol(id, bp).led = led

def infix_r(id, bp):
    def led(self, left):
        self.first = left
        self.second = expression(bp-1)
        return self
    symbol(id, bp).led = led

def prefix(id, bp):
    def nud(self):
        self.first = expression(bp)
        self.second = None
        return self
    symbol(id).nud = nud


infix("=", 10)
infix(",", 15)
symbol("?", 20)
infix_r("||", 30); infix_r("&&", 40); prefix("!", 50)

infix("<", 60); infix("<=", 60);
infix(">", 60); infix(">=", 60);
infix("==", 60)

# infix("|", 70); infix("^", 80);

# infix("<<", 100); infix(">>", 100)

infix("+", 110); infix("-", 110)
infix("*", 120); infix("/", 120);
infix("%", 120)

prefix("-", 130); prefix("+", 130); prefix("~", 130)
prefix("&", 130)

symbol(".", 150); symbol("[", 150); symbol("(", 150)


symbol("(symbol)")
symbol("(end)")

symbol("(number)").nud = lambda self: self
symbol("(string)").nud = lambda self: self
symbol("(symbol)").nud = lambda self: self

token_pat = re.compile(r"""
\s*(
(?P<number>\d+(\.\d+)?) |
(?P<string>\"[^"]*") |
(?P<complex>\((?P<_real>[+-]?\d+(\.\d+)?)\s*,\s*(?P<_imag>[+-]?\d+(\.\d+)?)) | # hack!
(?P<symbol>[a-zA-Z_][a-zA-Z0-9_]*) |
(?P<operator>\*\*|[+*/?:-]|==|=|\|\||\&\&|\(|\)|>=|<=|==|[<>=&|,])
)""", re.X)

def tokenize(program):
    pos = 0
    for m in token_pat.finditer(program):
        if m is None or m.start() != pos:
            raise SyntaxError("Unknown syntax at position %d in %r" % (pos, program))
        d = m.groupdict()
        for (name, tok) in d.items():
            if tok is None or name[:1] == "_":
                continue
            if name == "number":
                symbol_class = symbol_table["(number)"]
                symbol = symbol_class()
                symbol.value = tok
                break

            if name == "string":
                symbol_class = symbol_table["(string)"]
                symbol = symbol_class()
                symbol.value = tok
                break

            if name == "complex":
                symbol_class = symbol_table["(number)"]
                symbol = symbol_class()
                real = m.group("_real")
                imag = m.group("_imag")
                if imag[:1] not in "+-":
                    imag = "+" + imag
                symbol.value = "(%s%sj)" % (real, imag)
                break

            if name == "symbol":
                symbol_class = symbol_table["(symbol)"]
                symbol = symbol_class()
                symbol.value = tok
                break

            if name == "operator":
                symbol_class = symbol_table.get(tok)
                if not symbol_class:
                    raise SyntaxError("Unknown operator: %r" % (tok,))
                symbol = symbol_class()
                break
            
            raise AssertionError("Bad tokenizer")
        else:
            raise AssertionError("Bad tokenizer")

        yield symbol
        pos = m.end()

    if pos != len(program):
        s = program[pos:]
        if not s.isspace():
            raise AssertionError("Bad %d: %r" % (pos, s))
    
    symbol = symbol_table["(end)"]
    yield symbol()

def expression(rbp=0):
    global token
    t = token
    token = next()
    left = t.nud()
    while rbp < token.lbp:
        t = token
        token = next()
        left = t.led(left)
    return left

def parse(program):
    global token, next
    next = tokenize(program).next
    token = next()
    return expression()


    
class EmitPythonExpression(object):
    emit_handlers = {}
    def match(symbol, needs_parens=True, extra=None, emit_handlers=emit_handlers):
        def decorator(func):
            emit_handlers[symbol] = (func, needs_parens, extra)
        return decorator
    
    def write(self, text):
        self.outfile.write(text)

    def emit_to_file(self, ast, outfile):
        self.outfile = outfile
        self.depth = 0
        self._emit(ast)
        self.outfile = None

    def emit_to_string(self, ast):
        outfile = StringIO()
        self.emit_to_file(ast, outfile)
        return outfile.getvalue()
        

    def _emit(self, ast):
        func, needs_parens, extra = self.emit_handlers[ast.id]
        self.depth += 1
        try:
            if needs_parens:
                self.write("(")
                func(self, ast, extra)
                self.write(")")
            else:
                func(self, ast, extra)
        finally:
            self.depth -= 1

    def convert_unchanged(self, ast, extra):
        self._emit(ast.first)
        self.write(" %s " % (ast.id,))
        self._emit(ast.second)

    def convert_rename(self, ast, rename):
        self._emit(ast.first)
        self.write(" %s " % (rename,))
        self._emit(ast.second)

    def convert_unary_or_binary(self, ast, symbol):
        if ast.second is None:
            self.write(symbol)
            self._emit(ast.first)
        else:
            self._emit(ast.first)
            self.write(symbol)
            self._emit(ast.second)


    # Put '/' here, but that assumes "from future import division"
    for symbol in ("< <= == >= > * % /".split()):
        emit_handlers[symbol] = (convert_unchanged, True, None)

    for symbol in ("+ -".split()):
        emit_handlers[symbol] = (convert_unary_or_binary, True, symbol)
        
    for symbol, rename in (x.split(",") for x in "&&,and ||,or".split()):
        emit_handlers[symbol] = (convert_rename, True, rename)


    @match("(symbol)", False)
    def convert_symbol(self, ast, extra):
        if ast.value.lower() == "py_none": # f2py lowercases its variables
            self.write("None")
        elif ast.value.endswith("_capi"):
            self.write(ast.value[:-5])
        else:
            self.write(ast.value)

    @match("(number)", False)
    def convert_number(self, ast, extra):
        self.write(ast.value)

    @match("(string)", False)
    def convert_string(self, ast, extra):
        # TODO: better support for string regex
        # TODO: convert from C string to Python string.
        self.write(ast.value)

    @match("=", False)
    def convert_assignment(self, ast, extra):
        assert self.depth == 1
        assert ast.first.id == "(symbol)", ast.first.id
        self._emit(ast.first)
        self.write(" = ")
        self._emit(ast.second)
        
    @match("(", False)
    def convert_function_call(self, ast, extra):
        if ast.first.value == "len":
            self.write("(")
            self._emit(ast.second)
            self.write(").size")
        elif ast.first.value == "shape":
            self.write("_shape(")
            self.write(ast.second.first.value)
            self.write(", ")
            self._emit(ast.second.second)
            self.write(")")
        else:
            self._emit(ast.first)
            self.write("(")
            self._emit(ast.second)
            self.write(")")

    @match("?", needs_parens=False)
    def convert_ternary(self, ast, extra):
        self.write("(")
        self._emit(ast.second)
        self.write(")")
        self.write(" if ")
        self.write("(")
        self._emit(ast.first)
        self.write(")")
        self.write(" else ")
        self.write("(")
        self._emit(ast.third)
        self.write(")")

    @match(",", needs_parens=False)
    def convert_comma(self, ast, extra):
        self._emit(ast.first)
        self.write(", ")
        self._emit(ast.second)

    @match("&")
    def convert_deref(self, ast, extra):
        self.write(ast.first.value)
        #self._emit(ast.first)

    @match("(vector)", needs_parens=False)
    def convert_vector(self, vec, extra):
        if vec.first is None:
            self.write(vec.value)
        else:
            # This might be a 0 dimensional array
            self.write("(%s if (" % (vec.value,))
            self._emit(vec.first)
            self.write(") == 0 else %s[" % (vec.value,))
            self._emit(vec.first)
            self.write(":])")
        self.write(".ctypes.data_as(")
        self.write(vec.typeinfo)
        self.write(")")

    @match("(scalar)")
    def convert_vector(self, vec, extra):
        self.write(vec.value + ".value")
           

def transform_ast(ast, transform_node):
    if getattr(ast, "first", None) is not None:
        ast.first = transform_ast(ast.first, transform_node)
    if getattr(ast, "second", None) is not None:
        ast.second = transform_ast(ast.second, transform_node)
    if getattr(ast, "third", None) is not None:
        ast.third = transform_ast(ast.third, transform_node)
    return transform_node(ast)

def tag_vectors(node, vector_variables):
    def transform_symbol_to_vector(node):
        if node.id == "(symbol)":
            if node.value in vector_variables:
                datatype, typeinfo = vector_variables[node.value]
                node.id = datatype
                node.typeinfo = typeinfo
                if datatype == "(vector)":
                    node.first = None
        return node

    return transform_ast(node, transform_symbol_to_vector)

def clean_deref(ast):
    def transform_deref(node):
        if node.id == "&":
            assert node.first.id == "(scalar)", node.first.id
        return node

    return transform_ast(ast, transform_deref)

def use_vector_addition(ast):
    return transform_ast(ast, transform_vector_addition)

def transform_vector_addition(node):
    # Binary "+'
    if node.id == "+" and node.second is not None:
        # with a vector on the LHS
        if node.first.id == "(vector)":
            vec = node.first
            if vec.first is None:
                vec.first = node.second
                return vec
            s = symbol("+")()
            s.first = vec.first
            s.second = node.second
            return s
        
    return node

def fix_function(ast):
    return transform_ast(ast, transform_function_node)

def transform_function_node(node):
    if node.id == "(":
        assert node.first.id == "(symbol)", node.first.id
        fname = node.first.value
        if fname == "len":
            if node.second.id != "(vector)":
                raise AssertionError("len() only works on vectors")
            node.second.id = "(symbol)" # XXX? Do this to prevent rewrites on ouput
        elif fname == "abs":
            if node.second.id == "(vector)":
                raise AsertionError("abs() does not work on vectors")
        elif fname == "shape":
            # ??? What does this do?
            assert node.second.id == ",", "shape takes two parameters"
            assert node.second.second.id != ",", "shape takes only two parameters"
        else:
            #raise AssertionError("Unknown function %r" % (fname,))
            pass
    return node
    

def convert_c_expression(expr, vector_typeinfo):
    ast = None
    try:
        #print "Process", repr(expr)
        ast = parse(expr)
        #print "AST", ast
        ast = tag_vectors(ast, vector_typeinfo)
        ast = fix_function(ast)
        ast = clean_deref(ast)
        ast = use_vector_addition(ast)

        codegen = EmitPythonExpression()
        s = codegen.emit_to_string(ast)
        return s
    except Exception:
        print "Process", repr(expr)
        print "AST", ast
        raise

#print parse("x1+(2*-3)**2")
#print parse("x?y:z")

'''
for prog in """
offx>=0 && offx<len(x)
n = (len(x)-offx)/abs(incx)
incx==1||incx==-1
trans_b?kb==k:ldb==k
&n
x+offx
&incx
""".splitlines()[1:]:
    print "="*30
    print prog
    print convert_c_expression(prog, {"x": "ctypes.POINTER(ctypes.c_double)",
                                      "y": "ctypes.POINTER(ctypes.c_int)"})
'''