Parsing.py 88.7 KB
Newer Older
1
# cython: auto_cpdef=True, infer_types=True
William Stein's avatar
William Stein committed
2 3 4 5
#
#   Pyrex Parser
#

6 7 8 9
# This should be done automatically
import cython
cython.declare(Nodes=object, ExprNodes=object, EncodedString=object)

10 11 12
import os
import re
import sys
Lisandro Dalcin's avatar
Lisandro Dalcin committed
13

14
from Cython.Compiler.Scanning import PyrexScanner, FileSourceDescriptor
William Stein's avatar
William Stein committed
15 16
import Nodes
import ExprNodes
17
import StringEncoding
18
from StringEncoding import EncodedString, BytesLiteral, _unicode, _bytes
19
from ModuleNode import ModuleNode
20
from Errors import error, warning, InternalError
21
from Cython import Utils
Stefan Behnel's avatar
Stefan Behnel committed
22
import Future
23
import Options
William Stein's avatar
William Stein committed
24

25 26 27 28 29 30 31 32 33
class Ctx(object):
    #  Parsing context
    level = 'other'
    visibility = 'private'
    cdef_flag = 0
    typedef_flag = 0
    api = 0
    overridable = 0
    nogil = 0
34
    namespace = None
Danilo Freitas's avatar
Danilo Freitas committed
35
    templates = None
36 37 38 39 40 41 42 43 44 45 46

    def __init__(self, **kwds):
        self.__dict__.update(kwds)

    def __call__(self, **kwds):
        ctx = Ctx()
        d = ctx.__dict__
        d.update(self.__dict__)
        d.update(kwds)
        return ctx

William Stein's avatar
William Stein committed
47 48 49 50 51 52 53 54 55 56 57 58 59
def p_ident(s, message = "Expected an identifier"):
    if s.sy == 'IDENT':
        name = s.systring
        s.next()
        return name
    else:
        s.error(message)

def p_ident_list(s):
    names = []
    while s.sy == 'IDENT':
        names.append(s.systring)
        s.next()
Stefan Behnel's avatar
Stefan Behnel committed
60
        if s.sy != ',':
William Stein's avatar
William Stein committed
61 62 63 64 65 66 67 68 69 70
            break
        s.next()
    return names

#------------------------------------------
#
#   Expressions
#
#------------------------------------------

71 72 73 74 75 76
def p_binop_operator(s):
    pos = s.position()
    op = s.sy
    s.next()
    return op, pos

William Stein's avatar
William Stein committed
77 78 79
def p_binop_expr(s, ops, p_sub_expr):
    n1 = p_sub_expr(s)
    while s.sy in ops:
80
        op, pos = p_binop_operator(s)
William Stein's avatar
William Stein committed
81 82
        n2 = p_sub_expr(s)
        n1 = ExprNodes.binop_node(pos, op, n1, n2)
83 84 85 86 87
        if op == '/':
            if Future.division in s.context.future_directives:
                n1.truedivision = True
            else:
                n1.truedivision = None # unknown
William Stein's avatar
William Stein committed
88 89
    return n1

Stefan Behnel's avatar
Stefan Behnel committed
90 91 92 93 94 95 96 97 98 99
#lambdef: 'lambda' [varargslist] ':' test

def p_lambdef(s, allow_conditional=True):
    # s.sy == 'lambda'
    pos = s.position()
    s.next()
    if s.sy == ':':
        args = []
        star_arg = starstar_arg = None
    else:
100 101
        args, star_arg, starstar_arg = p_varargslist(
            s, terminator=':', annotated=False)
Stefan Behnel's avatar
Stefan Behnel committed
102 103
    s.expect(':')
    if allow_conditional:
104
        expr = p_test(s)
Stefan Behnel's avatar
Stefan Behnel committed
105 106 107 108 109 110 111 112 113 114 115 116
    else:
        expr = p_test_nocond(s)
    return ExprNodes.LambdaNode(
        pos, args = args,
        star_arg = star_arg, starstar_arg = starstar_arg,
        result_expr = expr)

#lambdef_nocond: 'lambda' [varargslist] ':' test_nocond

def p_lambdef_nocond(s):
    return p_lambdef(s, allow_conditional=False)

117
#test: or_test ['if' or_test 'else' test] | lambdef
William Stein's avatar
William Stein committed
118

Robert Bradshaw's avatar
Robert Bradshaw committed
119
def p_test(s):
120 121
    if s.sy == 'lambda':
        return p_lambdef(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
122 123 124 125 126
    pos = s.position()
    expr = p_or_test(s)
    if s.sy == 'if':
        s.next()
        test = p_or_test(s)
Stefan Behnel's avatar
Stefan Behnel committed
127 128 129
        s.expect('else')
        other = p_test(s)
        return ExprNodes.CondExprNode(pos, test=test, true_val=expr, false_val=other)
Robert Bradshaw's avatar
Robert Bradshaw committed
130 131 132
    else:
        return expr

Stefan Behnel's avatar
Stefan Behnel committed
133 134 135 136 137 138 139
#test_nocond: or_test | lambdef_nocond

def p_test_nocond(s):
    if s.sy == 'lambda':
        return p_lambdef_nocond(s)
    else:
        return p_or_test(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
140 141 142 143

#or_test: and_test ('or' and_test)*

def p_or_test(s):
William Stein's avatar
William Stein committed
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
    return p_rassoc_binop_expr(s, ('or',), p_and_test)

def p_rassoc_binop_expr(s, ops, p_subexpr):
    n1 = p_subexpr(s)
    if s.sy in ops:
        pos = s.position()
        op = s.sy
        s.next()
        n2 = p_rassoc_binop_expr(s, ops, p_subexpr)
        n1 = ExprNodes.binop_node(pos, op, n1, n2)
    return n1

#and_test: not_test ('and' not_test)*

def p_and_test(s):
    #return p_binop_expr(s, ('and',), p_not_test)
    return p_rassoc_binop_expr(s, ('and',), p_not_test)

#not_test: 'not' not_test | comparison

def p_not_test(s):
    if s.sy == 'not':
        pos = s.position()
        s.next()
        return ExprNodes.NotNode(pos, operand = p_not_test(s))
    else:
        return p_comparison(s)

#comparison: expr (comp_op expr)*
#comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'

def p_comparison(s):
176
    n1 = p_starred_expr(s)
William Stein's avatar
William Stein committed
177 178 179
    if s.sy in comparison_ops:
        pos = s.position()
        op = p_cmp_op(s)
180
        n2 = p_starred_expr(s)
William Stein's avatar
William Stein committed
181 182 183 184 185 186
        n1 = ExprNodes.PrimaryCmpNode(pos, 
            operator = op, operand1 = n1, operand2 = n2)
        if s.sy in comparison_ops:
            n1.cascade = p_cascaded_cmp(s)
    return n1

187 188 189 190 191 192
def p_test_or_starred_expr(s):
    if s.sy == '*':
        return p_starred_expr(s)
    else:
        return p_test(s)

193
def p_starred_expr(s):
194
    pos = s.position()
195 196 197 198 199 200
    if s.sy == '*':
        starred = True
        s.next()
    else:
        starred = False
    expr = p_bit_expr(s)
201 202
    if starred:
        expr = ExprNodes.StarredTargetNode(pos, expr)
203 204
    return expr

William Stein's avatar
William Stein committed
205 206 207
def p_cascaded_cmp(s):
    pos = s.position()
    op = p_cmp_op(s)
208
    n2 = p_starred_expr(s)
William Stein's avatar
William Stein committed
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
    result = ExprNodes.CascadedCmpNode(pos, 
        operator = op, operand2 = n2)
    if s.sy in comparison_ops:
        result.cascade = p_cascaded_cmp(s)
    return result

def p_cmp_op(s):
    if s.sy == 'not':
        s.next()
        s.expect('in')
        op = 'not_in'
    elif s.sy == 'is':
        s.next()
        if s.sy == 'not':
            s.next()
            op = 'is_not'
        else:
            op = 'is'
    else:
        op = s.sy
        s.next()
    if op == '<>':
        op = '!='
    return op
    
comparison_ops = (
    '<', '>', '==', '>=', '<=', '<>', '!=', 
    'in', 'is', 'not'
)

#expr: xor_expr ('|' xor_expr)*

def p_bit_expr(s):
    return p_binop_expr(s, ('|',), p_xor_expr)

#xor_expr: and_expr ('^' and_expr)*

def p_xor_expr(s):
    return p_binop_expr(s, ('^',), p_and_expr)

#and_expr: shift_expr ('&' shift_expr)*

def p_and_expr(s):
    return p_binop_expr(s, ('&',), p_shift_expr)

#shift_expr: arith_expr (('<<'|'>>') arith_expr)*

def p_shift_expr(s):
    return p_binop_expr(s, ('<<', '>>'), p_arith_expr)

#arith_expr: term (('+'|'-') term)*

def p_arith_expr(s):
    return p_binop_expr(s, ('+', '-'), p_term)

#term: factor (('*'|'/'|'%') factor)*

def p_term(s):
Robert Bradshaw's avatar
Robert Bradshaw committed
267
    return p_binop_expr(s, ('*', '/', '%', '//'), p_factor)
William Stein's avatar
William Stein committed
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

#factor: ('+'|'-'|'~'|'&'|typecast|sizeof) factor | power

def p_factor(s):
    sy = s.sy
    if sy in ('+', '-', '~'):
        op = s.sy
        pos = s.position()
        s.next()
        return ExprNodes.unop_node(pos, op, p_factor(s))
    elif sy == '&':
        pos = s.position()
        s.next()
        arg = p_factor(s)
        return ExprNodes.AmpersandNode(pos, operand = arg)
    elif sy == "<":
        return p_typecast(s)
    elif sy == 'IDENT' and s.systring == "sizeof":
        return p_sizeof(s)
    else:
        return p_power(s)

def p_typecast(s):
    # s.sy == "<"
    pos = s.position()
    s.next()
    base_type = p_c_base_type(s)
295 296
    if base_type.name is None:
        s.error("Unknown type")
William Stein's avatar
William Stein committed
297
    declarator = p_c_declarator(s, empty = 1)
298 299 300 301 302
    if s.sy == '?':
        s.next()
        typecheck = 1
    else:
        typecheck = 0
William Stein's avatar
William Stein committed
303 304 305 306 307
    s.expect(">")
    operand = p_factor(s)
    return ExprNodes.TypecastNode(pos, 
        base_type = base_type, 
        declarator = declarator,
308 309
        operand = operand,
        typecheck = typecheck)
William Stein's avatar
William Stein committed
310 311 312 313 314 315

def p_sizeof(s):
    # s.sy == ident "sizeof"
    pos = s.position()
    s.next()
    s.expect('(')
316 317 318
    # Here we decide if we are looking at an expression or type
    # If it is actually a type, but parsable as an expression, 
    # we treat it as an expression here. 
319
    if looking_at_expr(s):
320
        operand = p_test(s)
321 322
        node = ExprNodes.SizeofVarNode(pos, operand = operand)
    else:
William Stein's avatar
William Stein committed
323 324 325 326 327 328 329
        base_type = p_c_base_type(s)
        declarator = p_c_declarator(s, empty = 1)
        node = ExprNodes.SizeofTypeNode(pos, 
            base_type = base_type, declarator = declarator)
    s.expect(')')
    return node

330 331 332 333
def p_yield_expression(s):
    # s.sy == "yield"
    pos = s.position()
    s.next()
334
    if s.sy != ')' and s.sy not in statement_terminators:
335
        arg = p_testlist(s)
336 337 338 339 340 341 342 343
    else:
        arg = None
    return ExprNodes.YieldExprNode(pos, arg=arg)

def p_yield_statement(s):
    # s.sy == "yield"
    yield_expr = p_yield_expression(s)
    return Nodes.ExprStatNode(yield_expr.pos, expr=yield_expr)
344

William Stein's avatar
William Stein committed
345 346 347
#power: atom trailer* ('**' factor)*

def p_power(s):
348
    if s.systring == 'new' and s.peek()[0] == 'IDENT':
Danilo Freitas's avatar
Danilo Freitas committed
349
        return p_new_expr(s)
William Stein's avatar
William Stein committed
350 351 352 353 354 355 356 357 358 359
    n1 = p_atom(s)
    while s.sy in ('(', '[', '.'):
        n1 = p_trailer(s, n1)
    if s.sy == '**':
        pos = s.position()
        s.next()
        n2 = p_factor(s)
        n1 = ExprNodes.binop_node(pos, '**', n1, n2)
    return n1

Danilo Freitas's avatar
Danilo Freitas committed
360
def p_new_expr(s):
Danilo Freitas's avatar
Danilo Freitas committed
361
    # s.systring == 'new'.
Danilo Freitas's avatar
Danilo Freitas committed
362 363
    pos = s.position()
    s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
364 365
    cppclass = p_c_base_type(s)
    return p_call(s, ExprNodes.NewExprNode(pos, cppclass = cppclass))
Danilo Freitas's avatar
Danilo Freitas committed
366

William Stein's avatar
William Stein committed
367 368 369 370 371 372 373 374 375 376
#trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME

def p_trailer(s, node1):
    pos = s.position()
    if s.sy == '(':
        return p_call(s, node1)
    elif s.sy == '[':
        return p_index(s, node1)
    else: # s.sy == '.'
        s.next()
377
        name = EncodedString( p_ident(s) )
William Stein's avatar
William Stein committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391
        return ExprNodes.AttributeNode(pos, 
            obj = node1, attribute = name)

# arglist:  argument (',' argument)* [',']
# argument: [test '='] test       # Really [keyword '='] test

def p_call(s, function):
    # s.sy == '('
    pos = s.position()
    s.next()
    positional_args = []
    keyword_args = []
    star_arg = None
    starstar_arg = None
392 393 394 395 396
    while s.sy not in ('**', ')'):
        if s.sy == '*':
            if star_arg:
                s.error("only one star-arg parameter allowed",
                    pos = s.position())
William Stein's avatar
William Stein committed
397
            s.next()
398
            star_arg = p_test(s)
William Stein's avatar
William Stein committed
399
        else:
400
            arg = p_test(s)
401 402 403 404 405 406
            if s.sy == '=':
                s.next()
                if not arg.is_name:
                    s.error("Expected an identifier before '='",
                        pos = arg.pos)
                encoded_name = EncodedString(arg.name)
407
                keyword = ExprNodes.IdentifierStringNode(arg.pos, value = encoded_name)
408
                arg = p_test(s)
409 410 411 412 413 414 415 416 417
                keyword_args.append((keyword, arg))
            else:
                if keyword_args:
                    s.error("Non-keyword arg following keyword arg",
                        pos = arg.pos)
                if star_arg:
                    s.error("Non-keyword arg following star-arg",
                        pos = arg.pos)
                positional_args.append(arg)
Stefan Behnel's avatar
Stefan Behnel committed
418
        if s.sy != ',':
William Stein's avatar
William Stein committed
419 420
            break
        s.next()
421

422 423 424 425
    if s.sy == 'for':
        if len(positional_args) == 1 and not star_arg:
            positional_args = [ p_genexp(s, positional_args[0]) ]
    elif s.sy == '**':
William Stein's avatar
William Stein committed
426
        s.next()
427
        starstar_arg = p_test(s)
William Stein's avatar
William Stein committed
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
        if s.sy == ',':
            s.next()
    s.expect(')')
    if not (keyword_args or star_arg or starstar_arg):
        return ExprNodes.SimpleCallNode(pos,
            function = function,
            args = positional_args)
    else:
        arg_tuple = None
        keyword_dict = None
        if positional_args or not star_arg:
            arg_tuple = ExprNodes.TupleNode(pos, 
                args = positional_args)
        if star_arg:
            star_arg_tuple = ExprNodes.AsTupleNode(pos, arg = star_arg)
            if arg_tuple:
                arg_tuple = ExprNodes.binop_node(pos, 
                    operator = '+', operand1 = arg_tuple,
                    operand2 = star_arg_tuple)
            else:
                arg_tuple = star_arg_tuple
        if keyword_args:
450 451
            keyword_args = [ExprNodes.DictItemNode(pos=key.pos, key=key, value=value) 
                              for key, value in keyword_args]
William Stein's avatar
William Stein committed
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 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
            keyword_dict = ExprNodes.DictNode(pos,
                key_value_pairs = keyword_args)
        return ExprNodes.GeneralCallNode(pos, 
            function = function,
            positional_args = arg_tuple,
            keyword_args = keyword_dict,
            starstar_arg = starstar_arg)

#lambdef: 'lambda' [varargslist] ':' test

#subscriptlist: subscript (',' subscript)* [',']

def p_index(s, base):
    # s.sy == '['
    pos = s.position()
    s.next()
    subscripts = p_subscript_list(s)
    if len(subscripts) == 1 and len(subscripts[0]) == 2:
        start, stop = subscripts[0]
        result = ExprNodes.SliceIndexNode(pos, 
            base = base, start = start, stop = stop)
    else:
        indexes = make_slice_nodes(pos, subscripts)
        if len(indexes) == 1:
            index = indexes[0]
        else:
            index = ExprNodes.TupleNode(pos, args = indexes)
        result = ExprNodes.IndexNode(pos,
            base = base, index = index)
    s.expect(']')
    return result

def p_subscript_list(s):
    items = [p_subscript(s)]
    while s.sy == ',':
        s.next()
        if s.sy == ']':
            break
        items.append(p_subscript(s))
    return items

#subscript: '.' '.' '.' | test | [test] ':' [test] [':' [test]]

def p_subscript(s):
    # Parse a subscript and return a list of
    # 1, 2 or 3 ExprNodes, depending on how
    # many slice elements were encountered.
    pos = s.position()
    if s.sy == '.':
        expect_ellipsis(s)
        return [ExprNodes.EllipsisNode(pos)]
    else:
        start = p_slice_element(s, (':',))
Stefan Behnel's avatar
Stefan Behnel committed
505
        if s.sy != ':':
William Stein's avatar
William Stein committed
506 507 508
            return [start]
        s.next()
        stop = p_slice_element(s, (':', ',', ']'))
Stefan Behnel's avatar
Stefan Behnel committed
509
        if s.sy != ':':
William Stein's avatar
William Stein committed
510 511 512 513 514 515 516 517 518
            return [start, stop]
        s.next()
        step = p_slice_element(s, (':', ',', ']'))
        return [start, stop, step]

def p_slice_element(s, follow_set):
    # Simple expression which may be missing iff
    # it is followed by something in follow_set.
    if s.sy not in follow_set:
519
        return p_test(s)
William Stein's avatar
William Stein committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
    else:
        return None

def expect_ellipsis(s):
    s.expect('.')
    s.expect('.')
    s.expect('.')

def make_slice_nodes(pos, subscripts):
    # Convert a list of subscripts as returned
    # by p_subscript_list into a list of ExprNodes,
    # creating SliceNodes for elements with 2 or
    # more components.
    result = []
    for subscript in subscripts:
        if len(subscript) == 1:
            result.append(subscript[0])
        else:
            result.append(make_slice_node(pos, *subscript))
    return result

def make_slice_node(pos, start, stop = None, step = None):
    if not start:
        start = ExprNodes.NoneNode(pos)
    if not stop:
        stop = ExprNodes.NoneNode(pos)
    if not step:
        step = ExprNodes.NoneNode(pos)
    return ExprNodes.SliceNode(pos,
        start = start, stop = stop, step = step)

551
#atom: '(' [yield_expr|testlist_comp] ')' | '[' [listmaker] ']' | '{' [dict_or_set_maker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+
William Stein's avatar
William Stein committed
552 553 554 555 556 557 558 559

def p_atom(s):
    pos = s.position()
    sy = s.sy
    if sy == '(':
        s.next()
        if s.sy == ')':
            result = ExprNodes.TupleNode(pos, args = [])
560 561
        elif s.sy == 'yield':
            result = p_yield_expression(s)
William Stein's avatar
William Stein committed
562
        else:
563
            result = p_testlist_comp(s)
William Stein's avatar
William Stein committed
564 565 566 567 568
        s.expect(')')
        return result
    elif sy == '[':
        return p_list_maker(s)
    elif sy == '{':
569
        return p_dict_or_set_maker(s)
William Stein's avatar
William Stein committed
570 571 572
    elif sy == '`':
        return p_backquote_expr(s)
    elif sy == 'INT':
573
        value = s.systring
William Stein's avatar
William Stein committed
574
        s.next()
575 576 577 578 579 580 581 582 583 584 585 586
        unsigned = ""
        longness = ""
        while value[-1] in "UuLl":
            if value[-1] in "Ll":
                longness += "L"
            else:
                unsigned += "U"
            value = value[:-1]
        return ExprNodes.IntNode(pos, 
                                 value = value,
                                 unsigned = unsigned,
                                 longness = longness)
William Stein's avatar
William Stein committed
587 588 589 590 591 592 593 594
    elif sy == 'FLOAT':
        value = s.systring
        s.next()
        return ExprNodes.FloatNode(pos, value = value)
    elif sy == 'IMAG':
        value = s.systring[:-1]
        s.next()
        return ExprNodes.ImagNode(pos, value = value)
595
    elif sy == 'BEGIN_STRING':
William Stein's avatar
William Stein committed
596 597 598
        kind, value = p_cat_string_literal(s)
        if kind == 'c':
            return ExprNodes.CharNode(pos, value = value)
599 600
        elif kind == 'u':
            return ExprNodes.UnicodeNode(pos, value = value)
601 602
        elif kind == 'b':
            return ExprNodes.BytesNode(pos, value = value)
William Stein's avatar
William Stein committed
603 604 605
        else:
            return ExprNodes.StringNode(pos, value = value)
    elif sy == 'IDENT':
606
        name = EncodedString( s.systring )
William Stein's avatar
William Stein committed
607 608 609
        s.next()
        if name == "None":
            return ExprNodes.NoneNode(pos)
610
        elif name == "True":
611
            return ExprNodes.BoolNode(pos, value=True)
612
        elif name == "False":
613
            return ExprNodes.BoolNode(pos, value=False)
614 615
        elif name == "NULL":
            return ExprNodes.NullNode(pos)
William Stein's avatar
William Stein committed
616
        else:
617
            return p_name(s, name)
William Stein's avatar
William Stein committed
618 619 620
    else:
        s.error("Expected an identifier or literal")

621 622
def p_name(s, name):
    pos = s.position()
623 624 625 626 627 628 629 630 631 632 633
    if not s.compile_time_expr and name in s.compile_time_env:
        value = s.compile_time_env.lookup_here(name)
        rep = repr(value)
        if isinstance(value, bool):
            return ExprNodes.BoolNode(pos, value = value)
        elif isinstance(value, int):
            return ExprNodes.IntNode(pos, value = rep)
        elif isinstance(value, long):
            return ExprNodes.IntNode(pos, value = rep, longness = "L")
        elif isinstance(value, float):
            return ExprNodes.FloatNode(pos, value = rep)
634 635 636 637
        elif isinstance(value, _unicode):
            return ExprNodes.UnicodeNode(pos, value = value)
        elif isinstance(value, _bytes):
            return ExprNodes.BytesNode(pos, value = value)
638
        else:
639 640
            error(pos, "Invalid type for compile-time constant: %s"
                % value.__class__.__name__)
641 642
    return ExprNodes.NameNode(pos, name = name)

William Stein's avatar
William Stein committed
643 644
def p_cat_string_literal(s):
    # A sequence of one or more adjacent string literals.
645
    # Returns (kind, value) where kind in ('b', 'c', 'u', '')
William Stein's avatar
William Stein committed
646
    kind, value = p_string_literal(s)
647 648
    if s.sy != 'BEGIN_STRING':
        return kind, value
Stefan Behnel's avatar
Stefan Behnel committed
649
    if kind != 'c':
William Stein's avatar
William Stein committed
650
        strings = [value]
651
        while s.sy == 'BEGIN_STRING':
652
            pos = s.position()
William Stein's avatar
William Stein committed
653 654
            next_kind, next_value = p_string_literal(s)
            if next_kind == 'c':
655
                error(pos, "Cannot concatenate char literal with another string or char literal")
656
            elif next_kind != kind:
657 658
                error(pos, "Cannot mix string literals of different types, expected %s'', got %s''" %
                      (kind, next_kind))
659 660 661 662 663
            else:
                strings.append(next_value)
        if kind == 'u':
            value = EncodedString( u''.join(strings) )
        else:
Stefan Behnel's avatar
Stefan Behnel committed
664
            value = BytesLiteral( StringEncoding.join_bytes(strings) )
665
            value.encoding = s.source_encoding
William Stein's avatar
William Stein committed
666 667 668
    return kind, value

def p_opt_string_literal(s):
669
    if s.sy == 'BEGIN_STRING':
William Stein's avatar
William Stein committed
670 671 672 673
        return p_string_literal(s)
    else:
        return None

674
def p_string_literal(s, kind_override=None):
William Stein's avatar
William Stein committed
675
    # A single string or char literal.
Stefan Behnel's avatar
Stefan Behnel committed
676
    # Returns (kind, value) where kind in ('b', 'c', 'u', '')
William Stein's avatar
William Stein committed
677 678
    # s.sy == 'BEGIN_STRING'
    pos = s.position()
679
    is_raw = 0
William Stein's avatar
William Stein committed
680
    kind = s.systring[:1].lower()
681 682 683 684 685 686
    if kind == 'r':
        kind = ''
        is_raw = 1
    elif kind in 'ub':
        is_raw = s.systring[1:2].lower() == 'r'
    elif kind != 'c':
William Stein's avatar
William Stein committed
687
        kind = ''
Stefan Behnel's avatar
Stefan Behnel committed
688 689 690
    if Future.unicode_literals in s.context.future_directives:
        if kind == '':
            kind = 'u'
691 692
    if kind_override is not None and kind_override in 'ub':
        kind = kind_override
693 694 695 696
    if kind == 'u':
        chars = StringEncoding.UnicodeLiteralBuilder()
    else:
        chars = StringEncoding.BytesLiteralBuilder(s.source_encoding)
William Stein's avatar
William Stein committed
697 698 699 700 701
    while 1:
        s.next()
        sy = s.sy
        #print "p_string_literal: sy =", sy, repr(s.systring) ###
        if sy == 'CHARS':
702
            chars.append(s.systring)
William Stein's avatar
William Stein committed
703
        elif sy == 'ESCAPE':
704
            has_escape = True
William Stein's avatar
William Stein committed
705
            systr = s.systring
706
            if is_raw:
707 708 709 710 711 712
                if systr == u'\\\n':
                    chars.append(u'\\\n')
                elif systr == u'\\\"':
                    chars.append(u'"')
                elif systr == u'\\\'':
                    chars.append(u"'")
William Stein's avatar
William Stein committed
713
                else:
714
                    chars.append(systr)
William Stein's avatar
William Stein committed
715 716
            else:
                c = systr[1]
717 718 719
                if c in u"01234567":
                    chars.append_charval( int(systr[1:], 8) )
                elif c in u"'\"\\":
720
                    chars.append(c)
721 722 723 724
                elif c in u"abfnrtv":
                    chars.append(
                        StringEncoding.char_from_escape_sequence(systr))
                elif c == u'\n':
William Stein's avatar
William Stein committed
725
                    pass
726
                elif c in u'Uux':
727 728
                    if kind == 'u' or c == 'x':
                        chrval = int(systr[2:], 16)
729
                        if chrval > 1114111: # sys.maxunicode:
730 731
                            s.error("Invalid unicode escape '%s'" % systr,
                                    pos = pos)
732 733 734 735 736
                        elif chrval > 65535:
                            warning(s.position(),
                                    "Unicode characters above 65535 are not "
                                    "necessarily portable across Python installations", 1)
                        chars.append_charval(chrval)
737
                    else:
738
                        # unicode escapes in plain byte strings are not unescaped
739
                        chars.append(systr)
William Stein's avatar
William Stein committed
740
                else:
741
                    chars.append(u'\\' + systr[1:])
William Stein's avatar
William Stein committed
742
        elif sy == 'NEWLINE':
743
            chars.append(u'\n')
William Stein's avatar
William Stein committed
744 745 746 747 748 749 750 751
        elif sy == 'END_STRING':
            break
        elif sy == 'EOF':
            s.error("Unclosed string literal", pos = pos)
        else:
            s.error(
                "Unexpected token %r:%r in string literal" %
                    (sy, s.systring))
752 753 754 755 756 757
    if kind == 'c':
        value = chars.getchar()
        if len(value) != 1:
            error(pos, u"invalid character literal: %r" % value)
    else:
        value = chars.getstring()
William Stein's avatar
William Stein committed
758 759 760 761
    s.next()
    #print "p_string_literal: value =", repr(value) ###
    return kind, value

Robert Bradshaw's avatar
Robert Bradshaw committed
762
# list_display      ::=      "[" [listmaker] "]"
Stefan Behnel's avatar
Stefan Behnel committed
763 764 765 766
# listmaker     ::=     expression ( comp_for | ( "," expression )* [","] )
# comp_iter     ::=     comp_for | comp_if
# comp_for     ::=     "for" expression_list "in" testlist [comp_iter]
# comp_if     ::=     "if" test [comp_iter]
Robert Bradshaw's avatar
Robert Bradshaw committed
767
        
William Stein's avatar
William Stein committed
768 769 770 771
def p_list_maker(s):
    # s.sy == '['
    pos = s.position()
    s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
772 773 774
    if s.sy == ']':
        s.expect(']')
        return ExprNodes.ListNode(pos, args = [])
775
    expr = p_test(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
776
    if s.sy == 'for':
777 778 779
        target = ExprNodes.ListNode(pos, args = [])
        append = ExprNodes.ComprehensionAppendNode(
            pos, expr=expr, target=ExprNodes.CloneNode(target))
780
        loop = p_comp_for(s, append)
Robert Bradshaw's avatar
Robert Bradshaw committed
781
        s.expect(']')
782
        return ExprNodes.ComprehensionNode(
783 784
            pos, loop=loop, append=append, target=target,
            # list comprehensions leak their loop variable in Py2
Stefan Behnel's avatar
Stefan Behnel committed
785
            has_local_scope = s.context.language_level >= 3)
Robert Bradshaw's avatar
Robert Bradshaw committed
786 787 788
    else:
        if s.sy == ',':
            s.next()
789 790 791
            exprs = p_simple_expr_list(s, expr)
        else:
            exprs = [expr]
Robert Bradshaw's avatar
Robert Bradshaw committed
792 793 794
        s.expect(']')
        return ExprNodes.ListNode(pos, args = exprs)
        
Stefan Behnel's avatar
Stefan Behnel committed
795
def p_comp_iter(s, body):
Robert Bradshaw's avatar
Robert Bradshaw committed
796
    if s.sy == 'for':
Stefan Behnel's avatar
Stefan Behnel committed
797
        return p_comp_for(s, body)
Robert Bradshaw's avatar
Robert Bradshaw committed
798
    elif s.sy == 'if':
Stefan Behnel's avatar
Stefan Behnel committed
799
        return p_comp_if(s, body)
Robert Bradshaw's avatar
Robert Bradshaw committed
800
    else:
801 802
        # insert the 'append' operation into the loop
        return body
William Stein's avatar
William Stein committed
803

Stefan Behnel's avatar
Stefan Behnel committed
804
def p_comp_for(s, body):
Robert Bradshaw's avatar
Robert Bradshaw committed
805 806 807
    # s.sy == 'for'
    pos = s.position()
    s.next()
808
    kw = p_for_bounds(s, allow_testlist=False)
Robert Bradshaw's avatar
Robert Bradshaw committed
809
    kw['else_clause'] = None
Stefan Behnel's avatar
Stefan Behnel committed
810
    kw['body'] = p_comp_iter(s, body)
Robert Bradshaw's avatar
Robert Bradshaw committed
811 812
    return Nodes.ForStatNode(pos, **kw)
        
Stefan Behnel's avatar
Stefan Behnel committed
813
def p_comp_if(s, body):
Robert Bradshaw's avatar
Robert Bradshaw committed
814 815 816
    # s.sy == 'if'
    pos = s.position()
    s.next()
Stefan Behnel's avatar
Stefan Behnel committed
817
    test = p_test_nocond(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
818
    return Nodes.IfStatNode(pos, 
819
        if_clauses = [Nodes.IfClauseNode(pos, condition = test,
Stefan Behnel's avatar
Stefan Behnel committed
820
                                         body = p_comp_iter(s, body))],
Robert Bradshaw's avatar
Robert Bradshaw committed
821
        else_clause = None )
822

William Stein's avatar
William Stein committed
823 824
#dictmaker: test ':' test (',' test ':' test)* [',']

825
def p_dict_or_set_maker(s):
William Stein's avatar
William Stein committed
826 827 828
    # s.sy == '{'
    pos = s.position()
    s.next()
829
    if s.sy == '}':
William Stein's avatar
William Stein committed
830
        s.next()
831
        return ExprNodes.DictNode(pos, key_value_pairs = [])
832
    item = p_test(s)
833 834 835 836 837
    if s.sy == ',' or s.sy == '}':
        # set literal
        values = [item]
        while s.sy == ',':
            s.next()
838 839
            if s.sy == '}':
                break
840
            values.append( p_test(s) )
841 842 843 844
        s.expect('}')
        return ExprNodes.SetNode(pos, args=values)
    elif s.sy == 'for':
        # set comprehension
845 846 847
        target = ExprNodes.SetNode(pos, args=[])
        append = ExprNodes.ComprehensionAppendNode(
            item.pos, expr=item, target=ExprNodes.CloneNode(target))
848
        loop = p_comp_for(s, append)
849
        s.expect('}')
850 851
        return ExprNodes.ComprehensionNode(
            pos, loop=loop, append=append, target=target)
852 853 854 855
    elif s.sy == ':':
        # dict literal or comprehension
        key = item
        s.next()
856
        value = p_test(s)
857 858
        if s.sy == 'for':
            # dict comprehension
859
            target = ExprNodes.DictNode(pos, key_value_pairs = [])
860
            append = ExprNodes.DictComprehensionAppendNode(
861 862
                item.pos, key_expr=key, value_expr=value,
                target=ExprNodes.CloneNode(target))
863
            loop = p_comp_for(s, append)
864 865 866
            s.expect('}')
            return ExprNodes.ComprehensionNode(
                pos, loop=loop, append=append, target=target)
867 868 869 870 871
        else:
            # dict literal
            items = [ExprNodes.DictItemNode(key.pos, key=key, value=value)]
            while s.sy == ',':
                s.next()
872 873
                if s.sy == '}':
                    break
874
                key = p_test(s)
875
                s.expect(':')
876
                value = p_test(s)
877 878 879 880 881 882 883 884
                items.append(
                    ExprNodes.DictItemNode(key.pos, key=key, value=value))
            s.expect('}')
            return ExprNodes.DictNode(pos, key_value_pairs=items)
    else:
        # raise an error
        s.expect('}')
    return ExprNodes.DictNode(pos, key_value_pairs = [])
William Stein's avatar
William Stein committed
885

886
# NOTE: no longer in Py3 :)
William Stein's avatar
William Stein committed
887 888 889 890
def p_backquote_expr(s):
    # s.sy == '`'
    pos = s.position()
    s.next()
891 892 893 894
    args = [p_test(s)]
    while s.sy == ',':
        s.next()
        args.append(p_test(s))
William Stein's avatar
William Stein committed
895
    s.expect('`')
896 897 898 899
    if len(args) == 1:
        arg = args[0]
    else:
        arg = ExprNodes.TupleNode(pos, args = args)
William Stein's avatar
William Stein committed
900 901
    return ExprNodes.BackquoteNode(pos, arg = arg)

902 903
def p_simple_expr_list(s, expr=None):
    exprs = expr is not None and [expr] or []
William Stein's avatar
William Stein committed
904
    while s.sy not in expr_terminators:
905
        exprs.append( p_test(s) )
Stefan Behnel's avatar
Stefan Behnel committed
906
        if s.sy != ',':
William Stein's avatar
William Stein committed
907 908 909 910
            break
        s.next()
    return exprs

911 912 913 914 915 916 917 918 919 920 921 922 923
def p_test_or_starred_expr_list(s, expr=None):
    exprs = expr is not None and [expr] or []
    while s.sy not in expr_terminators:
        exprs.append( p_test_or_starred_expr(s) )
        if s.sy != ',':
            break
        s.next()
    return exprs
    

#testlist: test (',' test)* [',']

def p_testlist(s):
William Stein's avatar
William Stein committed
924
    pos = s.position()
925
    expr = p_test(s)
William Stein's avatar
William Stein committed
926 927
    if s.sy == ',':
        s.next()
928
        exprs = p_simple_expr_list(s, expr)
William Stein's avatar
William Stein committed
929 930 931 932
        return ExprNodes.TupleNode(pos, args = exprs)
    else:
        return expr

933
# testlist_star_expr: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
Robert Bradshaw's avatar
Robert Bradshaw committed
934

935
def p_testlist_star_expr(s):
Robert Bradshaw's avatar
Robert Bradshaw committed
936
    pos = s.position()
937
    expr = p_test_or_starred_expr(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
938
    if s.sy == ',':
939
        s.next()
940 941
        exprs = p_test_or_starred_expr_list(s, expr)
        return ExprNodes.TupleNode(pos, args = exprs)
Robert Bradshaw's avatar
Robert Bradshaw committed
942 943 944
    else:
        return expr

945 946 947
# testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )

def p_testlist_comp(s):
Robert Bradshaw's avatar
Robert Bradshaw committed
948
    pos = s.position()
949
    expr = p_test_or_starred_expr(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
950
    if s.sy == ',':
951
        s.next()
952
        exprs = p_test_or_starred_expr_list(s, expr)
Robert Bradshaw's avatar
Robert Bradshaw committed
953
        return ExprNodes.TupleNode(pos, args = exprs)
954 955
    elif s.sy == 'for':
        return p_genexp(s, expr)
Robert Bradshaw's avatar
Robert Bradshaw committed
956 957
    else:
        return expr
958 959 960

def p_genexp(s, expr):
    # s.sy == 'for'
961 962
    loop = p_comp_for(s, Nodes.ExprStatNode(
        expr.pos, expr = ExprNodes.YieldExprNode(expr.pos, arg=expr)))
963 964
    return ExprNodes.GeneratorExpressionNode(expr.pos, loop=loop)

William Stein's avatar
William Stein committed
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
expr_terminators = (')', ']', '}', ':', '=', 'NEWLINE')

#-------------------------------------------------------
#
#   Statements
#
#-------------------------------------------------------

def p_global_statement(s):
    # assume s.sy == 'global'
    pos = s.position()
    s.next()
    names = p_ident_list(s)
    return Nodes.GlobalNode(pos, names = names)

def p_expression_or_assignment(s):
981
    expr_list = [p_testlist_star_expr(s)]
William Stein's avatar
William Stein committed
982 983
    while s.sy == '=':
        s.next()
984 985 986 987 988
        if s.sy == 'yield':
            expr = p_yield_expression(s)
        else:
            expr = p_testlist_star_expr(s)
        expr_list.append(expr)
William Stein's avatar
William Stein committed
989
    if len(expr_list) == 1:
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
990
        if re.match(r"([+*/\%^\&|-]|<<|>>|\*\*|//)=", s.sy):
991 992 993
            lhs = expr_list[0]
            if not isinstance(lhs, (ExprNodes.AttributeNode, ExprNodes.IndexNode, ExprNodes.NameNode) ):
                error(lhs.pos, "Illegal operand for inplace operation.")
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
994
            operator = s.sy[:-1]
995
            s.next()
996 997 998 999
            if s.sy == 'yield':
                rhs = p_yield_expression(s)
            else:
                rhs = p_testlist(s)
1000
            return Nodes.InPlaceAssignmentNode(lhs.pos, operator = operator, lhs = lhs, rhs = rhs)
1001
        expr = expr_list[0]
1002
        if isinstance(expr, (ExprNodes.UnicodeNode, ExprNodes.StringNode, ExprNodes.BytesNode)):
1003
            return Nodes.PassStatNode(expr.pos)
1004 1005
        else:
            return Nodes.ExprStatNode(expr.pos, expr = expr)
1006

1007 1008
    rhs = expr_list[-1]
    if len(expr_list) == 2:
1009
        return Nodes.SingleAssignmentNode(rhs.pos, 
1010
            lhs = expr_list[0], rhs = rhs)
William Stein's avatar
William Stein committed
1011
    else:
1012
        return Nodes.CascadedAssignmentNode(rhs.pos,
1013
            lhs_list = expr_list[:-1], rhs = rhs)
William Stein's avatar
William Stein committed
1014 1015 1016 1017

def p_print_statement(s):
    # s.sy == 'print'
    pos = s.position()
1018
    ends_with_comma = 0
William Stein's avatar
William Stein committed
1019 1020
    s.next()
    if s.sy == '>>':
1021
        s.next()
1022
        stream = p_test(s)
1023 1024 1025 1026 1027
        if s.sy == ',':
            s.next()
            ends_with_comma = s.sy in ('NEWLINE', 'EOF')
    else:
        stream = None
William Stein's avatar
William Stein committed
1028 1029
    args = []
    if s.sy not in ('NEWLINE', 'EOF'):
1030
        args.append(p_test(s))
William Stein's avatar
William Stein committed
1031 1032 1033
        while s.sy == ',':
            s.next()
            if s.sy in ('NEWLINE', 'EOF'):
1034
                ends_with_comma = 1
William Stein's avatar
William Stein committed
1035
                break
1036
            args.append(p_test(s))
1037
    arg_tuple = ExprNodes.TupleNode(pos, args = args)
1038
    return Nodes.PrintStatNode(pos,
1039 1040
        arg_tuple = arg_tuple, stream = stream,
        append_newline = not ends_with_comma)
William Stein's avatar
William Stein committed
1041

1042 1043 1044 1045 1046 1047 1048
def p_exec_statement(s):
    # s.sy == 'exec'
    pos = s.position()
    s.next()
    args = [ p_bit_expr(s) ]
    if s.sy == 'in':
        s.next()
1049
        args.append(p_test(s))
1050 1051
        if s.sy == ',':
            s.next()
1052
            args.append(p_test(s))
1053 1054 1055 1056
    else:
        error(pos, "'exec' currently requires a target mapping (globals/locals)")
    return Nodes.ExecStatNode(pos, args = args)

William Stein's avatar
William Stein committed
1057 1058 1059 1060
def p_del_statement(s):
    # s.sy == 'del'
    pos = s.position()
    s.next()
1061
    # FIXME: 'exprlist' in Python
William Stein's avatar
William Stein committed
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
    args = p_simple_expr_list(s)
    return Nodes.DelStatNode(pos, args = args)

def p_pass_statement(s, with_newline = 0):
    pos = s.position()
    s.expect('pass')
    if with_newline:
        s.expect_newline("Expected a newline")
    return Nodes.PassStatNode(pos)

def p_break_statement(s):
    # s.sy == 'break'
    pos = s.position()
    s.next()
    return Nodes.BreakStatNode(pos)

def p_continue_statement(s):
    # s.sy == 'continue'
    pos = s.position()
    s.next()
    return Nodes.ContinueStatNode(pos)

def p_return_statement(s):
    # s.sy == 'return'
    pos = s.position()
    s.next()
    if s.sy not in statement_terminators:
1089
        value = p_testlist(s)
William Stein's avatar
William Stein committed
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    else:
        value = None
    return Nodes.ReturnStatNode(pos, value = value)

def p_raise_statement(s):
    # s.sy == 'raise'
    pos = s.position()
    s.next()
    exc_type = None
    exc_value = None
    exc_tb = None
    if s.sy not in statement_terminators:
1102
        exc_type = p_test(s)
William Stein's avatar
William Stein committed
1103 1104
        if s.sy == ',':
            s.next()
1105
            exc_value = p_test(s)
William Stein's avatar
William Stein committed
1106 1107
            if s.sy == ',':
                s.next()
1108
                exc_tb = p_test(s)
1109 1110 1111 1112 1113 1114 1115
    if exc_type or exc_value or exc_tb:
        return Nodes.RaiseStatNode(pos, 
            exc_type = exc_type,
            exc_value = exc_value,
            exc_tb = exc_tb)
    else:
        return Nodes.ReraiseStatNode(pos)
William Stein's avatar
William Stein committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127

def p_import_statement(s):
    # s.sy in ('import', 'cimport')
    pos = s.position()
    kind = s.sy
    s.next()
    items = [p_dotted_name(s, as_allowed = 1)]
    while s.sy == ',':
        s.next()
        items.append(p_dotted_name(s, as_allowed = 1))
    stats = []
    for pos, target_name, dotted_name, as_name in items:
1128
        dotted_name = EncodedString(dotted_name)
William Stein's avatar
William Stein committed
1129 1130 1131 1132 1133
        if kind == 'cimport':
            stat = Nodes.CImportStatNode(pos, 
                module_name = dotted_name,
                as_name = as_name)
        else:
1134 1135
            if as_name and "." in dotted_name:
                name_list = ExprNodes.ListNode(pos, args = [
1136
                        ExprNodes.IdentifierStringNode(pos, value = EncodedString("*"))])
1137 1138
            else:
                name_list = None
William Stein's avatar
William Stein committed
1139 1140 1141 1142
            stat = Nodes.SingleAssignmentNode(pos,
                lhs = ExprNodes.NameNode(pos, 
                    name = as_name or target_name),
                rhs = ExprNodes.ImportNode(pos, 
1143
                    module_name = ExprNodes.IdentifierStringNode(
1144
                        pos, value = dotted_name),
1145
                    name_list = name_list))
William Stein's avatar
William Stein committed
1146 1147 1148
        stats.append(stat)
    return Nodes.StatListNode(pos, stats = stats)

Stefan Behnel's avatar
Stefan Behnel committed
1149
def p_from_import_statement(s, first_statement = 0):
William Stein's avatar
William Stein committed
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    # s.sy == 'from'
    pos = s.position()
    s.next()
    (dotted_name_pos, _, dotted_name, _) = \
        p_dotted_name(s, as_allowed = 0)
    if s.sy in ('import', 'cimport'):
        kind = s.sy
        s.next()
    else:
        s.error("Expected 'import' or 'cimport'")
1160
    is_cimport = kind == 'cimport'
1161
    is_parenthesized = False
William Stein's avatar
William Stein committed
1162
    if s.sy == '*':
1163
        imported_names = [(s.position(), "*", None, None)]
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1164 1165
        s.next()
    else:
1166 1167 1168
        if s.sy == '(':
            is_parenthesized = True
            s.next()
1169
        imported_names = [p_imported_name(s, is_cimport)]
William Stein's avatar
William Stein committed
1170 1171
    while s.sy == ',':
        s.next()
1172 1173
        if is_parenthesized and s.sy == ')':
            break
1174
        imported_names.append(p_imported_name(s, is_cimport))
1175 1176
    if is_parenthesized:
        s.expect(')')
1177
    dotted_name = EncodedString(dotted_name)
Stefan Behnel's avatar
Stefan Behnel committed
1178 1179 1180 1181
    if dotted_name == '__future__':
        if not first_statement:
            s.error("from __future__ imports must occur at the beginning of the file")
        else:
1182
            for (name_pos, name, as_name, kind) in imported_names:
1183 1184 1185
                if name == "braces":
                    s.error("not a chance", name_pos)
                    break
Stefan Behnel's avatar
Stefan Behnel committed
1186 1187 1188
                try:
                    directive = getattr(Future, name)
                except AttributeError:
1189
                    s.error("future feature %s is not defined" % name, name_pos)
Stefan Behnel's avatar
Stefan Behnel committed
1190 1191 1192 1193
                    break
                s.context.future_directives.add(directive)
        return Nodes.PassStatNode(pos)
    elif kind == 'cimport':
William Stein's avatar
William Stein committed
1194 1195 1196 1197 1198 1199
        return Nodes.FromCImportStatNode(pos,
            module_name = dotted_name,
            imported_names = imported_names)
    else:
        imported_name_strings = []
        items = []
1200
        for (name_pos, name, as_name, kind) in imported_names:
1201
            encoded_name = EncodedString(name)
William Stein's avatar
William Stein committed
1202
            imported_name_strings.append(
1203
                ExprNodes.IdentifierStringNode(name_pos, value = encoded_name))
William Stein's avatar
William Stein committed
1204 1205 1206
            items.append(
                (name,
                 ExprNodes.NameNode(name_pos, 
Stefan Behnel's avatar
Stefan Behnel committed
1207
                                    name = as_name or name)))
William Stein's avatar
William Stein committed
1208 1209
        import_list = ExprNodes.ListNode(
            imported_names[0][0], args = imported_name_strings)
1210
        dotted_name = EncodedString(dotted_name)
William Stein's avatar
William Stein committed
1211 1212
        return Nodes.FromImportStatNode(pos,
            module = ExprNodes.ImportNode(dotted_name_pos,
1213
                module_name = ExprNodes.IdentifierStringNode(pos, value = dotted_name),
William Stein's avatar
William Stein committed
1214 1215 1216
                name_list = import_list),
            items = items)

1217 1218 1219
imported_name_kinds = ('class', 'struct', 'union')

def p_imported_name(s, is_cimport):
William Stein's avatar
William Stein committed
1220
    pos = s.position()
1221 1222 1223 1224
    kind = None
    if is_cimport and s.systring in imported_name_kinds:
        kind = s.systring
        s.next()
William Stein's avatar
William Stein committed
1225 1226
    name = p_ident(s)
    as_name = p_as_name(s)
1227
    return (pos, name, as_name, kind)
William Stein's avatar
William Stein committed
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238

def p_dotted_name(s, as_allowed):
    pos = s.position()
    target_name = p_ident(s)
    as_name = None
    names = [target_name]
    while s.sy == '.':
        s.next()
        names.append(p_ident(s))
    if as_allowed:
        as_name = p_as_name(s)
Stefan Behnel's avatar
Stefan Behnel committed
1239
    return (pos, target_name, u'.'.join(names), as_name)
William Stein's avatar
William Stein committed
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251

def p_as_name(s):
    if s.sy == 'IDENT' and s.systring == 'as':
        s.next()
        return p_ident(s)
    else:
        return None

def p_assert_statement(s):
    # s.sy == 'assert'
    pos = s.position()
    s.next()
1252
    cond = p_test(s)
William Stein's avatar
William Stein committed
1253 1254
    if s.sy == ',':
        s.next()
1255
        value = p_test(s)
William Stein's avatar
William Stein committed
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
    else:
        value = None
    return Nodes.AssertStatNode(pos, cond = cond, value = value)

statement_terminators = (';', 'NEWLINE', 'EOF')

def p_if_statement(s):
    # s.sy == 'if'
    pos = s.position()
    s.next()
    if_clauses = [p_if_clause(s)]
    while s.sy == 'elif':
        s.next()
        if_clauses.append(p_if_clause(s))
    else_clause = p_else_clause(s)
    return Nodes.IfStatNode(pos,
        if_clauses = if_clauses, else_clause = else_clause)

def p_if_clause(s):
    pos = s.position()
1276
    test = p_test(s)
William Stein's avatar
William Stein committed
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
    body = p_suite(s)
    return Nodes.IfClauseNode(pos,
        condition = test, body = body)

def p_else_clause(s):
    if s.sy == 'else':
        s.next()
        return p_suite(s)
    else:
        return None

def p_while_statement(s):
    # s.sy == 'while'
    pos = s.position()
    s.next()
1292
    test = p_test(s)
William Stein's avatar
William Stein committed
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
    body = p_suite(s)
    else_clause = p_else_clause(s)
    return Nodes.WhileStatNode(pos, 
        condition = test, body = body, 
        else_clause = else_clause)

def p_for_statement(s):
    # s.sy == 'for'
    pos = s.position()
    s.next()
1303
    kw = p_for_bounds(s, allow_testlist=True)
Robert Bradshaw's avatar
Robert Bradshaw committed
1304 1305 1306 1307
    kw['body'] = p_suite(s)
    kw['else_clause'] = p_else_clause(s)
    return Nodes.ForStatNode(pos, **kw)
            
1308
def p_for_bounds(s, allow_testlist=True):
William Stein's avatar
William Stein committed
1309 1310 1311
    target = p_for_target(s)
    if s.sy == 'in':
        s.next()
1312
        iterator = p_for_iterator(s, allow_testlist)
Robert Bradshaw's avatar
Robert Bradshaw committed
1313
        return { 'target': target, 'iterator': iterator }
1314
    elif not s.in_python_file:
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1315 1316 1317 1318 1319 1320
        if s.sy == 'from':
            s.next()
            bound1 = p_bit_expr(s)
        else:
            # Support shorter "for a <= x < b" syntax
            bound1, target = target, None
William Stein's avatar
William Stein committed
1321 1322 1323 1324 1325 1326
        rel1 = p_for_from_relation(s)
        name2_pos = s.position()
        name2 = p_ident(s)
        rel2_pos = s.position()
        rel2 = p_for_from_relation(s)
        bound2 = p_bit_expr(s)
1327
        step = p_for_from_step(s)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1328 1329 1330 1331 1332 1333 1334 1335 1336
        if target is None:
            target = ExprNodes.NameNode(name2_pos, name = name2)
        else:
            if not target.is_name:
                error(target.pos, 
                    "Target of for-from statement must be a variable name")
            elif name2 != target.name:
                error(name2_pos,
                    "Variable name in for-from range does not match target")
Stefan Behnel's avatar
Stefan Behnel committed
1337
        if rel1[0] != rel2[0]:
William Stein's avatar
William Stein committed
1338 1339
            error(rel2_pos,
                "Relation directions in for-from do not match")
Robert Bradshaw's avatar
Robert Bradshaw committed
1340 1341 1342 1343
        return {'target': target, 
                'bound1': bound1, 
                'relation1': rel1, 
                'relation2': rel2,
1344 1345
                'bound2': bound2,
                'step': step }
1346 1347 1348
    else:
        s.expect('in')
        return {}
William Stein's avatar
William Stein committed
1349 1350 1351 1352 1353 1354 1355 1356

def p_for_from_relation(s):
    if s.sy in inequality_relations:
        op = s.sy
        s.next()
        return op
    else:
        s.error("Expected one of '<', '<=', '>' '>='")
1357

1358 1359 1360 1361 1362 1363 1364
def p_for_from_step(s):
    if s.sy == 'by':
        s.next()
        step = p_bit_expr(s)
        return step
    else:
        return None
William Stein's avatar
William Stein committed
1365 1366 1367

inequality_relations = ('<', '<=', '>', '>=')

1368
def p_target(s, terminator):
William Stein's avatar
William Stein committed
1369
    pos = s.position()
1370
    expr = p_starred_expr(s)
William Stein's avatar
William Stein committed
1371 1372 1373
    if s.sy == ',':
        s.next()
        exprs = [expr]
1374
        while s.sy != terminator:
1375
            exprs.append(p_starred_expr(s))
Stefan Behnel's avatar
Stefan Behnel committed
1376
            if s.sy != ',':
William Stein's avatar
William Stein committed
1377 1378 1379 1380 1381 1382
                break
            s.next()
        return ExprNodes.TupleNode(pos, args = exprs)
    else:
        return expr

1383 1384 1385
def p_for_target(s):
    return p_target(s, 'in')

1386
def p_for_iterator(s, allow_testlist=True):
William Stein's avatar
William Stein committed
1387
    pos = s.position()
1388 1389 1390 1391
    if allow_testlist:
        expr = p_testlist(s)
    else:
        expr = p_or_test(s)
William Stein's avatar
William Stein committed
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
    return ExprNodes.IteratorNode(pos, sequence = expr)

def p_try_statement(s):
    # s.sy == 'try'
    pos = s.position()
    s.next()
    body = p_suite(s)
    except_clauses = []
    else_clause = None
    if s.sy in ('except', 'else'):
        while s.sy == 'except':
            except_clauses.append(p_except_clause(s))
        if s.sy == 'else':
            s.next()
            else_clause = p_suite(s)
1407
        body = Nodes.TryExceptStatNode(pos,
William Stein's avatar
William Stein committed
1408 1409
            body = body, except_clauses = except_clauses,
            else_clause = else_clause)
1410 1411 1412 1413
        if s.sy != 'finally':
            return body
        # try-except-finally is equivalent to nested try-except/try-finally
    if s.sy == 'finally':
William Stein's avatar
William Stein committed
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
        s.next()
        finally_clause = p_suite(s)
        return Nodes.TryFinallyStatNode(pos,
            body = body, finally_clause = finally_clause)
    else:
        s.error("Expected 'except' or 'finally'")

def p_except_clause(s):
    # s.sy == 'except'
    pos = s.position()
    s.next()
    exc_type = None
    exc_value = None
Stefan Behnel's avatar
Stefan Behnel committed
1427
    if s.sy != ':':
1428
        exc_type = p_test(s)
1429
        if s.sy == ',' or (s.sy == 'IDENT' and s.systring == 'as'):
William Stein's avatar
William Stein committed
1430
            s.next()
1431
            exc_value = p_test(s)
1432
        elif s.sy == 'IDENT' and s.systring == 'as':
1433
            # Py3 syntax requires a name here
1434
            s.next()
1435 1436 1437
            pos2 = s.position()
            name = p_ident(s)
            exc_value = ExprNodes.NameNode(pos2, name = name)
William Stein's avatar
William Stein committed
1438 1439 1440 1441
    body = p_suite(s)
    return Nodes.ExceptClauseNode(pos,
        pattern = exc_type, target = exc_value, body = body)

1442
def p_include_statement(s, ctx):
William Stein's avatar
William Stein committed
1443 1444 1445 1446
    pos = s.position()
    s.next() # 'include'
    _, include_file_name = p_string_literal(s)
    s.expect_newline("Syntax error in include statement")
1447
    if s.compile_time_eval:
1448
        include_file_name = include_file_name.decode(s.source_encoding)
1449 1450
        include_file_path = s.context.find_include_file(include_file_name, pos)
        if include_file_path:
1451
            s.included_files.append(include_file_name)
1452
            f = Utils.open_source_file(include_file_path, mode="rU")
1453
            source_desc = FileSourceDescriptor(include_file_path)
1454
            s2 = PyrexScanner(f, source_desc, s, source_encoding=f.encoding, parse_comments=s.parse_comments)
1455
            try:
1456
                tree = p_statement_list(s2, ctx)
1457 1458 1459 1460 1461
            finally:
                f.close()
            return tree
        else:
            return None
William Stein's avatar
William Stein committed
1462
    else:
1463 1464 1465 1466 1467
        return Nodes.PassStatNode(pos)

def p_with_statement(s):
    pos = s.position()
    s.next() # 'with'
Robert Bradshaw's avatar
Robert Bradshaw committed
1468
#    if s.sy == 'IDENT' and s.systring in ('gil', 'nogil'):
1469 1470 1471 1472 1473
    if s.sy == 'IDENT' and s.systring == 'nogil':
        state = s.systring
        s.next()
        body = p_suite(s)
        return Nodes.GILStatNode(pos, state = state, body = body)
Danilo Freitas's avatar
Danilo Freitas committed
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
    elif s.systring == 'template':
        templates = []
        s.next()
        s.expect('[')
        #s.next()
        templates.append(s.systring)
        s.next()
        while s.systring == ',':
            s.next()
            templates.append(s.systring)
            s.next()
        s.expect(']')
        if s.sy == ':':
            s.next()
            s.expect_newline("Syntax error in template function declaration")
            s.expect_indent()
            body_ctx = Ctx()
            body_ctx.templates = templates
            func_or_var = p_c_func_or_var_declaration(s, pos, body_ctx)
            s.expect_dedent()
            return func_or_var
        else:
            error(pos, "Syntax error in template function declaration")
1497
    else:
1498
        manager = p_test(s)
1499 1500 1501 1502 1503 1504 1505 1506
        target = None
        if s.sy == 'IDENT' and s.systring == 'as':
            s.next()
            allow_multi = (s.sy == '(')
            target = p_target(s, ':')
            if not allow_multi and isinstance(target, ExprNodes.TupleNode):
                s.error("Multiple with statement target values not allowed without paranthesis")
        body = p_suite(s)
1507
    return Nodes.WithStatNode(pos, manager = manager, 
Robert Bradshaw's avatar
Robert Bradshaw committed
1508
                              target = target, body = body)
William Stein's avatar
William Stein committed
1509
    
Stefan Behnel's avatar
Stefan Behnel committed
1510
def p_simple_statement(s, first_statement = 0):
William Stein's avatar
William Stein committed
1511 1512 1513 1514 1515
    #print "p_simple_statement:", s.sy, s.systring ###
    if s.sy == 'global':
        node = p_global_statement(s)
    elif s.sy == 'print':
        node = p_print_statement(s)
1516 1517
    elif s.sy == 'exec':
        node = p_exec_statement(s)
William Stein's avatar
William Stein committed
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    elif s.sy == 'del':
        node = p_del_statement(s)
    elif s.sy == 'break':
        node = p_break_statement(s)
    elif s.sy == 'continue':
        node = p_continue_statement(s)
    elif s.sy == 'return':
        node = p_return_statement(s)
    elif s.sy == 'raise':
        node = p_raise_statement(s)
    elif s.sy in ('import', 'cimport'):
        node = p_import_statement(s)
    elif s.sy == 'from':
Stefan Behnel's avatar
Stefan Behnel committed
1531
        node = p_from_import_statement(s, first_statement = first_statement)
1532
    elif s.sy == 'yield':
1533
        node = p_yield_statement(s)
William Stein's avatar
William Stein committed
1534 1535 1536 1537 1538 1539 1540 1541
    elif s.sy == 'assert':
        node = p_assert_statement(s)
    elif s.sy == 'pass':
        node = p_pass_statement(s)
    else:
        node = p_expression_or_assignment(s)
    return node

1542
def p_simple_statement_list(s, ctx, first_statement = 0):
William Stein's avatar
William Stein committed
1543 1544
    # Parse a series of simple statements on one line
    # separated by semicolons.
Stefan Behnel's avatar
Stefan Behnel committed
1545
    stat = p_simple_statement(s, first_statement = first_statement)
William Stein's avatar
William Stein committed
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
    if s.sy == ';':
        stats = [stat]
        while s.sy == ';':
            #print "p_simple_statement_list: maybe more to follow" ###
            s.next()
            if s.sy in ('NEWLINE', 'EOF'):
                break
            stats.append(p_simple_statement(s))
        stat = Nodes.StatListNode(stats[0].pos, stats = stats)
    s.expect_newline("Syntax error in simple statement list")
    return stat

1558 1559 1560
def p_compile_time_expr(s):
    old = s.compile_time_expr
    s.compile_time_expr = 1
1561
    expr = p_testlist(s)
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
    s.compile_time_expr = old
    return expr

def p_DEF_statement(s):
    pos = s.position()
    denv = s.compile_time_env
    s.next() # 'DEF'
    name = p_ident(s)
    s.expect('=')
    expr = p_compile_time_expr(s)
    value = expr.compile_time_value(denv)
    #print "p_DEF_statement: %s = %r" % (name, value) ###
    denv.declare(name, value)
    s.expect_newline()
    return Nodes.PassStatNode(pos)

1578
def p_IF_statement(s, ctx):
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1579
    pos = s.position()
1580 1581 1582 1583 1584 1585 1586 1587
    saved_eval = s.compile_time_eval
    current_eval = saved_eval
    denv = s.compile_time_env
    result = None
    while 1:
        s.next() # 'IF' or 'ELIF'
        expr = p_compile_time_expr(s)
        s.compile_time_eval = current_eval and bool(expr.compile_time_value(denv))
1588
        body = p_suite(s, ctx)
1589 1590 1591
        if s.compile_time_eval:
            result = body
            current_eval = 0
Stefan Behnel's avatar
Stefan Behnel committed
1592
        if s.sy != 'ELIF':
1593 1594 1595 1596
            break
    if s.sy == 'ELSE':
        s.next()
        s.compile_time_eval = current_eval
1597
        body = p_suite(s, ctx)
1598 1599 1600
        if current_eval:
            result = body
    if not result:
Stefan Behnel's avatar
Stefan Behnel committed
1601
        result = Nodes.PassStatNode(pos)
1602 1603 1604
    s.compile_time_eval = saved_eval
    return result

1605 1606
def p_statement(s, ctx, first_statement = 0):
    cdef_flag = ctx.cdef_flag
Robert Bradshaw's avatar
Robert Bradshaw committed
1607
    decorators = None
William Stein's avatar
William Stein committed
1608
    if s.sy == 'ctypedef':
1609
        if ctx.level not in ('module', 'module_pxd'):
William Stein's avatar
William Stein committed
1610
            s.error("ctypedef statement not allowed here")
1611 1612
        #if ctx.api:
        #    error(s.position(), "'api' not allowed with 'ctypedef'")
1613
        return p_ctypedef_statement(s, ctx)
1614 1615 1616
    elif s.sy == 'DEF':
        return p_DEF_statement(s)
    elif s.sy == 'IF':
1617
        return p_IF_statement(s, ctx)
1618
    elif s.sy == 'DECORATOR':
1619
        if ctx.level not in ('module', 'class', 'c_class', 'function', 'property', 'module_pxd', 'c_class_pxd'):
1620
            print ctx.level
1621 1622 1623
            s.error('decorator not allowed here')
        s.level = ctx.level
        decorators = p_decorators(s)
1624 1625
        if s.sy not in ('def', 'cdef', 'cpdef', 'class'):
            s.error("Decorators can only be followed by functions or classes")
1626 1627 1628
    elif s.sy == 'pass' and cdef_flag:
        # empty cdef block
        return p_pass_statement(s, with_newline = 1)
1629 1630 1631 1632 1633

    overridable = 0
    if s.sy == 'cdef':
        cdef_flag = 1
        s.next()
1634
    elif s.sy == 'cpdef':
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
        cdef_flag = 1
        overridable = 1
        s.next()
    if cdef_flag:
        if ctx.level not in ('module', 'module_pxd', 'function', 'c_class', 'c_class_pxd'):
            s.error('cdef statement not allowed here')
        s.level = ctx.level
        node = p_cdef_statement(s, ctx(overridable = overridable))
        if decorators is not None:
            if not isinstance(node, (Nodes.CFuncDefNode, Nodes.CVarDefNode)):
1645
                s.error("Decorators can only be followed by functions or Python classes")
1646 1647
            node.decorators = decorators
        return node
William Stein's avatar
William Stein committed
1648
    else:
1649
        if ctx.api:
1650
            s.error("'api' not allowed with this statement")
1651
        elif s.sy == 'def':
1652 1653 1654
            # def statements aren't allowed in pxd files, except
            # as part of a cdef class
            if ('pxd' in ctx.level) and (ctx.level != 'c_class_pxd'):
1655
                s.error('def statement not allowed here')
1656
            s.level = ctx.level
1657 1658 1659 1660
            return p_def_statement(s, decorators)
        elif s.sy == 'class':
            if ctx.level != 'module':
                s.error("class definition not allowed here")
1661
            return p_class_statement(s, decorators)
1662 1663 1664 1665 1666 1667 1668 1669
        elif s.sy == 'include':
            if ctx.level not in ('module', 'module_pxd'):
                s.error("include statement not allowed here")
            return p_include_statement(s, ctx)
        elif ctx.level == 'c_class' and s.sy == 'IDENT' and s.systring == 'property':
            return p_property_decl(s)
        elif s.sy == 'pass' and ctx.level != 'property':
            return p_pass_statement(s, with_newline = 1)
William Stein's avatar
William Stein committed
1670
        else:
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
            if ctx.level in ('c_class_pxd', 'property'):
                s.error("Executable statement not allowed here")
            if s.sy == 'if':
                return p_if_statement(s)
            elif s.sy == 'while':
                return p_while_statement(s)
            elif s.sy == 'for':
                return p_for_statement(s)
            elif s.sy == 'try':
                return p_try_statement(s)
            elif s.sy == 'with':
                return p_with_statement(s)
1683
            else:
1684 1685
                return p_simple_statement_list(
                    s, ctx, first_statement = first_statement)
William Stein's avatar
William Stein committed
1686

1687
def p_statement_list(s, ctx, first_statement = 0):
William Stein's avatar
William Stein committed
1688 1689 1690 1691
    # Parse a series of statements separated by newlines.
    pos = s.position()
    stats = []
    while s.sy not in ('DEDENT', 'EOF'):
1692
        stats.append(p_statement(s, ctx, first_statement = first_statement))
Stefan Behnel's avatar
Stefan Behnel committed
1693
        first_statement = 0
1694 1695 1696 1697
    if len(stats) == 1:
        return stats[0]
    else:
        return Nodes.StatListNode(pos, stats = stats)
William Stein's avatar
William Stein committed
1698

1699
def p_suite(s, ctx = Ctx(), with_doc = 0, with_pseudo_doc = 0):
William Stein's avatar
William Stein committed
1700 1701 1702 1703 1704 1705 1706
    pos = s.position()
    s.expect(':')
    doc = None
    stmts = []
    if s.sy == 'NEWLINE':
        s.next()
        s.expect_indent()
1707
        if with_doc or with_pseudo_doc:
William Stein's avatar
William Stein committed
1708
            doc = p_doc_string(s)
1709
        body = p_statement_list(s, ctx)
William Stein's avatar
William Stein committed
1710 1711
        s.expect_dedent()
    else:
1712
        if ctx.api:
1713
            s.error("'api' not allowed with this statement")
1714 1715
        if ctx.level in ('module', 'class', 'function', 'other'):
            body = p_simple_statement_list(s, ctx)
William Stein's avatar
William Stein committed
1716 1717 1718 1719 1720 1721 1722 1723
        else:
            body = p_pass_statement(s)
            s.expect_newline("Syntax error in declarations")
    if with_doc:
        return doc, body
    else:
        return body

1724
def p_positional_and_keyword_args(s, end_sy_set, templates = None):
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
    """
    Parses positional and keyword arguments. end_sy_set
    should contain any s.sy that terminate the argument list.
    Argument expansion (* and **) are not allowed.

    Returns: (positional_args, keyword_args)
    """
    positional_args = []
    keyword_args = []
    pos_idx = 0

    while s.sy not in end_sy_set:
        if s.sy == '*' or s.sy == '**':
            s.error('Argument expansion not allowed here.')

        parsed_type = False
1741
        if s.sy == 'IDENT' and s.peek()[0] == '=':
1742
            ident = s.systring
1743
            s.next() # s.sy is '='
1744
            s.next()
1745
            if looking_at_expr(s):
1746
                arg = p_test(s)
1747 1748
            else:
                base_type = p_c_base_type(s, templates = templates)
1749 1750 1751 1752 1753 1754 1755 1756
                declarator = p_c_declarator(s, empty = 1)
                arg = Nodes.CComplexBaseTypeNode(base_type.pos, 
                    base_type = base_type, declarator = declarator)
                parsed_type = True
            keyword_node = ExprNodes.IdentifierStringNode(
                arg.pos, value = EncodedString(ident))
            keyword_args.append((keyword_node, arg))
            was_keyword = True
1757
                
1758
        else:
1759
            if looking_at_expr(s):
1760
                arg = p_test(s)
1761 1762
            else:
                base_type = p_c_base_type(s, templates = templates)
1763 1764 1765
                declarator = p_c_declarator(s, empty = 1)
                arg = Nodes.CComplexBaseTypeNode(base_type.pos, 
                    base_type = base_type, declarator = declarator)
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
                parsed_type = True
            positional_args.append(arg)
            pos_idx += 1
            if len(keyword_args) > 0:
                s.error("Non-keyword arg following keyword arg",
                        pos = arg.pos)

        if s.sy != ',':
            if s.sy not in end_sy_set:
                if parsed_type:
1776
                    s.error("Unmatched %s" % " or ".join(end_sy_set))
1777 1778 1779 1780
            break
        s.next()
    return positional_args, keyword_args

Danilo Freitas's avatar
Danilo Freitas committed
1781
def p_c_base_type(s, self_flag = 0, nonempty = 0, templates = None):
William Stein's avatar
William Stein committed
1782 1783 1784 1785 1786
    # If self_flag is true, this is the base type for the
    # self argument of a C method of an extension type.
    if s.sy == '(':
        return p_c_complex_base_type(s)
    else:
Danilo Freitas's avatar
Danilo Freitas committed
1787
        return p_c_simple_base_type(s, self_flag, nonempty = nonempty, templates = templates)
William Stein's avatar
William Stein committed
1788

1789 1790 1791 1792 1793 1794 1795 1796
def p_calling_convention(s):
    if s.sy == 'IDENT' and s.systring in calling_convention_words:
        result = s.systring
        s.next()
        return result
    else:
        return ""

1797
calling_convention_words = ("__stdcall", "__cdecl", "__fastcall")
1798

William Stein's avatar
William Stein committed
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
def p_c_complex_base_type(s):
    # s.sy == '('
    pos = s.position()
    s.next()
    base_type = p_c_base_type(s)
    declarator = p_c_declarator(s, empty = 1)
    s.expect(')')
    return Nodes.CComplexBaseTypeNode(pos, 
        base_type = base_type, declarator = declarator)

Danilo Freitas's avatar
Danilo Freitas committed
1809
def p_c_simple_base_type(s, self_flag, nonempty, templates = None):
1810
    #print "p_c_simple_base_type: self_flag =", self_flag, nonempty
William Stein's avatar
William Stein committed
1811 1812 1813
    is_basic = 0
    signed = 1
    longness = 0
1814
    complex = 0
William Stein's avatar
William Stein committed
1815
    module_path = []
1816
    pos = s.position()
1817 1818
    if not s.sy == 'IDENT':
        error(pos, "Expected an identifier, found '%s'" % s.sy)
William Stein's avatar
William Stein committed
1819 1820 1821
    if looking_at_base_type(s):
        #print "p_c_simple_base_type: looking_at_base_type at", s.position()
        is_basic = 1
1822 1823
        if s.sy == 'IDENT' and s.systring in special_basic_c_types:
            signed, longness = special_basic_c_types[s.systring]
William Stein's avatar
William Stein committed
1824 1825 1826
            name = s.systring
            s.next()
        else:
1827 1828 1829 1830 1831 1832
            signed, longness = p_sign_and_longness(s)
            if s.sy == 'IDENT' and s.systring in basic_c_type_names:
                name = s.systring
                s.next()
            else:
                name = 'int'
1833 1834 1835
        if s.sy == 'IDENT' and s.systring == 'complex':
            complex = 1
            s.next()
1836 1837 1838 1839 1840 1841 1842 1843
    elif looking_at_dotted_name(s):
        #print "p_c_simple_base_type: looking_at_type_name at", s.position()
        name = s.systring
        s.next()
        while s.sy == '.':
            module_path.append(name)
            s.next()
            name = p_ident(s)
1844
    else:
1845 1846 1847
        name = s.systring
        s.next()
        if nonempty and s.sy != 'IDENT':
1848
            # Make sure this is not a declaration of a variable or function.  
1849 1850
            if s.sy == '(':
                s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
1851
                if s.sy == '*' or s.sy == '**' or s.sy == '&':
1852 1853 1854 1855 1856
                    s.put_back('(', '(')
                else:
                    s.put_back('(', '(')
                    s.put_back('IDENT', name)
                    name = None
Robert Bradshaw's avatar
Robert Bradshaw committed
1857
            elif s.sy not in ('*', '**', '[', '&'):
1858 1859
                s.put_back('IDENT', name)
                name = None
Danilo Freitas's avatar
Danilo Freitas committed
1860

1861
    type_node = Nodes.CSimpleBaseTypeNode(pos, 
William Stein's avatar
William Stein committed
1862 1863
        name = name, module_path = module_path,
        is_basic_c_type = is_basic, signed = signed,
1864
        complex = complex, longness = longness, 
Danilo Freitas's avatar
Danilo Freitas committed
1865
        is_self_arg = self_flag, templates = templates)
William Stein's avatar
William Stein committed
1866

1867
    if s.sy == '[':
Robert Bradshaw's avatar
Robert Bradshaw committed
1868 1869 1870 1871 1872 1873 1874 1875
        type_node = p_buffer_or_template(s, type_node, templates)
    
    if s.sy == '.':
        s.next()
        name = p_ident(s)
        type_node = Nodes.CNestedBaseTypeNode(pos, base_type = type_node, name = name)
    
    return type_node
1876

1877
def p_buffer_or_template(s, base_type_node, templates):
1878 1879 1880
    # s.sy == '['
    pos = s.position()
    s.next()
1881 1882
    # Note that buffer_positional_options_count=1, so the only positional argument is dtype. 
    # For templated types, all parameters are types. 
1883
    positional_args, keyword_args = (
1884
        p_positional_and_keyword_args(s, (']',), templates)
1885 1886 1887 1888 1889 1890 1891 1892
    )
    s.expect(']')

    keyword_dict = ExprNodes.DictNode(pos,
        key_value_pairs = [
            ExprNodes.DictItemNode(pos=key.pos, key=key, value=value)
            for key, value in keyword_args
        ])
1893
    result = Nodes.TemplatedTypeNode(pos,
1894 1895
        positional_args = positional_args,
        keyword_args = keyword_dict,
1896
        base_type_node = base_type_node)
1897 1898 1899
    return result
    

1900
def looking_at_name(s):
1901 1902
    return s.sy == 'IDENT' and not s.systring in calling_convention_words

1903
def looking_at_expr(s):
1904
    if s.systring in base_type_start_words:
1905
        return False
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
    elif s.sy == 'IDENT':
        is_type = False
        name = s.systring
        dotted_path = []
        s.next()
        while s.sy == '.':
            s.next()
            dotted_path.append(s.systring)
            s.expect('IDENT')
        saved = s.sy, s.systring
1916 1917 1918
        if s.sy == 'IDENT':
            is_type = True
        elif s.sy == '*' or s.sy == '**':
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
            s.next()
            is_type = s.sy == ')'
            s.put_back(*saved)
        elif s.sy == '(':
            s.next()
            is_type = s.sy == '*'
            s.put_back(*saved)
        elif s.sy == '[':
            s.next()
            is_type = s.sy == ']'
            s.put_back(*saved)
        dotted_path.reverse()
        for p in dotted_path:
            s.put_back('IDENT', p)
            s.put_back('.', '.')
        s.put_back('IDENT', name)
1935
        return not is_type
1936
    else:
1937
        return True
William Stein's avatar
William Stein committed
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951

def looking_at_base_type(s):
    #print "looking_at_base_type?", s.sy, s.systring, s.position()
    return s.sy == 'IDENT' and s.systring in base_type_start_words

def looking_at_dotted_name(s):
    if s.sy == 'IDENT':
        name = s.systring
        s.next()
        result = s.sy == '.'
        s.put_back('IDENT', name)
        return result
    else:
        return 0
1952

1953 1954 1955 1956
basic_c_type_names = ("void", "char", "int", "float", "double", "bint")

special_basic_c_types = {
    # name : (signed, longness)
1957
    "Py_UNICODE" : (0, 0),
1958
    "Py_ssize_t" : (2, 0),
1959
    "ssize_t"    : (2, 0),
1960 1961
    "size_t"     : (0, 0),
}
William Stein's avatar
William Stein committed
1962 1963 1964

sign_and_longness_words = ("short", "long", "signed", "unsigned")

1965
base_type_start_words = \
1966
    basic_c_type_names + sign_and_longness_words + tuple(special_basic_c_types)
William Stein's avatar
William Stein committed
1967 1968 1969 1970 1971 1972 1973

def p_sign_and_longness(s):
    signed = 1
    longness = 0
    while s.sy == 'IDENT' and s.systring in sign_and_longness_words:
        if s.systring == 'unsigned':
            signed = 0
1974 1975
        elif s.systring == 'signed':
            signed = 2
William Stein's avatar
William Stein committed
1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
        elif s.systring == 'short':
            longness = -1
        elif s.systring == 'long':
            longness += 1
        s.next()
    return signed, longness

def p_opt_cname(s):
    literal = p_opt_string_literal(s)
    if literal:
        _, cname = literal
Stefan Behnel's avatar
Stefan Behnel committed
1987 1988
        cname = EncodedString(cname)
        cname.encoding = s.source_encoding
William Stein's avatar
William Stein committed
1989 1990 1991 1992
    else:
        cname = None
    return cname

1993 1994 1995
def p_c_declarator(s, ctx = Ctx(), empty = 0, is_type = 0, cmethod_flag = 0,
                   assignable = 0, nonempty = 0,
                   calling_convention_allowed = 0):
1996 1997
    # If empty is true, the declarator must be empty. If nonempty is true,
    # the declarator must be nonempty. Otherwise we don't care.
William Stein's avatar
William Stein committed
1998 1999 2000
    # If cmethod_flag is true, then if this declarator declares
    # a function, it's a C method of an extension type.
    pos = s.position()
2001 2002
    if s.sy == '(':
        s.next()
2003
        if s.sy == ')' or looking_at_name(s):
2004
            base = Nodes.CNameDeclaratorNode(pos, name = EncodedString(u""), cname = None)
2005
            result = p_c_func_declarator(s, pos, ctx, base, cmethod_flag)
2006
        else:
2007 2008 2009 2010
            result = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
                                    cmethod_flag = cmethod_flag,
                                    nonempty = nonempty,
                                    calling_convention_allowed = 1)
2011 2012
            s.expect(')')
    else:
2013 2014
        result = p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
                                       assignable, nonempty)
Stefan Behnel's avatar
Stefan Behnel committed
2015
    if not calling_convention_allowed and result.calling_convention and s.sy != '(':
2016 2017 2018 2019 2020 2021 2022 2023
        error(s.position(), "%s on something that is not a function"
            % result.calling_convention)
    while s.sy in ('[', '('):
        pos = s.position()
        if s.sy == '[':
            result = p_c_array_declarator(s, result)
        else: # sy == '('
            s.next()
2024
            result = p_c_func_declarator(s, pos, ctx, result, cmethod_flag)
2025 2026 2027 2028 2029 2030
        cmethod_flag = 0
    return result

def p_c_array_declarator(s, base):
    pos = s.position()
    s.next() # '['
Stefan Behnel's avatar
Stefan Behnel committed
2031
    if s.sy != ']':
2032
        dim = p_testlist(s)
2033 2034 2035 2036 2037
    else:
        dim = None
    s.expect(']')
    return Nodes.CArrayDeclaratorNode(pos, base = base, dimension = dim)

2038
def p_c_func_declarator(s, pos, ctx, base, cmethod_flag):
2039
    #  Opening paren has already been skipped
2040 2041
    args = p_c_arg_list(s, ctx, cmethod_flag = cmethod_flag,
                        nonempty_declarators = 0)
2042 2043 2044 2045 2046 2047 2048 2049
    ellipsis = p_optional_ellipsis(s)
    s.expect(')')
    nogil = p_nogil(s)
    exc_val, exc_check = p_exception_value_clause(s)
    with_gil = p_with_gil(s)
    return Nodes.CFuncDeclaratorNode(pos, 
        base = base, args = args, has_varargs = ellipsis,
        exception_value = exc_val, exception_check = exc_check,
2050
        nogil = nogil or ctx.nogil or with_gil, with_gil = with_gil)
2051

Stefan Behnel's avatar
Stefan Behnel committed
2052
supported_overloaded_operators = cython.set([
Robert Bradshaw's avatar
Robert Bradshaw committed
2053 2054 2055
    '+', '-', '*', '/', '%', 
    '++', '--', '~', '|', '&', '^', '<<', '>>',
    '==', '!=', '>=', '>', '<=', '<',
Robert Bradshaw's avatar
Robert Bradshaw committed
2056
    '[]', '()',
Robert Bradshaw's avatar
Robert Bradshaw committed
2057
])
2058

2059 2060
def p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
                          assignable, nonempty):
2061 2062
    pos = s.position()
    calling_convention = p_calling_convention(s)
William Stein's avatar
William Stein committed
2063 2064
    if s.sy == '*':
        s.next()
2065 2066 2067
        base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
                              cmethod_flag = cmethod_flag,
                              assignable = assignable, nonempty = nonempty)
William Stein's avatar
William Stein committed
2068 2069 2070 2071
        result = Nodes.CPtrDeclaratorNode(pos, 
            base = base)
    elif s.sy == '**': # scanner returns this as a single token
        s.next()
2072 2073 2074
        base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
                              cmethod_flag = cmethod_flag,
                              assignable = assignable, nonempty = nonempty)
William Stein's avatar
William Stein committed
2075 2076 2077
        result = Nodes.CPtrDeclaratorNode(pos,
            base = Nodes.CPtrDeclaratorNode(pos,
                base = base))
Robert Bradshaw's avatar
merge  
Robert Bradshaw committed
2078
    elif s.sy == '&':
2079 2080 2081 2082 2083
        s.next()
        base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
                              cmethod_flag = cmethod_flag,
                              assignable = assignable, nonempty = nonempty)
        result = Nodes.CReferenceDeclaratorNode(pos, base = base)
William Stein's avatar
William Stein committed
2084
    else:
2085 2086
        rhs = None
        if s.sy == 'IDENT':
2087
            name = EncodedString(s.systring)
2088 2089
            if empty:
                error(s.position(), "Declarator should be empty")
William Stein's avatar
William Stein committed
2090
            s.next()
2091
            cname = p_opt_cname(s)
2092
            if name != "operator" and s.sy == '=' and assignable:
2093
                s.next()
2094
                rhs = p_test(s)
William Stein's avatar
William Stein committed
2095
        else:
2096 2097 2098 2099
            if nonempty:
                error(s.position(), "Empty declarator")
            name = ""
            cname = None
2100 2101
        if cname is None and ctx.namespace is not None:
            cname = ctx.namespace + "::" + name
Robert Bradshaw's avatar
Robert Bradshaw committed
2102
        if name == 'operator' and ctx.visibility == 'extern':
2103
            op = s.sy
Robert Bradshaw's avatar
Robert Bradshaw committed
2104
            s.next()
2105 2106 2107 2108 2109 2110 2111
            # Handle diphthong operators.
            if op == '(':
                s.expect(')')
                op = '()'
            elif op == '[':
                s.expect(']')
                op = '[]'
2112
            if op in ['-', '+', '|', '&'] and s.sy == op:
2113
                op = op*2
2114
                s.next()
2115 2116 2117
            if s.sy == '=':
                op += s.sy
                s.next()
2118 2119 2120
            if op not in supported_overloaded_operators:
                s.error("Overloading operator '%s' not yet supported." % op)
            name = name+op
2121
        result = Nodes.CNameDeclaratorNode(pos,
Robert Bradshaw's avatar
Robert Bradshaw committed
2122
            name = name, cname = cname, default = rhs)
2123
    result.calling_convention = calling_convention
William Stein's avatar
William Stein committed
2124 2125
    return result

2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
def p_nogil(s):
    if s.sy == 'IDENT' and s.systring == 'nogil':
        s.next()
        return 1
    else:
        return 0

def p_with_gil(s):
    if s.sy == 'with':
        s.next()
        s.expect_keyword('gil')
        return 1
    else:
        return 0

William Stein's avatar
William Stein committed
2141 2142 2143 2144 2145 2146 2147 2148
def p_exception_value_clause(s):
    exc_val = None
    exc_check = 0
    if s.sy == 'except':
        s.next()
        if s.sy == '*':
            exc_check = 1
            s.next()
Felix Wu's avatar
Felix Wu committed
2149 2150 2151
        elif s.sy == '+':
            exc_check = '+'
            s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
2152 2153 2154 2155
            if s.sy == 'IDENT':
                name = s.systring
                s.next()
                exc_val = p_name(s, name)
William Stein's avatar
William Stein committed
2156 2157 2158 2159
        else:
            if s.sy == '?':
                exc_check = 1
                s.next()
2160
            exc_val = p_test(s)
William Stein's avatar
William Stein committed
2161 2162 2163 2164
    return exc_val, exc_check

c_arg_list_terminators = ('*', '**', '.', ')')

2165
def p_c_arg_list(s, ctx = Ctx(), in_pyfunc = 0, cmethod_flag = 0,
2166
                 nonempty_declarators = 0, kw_only = 0, annotated = 1):
2167 2168
    #  Comma-separated list of C argument declarations, possibly empty.
    #  May have a trailing comma.
William Stein's avatar
William Stein committed
2169
    args = []
2170 2171
    is_self_arg = cmethod_flag
    while s.sy not in c_arg_list_terminators:
2172
        args.append(p_c_arg_decl(s, ctx, in_pyfunc, is_self_arg,
2173 2174
            nonempty = nonempty_declarators, kw_only = kw_only,
            annotated = annotated))
2175 2176 2177 2178
        if s.sy != ',':
            break
        s.next()
        is_self_arg = 0
William Stein's avatar
William Stein committed
2179 2180 2181 2182 2183 2184 2185 2186 2187
    return args

def p_optional_ellipsis(s):
    if s.sy == '.':
        expect_ellipsis(s)
        return 1
    else:
        return 0

2188 2189
def p_c_arg_decl(s, ctx, in_pyfunc, cmethod_flag = 0, nonempty = 0,
                 kw_only = 0, annotated = 1):
William Stein's avatar
William Stein committed
2190
    pos = s.position()
2191
    not_none = or_none = 0
William Stein's avatar
William Stein committed
2192
    default = None
2193
    annotation = None
2194 2195 2196 2197 2198 2199 2200 2201 2202
    if s.in_python_file:
        # empty type declaration
        base_type = Nodes.CSimpleBaseTypeNode(pos,
            name = None, module_path = [],
            is_basic_c_type = 0, signed = 0,
            complex = 0, longness = 0,
            is_self_arg = cmethod_flag, templates = None)
    else:
        base_type = p_c_base_type(s, cmethod_flag, nonempty = nonempty)
2203
    declarator = p_c_declarator(s, ctx, nonempty = nonempty)
2204 2205
    if s.sy in ('not', 'or') and not s.in_python_file:
        kind = s.sy
William Stein's avatar
William Stein committed
2206 2207 2208 2209 2210 2211
        s.next()
        if s.sy == 'IDENT' and s.systring == 'None':
            s.next()
        else:
            s.error("Expected 'None'")
        if not in_pyfunc:
2212 2213 2214
            error(pos, "'%s None' only allowed in Python functions" % kind)
        or_none = kind == 'or'
        not_none = kind == 'not'
2215 2216
    if annotated and s.sy == ':':
        s.next()
2217
        annotation = p_test(s)
William Stein's avatar
William Stein committed
2218 2219
    if s.sy == '=':
        s.next()
2220 2221 2222
        if 'pxd' in s.level:
            if s.sy not in ['*', '?']:
                error(pos, "default values cannot be specified in pxd files, use ? or *")
Robert Bradshaw's avatar
Robert Bradshaw committed
2223
            default = ExprNodes.BoolNode(1)
2224 2225
            s.next()
        else:
2226
            default = p_test(s)
William Stein's avatar
William Stein committed
2227 2228 2229 2230
    return Nodes.CArgDeclNode(pos,
        base_type = base_type,
        declarator = declarator,
        not_none = not_none,
2231
        or_none = or_none,
2232
        default = default,
2233
        annotation = annotation,
2234
        kw_only = kw_only)
William Stein's avatar
William Stein committed
2235

2236 2237 2238 2239 2240 2241 2242
def p_api(s):
    if s.sy == 'IDENT' and s.systring == 'api':
        s.next()
        return 1
    else:
        return 0

2243
def p_cdef_statement(s, ctx):
William Stein's avatar
William Stein committed
2244
    pos = s.position()
2245 2246 2247 2248 2249 2250 2251
    ctx.visibility = p_visibility(s, ctx.visibility)
    ctx.api = ctx.api or p_api(s)
    if ctx.api:
        if ctx.visibility not in ('private', 'public'):
            error(pos, "Cannot combine 'api' with '%s'" % ctx.visibility)
    if (ctx.visibility == 'extern') and s.sy == 'from':
        return p_cdef_extern_block(s, pos, ctx)
Robert Bradshaw's avatar
Robert Bradshaw committed
2252 2253
    elif s.sy == 'import':
        s.next()
2254
        return p_cdef_extern_block(s, pos, ctx)
2255
    elif p_nogil(s):
2256
        ctx.nogil = 1
2257 2258 2259 2260 2261 2262
        if ctx.overridable:
            error(pos, "cdef blocks cannot be declared cpdef")
        return p_cdef_block(s, ctx)
    elif s.sy == ':':
        if ctx.overridable:
            error(pos, "cdef blocks cannot be declared cpdef")
2263
        return p_cdef_block(s, ctx)
William Stein's avatar
William Stein committed
2264
    elif s.sy == 'class':
2265
        if ctx.level not in ('module', 'module_pxd'):
William Stein's avatar
William Stein committed
2266
            error(pos, "Extension type definition not allowed here")
2267 2268
        if ctx.overridable:
            error(pos, "Extension types cannot be declared cpdef")
2269
        return p_c_class_definition(s, pos, ctx)
Robert Bradshaw's avatar
Robert Bradshaw committed
2270 2271
    elif s.sy == 'IDENT' and s.systring == 'cppclass':
        if ctx.visibility != 'extern':
2272
            error(pos, "C++ classes need to be declared extern")
Robert Bradshaw's avatar
Robert Bradshaw committed
2273
        return p_cpp_class_definition(s, pos, ctx)
2274
    elif s.sy == 'IDENT' and s.systring in ("struct", "union", "enum", "packed"):
2275
        if ctx.level not in ('module', 'module_pxd'):
William Stein's avatar
William Stein committed
2276
            error(pos, "C struct/union/enum definition not allowed here")
2277 2278
        if ctx.overridable:
            error(pos, "C struct/union/enum cannot be declared cpdef")
William Stein's avatar
William Stein committed
2279
        if s.systring == "enum":
2280
            return p_c_enum_definition(s, pos, ctx)
William Stein's avatar
William Stein committed
2281
        else:
2282
            return p_c_struct_or_union_definition(s, pos, ctx)
William Stein's avatar
William Stein committed
2283
    else:
2284
        return p_c_func_or_var_declaration(s, pos, ctx)
2285

2286 2287
def p_cdef_block(s, ctx):
    return p_suite(s, ctx(cdef_flag = 1))
William Stein's avatar
William Stein committed
2288

2289
def p_cdef_extern_block(s, pos, ctx):
2290 2291
    if ctx.overridable:
        error(pos, "cdef extern blocks cannot be declared cpdef")
William Stein's avatar
William Stein committed
2292 2293 2294 2295 2296 2297
    include_file = None
    s.expect('from')
    if s.sy == '*':
        s.next()
    else:
        _, include_file = p_string_literal(s)
2298
    ctx = ctx(cdef_flag = 1, visibility = 'extern')
2299 2300
    if s.systring == "namespace":
        s.next()
2301
        ctx.namespace = p_string_literal(s, kind_override='u')[1]
2302 2303 2304
    if p_nogil(s):
        ctx.nogil = 1
    body = p_suite(s, ctx)
William Stein's avatar
William Stein committed
2305 2306
    return Nodes.CDefExternNode(pos,
        include_file = include_file,
2307
        body = body,
Robert Bradshaw's avatar
Robert Bradshaw committed
2308
        namespace = ctx.namespace)
William Stein's avatar
William Stein committed
2309

2310
def p_c_enum_definition(s, pos, ctx):
William Stein's avatar
William Stein committed
2311 2312 2313 2314 2315 2316
    # s.sy == ident 'enum'
    s.next()
    if s.sy == 'IDENT':
        name = s.systring
        s.next()
        cname = p_opt_cname(s)
2317 2318
        if cname is None and ctx.namespace is not None:
            cname = ctx.namespace + "::" + name
William Stein's avatar
William Stein committed
2319 2320 2321 2322 2323 2324
    else:
        name = None
        cname = None
    items = None
    s.expect(':')
    items = []
Stefan Behnel's avatar
Stefan Behnel committed
2325
    if s.sy != 'NEWLINE':
2326
        p_c_enum_line(s, ctx, items)
William Stein's avatar
William Stein committed
2327 2328 2329 2330
    else:
        s.next() # 'NEWLINE'
        s.expect_indent()
        while s.sy not in ('DEDENT', 'EOF'):
2331
            p_c_enum_line(s, ctx, items)
William Stein's avatar
William Stein committed
2332
        s.expect_dedent()
2333 2334 2335 2336
    return Nodes.CEnumDefNode(
        pos, name = name, cname = cname, items = items,
        typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
        in_pxd = ctx.level == 'module_pxd')
William Stein's avatar
William Stein committed
2337

2338
def p_c_enum_line(s, ctx, items):
Stefan Behnel's avatar
Stefan Behnel committed
2339
    if s.sy != 'pass':
2340
        p_c_enum_item(s, ctx, items)
William Stein's avatar
William Stein committed
2341 2342 2343 2344
        while s.sy == ',':
            s.next()
            if s.sy in ('NEWLINE', 'EOF'):
                break
2345
            p_c_enum_item(s, ctx, items)
William Stein's avatar
William Stein committed
2346 2347 2348 2349
    else:
        s.next()
    s.expect_newline("Syntax error in enum item list")

2350
def p_c_enum_item(s, ctx, items):
William Stein's avatar
William Stein committed
2351 2352 2353
    pos = s.position()
    name = p_ident(s)
    cname = p_opt_cname(s)
2354 2355
    if cname is None and ctx.namespace is not None:
        cname = ctx.namespace + "::" + name
William Stein's avatar
William Stein committed
2356 2357 2358
    value = None
    if s.sy == '=':
        s.next()
2359
        value = p_test(s)
William Stein's avatar
William Stein committed
2360 2361 2362
    items.append(Nodes.CEnumDefItemNode(pos, 
        name = name, cname = cname, value = value))

2363
def p_c_struct_or_union_definition(s, pos, ctx):
2364 2365 2366 2367
    packed = False
    if s.systring == 'packed':
        packed = True
        s.next()
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
2368
        if s.sy != 'IDENT' or s.systring != 'struct':
2369
            s.expected('struct')
William Stein's avatar
William Stein committed
2370 2371 2372 2373 2374
    # s.sy == ident 'struct' or 'union'
    kind = s.systring
    s.next()
    name = p_ident(s)
    cname = p_opt_cname(s)
2375 2376
    if cname is None and ctx.namespace is not None:
        cname = ctx.namespace + "::" + name
William Stein's avatar
William Stein committed
2377 2378 2379 2380 2381 2382
    attributes = None
    if s.sy == ':':
        s.next()
        s.expect('NEWLINE')
        s.expect_indent()
        attributes = []
2383
        body_ctx = Ctx()
Stefan Behnel's avatar
Stefan Behnel committed
2384 2385
        while s.sy != 'DEDENT':
            if s.sy != 'pass':
William Stein's avatar
William Stein committed
2386
                attributes.append(
2387
                    p_c_func_or_var_declaration(s, s.position(), body_ctx))
William Stein's avatar
William Stein committed
2388 2389 2390 2391 2392 2393 2394 2395
            else:
                s.next()
                s.expect_newline("Expected a newline")
        s.expect_dedent()
    else:
        s.expect_newline("Syntax error in struct or union definition")
    return Nodes.CStructOrUnionDefNode(pos, 
        name = name, cname = cname, kind = kind, attributes = attributes,
2396
        typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2397
        in_pxd = ctx.level == 'module_pxd', packed = packed)
William Stein's avatar
William Stein committed
2398 2399 2400 2401 2402 2403

def p_visibility(s, prev_visibility):
    pos = s.position()
    visibility = prev_visibility
    if s.sy == 'IDENT' and s.systring in ('extern', 'public', 'readonly'):
        visibility = s.systring
Stefan Behnel's avatar
Stefan Behnel committed
2404
        if prev_visibility != 'private' and visibility != prev_visibility:
William Stein's avatar
William Stein committed
2405 2406 2407 2408
            s.error("Conflicting visibility options '%s' and '%s'"
                % (prev_visibility, visibility))
        s.next()
    return visibility
2409 2410
    
def p_c_modifiers(s):
2411
    if s.sy == 'IDENT' and s.systring in ('inline',):
2412
        modifier = s.systring
2413
        s.next()
2414 2415
        return [modifier] + p_c_modifiers(s)
    return []
William Stein's avatar
William Stein committed
2416

2417 2418
def p_c_func_or_var_declaration(s, pos, ctx):
    cmethod_flag = ctx.level in ('c_class', 'c_class_pxd')
2419
    modifiers = p_c_modifiers(s)
Danilo Freitas's avatar
Danilo Freitas committed
2420
    base_type = p_c_base_type(s, nonempty = 1, templates = ctx.templates)
2421 2422 2423
    declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
                                assignable = 1, nonempty = 1)
    declarator.overridable = ctx.overridable
William Stein's avatar
William Stein committed
2424
    if s.sy == ':':
Danilo Freitas's avatar
Danilo Freitas committed
2425
        if ctx.level not in ('module', 'c_class', 'module_pxd', 'c_class_pxd') and not ctx.templates:
William Stein's avatar
William Stein committed
2426
            s.error("C function definition not allowed here")
2427
        doc, suite = p_suite(s, Ctx(level = 'function'), with_doc = 1)
William Stein's avatar
William Stein committed
2428
        result = Nodes.CFuncDefNode(pos,
2429
            visibility = ctx.visibility,
William Stein's avatar
William Stein committed
2430 2431
            base_type = base_type,
            declarator = declarator, 
2432
            body = suite,
2433
            doc = doc,
2434
            modifiers = modifiers,
2435 2436
            api = ctx.api,
            overridable = ctx.overridable)
William Stein's avatar
William Stein committed
2437
    else:
Stefan Behnel's avatar
Stefan Behnel committed
2438
        #if api:
2439
        #    s.error("'api' not allowed with variable declaration")
William Stein's avatar
William Stein committed
2440 2441 2442 2443 2444
        declarators = [declarator]
        while s.sy == ',':
            s.next()
            if s.sy == 'NEWLINE':
                break
2445 2446
            declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
                                        assignable = 1, nonempty = 1)
William Stein's avatar
William Stein committed
2447 2448 2449
            declarators.append(declarator)
        s.expect_newline("Syntax error in C variable declaration")
        result = Nodes.CVarDefNode(pos, 
2450 2451
            visibility = ctx.visibility,
            base_type = base_type,
2452
            declarators = declarators,
2453 2454 2455
            in_pxd = ctx.level == 'module_pxd',
            api = ctx.api,
            overridable = ctx.overridable)
William Stein's avatar
William Stein committed
2456 2457
    return result

2458
def p_ctypedef_statement(s, ctx):
William Stein's avatar
William Stein committed
2459 2460 2461
    # s.sy == 'ctypedef'
    pos = s.position()
    s.next()
2462
    visibility = p_visibility(s, ctx.visibility)
2463
    api = p_api(s)
2464
    ctx = ctx(typedef_flag = 1, visibility = visibility)
2465 2466
    if api:
        ctx.api = 1
William Stein's avatar
William Stein committed
2467
    if s.sy == 'class':
2468
        return p_c_class_definition(s, pos, ctx)
2469
    elif s.sy == 'IDENT' and s.systring in ('packed', 'struct', 'union', 'enum'):
William Stein's avatar
William Stein committed
2470
        if s.systring == 'enum':
2471
            return p_c_enum_definition(s, pos, ctx)
William Stein's avatar
William Stein committed
2472
        else:
2473
            return p_c_struct_or_union_definition(s, pos, ctx)
William Stein's avatar
William Stein committed
2474
    else:
2475
        base_type = p_c_base_type(s, nonempty = 1)
2476 2477
        if base_type.name is None:
            s.error("Syntax error in ctypedef statement")
2478
        declarator = p_c_declarator(s, ctx, is_type = 1, nonempty = 1)
William Stein's avatar
William Stein committed
2479
        s.expect_newline("Syntax error in ctypedef statement")
2480 2481 2482 2483
        return Nodes.CTypeDefNode(
            pos, base_type = base_type,
            declarator = declarator, visibility = visibility,
            in_pxd = ctx.level == 'module_pxd')
William Stein's avatar
William Stein committed
2484

2485 2486 2487 2488 2489
def p_decorators(s):
    decorators = []
    while s.sy == 'DECORATOR':
        pos = s.position()
        s.next()
2490 2491
        decstring = p_dotted_name(s, as_allowed=0)[2]
        names = decstring.split('.')
2492
        decorator = ExprNodes.NameNode(pos, name=EncodedString(names[0]))
2493 2494
        for name in names[1:]:
            decorator = ExprNodes.AttributeNode(pos,
2495
                                           attribute=EncodedString(name),
2496
                                           obj=decorator)
2497 2498 2499 2500 2501 2502 2503
        if s.sy == '(':
            decorator = p_call(s, decorator)
        decorators.append(Nodes.DecoratorNode(pos, decorator=decorator))
        s.expect_newline("Expected a newline after decorator")
    return decorators

def p_def_statement(s, decorators=None):
William Stein's avatar
William Stein committed
2504 2505 2506
    # s.sy == 'def'
    pos = s.position()
    s.next()
2507
    name = EncodedString( p_ident(s) )
William Stein's avatar
William Stein committed
2508
    s.expect('(');
Stefan Behnel's avatar
Stefan Behnel committed
2509 2510 2511
    args, star_arg, starstar_arg = p_varargslist(s, terminator=')')
    s.expect(')')
    if p_nogil(s):
2512
        error(pos, "Python function cannot be declared nogil")
2513 2514 2515
    return_type_annotation = None
    if s.sy == '->':
        s.next()
2516
        return_type_annotation = p_test(s)
Stefan Behnel's avatar
Stefan Behnel committed
2517 2518 2519
    doc, body = p_suite(s, Ctx(level = 'function'), with_doc = 1)
    return Nodes.DefNode(pos, name = name, args = args, 
        star_arg = star_arg, starstar_arg = starstar_arg,
2520 2521
        doc = doc, body = body, decorators = decorators,
        return_type_annotation = return_type_annotation)
Stefan Behnel's avatar
Stefan Behnel committed
2522

2523 2524 2525
def p_varargslist(s, terminator=')', annotated=1):
    args = p_c_arg_list(s, in_pyfunc = 1, nonempty_declarators = 1,
                        annotated = annotated)
William Stein's avatar
William Stein committed
2526 2527 2528 2529
    star_arg = None
    starstar_arg = None
    if s.sy == '*':
        s.next()
2530 2531
        if s.sy == 'IDENT':
            star_arg = p_py_arg_decl(s)
William Stein's avatar
William Stein committed
2532 2533
        if s.sy == ',':
            s.next()
2534 2535
            args.extend(p_c_arg_list(s, in_pyfunc = 1,
                nonempty_declarators = 1, kw_only = 1))
Stefan Behnel's avatar
Stefan Behnel committed
2536
        elif s.sy != terminator:
2537 2538
            s.error("Syntax error in Python function argument list")
    if s.sy == '**':
William Stein's avatar
William Stein committed
2539 2540
        s.next()
        starstar_arg = p_py_arg_decl(s)
Stefan Behnel's avatar
Stefan Behnel committed
2541
    return (args, star_arg, starstar_arg)
William Stein's avatar
William Stein committed
2542 2543 2544 2545

def p_py_arg_decl(s):
    pos = s.position()
    name = p_ident(s)
2546 2547 2548
    annotation = None
    if s.sy == ':':
        s.next()
2549
        annotation = p_test(s)
2550
    return Nodes.PyArgDeclNode(pos, name = name, annotation = annotation)
William Stein's avatar
William Stein committed
2551

2552
def p_class_statement(s, decorators):
William Stein's avatar
William Stein committed
2553 2554 2555
    # s.sy == 'class'
    pos = s.position()
    s.next()
2556
    class_name = EncodedString( p_ident(s) )
2557
    class_name.encoding = s.source_encoding
William Stein's avatar
William Stein committed
2558 2559 2560 2561 2562 2563
    if s.sy == '(':
        s.next()
        base_list = p_simple_expr_list(s)
        s.expect(')')
    else:
        base_list = []
2564
    doc, body = p_suite(s, Ctx(level = 'class'), with_doc = 1)
William Stein's avatar
William Stein committed
2565 2566 2567
    return Nodes.PyClassDefNode(pos,
        name = class_name,
        bases = ExprNodes.TupleNode(pos, args = base_list),
2568
        doc = doc, body = body, decorators = decorators)
William Stein's avatar
William Stein committed
2569

2570
def p_c_class_definition(s, pos,  ctx):
William Stein's avatar
William Stein committed
2571 2572 2573 2574 2575 2576 2577 2578
    # s.sy == 'class'
    s.next()
    module_path = []
    class_name = p_ident(s)
    while s.sy == '.':
        s.next()
        module_path.append(class_name)
        class_name = p_ident(s)
2579
    if module_path and ctx.visibility != 'extern':
William Stein's avatar
William Stein committed
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
        error(pos, "Qualified class name only allowed for 'extern' C class")
    if module_path and s.sy == 'IDENT' and s.systring == 'as':
        s.next()
        as_name = p_ident(s)
    else:
        as_name = class_name
    objstruct_name = None
    typeobj_name = None
    base_class_module = None
    base_class_name = None
    if s.sy == '(':
        s.next()
        base_class_path = [p_ident(s)]
        while s.sy == '.':
            s.next()
            base_class_path.append(p_ident(s))
        if s.sy == ',':
            s.error("C class may only have one base class")
        s.expect(')')
        base_class_module = ".".join(base_class_path[:-1])
        base_class_name = base_class_path[-1]
    if s.sy == '[':
2602
        if ctx.visibility not in ('public', 'extern'):
William Stein's avatar
William Stein committed
2603 2604 2605
            error(s.position(), "Name options only allowed for 'public' or 'extern' C class")
        objstruct_name, typeobj_name = p_c_class_options(s)
    if s.sy == ':':
2606
        if ctx.level == 'module_pxd':
William Stein's avatar
William Stein committed
2607 2608 2609
            body_level = 'c_class_pxd'
        else:
            body_level = 'c_class'
2610
        doc, body = p_suite(s, Ctx(level = body_level), with_doc = 1)
William Stein's avatar
William Stein committed
2611 2612 2613 2614
    else:
        s.expect_newline("Syntax error in C class definition")
        doc = None
        body = None
2615
    if ctx.visibility == 'extern':
William Stein's avatar
William Stein committed
2616 2617 2618 2619
        if not module_path:
            error(pos, "Module name required for 'extern' C class")
        if typeobj_name:
            error(pos, "Type object name specification not allowed for 'extern' C class")
2620
    elif ctx.visibility == 'public':
William Stein's avatar
William Stein committed
2621 2622 2623 2624
        if not objstruct_name:
            error(pos, "Object struct name specification required for 'public' C class")
        if not typeobj_name:
            error(pos, "Type object name specification required for 'public' C class")
2625 2626
    elif ctx.visibility == 'private':
        if ctx.api:
Stefan Behnel's avatar
Stefan Behnel committed
2627
            error(pos, "Only 'public' C class can be declared 'api'")
2628
    else:
2629
        error(pos, "Invalid class visibility '%s'" % ctx.visibility)
William Stein's avatar
William Stein committed
2630
    return Nodes.CClassDefNode(pos,
2631 2632 2633
        visibility = ctx.visibility,
        typedef_flag = ctx.typedef_flag,
        api = ctx.api,
William Stein's avatar
William Stein committed
2634 2635 2636 2637 2638 2639 2640
        module_name = ".".join(module_path),
        class_name = class_name,
        as_name = as_name,
        base_class_module = base_class_module,
        base_class_name = base_class_name,
        objstruct_name = objstruct_name,
        typeobj_name = typeobj_name,
2641
        in_pxd = ctx.level == 'module_pxd',
William Stein's avatar
William Stein committed
2642 2643 2644 2645 2646 2647 2648 2649
        doc = doc,
        body = body)

def p_c_class_options(s):
    objstruct_name = None
    typeobj_name = None
    s.expect('[')
    while 1:
Stefan Behnel's avatar
Stefan Behnel committed
2650
        if s.sy != 'IDENT':
William Stein's avatar
William Stein committed
2651 2652 2653 2654 2655 2656 2657
            break
        if s.systring == 'object':
            s.next()
            objstruct_name = p_ident(s)
        elif s.systring == 'type':
            s.next()
            typeobj_name = p_ident(s)
Stefan Behnel's avatar
Stefan Behnel committed
2658
        if s.sy != ',':
William Stein's avatar
William Stein committed
2659 2660 2661 2662 2663 2664 2665 2666 2667
            break
        s.next()
    s.expect(']', "Expected 'object' or 'type'")
    return objstruct_name, typeobj_name

def p_property_decl(s):
    pos = s.position()
    s.next() # 'property'
    name = p_ident(s)
2668
    doc, body = p_suite(s, Ctx(level = 'property'), with_doc = 1)
William Stein's avatar
William Stein committed
2669 2670 2671
    return Nodes.PropertyNode(pos, name = name, doc = doc, body = body)

def p_doc_string(s):
2672
    if s.sy == 'BEGIN_STRING':
2673 2674
        pos = s.position()
        kind, result = p_cat_string_literal(s)
Stefan Behnel's avatar
Stefan Behnel committed
2675
        if s.sy != 'EOF':
William Stein's avatar
William Stein committed
2676
            s.expect_newline("Syntax error in doc string")
2677 2678 2679 2680
        if kind != 'u':
            # warning(pos, "Python 3 requires docstrings to be unicode strings")
            if kind == 'b':
                result.encoding = None # force a unicode string
William Stein's avatar
William Stein committed
2681 2682 2683
        return result
    else:
        return None
2684 2685 2686 2687 2688 2689 2690
        
def p_code(s, level=None):
    body = p_statement_list(s, Ctx(level = level), first_statement = 1)
    if s.sy != 'EOF':
        s.error("Syntax error in statement [%s,%s]" % (
            repr(s.sy), repr(s.systring)))
    return body
William Stein's avatar
William Stein committed
2691

2692
COMPILER_DIRECTIVE_COMMENT_RE = re.compile(r"^#\s*cython:\s*((\w|[.])+\s*=.*)$")
2693 2694

def p_compiler_directive_comments(s):
2695
    result = {}
2696 2697 2698
    while s.sy == 'commentline':
        m = COMPILER_DIRECTIVE_COMMENT_RE.match(s.systring)
        if m:
2699
            directives = m.group(1).strip()
2700
            try:
2701 2702
                result.update( Options.parse_directive_list(
                    directives, ignore_unknown=True) )
2703
            except ValueError, e:
2704
                s.error(e.args[0], fatal=False)
2705 2706 2707
        s.next()
    return result

2708
def p_module(s, pxd, full_module_name):
William Stein's avatar
William Stein committed
2709
    pos = s.position()
2710

2711
    directive_comments = p_compiler_directive_comments(s)
2712 2713
    s.parse_comments = False

2714
    if 'language_level' in directive_comments:
Stefan Behnel's avatar
Stefan Behnel committed
2715
        s.context.set_language_level(directive_comments['language_level'])
2716

William Stein's avatar
William Stein committed
2717 2718 2719 2720 2721
    doc = p_doc_string(s)
    if pxd:
        level = 'module_pxd'
    else:
        level = 'module'
2722

2723
    body = p_statement_list(s, Ctx(level = level), first_statement = 1)
Stefan Behnel's avatar
Stefan Behnel committed
2724
    if s.sy != 'EOF':
William Stein's avatar
William Stein committed
2725 2726
        s.error("Syntax error in statement [%s,%s]" % (
            repr(s.sy), repr(s.systring)))
2727 2728
    return ModuleNode(pos, doc = doc, body = body,
                      full_module_name = full_module_name,
2729
                      directive_comments = directive_comments)
William Stein's avatar
William Stein committed
2730

2731 2732 2733 2734 2735
def p_cpp_class_definition(s, pos,  ctx):
    # s.sy == 'cppclass'
    s.next()
    module_path = []
    class_name = p_ident(s)
2736 2737 2738
    cname = p_opt_cname(s)
    if cname is None and ctx.namespace is not None:
        cname = ctx.namespace + "::" + class_name
2739
    if s.sy == '.':
2740
        error(pos, "Qualified class name not allowed C++ class")
Danilo Freitas's avatar
Danilo Freitas committed
2741 2742
    if s.sy == '[':
        s.next()
2743
        templates = [p_ident(s)]
Danilo Freitas's avatar
Danilo Freitas committed
2744 2745
        while s.sy == ',':
            s.next()
2746
            templates.append(p_ident(s))
Danilo Freitas's avatar
Danilo Freitas committed
2747
        s.expect(']')
2748 2749
    else:
        templates = None
2750
    if s.sy == '(':
2751 2752 2753
        s.next()
        base_classes = [p_dotted_name(s, False)[2]]
        while s.sy == ',':
2754
            s.next()
2755
            base_classes.append(p_dotted_name(s, False)[2])
2756
        s.expect(')')
2757 2758
    else:
        base_classes = []
2759
    if s.sy == '[':
2760
        error(s.position(), "Name options not allowed for C++ class")
2761
    if s.sy == ':':
2762 2763 2764 2765
        s.next()
        s.expect('NEWLINE')
        s.expect_indent()
        attributes = []
Robert Bradshaw's avatar
Robert Bradshaw committed
2766
        body_ctx = Ctx(visibility = ctx.visibility)
Danilo Freitas's avatar
Danilo Freitas committed
2767
        body_ctx.templates = templates
2768
        while s.sy != 'DEDENT':
Robert Bradshaw's avatar
Robert Bradshaw committed
2769 2770 2771 2772
            if s.systring == 'cppclass':
                attributes.append(
                    p_cpp_class_definition(s, s.position(), body_ctx))
            elif s.sy != 'pass':
2773 2774 2775 2776 2777 2778
                attributes.append(
                    p_c_func_or_var_declaration(s, s.position(), body_ctx))
            else:
                s.next()
                s.expect_newline("Expected a newline")
        s.expect_dedent()
2779
    else:
2780
        attributes = None
2781 2782 2783
        s.expect_newline("Syntax error in C++ class definition")
    return Nodes.CppClassNode(pos,
        name = class_name,
2784
        cname = cname,
2785
        base_classes = base_classes,
2786 2787
        visibility = ctx.visibility,
        in_pxd = ctx.level == 'module_pxd',
Danilo Freitas's avatar
Danilo Freitas committed
2788 2789
        attributes = attributes,
        templates = templates)
2790 2791 2792



William Stein's avatar
William Stein committed
2793 2794 2795 2796 2797 2798
#----------------------------------------------
#
#   Debugging
#
#----------------------------------------------

Stefan Behnel's avatar
Stefan Behnel committed
2799
def print_parse_tree(f, node, level, key = None):
Stefan Behnel's avatar
Stefan Behnel committed
2800
    from types import ListType, TupleType
2801
    from Nodes import Node
William Stein's avatar
William Stein committed
2802 2803 2804 2805 2806 2807
    ind = "  " * level
    if node:
        f.write(ind)
        if key:
            f.write("%s: " % key)
        t = type(node)
Stefan Behnel's avatar
Stefan Behnel committed
2808
        if t is tuple:
William Stein's avatar
William Stein committed
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
            f.write("(%s @ %s\n" % (node[0], node[1]))
            for i in xrange(2, len(node)):
                print_parse_tree(f, node[i], level+1)
            f.write("%s)\n" % ind)
            return
        elif isinstance(node, Node):
            try:
                tag = node.tag
            except AttributeError:
                tag = node.__class__.__name__
            f.write("%s @ %s\n" % (tag, node.pos))
            for name, value in node.__dict__.items():
Stefan Behnel's avatar
Stefan Behnel committed
2821
                if name != 'tag' and name != 'pos':
William Stein's avatar
William Stein committed
2822 2823
                    print_parse_tree(f, value, level+1, name)
            return
Stefan Behnel's avatar
Stefan Behnel committed
2824
        elif t is list:
William Stein's avatar
William Stein committed
2825 2826 2827 2828 2829 2830 2831
            f.write("[\n")
            for i in xrange(len(node)):
                print_parse_tree(f, node[i], level+1)
            f.write("%s]\n" % ind)
            return
    f.write("%s%s\n" % (ind, node))