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

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

10
import re
Lisandro Dalcin's avatar
Lisandro Dalcin committed
11

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

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

    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
46 47 48 49 50 51 52 53 54 55 56 57 58
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
59
        if s.sy != ',':
William Stein's avatar
William Stein committed
60 61 62 63 64 65 66 67 68 69
            break
        s.next()
    return names

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

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

William Stein's avatar
William Stein committed
76 77 78
def p_binop_expr(s, ops, p_sub_expr):
    n1 = p_sub_expr(s)
    while s.sy in ops:
79
        op, pos = p_binop_operator(s)
William Stein's avatar
William Stein committed
80 81
        n2 = p_sub_expr(s)
        n1 = ExprNodes.binop_node(pos, op, n1, n2)
82 83 84 85 86
        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
87 88
    return n1

Stefan Behnel's avatar
Stefan Behnel committed
89 90 91 92 93 94 95 96 97 98
#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:
99 100
        args, star_arg, starstar_arg = p_varargslist(
            s, terminator=':', annotated=False)
Stefan Behnel's avatar
Stefan Behnel committed
101 102
    s.expect(':')
    if allow_conditional:
103
        expr = p_test(s)
Stefan Behnel's avatar
Stefan Behnel committed
104 105 106 107 108 109 110 111 112 113 114 115
    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)

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

Robert Bradshaw's avatar
Robert Bradshaw committed
118
def p_test(s):
119 120
    if s.sy == 'lambda':
        return p_lambdef(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
121 122 123 124 125
    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
126 127 128
        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
129 130 131
    else:
        return expr

Stefan Behnel's avatar
Stefan Behnel committed
132 133 134 135 136 137 138
#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
139 140 141 142

#or_test: and_test ('or' and_test)*

def p_or_test(s):
William Stein's avatar
William Stein committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    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):
175
    n1 = p_starred_expr(s)
William Stein's avatar
William Stein committed
176 177 178
    if s.sy in comparison_ops:
        pos = s.position()
        op = p_cmp_op(s)
179
        n2 = p_starred_expr(s)
180
        n1 = ExprNodes.PrimaryCmpNode(pos,
William Stein's avatar
William Stein committed
181 182 183 184 185
            operator = op, operand1 = n1, operand2 = n2)
        if s.sy in comparison_ops:
            n1.cascade = p_cascaded_cmp(s)
    return n1

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

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

William Stein's avatar
William Stein committed
204 205 206
def p_cascaded_cmp(s):
    pos = s.position()
    op = p_cmp_op(s)
207
    n2 = p_starred_expr(s)
208
    result = ExprNodes.CascadedCmpNode(pos,
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
        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
232

William Stein's avatar
William Stein committed
233
comparison_ops = (
234
    '<', '>', '==', '>=', '<=', '<>', '!=',
William Stein's avatar
William Stein committed
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
    '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
266
    return p_binop_expr(s, ('*', '/', '%', '//'), p_factor)
William Stein's avatar
William Stein committed
267 268 269 270

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

def p_factor(s):
271 272 273 274
    # little indirection for C-ification purposes
    return _p_factor(s)

def _p_factor(s):
William Stein's avatar
William Stein committed
275 276 277 278 279 280
    sy = s.sy
    if sy in ('+', '-', '~'):
        op = s.sy
        pos = s.position()
        s.next()
        return ExprNodes.unop_node(pos, op, p_factor(s))
281 282 283 284 285 286 287 288 289 290 291
    elif not s.in_python_file:
        if 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)
    return p_power(s)
William Stein's avatar
William Stein committed
292 293 294 295 296 297

def p_typecast(s):
    # s.sy == "<"
    pos = s.position()
    s.next()
    base_type = p_c_base_type(s)
298
    is_memslice = isinstance(base_type, Nodes.MemoryViewSliceTypeNode)
Vladimir Cerny's avatar
Vladimir Cerny committed
299 300
    is_template =isinstance(base_type, Nodes.TemplatedTypeNode)
    if not is_memslice and not is_template and base_type.name is None:
301
        s.error("Unknown type")
William Stein's avatar
William Stein committed
302
    declarator = p_c_declarator(s, empty = 1)
303 304 305 306 307
    if s.sy == '?':
        s.next()
        typecheck = 1
    else:
        typecheck = 0
William Stein's avatar
William Stein committed
308 309
    s.expect(">")
    operand = p_factor(s)
310 311 312 313
    if is_memslice:
        return ExprNodes.CythonArrayNode(pos, base_type_node=base_type,
                                         operand=operand)

314 315
    return ExprNodes.TypecastNode(pos,
        base_type = base_type,
William Stein's avatar
William Stein committed
316
        declarator = declarator,
317 318
        operand = operand,
        typecheck = typecheck)
William Stein's avatar
William Stein committed
319 320 321 322 323 324

def p_sizeof(s):
    # s.sy == ident "sizeof"
    pos = s.position()
    s.next()
    s.expect('(')
325
    # Here we decide if we are looking at an expression or type
326 327
    # If it is actually a type, but parsable as an expression,
    # we treat it as an expression here.
328
    if looking_at_expr(s):
329
        operand = p_test(s)
330 331
        node = ExprNodes.SizeofVarNode(pos, operand = operand)
    else:
William Stein's avatar
William Stein committed
332 333
        base_type = p_c_base_type(s)
        declarator = p_c_declarator(s, empty = 1)
334
        node = ExprNodes.SizeofTypeNode(pos,
William Stein's avatar
William Stein committed
335 336 337 338
            base_type = base_type, declarator = declarator)
    s.expect(')')
    return node

339 340 341 342
def p_yield_expression(s):
    # s.sy == "yield"
    pos = s.position()
    s.next()
343 344 345 346
    is_yield_from = False
    if s.sy == 'from':
        is_yield_from = True
        s.next()
347
    if s.sy != ')' and s.sy not in statement_terminators:
348
        arg = p_testlist(s)
349
    else:
350 351
        if is_yield_from:
            s.error("'yield from' requires a source argument", pos=pos)
352
        arg = None
353 354 355 356
    if is_yield_from:
        return ExprNodes.YieldFromExprNode(pos, arg=arg)
    else:
        return ExprNodes.YieldExprNode(pos, arg=arg)
357 358 359 360 361

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

William Stein's avatar
William Stein committed
363 364 365
#power: atom trailer* ('**' factor)*

def p_power(s):
366
    if s.systring == 'new' and s.peek()[0] == 'IDENT':
Danilo Freitas's avatar
Danilo Freitas committed
367
        return p_new_expr(s)
William Stein's avatar
William Stein committed
368 369 370 371 372 373 374 375 376 377
    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
378
def p_new_expr(s):
Danilo Freitas's avatar
Danilo Freitas committed
379
    # s.systring == 'new'.
Danilo Freitas's avatar
Danilo Freitas committed
380 381
    pos = s.position()
    s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
382 383
    cppclass = p_c_base_type(s)
    return p_call(s, ExprNodes.NewExprNode(pos, cppclass = cppclass))
Danilo Freitas's avatar
Danilo Freitas committed
384

William Stein's avatar
William Stein committed
385 386 387 388 389 390 391 392 393 394
#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()
395
        name = EncodedString( p_ident(s) )
396
        return ExprNodes.AttributeNode(pos,
William Stein's avatar
William Stein committed
397 398 399 400 401
            obj = node1, attribute = name)

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

402
def p_call_parse_args(s, allow_genexp = True):
William Stein's avatar
William Stein committed
403 404 405 406 407 408 409
    # s.sy == '('
    pos = s.position()
    s.next()
    positional_args = []
    keyword_args = []
    star_arg = None
    starstar_arg = None
410 411 412 413 414
    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
415
            s.next()
416
            star_arg = p_test(s)
William Stein's avatar
William Stein committed
417
        else:
418
            arg = p_test(s)
419 420 421 422 423 424
            if s.sy == '=':
                s.next()
                if not arg.is_name:
                    s.error("Expected an identifier before '='",
                        pos = arg.pos)
                encoded_name = EncodedString(arg.name)
425
                keyword = ExprNodes.IdentifierStringNode(arg.pos, value = encoded_name)
426
                arg = p_test(s)
427 428 429 430 431 432 433 434 435
                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
436
        if s.sy != ',':
William Stein's avatar
William Stein committed
437 438
            break
        s.next()
439

440 441 442 443
    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
444
        s.next()
445
        starstar_arg = p_test(s)
William Stein's avatar
William Stein committed
446 447 448
        if s.sy == ',':
            s.next()
    s.expect(')')
449 450
    return positional_args, keyword_args, star_arg, starstar_arg

451
def p_call_build_packed_args(pos, positional_args, keyword_args,
Stefan Behnel's avatar
Stefan Behnel committed
452
                             star_arg, starstar_arg):
453 454 455 456 457 458 459 460 461 462 463 464 465
    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
466
    if keyword_args or starstar_arg:
467 468
        keyword_args = [ExprNodes.DictItemNode(pos=key.pos, key=key, value=value)
                          for key, value in keyword_args]
469
        if starstar_arg:
470
            keyword_dict = ExprNodes.KeywordArgsNode(
471
                pos,
472 473
                starstar_arg = starstar_arg,
                keyword_args = keyword_args)
474 475 476
        else:
            keyword_dict = ExprNodes.DictNode(
                pos, key_value_pairs = keyword_args)
477 478 479 480 481 482 483
    return arg_tuple, keyword_dict

def p_call(s, function):
    # s.sy == '('
    pos = s.position()

    positional_args, keyword_args, star_arg, starstar_arg = \
484
                     p_call_parse_args(s)
485

William Stein's avatar
William Stein committed
486 487 488 489 490
    if not (keyword_args or star_arg or starstar_arg):
        return ExprNodes.SimpleCallNode(pos,
            function = function,
            args = positional_args)
    else:
491
        arg_tuple, keyword_dict = p_call_build_packed_args(
492
            pos, positional_args, keyword_args, star_arg, starstar_arg)
493
        return ExprNodes.GeneralCallNode(pos,
William Stein's avatar
William Stein committed
494 495
            function = function,
            positional_args = arg_tuple,
496
            keyword_args = keyword_dict)
William Stein's avatar
William Stein committed
497 498 499 500 501 502 503 504 505 506 507 508

#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]
509
        result = ExprNodes.SliceIndexNode(pos,
William Stein's avatar
William Stein committed
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
            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()
538 539 540 541 542 543 544 545 546 547
    start = p_slice_element(s, (':',))
    if s.sy != ':':
        return [start]
    s.next()
    stop = p_slice_element(s, (':', ',', ']'))
    if s.sy != ':':
        return [start, stop]
    s.next()
    step = p_slice_element(s, (':', ',', ']'))
    return [start, stop, step]
William Stein's avatar
William Stein committed
548 549 550 551 552

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:
553
        return p_test(s)
William Stein's avatar
William Stein committed
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
    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)

585
#atom: '(' [yield_expr|testlist_comp] ')' | '[' [listmaker] ']' | '{' [dict_or_set_maker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+
William Stein's avatar
William Stein committed
586 587 588 589 590 591 592 593

def p_atom(s):
    pos = s.position()
    sy = s.sy
    if sy == '(':
        s.next()
        if s.sy == ')':
            result = ExprNodes.TupleNode(pos, args = [])
594 595
        elif s.sy == 'yield':
            result = p_yield_expression(s)
William Stein's avatar
William Stein committed
596
        else:
597
            result = p_testlist_comp(s)
William Stein's avatar
William Stein committed
598 599 600 601 602
        s.expect(')')
        return result
    elif sy == '[':
        return p_list_maker(s)
    elif sy == '{':
603
        return p_dict_or_set_maker(s)
William Stein's avatar
William Stein committed
604 605
    elif sy == '`':
        return p_backquote_expr(s)
606 607 608
    elif sy == '.':
        expect_ellipsis(s)
        return ExprNodes.EllipsisNode(pos)
William Stein's avatar
William Stein committed
609
    elif sy == 'INT':
610
        return p_int_literal(s)
William Stein's avatar
William Stein committed
611 612 613 614 615 616 617 618
    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)
619
    elif sy == 'BEGIN_STRING':
620
        kind, bytes_value, unicode_value = p_cat_string_literal(s)
William Stein's avatar
William Stein committed
621
        if kind == 'c':
622
            return ExprNodes.CharNode(pos, value = bytes_value)
623
        elif kind == 'u':
624
            return ExprNodes.UnicodeNode(pos, value = unicode_value, bytes_value = bytes_value)
625
        elif kind == 'b':
626
            return ExprNodes.BytesNode(pos, value = bytes_value)
William Stein's avatar
William Stein committed
627
        else:
628
            return ExprNodes.StringNode(pos, value = bytes_value, unicode_value = unicode_value)
William Stein's avatar
William Stein committed
629
    elif sy == 'IDENT':
630
        name = EncodedString( s.systring )
William Stein's avatar
William Stein committed
631 632 633
        s.next()
        if name == "None":
            return ExprNodes.NoneNode(pos)
634
        elif name == "True":
635
            return ExprNodes.BoolNode(pos, value=True)
636
        elif name == "False":
637
            return ExprNodes.BoolNode(pos, value=False)
638
        elif name == "NULL" and not s.in_python_file:
639
            return ExprNodes.NullNode(pos)
William Stein's avatar
William Stein committed
640
        else:
641
            return p_name(s, name)
William Stein's avatar
William Stein committed
642 643 644
    else:
        s.error("Expected an identifier or literal")

645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
def p_int_literal(s):
    pos = s.position()
    value = s.systring
    s.next()
    unsigned = ""
    longness = ""
    while value[-1] in u"UuLl":
        if value[-1] in u"Ll":
            longness += "L"
        else:
            unsigned += "U"
        value = value[:-1]
    # '3L' is ambiguous in Py2 but not in Py3.  '3U' and '3LL' are
    # illegal in Py2 Python files.  All suffixes are illegal in Py3
    # Python files.
    is_c_literal = None
    if unsigned:
        is_c_literal = True
    elif longness:
        if longness == 'LL' or s.context.language_level >= 3:
            is_c_literal = True
    if s.in_python_file:
        if is_c_literal:
            error(pos, "illegal integer literal syntax in Python source file")
        is_c_literal = False
    return ExprNodes.IntNode(pos,
                             is_c_literal = is_c_literal,
                             value = value,
                             unsigned = unsigned,
                             longness = longness)

676 677
def p_name(s, name):
    pos = s.position()
678 679 680 681 682 683 684 685 686 687 688
    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)
689 690 691 692
        elif isinstance(value, _unicode):
            return ExprNodes.UnicodeNode(pos, value = value)
        elif isinstance(value, _bytes):
            return ExprNodes.BytesNode(pos, value = value)
693
        else:
694 695
            error(pos, "Invalid type for compile-time constant: %s"
                % value.__class__.__name__)
696 697
    return ExprNodes.NameNode(pos, name = name)

William Stein's avatar
William Stein committed
698 699
def p_cat_string_literal(s):
    # A sequence of one or more adjacent string literals.
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    # Returns (kind, bytes_value, unicode_value)
    # where kind in ('b', 'c', 'u', '')
    kind, bytes_value, unicode_value = p_string_literal(s)
    if kind == 'c' or s.sy != 'BEGIN_STRING':
        return kind, bytes_value, unicode_value
    bstrings, ustrings = [bytes_value], [unicode_value]
    bytes_value = unicode_value = None
    while s.sy == 'BEGIN_STRING':
        pos = s.position()
        next_kind, next_bytes_value, next_unicode_value = p_string_literal(s)
        if next_kind == 'c':
            error(pos, "Cannot concatenate char literal with another string or char literal")
        elif next_kind != kind:
            error(pos, "Cannot mix string literals of different types, expected %s'', got %s''" %
                  (kind, next_kind))
715
        else:
716 717 718
            bstrings.append(next_bytes_value)
            ustrings.append(next_unicode_value)
    # join and rewrap the partial literals
719
    if kind in ('b', 'c', '') or kind == 'u' and None not in bstrings:
720
        # Py3 enforced unicode literals are parsed as bytes/unicode combination
721
        bytes_value = BytesLiteral( StringEncoding.join_bytes(bstrings) )
722 723 724 725 726 727
        bytes_value.encoding = s.source_encoding
    if kind in ('u', ''):
        unicode_value = EncodedString( u''.join([ u for u in ustrings if u is not None ]) )
    return kind, bytes_value, unicode_value

def p_opt_string_literal(s, required_type='u'):
728
    if s.sy == 'BEGIN_STRING':
729 730 731 732 733 734 735
        kind, bytes_value, unicode_value = p_string_literal(s, required_type)
        if required_type == 'u':
            return unicode_value
        elif required_type == 'b':
            return bytes_value
        else:
            s.error("internal parser configuration error")
William Stein's avatar
William Stein committed
736 737 738
    else:
        return None

739 740 741 742 743 744
def check_for_non_ascii_characters(string):
    for c in string:
        if c >= u'\x80':
            return True
    return False

745
def p_string_literal(s, kind_override=None):
746 747 748 749 750 751 752
    # A single string or char literal.  Returns (kind, bvalue, uvalue)
    # where kind in ('b', 'c', 'u', '').  The 'bvalue' is the source
    # code byte sequence of the string literal, 'uvalue' is the
    # decoded Unicode string.  Either of the two may be None depending
    # on the 'kind' of string, only unprefixed strings have both
    # representations.

William Stein's avatar
William Stein committed
753 754
    # s.sy == 'BEGIN_STRING'
    pos = s.position()
755
    is_raw = 0
756
    is_python3_source = s.context.language_level >= 3
757
    has_non_ASCII_literal_characters = False
William Stein's avatar
William Stein committed
758
    kind = s.systring[:1].lower()
759 760 761 762 763 764
    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
765
        kind = ''
766 767 768 769 770 771 772 773 774 775 776 777
    if kind == '' and kind_override is None and Future.unicode_literals in s.context.future_directives:
        chars = StringEncoding.StrLiteralBuilder(s.source_encoding)
        kind = 'u'
    else:
        if kind_override is not None and kind_override in 'ub':
            kind = kind_override
        if kind == 'u':
            chars = StringEncoding.UnicodeLiteralBuilder()
        elif kind == '':
            chars = StringEncoding.StrLiteralBuilder(s.source_encoding)
        else:
            chars = StringEncoding.BytesLiteralBuilder(s.source_encoding)
William Stein's avatar
William Stein committed
778 779 780
    while 1:
        s.next()
        sy = s.sy
781
        systr = s.systring
William Stein's avatar
William Stein committed
782 783
        #print "p_string_literal: sy =", sy, repr(s.systring) ###
        if sy == 'CHARS':
784
            chars.append(systr)
785
            if is_python3_source and not has_non_ASCII_literal_characters and check_for_non_ascii_characters(systr):
786
                has_non_ASCII_literal_characters = True
William Stein's avatar
William Stein committed
787
        elif sy == 'ESCAPE':
788
            if is_raw:
789 790 791 792
                chars.append(systr)
                if is_python3_source and not has_non_ASCII_literal_characters \
                       and check_for_non_ascii_characters(systr):
                    has_non_ASCII_literal_characters = True
William Stein's avatar
William Stein committed
793 794
            else:
                c = systr[1]
795 796 797
                if c in u"01234567":
                    chars.append_charval( int(systr[1:], 8) )
                elif c in u"'\"\\":
798
                    chars.append(c)
799 800 801 802
                elif c in u"abfnrtv":
                    chars.append(
                        StringEncoding.char_from_escape_sequence(systr))
                elif c == u'\n':
William Stein's avatar
William Stein committed
803
                    pass
804
                elif c == u'x':
805 806 807
                    if len(systr) == 4:
                        chars.append_charval( int(systr[2:], 16) )
                    else:
808
                        s.error("Invalid hex escape '%s'" % systr)
809 810
                elif c in u'Uu':
                    if kind in ('u', ''):
811 812 813
                        if len(systr) in (6,10):
                            chrval = int(systr[2:], 16)
                            if chrval > 1114111: # sys.maxunicode:
814
                                s.error("Invalid unicode escape '%s'" % systr)
815
                        else:
816
                            s.error("Invalid unicode escape '%s'" % systr)
817
                    else:
818
                        # unicode escapes in byte strings are not unescaped
819 820
                        chrval = None
                    chars.append_uescape(chrval, systr)
William Stein's avatar
William Stein committed
821
                else:
822
                    chars.append(u'\\' + systr[1:])
823 824
                    if is_python3_source and not has_non_ASCII_literal_characters \
                           and check_for_non_ascii_characters(systr):
825
                        has_non_ASCII_literal_characters = True
William Stein's avatar
William Stein committed
826
        elif sy == 'NEWLINE':
827
            chars.append(u'\n')
William Stein's avatar
William Stein committed
828 829 830 831 832 833 834 835
        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))
836
    if kind == 'c':
837 838 839 840
        unicode_value = None
        bytes_value = chars.getchar()
        if len(bytes_value) != 1:
            error(pos, u"invalid character literal: %r" % bytes_value)
841
    else:
842
        bytes_value, unicode_value = chars.getstrings()
843
        if is_python3_source and has_non_ASCII_literal_characters:
844 845 846 847
            # Python 3 forbids literal non-ASCII characters in byte strings
            if kind != 'u':
                s.error("bytes can only contain ASCII literal characters.", pos = pos)
            bytes_value = None
William Stein's avatar
William Stein committed
848
    s.next()
849
    return (kind, bytes_value, unicode_value)
William Stein's avatar
William Stein committed
850

Robert Bradshaw's avatar
Robert Bradshaw committed
851
# list_display      ::=      "[" [listmaker] "]"
Stefan Behnel's avatar
Stefan Behnel committed
852 853 854 855
# 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]
856

William Stein's avatar
William Stein committed
857 858 859 860
def p_list_maker(s):
    # s.sy == '['
    pos = s.position()
    s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
861 862 863
    if s.sy == ']':
        s.expect(']')
        return ExprNodes.ListNode(pos, args = [])
864
    expr = p_test(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
865
    if s.sy == 'for':
866 867 868
        target = ExprNodes.ListNode(pos, args = [])
        append = ExprNodes.ComprehensionAppendNode(
            pos, expr=expr, target=ExprNodes.CloneNode(target))
869
        loop = p_comp_for(s, append)
Robert Bradshaw's avatar
Robert Bradshaw committed
870
        s.expect(']')
871
        return ExprNodes.ComprehensionNode(
872 873
            pos, loop=loop, append=append, target=target,
            # list comprehensions leak their loop variable in Py2
Stefan Behnel's avatar
Stefan Behnel committed
874
            has_local_scope = s.context.language_level >= 3)
Robert Bradshaw's avatar
Robert Bradshaw committed
875 876 877
    else:
        if s.sy == ',':
            s.next()
878 879 880
            exprs = p_simple_expr_list(s, expr)
        else:
            exprs = [expr]
Robert Bradshaw's avatar
Robert Bradshaw committed
881 882
        s.expect(']')
        return ExprNodes.ListNode(pos, args = exprs)
883

Stefan Behnel's avatar
Stefan Behnel committed
884
def p_comp_iter(s, body):
Robert Bradshaw's avatar
Robert Bradshaw committed
885
    if s.sy == 'for':
Stefan Behnel's avatar
Stefan Behnel committed
886
        return p_comp_for(s, body)
Robert Bradshaw's avatar
Robert Bradshaw committed
887
    elif s.sy == 'if':
Stefan Behnel's avatar
Stefan Behnel committed
888
        return p_comp_if(s, body)
Robert Bradshaw's avatar
Robert Bradshaw committed
889
    else:
890 891
        # insert the 'append' operation into the loop
        return body
William Stein's avatar
William Stein committed
892

Stefan Behnel's avatar
Stefan Behnel committed
893
def p_comp_for(s, body):
Robert Bradshaw's avatar
Robert Bradshaw committed
894 895 896
    # s.sy == 'for'
    pos = s.position()
    s.next()
897
    kw = p_for_bounds(s, allow_testlist=False)
Robert Bradshaw's avatar
Robert Bradshaw committed
898
    kw.update(else_clause = None, body = p_comp_iter(s, body))
Robert Bradshaw's avatar
Robert Bradshaw committed
899
    return Nodes.ForStatNode(pos, **kw)
900

Stefan Behnel's avatar
Stefan Behnel committed
901
def p_comp_if(s, body):
Robert Bradshaw's avatar
Robert Bradshaw committed
902 903 904
    # s.sy == 'if'
    pos = s.position()
    s.next()
Stefan Behnel's avatar
Stefan Behnel committed
905
    test = p_test_nocond(s)
906
    return Nodes.IfStatNode(pos,
907
        if_clauses = [Nodes.IfClauseNode(pos, condition = test,
Stefan Behnel's avatar
Stefan Behnel committed
908
                                         body = p_comp_iter(s, body))],
Robert Bradshaw's avatar
Robert Bradshaw committed
909
        else_clause = None )
910

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

913
def p_dict_or_set_maker(s):
William Stein's avatar
William Stein committed
914 915 916
    # s.sy == '{'
    pos = s.position()
    s.next()
917
    if s.sy == '}':
William Stein's avatar
William Stein committed
918
        s.next()
919
        return ExprNodes.DictNode(pos, key_value_pairs = [])
920
    item = p_test(s)
921 922 923 924 925
    if s.sy == ',' or s.sy == '}':
        # set literal
        values = [item]
        while s.sy == ',':
            s.next()
926 927
            if s.sy == '}':
                break
928
            values.append( p_test(s) )
929 930 931 932
        s.expect('}')
        return ExprNodes.SetNode(pos, args=values)
    elif s.sy == 'for':
        # set comprehension
933 934 935
        target = ExprNodes.SetNode(pos, args=[])
        append = ExprNodes.ComprehensionAppendNode(
            item.pos, expr=item, target=ExprNodes.CloneNode(target))
936
        loop = p_comp_for(s, append)
937
        s.expect('}')
938 939
        return ExprNodes.ComprehensionNode(
            pos, loop=loop, append=append, target=target)
940 941 942 943
    elif s.sy == ':':
        # dict literal or comprehension
        key = item
        s.next()
944
        value = p_test(s)
945 946
        if s.sy == 'for':
            # dict comprehension
947
            target = ExprNodes.DictNode(pos, key_value_pairs = [])
948
            append = ExprNodes.DictComprehensionAppendNode(
949 950
                item.pos, key_expr=key, value_expr=value,
                target=ExprNodes.CloneNode(target))
951
            loop = p_comp_for(s, append)
952 953 954
            s.expect('}')
            return ExprNodes.ComprehensionNode(
                pos, loop=loop, append=append, target=target)
955 956 957 958 959
        else:
            # dict literal
            items = [ExprNodes.DictItemNode(key.pos, key=key, value=value)]
            while s.sy == ',':
                s.next()
960 961
                if s.sy == '}':
                    break
962
                key = p_test(s)
963
                s.expect(':')
964
                value = p_test(s)
965 966 967 968 969 970 971 972
                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
973

974
# NOTE: no longer in Py3 :)
William Stein's avatar
William Stein committed
975 976 977 978
def p_backquote_expr(s):
    # s.sy == '`'
    pos = s.position()
    s.next()
979 980 981 982
    args = [p_test(s)]
    while s.sy == ',':
        s.next()
        args.append(p_test(s))
William Stein's avatar
William Stein committed
983
    s.expect('`')
984 985 986 987
    if len(args) == 1:
        arg = args[0]
    else:
        arg = ExprNodes.TupleNode(pos, args = args)
William Stein's avatar
William Stein committed
988 989
    return ExprNodes.BackquoteNode(pos, arg = arg)

990 991
def p_simple_expr_list(s, expr=None):
    exprs = expr is not None and [expr] or []
William Stein's avatar
William Stein committed
992
    while s.sy not in expr_terminators:
993
        exprs.append( p_test(s) )
Stefan Behnel's avatar
Stefan Behnel committed
994
        if s.sy != ',':
William Stein's avatar
William Stein committed
995 996 997 998
            break
        s.next()
    return exprs

999 1000 1001 1002 1003 1004 1005 1006
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
1007

1008 1009 1010 1011

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

def p_testlist(s):
William Stein's avatar
William Stein committed
1012
    pos = s.position()
1013
    expr = p_test(s)
William Stein's avatar
William Stein committed
1014 1015
    if s.sy == ',':
        s.next()
1016
        exprs = p_simple_expr_list(s, expr)
William Stein's avatar
William Stein committed
1017 1018 1019 1020
        return ExprNodes.TupleNode(pos, args = exprs)
    else:
        return expr

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

1023
def p_testlist_star_expr(s):
Robert Bradshaw's avatar
Robert Bradshaw committed
1024
    pos = s.position()
1025
    expr = p_test_or_starred_expr(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
1026
    if s.sy == ',':
1027
        s.next()
1028 1029
        exprs = p_test_or_starred_expr_list(s, expr)
        return ExprNodes.TupleNode(pos, args = exprs)
Robert Bradshaw's avatar
Robert Bradshaw committed
1030 1031 1032
    else:
        return expr

1033 1034 1035
# testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )

def p_testlist_comp(s):
Robert Bradshaw's avatar
Robert Bradshaw committed
1036
    pos = s.position()
1037
    expr = p_test_or_starred_expr(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
1038
    if s.sy == ',':
1039
        s.next()
1040
        exprs = p_test_or_starred_expr_list(s, expr)
Robert Bradshaw's avatar
Robert Bradshaw committed
1041
        return ExprNodes.TupleNode(pos, args = exprs)
1042 1043
    elif s.sy == 'for':
        return p_genexp(s, expr)
Robert Bradshaw's avatar
Robert Bradshaw committed
1044 1045
    else:
        return expr
1046 1047 1048

def p_genexp(s, expr):
    # s.sy == 'for'
1049
    loop = p_comp_for(s, Nodes.ExprStatNode(
Vitja Makarov's avatar
Vitja Makarov committed
1050
        expr.pos, expr = ExprNodes.YieldExprNode(expr.pos, arg=expr)))
1051 1052
    return ExprNodes.GeneratorExpressionNode(expr.pos, loop=loop)

William Stein's avatar
William Stein committed
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
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)

1068 1069 1070 1071 1072 1073
def p_nonlocal_statement(s):
    pos = s.position()
    s.next()
    names = p_ident_list(s)
    return Nodes.NonlocalNode(pos, names = names)

William Stein's avatar
William Stein committed
1074
def p_expression_or_assignment(s):
1075
    expr_list = [p_testlist_star_expr(s)]
1076 1077 1078 1079 1080 1081
    if s.sy == '=' and expr_list[0].is_starred:
        # This is a common enough error to make when learning Cython to let
        # it fail as early as possible and give a very clear error message.
        s.error("a starred assignment target must be in a list or tuple"
                " - maybe you meant to use an index assignment: var[0] = ...",
                pos=expr_list[0].pos)
William Stein's avatar
William Stein committed
1082 1083
    while s.sy == '=':
        s.next()
1084 1085 1086 1087 1088
        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
1089
    if len(expr_list) == 1:
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1090
        if re.match(r"([+*/\%^\&|-]|<<|>>|\*\*|//)=", s.sy):
1091 1092 1093
            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
1094
            operator = s.sy[:-1]
1095
            s.next()
1096 1097 1098 1099
            if s.sy == 'yield':
                rhs = p_yield_expression(s)
            else:
                rhs = p_testlist(s)
1100
            return Nodes.InPlaceAssignmentNode(lhs.pos, operator = operator, lhs = lhs, rhs = rhs)
1101
        expr = expr_list[0]
1102 1103 1104 1105
        if isinstance(expr, (ExprNodes.UnicodeNode, ExprNodes.StringNode, ExprNodes.BytesNode)):
            return Nodes.PassStatNode(expr.pos)
        else:
            return Nodes.ExprStatNode(expr.pos, expr = expr)
1106

1107 1108
    rhs = expr_list[-1]
    if len(expr_list) == 2:
1109
        return Nodes.SingleAssignmentNode(rhs.pos,
1110
            lhs = expr_list[0], rhs = rhs)
William Stein's avatar
William Stein committed
1111
    else:
1112
        return Nodes.CascadedAssignmentNode(rhs.pos,
1113
            lhs_list = expr_list[:-1], rhs = rhs)
William Stein's avatar
William Stein committed
1114 1115 1116 1117

def p_print_statement(s):
    # s.sy == 'print'
    pos = s.position()
1118
    ends_with_comma = 0
William Stein's avatar
William Stein committed
1119 1120
    s.next()
    if s.sy == '>>':
1121
        s.next()
1122
        stream = p_test(s)
1123 1124 1125 1126 1127
        if s.sy == ',':
            s.next()
            ends_with_comma = s.sy in ('NEWLINE', 'EOF')
    else:
        stream = None
William Stein's avatar
William Stein committed
1128 1129
    args = []
    if s.sy not in ('NEWLINE', 'EOF'):
1130
        args.append(p_test(s))
William Stein's avatar
William Stein committed
1131 1132 1133
        while s.sy == ',':
            s.next()
            if s.sy in ('NEWLINE', 'EOF'):
1134
                ends_with_comma = 1
William Stein's avatar
William Stein committed
1135
                break
1136
            args.append(p_test(s))
1137
    arg_tuple = ExprNodes.TupleNode(pos, args = args)
1138
    return Nodes.PrintStatNode(pos,
1139 1140
        arg_tuple = arg_tuple, stream = stream,
        append_newline = not ends_with_comma)
William Stein's avatar
William Stein committed
1141

1142 1143 1144 1145 1146 1147 1148
def p_exec_statement(s):
    # s.sy == 'exec'
    pos = s.position()
    s.next()
    args = [ p_bit_expr(s) ]
    if s.sy == 'in':
        s.next()
1149
        args.append(p_test(s))
1150 1151
        if s.sy == ',':
            s.next()
1152
            args.append(p_test(s))
1153 1154
    return Nodes.ExecStatNode(pos, args = args)

William Stein's avatar
William Stein committed
1155 1156 1157 1158
def p_del_statement(s):
    # s.sy == 'del'
    pos = s.position()
    s.next()
1159
    # FIXME: 'exprlist' in Python
William Stein's avatar
William Stein committed
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    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:
1187
        value = p_testlist(s)
William Stein's avatar
William Stein committed
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    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
Haoyu Bai's avatar
Haoyu Bai committed
1199
    cause = None
William Stein's avatar
William Stein committed
1200
    if s.sy not in statement_terminators:
1201
        exc_type = p_test(s)
William Stein's avatar
William Stein committed
1202 1203
        if s.sy == ',':
            s.next()
1204
            exc_value = p_test(s)
William Stein's avatar
William Stein committed
1205 1206
            if s.sy == ',':
                s.next()
1207
                exc_tb = p_test(s)
Haoyu Bai's avatar
Haoyu Bai committed
1208 1209 1210
        elif s.sy == 'from':
            s.next()
            cause = p_test(s)
1211
    if exc_type or exc_value or exc_tb:
1212
        return Nodes.RaiseStatNode(pos,
1213 1214
            exc_type = exc_type,
            exc_value = exc_value,
Haoyu Bai's avatar
Haoyu Bai committed
1215 1216
            exc_tb = exc_tb,
            cause = cause)
1217 1218
    else:
        return Nodes.ReraiseStatNode(pos)
William Stein's avatar
William Stein committed
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230

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:
1231
        dotted_name = EncodedString(dotted_name)
William Stein's avatar
William Stein committed
1232
        if kind == 'cimport':
1233
            stat = Nodes.CImportStatNode(pos,
William Stein's avatar
William Stein committed
1234 1235 1236
                module_name = dotted_name,
                as_name = as_name)
        else:
1237 1238
            if as_name and "." in dotted_name:
                name_list = ExprNodes.ListNode(pos, args = [
1239
                        ExprNodes.IdentifierStringNode(pos, value = EncodedString("*"))])
1240 1241
            else:
                name_list = None
William Stein's avatar
William Stein committed
1242
            stat = Nodes.SingleAssignmentNode(pos,
1243
                lhs = ExprNodes.NameNode(pos,
William Stein's avatar
William Stein committed
1244
                    name = as_name or target_name),
1245
                rhs = ExprNodes.ImportNode(pos,
1246
                    module_name = ExprNodes.IdentifierStringNode(
1247
                        pos, value = dotted_name),
1248
                    level = None,
1249
                    name_list = name_list))
William Stein's avatar
William Stein committed
1250 1251 1252
        stats.append(stat)
    return Nodes.StatListNode(pos, stats = stats)

Stefan Behnel's avatar
Stefan Behnel committed
1253
def p_from_import_statement(s, first_statement = 0):
William Stein's avatar
William Stein committed
1254 1255 1256
    # s.sy == 'from'
    pos = s.position()
    s.next()
Haoyu Bai's avatar
Haoyu Bai committed
1257 1258 1259 1260 1261 1262
    if s.sy == '.':
        # count relative import level
        level = 0
        while s.sy == '.':
            level += 1
            s.next()
1263 1264
        if s.sy == 'cimport':
            s.error("Relative cimport is not supported yet")
Haoyu Bai's avatar
Haoyu Bai committed
1265
    else:
1266 1267
        level = None
    if level is not None and s.sy == 'import':
Haoyu Bai's avatar
Haoyu Bai committed
1268 1269
        # we are dealing with "from .. import foo, bar"
        dotted_name_pos, dotted_name = s.position(), ''
1270 1271 1272
    elif level is not None and s.sy == 'cimport':
        # "from .. cimport"
        s.error("Relative cimport is not supported yet")
Haoyu Bai's avatar
Haoyu Bai committed
1273 1274 1275
    else:
        (dotted_name_pos, _, dotted_name, _) = \
            p_dotted_name(s, as_allowed = 0)
William Stein's avatar
William Stein committed
1276 1277 1278 1279 1280
    if s.sy in ('import', 'cimport'):
        kind = s.sy
        s.next()
    else:
        s.error("Expected 'import' or 'cimport'")
Haoyu Bai's avatar
Haoyu Bai committed
1281

1282
    is_cimport = kind == 'cimport'
1283
    is_parenthesized = False
William Stein's avatar
William Stein committed
1284
    if s.sy == '*':
1285
        imported_names = [(s.position(), "*", None, None)]
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1286 1287
        s.next()
    else:
1288 1289 1290
        if s.sy == '(':
            is_parenthesized = True
            s.next()
1291
        imported_names = [p_imported_name(s, is_cimport)]
William Stein's avatar
William Stein committed
1292 1293
    while s.sy == ',':
        s.next()
1294 1295
        if is_parenthesized and s.sy == ')':
            break
1296
        imported_names.append(p_imported_name(s, is_cimport))
1297 1298
    if is_parenthesized:
        s.expect(')')
1299
    dotted_name = EncodedString(dotted_name)
Stefan Behnel's avatar
Stefan Behnel committed
1300 1301 1302
    if dotted_name == '__future__':
        if not first_statement:
            s.error("from __future__ imports must occur at the beginning of the file")
Haoyu Bai's avatar
Haoyu Bai committed
1303 1304
        elif level is not None:
            s.error("invalid syntax")
Stefan Behnel's avatar
Stefan Behnel committed
1305
        else:
1306
            for (name_pos, name, as_name, kind) in imported_names:
1307 1308 1309
                if name == "braces":
                    s.error("not a chance", name_pos)
                    break
Stefan Behnel's avatar
Stefan Behnel committed
1310 1311 1312
                try:
                    directive = getattr(Future, name)
                except AttributeError:
1313
                    s.error("future feature %s is not defined" % name, name_pos)
Stefan Behnel's avatar
Stefan Behnel committed
1314 1315 1316 1317
                    break
                s.context.future_directives.add(directive)
        return Nodes.PassStatNode(pos)
    elif kind == 'cimport':
William Stein's avatar
William Stein committed
1318 1319 1320 1321 1322 1323
        return Nodes.FromCImportStatNode(pos,
            module_name = dotted_name,
            imported_names = imported_names)
    else:
        imported_name_strings = []
        items = []
1324
        for (name_pos, name, as_name, kind) in imported_names:
1325
            encoded_name = EncodedString(name)
William Stein's avatar
William Stein committed
1326
            imported_name_strings.append(
1327
                ExprNodes.IdentifierStringNode(name_pos, value = encoded_name))
William Stein's avatar
William Stein committed
1328 1329
            items.append(
                (name,
1330
                 ExprNodes.NameNode(name_pos,
Stefan Behnel's avatar
Stefan Behnel committed
1331
                                    name = as_name or name)))
William Stein's avatar
William Stein committed
1332 1333
        import_list = ExprNodes.ListNode(
            imported_names[0][0], args = imported_name_strings)
1334
        dotted_name = EncodedString(dotted_name)
William Stein's avatar
William Stein committed
1335 1336
        return Nodes.FromImportStatNode(pos,
            module = ExprNodes.ImportNode(dotted_name_pos,
1337
                module_name = ExprNodes.IdentifierStringNode(pos, value = dotted_name),
Haoyu Bai's avatar
Haoyu Bai committed
1338
                level = level,
William Stein's avatar
William Stein committed
1339 1340 1341
                name_list = import_list),
            items = items)

1342 1343 1344
imported_name_kinds = ('class', 'struct', 'union')

def p_imported_name(s, is_cimport):
William Stein's avatar
William Stein committed
1345
    pos = s.position()
1346 1347 1348 1349
    kind = None
    if is_cimport and s.systring in imported_name_kinds:
        kind = s.systring
        s.next()
William Stein's avatar
William Stein committed
1350 1351
    name = p_ident(s)
    as_name = p_as_name(s)
1352
    return (pos, name, as_name, kind)
William Stein's avatar
William Stein committed
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363

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
1364
    return (pos, target_name, u'.'.join(names), as_name)
William Stein's avatar
William Stein committed
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376

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()
1377
    cond = p_test(s)
William Stein's avatar
William Stein committed
1378 1379
    if s.sy == ',':
        s.next()
1380
        value = p_test(s)
William Stein's avatar
William Stein committed
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
    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()
1401
    test = p_test(s)
William Stein's avatar
William Stein committed
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
    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()
1417
    test = p_test(s)
William Stein's avatar
William Stein committed
1418 1419
    body = p_suite(s)
    else_clause = p_else_clause(s)
1420 1421
    return Nodes.WhileStatNode(pos,
        condition = test, body = body,
William Stein's avatar
William Stein committed
1422 1423 1424 1425 1426 1427
        else_clause = else_clause)

def p_for_statement(s):
    # s.sy == 'for'
    pos = s.position()
    s.next()
1428
    kw = p_for_bounds(s, allow_testlist=True)
1429 1430
    body = p_suite(s)
    else_clause = p_else_clause(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
1431
    kw.update(body = body, else_clause = else_clause)
Robert Bradshaw's avatar
Robert Bradshaw committed
1432
    return Nodes.ForStatNode(pos, **kw)
1433

1434
def p_for_bounds(s, allow_testlist=True):
William Stein's avatar
William Stein committed
1435 1436 1437
    target = p_for_target(s)
    if s.sy == 'in':
        s.next()
1438
        iterator = p_for_iterator(s, allow_testlist)
1439
        return dict( target = target, iterator = iterator )
1440
    elif not s.in_python_file:
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1441 1442 1443 1444 1445 1446
        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
1447 1448 1449 1450 1451 1452
        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)
1453
        step = p_for_from_step(s)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1454 1455 1456 1457
        if target is None:
            target = ExprNodes.NameNode(name2_pos, name = name2)
        else:
            if not target.is_name:
1458
                error(target.pos,
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1459 1460 1461 1462
                    "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
1463
        if rel1[0] != rel2[0]:
William Stein's avatar
William Stein committed
1464 1465
            error(rel2_pos,
                "Relation directions in for-from do not match")
1466 1467 1468
        return dict(target = target,
                    bound1 = bound1,
                    relation1 = rel1,
1469 1470 1471 1472
                    relation2 = rel2,
                    bound2 = bound2,
                    step = step,
                    )
1473 1474 1475
    else:
        s.expect('in')
        return {}
William Stein's avatar
William Stein committed
1476 1477 1478 1479 1480 1481 1482 1483

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 '<', '<=', '>' '>='")
1484

1485
def p_for_from_step(s):
1486
    if s.sy == 'IDENT' and s.systring == 'by':
1487 1488 1489 1490 1491
        s.next()
        step = p_bit_expr(s)
        return step
    else:
        return None
William Stein's avatar
William Stein committed
1492 1493 1494

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

1495
def p_target(s, terminator):
William Stein's avatar
William Stein committed
1496
    pos = s.position()
1497
    expr = p_starred_expr(s)
William Stein's avatar
William Stein committed
1498 1499 1500
    if s.sy == ',':
        s.next()
        exprs = [expr]
1501
        while s.sy != terminator:
1502
            exprs.append(p_starred_expr(s))
Stefan Behnel's avatar
Stefan Behnel committed
1503
            if s.sy != ',':
William Stein's avatar
William Stein committed
1504 1505 1506 1507 1508 1509
                break
            s.next()
        return ExprNodes.TupleNode(pos, args = exprs)
    else:
        return expr

1510 1511 1512
def p_for_target(s):
    return p_target(s, 'in')

1513
def p_for_iterator(s, allow_testlist=True):
William Stein's avatar
William Stein committed
1514
    pos = s.position()
1515 1516 1517 1518
    if allow_testlist:
        expr = p_testlist(s)
    else:
        expr = p_or_test(s)
William Stein's avatar
William Stein committed
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
    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)
1534
        body = Nodes.TryExceptStatNode(pos,
William Stein's avatar
William Stein committed
1535 1536
            body = body, except_clauses = except_clauses,
            else_clause = else_clause)
1537 1538 1539 1540
        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
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
        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
1554
    if s.sy != ':':
1555
        exc_type = p_test(s)
1556 1557 1558 1559 1560
        # normalise into list of single exception tests
        if isinstance(exc_type, ExprNodes.TupleNode):
            exc_type = exc_type.args
        else:
            exc_type = [exc_type]
1561
        if s.sy == ',' or (s.sy == 'IDENT' and s.systring == 'as'):
William Stein's avatar
William Stein committed
1562
            s.next()
1563
            exc_value = p_test(s)
1564
        elif s.sy == 'IDENT' and s.systring == 'as':
1565
            # Py3 syntax requires a name here
1566
            s.next()
1567 1568 1569
            pos2 = s.position()
            name = p_ident(s)
            exc_value = ExprNodes.NameNode(pos2, name = name)
William Stein's avatar
William Stein committed
1570 1571 1572 1573
    body = p_suite(s)
    return Nodes.ExceptClauseNode(pos,
        pattern = exc_type, target = exc_value, body = body)

1574
def p_include_statement(s, ctx):
William Stein's avatar
William Stein committed
1575 1576
    pos = s.position()
    s.next() # 'include'
1577
    unicode_include_file_name = p_string_literal(s, 'u')[2]
William Stein's avatar
William Stein committed
1578
    s.expect_newline("Syntax error in include statement")
1579
    if s.compile_time_eval:
1580
        include_file_name = unicode_include_file_name
1581 1582
        include_file_path = s.context.find_include_file(include_file_name, pos)
        if include_file_path:
1583
            s.included_files.append(include_file_name)
1584
            f = Utils.open_source_file(include_file_path, mode="rU")
1585
            source_desc = FileSourceDescriptor(include_file_path)
1586
            s2 = PyrexScanner(f, source_desc, s, source_encoding=f.encoding, parse_comments=s.parse_comments)
1587
            try:
1588
                tree = p_statement_list(s2, ctx)
1589 1590 1591 1592 1593
            finally:
                f.close()
            return tree
        else:
            return None
William Stein's avatar
William Stein committed
1594
    else:
1595 1596 1597 1598
        return Nodes.PassStatNode(pos)

def p_with_statement(s):
    s.next() # 'with'
1599
    if s.systring == 'template' and not s.in_python_file:
1600 1601 1602 1603 1604 1605 1606
        node = p_with_template(s)
    else:
        node = p_with_items(s)
    return node

def p_with_items(s):
    pos = s.position()
1607
    if not s.in_python_file and s.sy == 'IDENT' and s.systring in ('nogil', 'gil'):
1608 1609
        state = s.systring
        s.next()
1610
        if s.sy == ',':
Danilo Freitas's avatar
Danilo Freitas committed
1611
            s.next()
1612
            body = p_with_items(s)
Danilo Freitas's avatar
Danilo Freitas committed
1613
        else:
1614 1615
            body = p_suite(s)
        return Nodes.GILStatNode(pos, state = state, body = body)
1616
    else:
1617
        manager = p_test(s)
1618 1619 1620
        target = None
        if s.sy == 'IDENT' and s.systring == 'as':
            s.next()
1621 1622 1623 1624 1625 1626
            target = p_starred_expr(s)
        if s.sy == ',':
            s.next()
            body = p_with_items(s)
        else:
            body = p_suite(s)
1627
    return Nodes.WithStatNode(pos, manager = manager,
Robert Bradshaw's avatar
Robert Bradshaw committed
1628
                              target = target, body = body)
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653

def p_with_template(s):
    pos = s.position()
    templates = []
    s.next()
    s.expect('[')
    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")

Stefan Behnel's avatar
Stefan Behnel committed
1654
def p_simple_statement(s, first_statement = 0):
William Stein's avatar
William Stein committed
1655 1656 1657
    #print "p_simple_statement:", s.sy, s.systring ###
    if s.sy == 'global':
        node = p_global_statement(s)
1658 1659
    elif s.sy == 'nonlocal':
        node = p_nonlocal_statement(s)
William Stein's avatar
William Stein committed
1660 1661
    elif s.sy == 'print':
        node = p_print_statement(s)
1662 1663
    elif s.sy == 'exec':
        node = p_exec_statement(s)
William Stein's avatar
William Stein committed
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
    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
1677
        node = p_from_import_statement(s, first_statement = first_statement)
1678
    elif s.sy == 'yield':
1679
        node = p_yield_statement(s)
William Stein's avatar
William Stein committed
1680 1681 1682 1683 1684 1685 1686 1687
    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

1688
def p_simple_statement_list(s, ctx, first_statement = 0):
William Stein's avatar
William Stein committed
1689 1690
    # Parse a series of simple statements on one line
    # separated by semicolons.
Stefan Behnel's avatar
Stefan Behnel committed
1691
    stat = p_simple_statement(s, first_statement = first_statement)
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
    pos = stat.pos
    stats = []
    if not isinstance(stat, Nodes.PassStatNode):
        stats.append(stat)
    while s.sy == ';':
        #print "p_simple_statement_list: maybe more to follow" ###
        s.next()
        if s.sy in ('NEWLINE', 'EOF'):
            break
        stat = p_simple_statement(s, first_statement = first_statement)
        if isinstance(stat, Nodes.PassStatNode):
            continue
        stats.append(stat)
        first_statement = False

    if not stats:
        stat = Nodes.PassStatNode(pos)
    elif len(stats) == 1:
        stat = stats[0]
    else:
        stat = Nodes.StatListNode(pos, stats = stats)
William Stein's avatar
William Stein committed
1713 1714 1715
    s.expect_newline("Syntax error in simple statement list")
    return stat

1716 1717 1718
def p_compile_time_expr(s):
    old = s.compile_time_expr
    s.compile_time_expr = 1
1719
    expr = p_testlist(s)
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
    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)

1736
def p_IF_statement(s, ctx):
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1737
    pos = s.position()
1738 1739 1740 1741 1742 1743 1744 1745
    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))
1746
        body = p_suite(s, ctx)
1747 1748 1749
        if s.compile_time_eval:
            result = body
            current_eval = 0
Stefan Behnel's avatar
Stefan Behnel committed
1750
        if s.sy != 'ELIF':
1751 1752 1753 1754
            break
    if s.sy == 'ELSE':
        s.next()
        s.compile_time_eval = current_eval
1755
        body = p_suite(s, ctx)
1756 1757 1758
        if current_eval:
            result = body
    if not result:
Stefan Behnel's avatar
Stefan Behnel committed
1759
        result = Nodes.PassStatNode(pos)
1760 1761 1762
    s.compile_time_eval = saved_eval
    return result

1763 1764
def p_statement(s, ctx, first_statement = 0):
    cdef_flag = ctx.cdef_flag
Robert Bradshaw's avatar
Robert Bradshaw committed
1765
    decorators = None
William Stein's avatar
William Stein committed
1766
    if s.sy == 'ctypedef':
1767
        if ctx.level not in ('module', 'module_pxd'):
William Stein's avatar
William Stein committed
1768
            s.error("ctypedef statement not allowed here")
1769 1770
        #if ctx.api:
        #    error(s.position(), "'api' not allowed with 'ctypedef'")
1771
        return p_ctypedef_statement(s, ctx)
1772 1773 1774
    elif s.sy == 'DEF':
        return p_DEF_statement(s)
    elif s.sy == 'IF':
1775
        return p_IF_statement(s, ctx)
1776
    elif s.sy == 'DECORATOR':
Haoyu Bai's avatar
Haoyu Bai committed
1777
        if ctx.level not in ('module', 'class', 'c_class', 'function', 'property', 'module_pxd', 'c_class_pxd', 'other'):
1778 1779 1780
            s.error('decorator not allowed here')
        s.level = ctx.level
        decorators = p_decorators(s)
1781 1782
        bad_toks =  'def', 'cdef', 'cpdef', 'class'
        if not ctx.allow_struct_enum_decorator and s.sy not in bad_toks:
1783
            s.error("Decorators can only be followed by functions or classes")
1784 1785 1786
    elif s.sy == 'pass' and cdef_flag:
        # empty cdef block
        return p_pass_statement(s, with_newline = 1)
1787 1788 1789 1790 1791

    overridable = 0
    if s.sy == 'cdef':
        cdef_flag = 1
        s.next()
1792
    elif s.sy == 'cpdef':
1793 1794 1795 1796 1797 1798 1799 1800 1801
        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:
1802 1803 1804 1805
            tup = Nodes.CFuncDefNode, Nodes.CVarDefNode, Nodes.CClassDefNode
            if ctx.allow_struct_enum_decorator:
                tup += Nodes.CStructOrUnionDefNode, Nodes.CEnumDefNode
            if not isinstance(node, tup):
1806
                s.error("Decorators can only be followed by functions or classes")
1807 1808
            node.decorators = decorators
        return node
William Stein's avatar
William Stein committed
1809
    else:
1810
        if ctx.api:
1811
            s.error("'api' not allowed with this statement")
1812
        elif s.sy == 'def':
1813 1814 1815
            # 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'):
1816
                s.error('def statement not allowed here')
1817
            s.level = ctx.level
1818 1819
            return p_def_statement(s, decorators)
        elif s.sy == 'class':
1820
            if ctx.level not in ('module', 'function', 'class', 'other'):
1821
                s.error("class definition not allowed here")
1822
            return p_class_statement(s, decorators)
1823 1824 1825 1826 1827 1828 1829 1830
        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
1831
        else:
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
            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)
1844
            else:
1845 1846
                return p_simple_statement_list(
                    s, ctx, first_statement = first_statement)
William Stein's avatar
William Stein committed
1847

1848
def p_statement_list(s, ctx, first_statement = 0):
William Stein's avatar
William Stein committed
1849 1850 1851 1852
    # Parse a series of statements separated by newlines.
    pos = s.position()
    stats = []
    while s.sy not in ('DEDENT', 'EOF'):
1853 1854 1855 1856 1857 1858 1859 1860
        stat = p_statement(s, ctx, first_statement = first_statement)
        if isinstance(stat, Nodes.PassStatNode):
            continue
        stats.append(stat)
        first_statement = False
    if not stats:
        return Nodes.PassStatNode(pos)
    elif len(stats) == 1:
1861 1862 1863
        return stats[0]
    else:
        return Nodes.StatListNode(pos, stats = stats)
William Stein's avatar
William Stein committed
1864

1865
def p_suite(s, ctx = Ctx(), with_doc = 0, with_pseudo_doc = 0):
William Stein's avatar
William Stein committed
1866 1867 1868 1869 1870 1871 1872
    pos = s.position()
    s.expect(':')
    doc = None
    stmts = []
    if s.sy == 'NEWLINE':
        s.next()
        s.expect_indent()
1873 1874
        if with_doc or with_pseudo_doc:
            doc = p_doc_string(s)
1875
        body = p_statement_list(s, ctx)
William Stein's avatar
William Stein committed
1876 1877
        s.expect_dedent()
    else:
1878
        if ctx.api:
1879
            s.error("'api' not allowed with this statement")
1880 1881
        if ctx.level in ('module', 'class', 'function', 'other'):
            body = p_simple_statement_list(s, ctx)
William Stein's avatar
William Stein committed
1882 1883 1884 1885 1886 1887 1888 1889
        else:
            body = p_pass_statement(s)
            s.expect_newline("Syntax error in declarations")
    if with_doc:
        return doc, body
    else:
        return body

1890
def p_positional_and_keyword_args(s, end_sy_set, templates = None):
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    """
    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
1907
        if s.sy == 'IDENT' and s.peek()[0] == '=':
1908
            ident = s.systring
1909
            s.next() # s.sy is '='
1910
            s.next()
1911
            if looking_at_expr(s):
1912
                arg = p_test(s)
1913 1914
            else:
                base_type = p_c_base_type(s, templates = templates)
1915
                declarator = p_c_declarator(s, empty = 1)
1916
                arg = Nodes.CComplexBaseTypeNode(base_type.pos,
1917 1918 1919 1920 1921 1922
                    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
1923

1924
        else:
1925
            if looking_at_expr(s):
1926
                arg = p_test(s)
1927 1928
            else:
                base_type = p_c_base_type(s, templates = templates)
1929
                declarator = p_c_declarator(s, empty = 1)
1930
                arg = Nodes.CComplexBaseTypeNode(base_type.pos,
1931
                    base_type = base_type, declarator = declarator)
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
                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:
1942
                    s.error("Unmatched %s" % " or ".join(end_sy_set))
1943 1944 1945 1946
            break
        s.next()
    return positional_args, keyword_args

Danilo Freitas's avatar
Danilo Freitas committed
1947
def p_c_base_type(s, self_flag = 0, nonempty = 0, templates = None):
William Stein's avatar
William Stein committed
1948 1949 1950 1951 1952
    # 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
1953
        return p_c_simple_base_type(s, self_flag, nonempty = nonempty, templates = templates)
William Stein's avatar
William Stein committed
1954

1955 1956 1957 1958 1959 1960 1961 1962
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 ""

1963
calling_convention_words = ("__stdcall", "__cdecl", "__fastcall")
1964

William Stein's avatar
William Stein committed
1965 1966 1967 1968 1969 1970 1971
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(')')
1972
    return Nodes.CComplexBaseTypeNode(pos,
William Stein's avatar
William Stein committed
1973 1974
        base_type = base_type, declarator = declarator)

Danilo Freitas's avatar
Danilo Freitas committed
1975
def p_c_simple_base_type(s, self_flag, nonempty, templates = None):
1976
    #print "p_c_simple_base_type: self_flag =", self_flag, nonempty
William Stein's avatar
William Stein committed
1977 1978 1979
    is_basic = 0
    signed = 1
    longness = 0
1980
    complex = 0
William Stein's avatar
William Stein committed
1981
    module_path = []
1982
    pos = s.position()
1983 1984
    if not s.sy == 'IDENT':
        error(pos, "Expected an identifier, found '%s'" % s.sy)
Robert Bradshaw's avatar
Robert Bradshaw committed
1985 1986 1987 1988 1989
    if s.systring == 'const':
        s.next()
        base_type = p_c_base_type(s,
            self_flag = self_flag, nonempty = nonempty, templates = templates)
        return Nodes.CConstTypeNode(pos, base_type = base_type)
William Stein's avatar
William Stein committed
1990 1991 1992
    if looking_at_base_type(s):
        #print "p_c_simple_base_type: looking_at_base_type at", s.position()
        is_basic = 1
1993 1994
        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
1995 1996 1997
            name = s.systring
            s.next()
        else:
1998 1999 2000 2001 2002
            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:
Stefan Behnel's avatar
Stefan Behnel committed
2003
                name = 'int'  # long [int], short [int], long [int] complex, etc.
2004 2005 2006
        if s.sy == 'IDENT' and s.systring == 'complex':
            complex = 1
            s.next()
2007 2008 2009 2010 2011 2012 2013 2014
    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)
2015
    else:
2016 2017 2018
        name = s.systring
        s.next()
        if nonempty and s.sy != 'IDENT':
2019
            # Make sure this is not a declaration of a variable or function.
2020 2021
            if s.sy == '(':
                s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
2022
                if s.sy == '*' or s.sy == '**' or s.sy == '&':
2023 2024 2025 2026 2027
                    s.put_back('(', '(')
                else:
                    s.put_back('(', '(')
                    s.put_back('IDENT', name)
                    name = None
Robert Bradshaw's avatar
Robert Bradshaw committed
2028
            elif s.sy not in ('*', '**', '[', '&'):
2029 2030
                s.put_back('IDENT', name)
                name = None
Danilo Freitas's avatar
Danilo Freitas committed
2031

2032
    type_node = Nodes.CSimpleBaseTypeNode(pos,
William Stein's avatar
William Stein committed
2033 2034
        name = name, module_path = module_path,
        is_basic_c_type = is_basic, signed = signed,
2035
        complex = complex, longness = longness,
Danilo Freitas's avatar
Danilo Freitas committed
2036
        is_self_arg = self_flag, templates = templates)
William Stein's avatar
William Stein committed
2037

2038
    #    declarations here.
2039
    if s.sy == '[':
2040
        if is_memoryviewslice_access(s):
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
2041
            type_node = p_memoryviewslice_access(s, type_node)
2042 2043
        else:
            type_node = p_buffer_or_template(s, type_node, templates)
2044

Robert Bradshaw's avatar
Robert Bradshaw committed
2045 2046 2047 2048
    if s.sy == '.':
        s.next()
        name = p_ident(s)
        type_node = Nodes.CNestedBaseTypeNode(pos, base_type = type_node, name = name)
2049

Robert Bradshaw's avatar
Robert Bradshaw committed
2050
    return type_node
2051

2052
def p_buffer_or_template(s, base_type_node, templates):
2053 2054 2055
    # s.sy == '['
    pos = s.position()
    s.next()
2056 2057
    # Note that buffer_positional_options_count=1, so the only positional argument is dtype.
    # For templated types, all parameters are types.
2058
    positional_args, keyword_args = (
2059
        p_positional_and_keyword_args(s, (']',), templates)
2060 2061 2062 2063 2064 2065 2066 2067
    )
    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
        ])
2068
    result = Nodes.TemplatedTypeNode(pos,
2069 2070
        positional_args = positional_args,
        keyword_args = keyword_dict,
2071
        base_type_node = base_type_node)
2072
    return result
2073

2074 2075 2076 2077 2078 2079
def p_bracketed_base_type(s, base_type_node, nonempty, empty):
    # s.sy == '['
    if empty and not nonempty:
        # sizeof-like thing.  Only anonymous C arrays allowed (int[SIZE]).
        return base_type_node
    elif not empty and nonempty:
2080 2081 2082
        # declaration of either memoryview slice or buffer.
        if is_memoryviewslice_access(s):
            return p_memoryviewslice_access(s, base_type_node)
2083
        else:
Mark Florisson's avatar
Mark Florisson committed
2084 2085
            return p_buffer_or_template(s, base_type_node, None)
            # return p_buffer_access(s, base_type_node)
2086
    elif not empty and not nonempty:
2087 2088 2089 2090 2091
        # only anonymous C arrays and memoryview slice arrays here.  We
        # disallow buffer declarations for now, due to ambiguity with anonymous
        # C arrays.
        if is_memoryviewslice_access(s):
            return p_memoryviewslice_access(s, base_type_node)
2092 2093 2094
        else:
            return base_type_node

2095
def is_memoryviewslice_access(s):
2096
    # s.sy == '['
2097
    # a memoryview slice declaration is distinguishable from a buffer access
2098
    # declaration by the first entry in the bracketed list.  The buffer will
2099
    # not have an unnested colon in the first entry; the memoryview slice will.
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
    saved = [(s.sy, s.systring)]
    s.next()
    retval = False
    if s.systring == ':':
        retval = True
    elif s.sy == 'INT':
        saved.append((s.sy, s.systring))
        s.next()
        if s.sy == ':':
            retval = True

2111
    for sv in saved[::-1]:
2112 2113 2114 2115
        s.put_back(*sv)

    return retval

2116
def p_memoryviewslice_access(s, base_type_node):
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
    # s.sy == '['
    pos = s.position()
    s.next()
    subscripts = p_subscript_list(s)
    # make sure each entry in subscripts is a slice
    for subscript in subscripts:
        if len(subscript) < 2:
            s.error("An axis specification in memoryview declaration does not have a ':'.")
    s.expect(']')
    indexes = make_slice_nodes(pos, subscripts)
2127
    result = Nodes.MemoryViewSliceTypeNode(pos,
2128 2129 2130
            base_type_node = base_type_node,
            axes = indexes)
    return result
2131

2132
def looking_at_name(s):
2133 2134
    return s.sy == 'IDENT' and not s.systring in calling_convention_words

2135
def looking_at_expr(s):
2136
    if s.systring in base_type_start_words:
2137
        return False
2138 2139 2140 2141 2142
    elif s.sy == 'IDENT':
        is_type = False
        name = s.systring
        dotted_path = []
        s.next()
2143

2144 2145 2146 2147
        while s.sy == '.':
            s.next()
            dotted_path.append(s.systring)
            s.expect('IDENT')
2148

2149
        saved = s.sy, s.systring
2150 2151 2152
        if s.sy == 'IDENT':
            is_type = True
        elif s.sy == '*' or s.sy == '**':
2153
            s.next()
2154
            is_type = s.sy in (')', ']')
2155 2156 2157 2158 2159 2160 2161 2162 2163
            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)
2164

2165 2166 2167 2168
        dotted_path.reverse()
        for p in dotted_path:
            s.put_back('IDENT', p)
            s.put_back('.', '.')
2169

2170
        s.put_back('IDENT', name)
2171
        return not is_type and saved[0]
2172
    else:
2173
        return True
William Stein's avatar
William Stein committed
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187

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
2188

2189 2190 2191 2192 2193 2194
def looking_at_call(s):
    "See if we're looking at a.b.c("
    # Don't mess up the original position, so save and restore it.
    # Unfortunately there's no good way to handle this, as a subsequent call
    # to next() will not advance the position until it reads a new token.
    position = s.start_line, s.start_col
Mark Florisson's avatar
Mark Florisson committed
2195
    result = looking_at_expr(s) == u'('
2196 2197 2198 2199
    if not result:
        s.start_line, s.start_col = position
    return result

2200 2201 2202 2203
basic_c_type_names = ("void", "char", "int", "float", "double", "bint")

special_basic_c_types = {
    # name : (signed, longness)
2204
    "Py_UNICODE" : (0, 0),
Stefan Behnel's avatar
Stefan Behnel committed
2205
    "Py_UCS4"    : (0, 0),
2206
    "Py_ssize_t" : (2, 0),
2207
    "ssize_t"    : (2, 0),
2208 2209
    "size_t"     : (0, 0),
}
William Stein's avatar
William Stein committed
2210 2211 2212

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

2213
base_type_start_words = \
2214
    basic_c_type_names + sign_and_longness_words + tuple(special_basic_c_types)
William Stein's avatar
William Stein committed
2215

Mark Florisson's avatar
Mark Florisson committed
2216 2217
struct_enum_union = ("struct", "union", "enum", "packed")

William Stein's avatar
William Stein committed
2218 2219 2220 2221 2222 2223
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
2224 2225
        elif s.systring == 'signed':
            signed = 2
William Stein's avatar
William Stein committed
2226 2227 2228 2229 2230 2231 2232 2233
        elif s.systring == 'short':
            longness = -1
        elif s.systring == 'long':
            longness += 1
        s.next()
    return signed, longness

def p_opt_cname(s):
2234 2235 2236
    literal = p_opt_string_literal(s, 'u')
    if literal is not None:
        cname = EncodedString(literal)
Stefan Behnel's avatar
Stefan Behnel committed
2237
        cname.encoding = s.source_encoding
William Stein's avatar
William Stein committed
2238 2239 2240 2241
    else:
        cname = None
    return cname

2242 2243 2244
def p_c_declarator(s, ctx = Ctx(), empty = 0, is_type = 0, cmethod_flag = 0,
                   assignable = 0, nonempty = 0,
                   calling_convention_allowed = 0):
2245 2246
    # 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
2247 2248 2249
    # If cmethod_flag is true, then if this declarator declares
    # a function, it's a C method of an extension type.
    pos = s.position()
2250 2251
    if s.sy == '(':
        s.next()
2252
        if s.sy == ')' or looking_at_name(s):
2253
            base = Nodes.CNameDeclaratorNode(pos, name = EncodedString(u""), cname = None)
2254
            result = p_c_func_declarator(s, pos, ctx, base, cmethod_flag)
2255
        else:
2256 2257 2258 2259
            result = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
                                    cmethod_flag = cmethod_flag,
                                    nonempty = nonempty,
                                    calling_convention_allowed = 1)
2260 2261
            s.expect(')')
    else:
2262 2263
        result = p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
                                       assignable, nonempty)
Stefan Behnel's avatar
Stefan Behnel committed
2264
    if not calling_convention_allowed and result.calling_convention and s.sy != '(':
2265 2266 2267 2268 2269 2270 2271 2272
        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()
2273
            result = p_c_func_declarator(s, pos, ctx, result, cmethod_flag)
2274 2275 2276 2277 2278 2279
        cmethod_flag = 0
    return result

def p_c_array_declarator(s, base):
    pos = s.position()
    s.next() # '['
Stefan Behnel's avatar
Stefan Behnel committed
2280
    if s.sy != ']':
2281
        dim = p_testlist(s)
2282 2283 2284 2285 2286
    else:
        dim = None
    s.expect(']')
    return Nodes.CArrayDeclaratorNode(pos, base = base, dimension = dim)

2287
def p_c_func_declarator(s, pos, ctx, base, cmethod_flag):
2288
    #  Opening paren has already been skipped
2289 2290
    args = p_c_arg_list(s, ctx, cmethod_flag = cmethod_flag,
                        nonempty_declarators = 0)
2291 2292 2293 2294 2295
    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)
2296
    return Nodes.CFuncDeclaratorNode(pos,
2297 2298
        base = base, args = args, has_varargs = ellipsis,
        exception_value = exc_val, exception_check = exc_check,
2299
        nogil = nogil or ctx.nogil or with_gil, with_gil = with_gil)
2300

Robert Bradshaw's avatar
Robert Bradshaw committed
2301
supported_overloaded_operators = set([
2302
    '+', '-', '*', '/', '%',
Robert Bradshaw's avatar
Robert Bradshaw committed
2303
    '++', '--', '~', '|', '&', '^', '<<', '>>', ',',
Robert Bradshaw's avatar
Robert Bradshaw committed
2304
    '==', '!=', '>=', '>', '<=', '<',
2305
    '[]', '()', '!',
Robert Bradshaw's avatar
Robert Bradshaw committed
2306
])
2307

2308 2309
def p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
                          assignable, nonempty):
2310 2311
    pos = s.position()
    calling_convention = p_calling_convention(s)
William Stein's avatar
William Stein committed
2312 2313
    if s.sy == '*':
        s.next()
2314 2315 2316
        base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
                              cmethod_flag = cmethod_flag,
                              assignable = assignable, nonempty = nonempty)
2317
        result = Nodes.CPtrDeclaratorNode(pos,
William Stein's avatar
William Stein committed
2318 2319 2320
            base = base)
    elif s.sy == '**': # scanner returns this as a single token
        s.next()
2321 2322 2323
        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
2324 2325 2326
        result = Nodes.CPtrDeclaratorNode(pos,
            base = Nodes.CPtrDeclaratorNode(pos,
                base = base))
Robert Bradshaw's avatar
merge  
Robert Bradshaw committed
2327
    elif s.sy == '&':
2328 2329 2330 2331 2332
        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
2333
    else:
2334 2335
        rhs = None
        if s.sy == 'IDENT':
2336
            name = EncodedString(s.systring)
2337 2338
            if empty:
                error(s.position(), "Declarator should be empty")
William Stein's avatar
William Stein committed
2339
            s.next()
2340
            cname = p_opt_cname(s)
2341
            if name != 'operator' and s.sy == '=' and assignable:
2342
                s.next()
2343
                rhs = p_test(s)
William Stein's avatar
William Stein committed
2344
        else:
2345 2346 2347 2348
            if nonempty:
                error(s.position(), "Empty declarator")
            name = ""
            cname = None
2349
        if cname is None and ctx.namespace is not None and nonempty:
2350
            cname = ctx.namespace + "::" + name
2351
        if name == 'operator' and ctx.visibility == 'extern' and nonempty:
2352
            op = s.sy
2353
            if [1 for c in op if c in '+-*/<=>!%&|([^~,']:
2354
                s.next()
2355 2356 2357 2358 2359 2360 2361
                # Handle diphthong operators.
                if op == '(':
                    s.expect(')')
                    op = '()'
                elif op == '[':
                    s.expect(']')
                    op = '[]'
Stefan Behnel's avatar
Stefan Behnel committed
2362 2363
                elif op in ('-', '+', '|', '&') and s.sy == op:
                    op *= 2       # ++, --, ...
2364
                    s.next()
Stefan Behnel's avatar
Stefan Behnel committed
2365 2366
                elif s.sy == '=':
                    op += s.sy    # +=, -=, ...
2367 2368 2369 2370
                    s.next()
                if op not in supported_overloaded_operators:
                    s.error("Overloading operator '%s' not yet supported." % op)
                name = name+op
2371
        result = Nodes.CNameDeclaratorNode(pos,
Robert Bradshaw's avatar
Robert Bradshaw committed
2372
            name = name, cname = cname, default = rhs)
2373
    result.calling_convention = calling_convention
William Stein's avatar
William Stein committed
2374 2375
    return result

2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390
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
2391 2392 2393 2394 2395 2396 2397 2398
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
2399 2400 2401
        elif s.sy == '+':
            exc_check = '+'
            s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
2402 2403 2404 2405
            if s.sy == 'IDENT':
                name = s.systring
                s.next()
                exc_val = p_name(s, name)
William Stein's avatar
William Stein committed
2406 2407 2408 2409
        else:
            if s.sy == '?':
                exc_check = 1
                s.next()
2410
            exc_val = p_test(s)
William Stein's avatar
William Stein committed
2411 2412 2413 2414
    return exc_val, exc_check

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

2415
def p_c_arg_list(s, ctx = Ctx(), in_pyfunc = 0, cmethod_flag = 0,
2416
                 nonempty_declarators = 0, kw_only = 0, annotated = 1):
2417 2418
    #  Comma-separated list of C argument declarations, possibly empty.
    #  May have a trailing comma.
William Stein's avatar
William Stein committed
2419
    args = []
2420 2421
    is_self_arg = cmethod_flag
    while s.sy not in c_arg_list_terminators:
2422
        args.append(p_c_arg_decl(s, ctx, in_pyfunc, is_self_arg,
2423 2424
            nonempty = nonempty_declarators, kw_only = kw_only,
            annotated = annotated))
2425 2426 2427 2428
        if s.sy != ',':
            break
        s.next()
        is_self_arg = 0
William Stein's avatar
William Stein committed
2429 2430 2431 2432 2433 2434 2435 2436 2437
    return args

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

2438 2439
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
2440
    pos = s.position()
2441
    not_none = or_none = 0
William Stein's avatar
William Stein committed
2442
    default = None
2443
    annotation = None
2444 2445 2446 2447 2448 2449 2450 2451 2452
    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)
2453
    declarator = p_c_declarator(s, ctx, nonempty = nonempty)
2454 2455
    if s.sy in ('not', 'or') and not s.in_python_file:
        kind = s.sy
William Stein's avatar
William Stein committed
2456 2457 2458 2459 2460 2461
        s.next()
        if s.sy == 'IDENT' and s.systring == 'None':
            s.next()
        else:
            s.error("Expected 'None'")
        if not in_pyfunc:
2462 2463 2464
            error(pos, "'%s None' only allowed in Python functions" % kind)
        or_none = kind == 'or'
        not_none = kind == 'not'
2465 2466
    if annotated and s.sy == ':':
        s.next()
2467
        annotation = p_test(s)
William Stein's avatar
William Stein committed
2468 2469
    if s.sy == '=':
        s.next()
Stefan Behnel's avatar
Stefan Behnel committed
2470
        if 'pxd' in ctx.level:
2471 2472
            if s.sy not in ['*', '?']:
                error(pos, "default values cannot be specified in pxd files, use ? or *")
Robert Bradshaw's avatar
Robert Bradshaw committed
2473
            default = ExprNodes.BoolNode(1)
2474 2475
            s.next()
        else:
2476
            default = p_test(s)
William Stein's avatar
William Stein committed
2477 2478 2479 2480
    return Nodes.CArgDeclNode(pos,
        base_type = base_type,
        declarator = declarator,
        not_none = not_none,
2481
        or_none = or_none,
2482
        default = default,
2483
        annotation = annotation,
2484
        kw_only = kw_only)
William Stein's avatar
William Stein committed
2485

2486 2487 2488 2489 2490 2491 2492
def p_api(s):
    if s.sy == 'IDENT' and s.systring == 'api':
        s.next()
        return 1
    else:
        return 0

2493
def p_cdef_statement(s, ctx):
William Stein's avatar
William Stein committed
2494
    pos = s.position()
2495 2496 2497 2498 2499 2500 2501
    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
2502 2503
    elif s.sy == 'import':
        s.next()
2504
        return p_cdef_extern_block(s, pos, ctx)
2505
    elif p_nogil(s):
2506
        ctx.nogil = 1
2507 2508 2509 2510 2511 2512
        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")
2513
        return p_cdef_block(s, ctx)
William Stein's avatar
William Stein committed
2514
    elif s.sy == 'class':
2515
        if ctx.level not in ('module', 'module_pxd'):
William Stein's avatar
William Stein committed
2516
            error(pos, "Extension type definition not allowed here")
2517 2518
        if ctx.overridable:
            error(pos, "Extension types cannot be declared cpdef")
2519
        return p_c_class_definition(s, pos, ctx)
Robert Bradshaw's avatar
Robert Bradshaw committed
2520 2521
    elif s.sy == 'IDENT' and s.systring == 'cppclass':
        return p_cpp_class_definition(s, pos, ctx)
Mark Florisson's avatar
Mark Florisson committed
2522
    elif s.sy == 'IDENT' and s.systring in struct_enum_union:
2523
        if ctx.level not in ('module', 'module_pxd'):
William Stein's avatar
William Stein committed
2524
            error(pos, "C struct/union/enum definition not allowed here")
2525 2526
        if ctx.overridable:
            error(pos, "C struct/union/enum cannot be declared cpdef")
Mark Florisson's avatar
Mark Florisson committed
2527 2528 2529
        return p_struct_enum(s, pos, ctx)
    elif s.sy == 'IDENT' and s.systring == 'fused':
        return p_fused_definition(s, pos, ctx)
William Stein's avatar
William Stein committed
2530
    else:
2531
        return p_c_func_or_var_declaration(s, pos, ctx)
2532

2533 2534
def p_cdef_block(s, ctx):
    return p_suite(s, ctx(cdef_flag = 1))
William Stein's avatar
William Stein committed
2535

2536
def p_cdef_extern_block(s, pos, ctx):
2537 2538
    if ctx.overridable:
        error(pos, "cdef extern blocks cannot be declared cpdef")
William Stein's avatar
William Stein committed
2539 2540 2541 2542 2543
    include_file = None
    s.expect('from')
    if s.sy == '*':
        s.next()
    else:
2544
        include_file = p_string_literal(s, 'u')[2]
2545
    ctx = ctx(cdef_flag = 1, visibility = 'extern')
2546 2547
    if s.systring == "namespace":
        s.next()
2548
        ctx.namespace = p_string_literal(s, 'u')[2]
2549 2550 2551
    if p_nogil(s):
        ctx.nogil = 1
    body = p_suite(s, ctx)
William Stein's avatar
William Stein committed
2552 2553
    return Nodes.CDefExternNode(pos,
        include_file = include_file,
2554
        body = body,
Robert Bradshaw's avatar
Robert Bradshaw committed
2555
        namespace = ctx.namespace)
William Stein's avatar
William Stein committed
2556

2557
def p_c_enum_definition(s, pos, ctx):
William Stein's avatar
William Stein committed
2558 2559 2560 2561 2562 2563
    # s.sy == ident 'enum'
    s.next()
    if s.sy == 'IDENT':
        name = s.systring
        s.next()
        cname = p_opt_cname(s)
2564 2565
        if cname is None and ctx.namespace is not None:
            cname = ctx.namespace + "::" + name
William Stein's avatar
William Stein committed
2566 2567 2568 2569 2570 2571
    else:
        name = None
        cname = None
    items = None
    s.expect(':')
    items = []
Stefan Behnel's avatar
Stefan Behnel committed
2572
    if s.sy != 'NEWLINE':
2573
        p_c_enum_line(s, ctx, items)
William Stein's avatar
William Stein committed
2574 2575 2576 2577
    else:
        s.next() # 'NEWLINE'
        s.expect_indent()
        while s.sy not in ('DEDENT', 'EOF'):
2578
            p_c_enum_line(s, ctx, items)
William Stein's avatar
William Stein committed
2579
        s.expect_dedent()
2580 2581 2582
    return Nodes.CEnumDefNode(
        pos, name = name, cname = cname, items = items,
        typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2583
        api = ctx.api, in_pxd = ctx.level == 'module_pxd')
William Stein's avatar
William Stein committed
2584

2585
def p_c_enum_line(s, ctx, items):
Stefan Behnel's avatar
Stefan Behnel committed
2586
    if s.sy != 'pass':
2587
        p_c_enum_item(s, ctx, items)
William Stein's avatar
William Stein committed
2588 2589 2590 2591
        while s.sy == ',':
            s.next()
            if s.sy in ('NEWLINE', 'EOF'):
                break
2592
            p_c_enum_item(s, ctx, items)
William Stein's avatar
William Stein committed
2593 2594 2595 2596
    else:
        s.next()
    s.expect_newline("Syntax error in enum item list")

2597
def p_c_enum_item(s, ctx, items):
William Stein's avatar
William Stein committed
2598 2599 2600
    pos = s.position()
    name = p_ident(s)
    cname = p_opt_cname(s)
2601 2602
    if cname is None and ctx.namespace is not None:
        cname = ctx.namespace + "::" + name
William Stein's avatar
William Stein committed
2603 2604 2605
    value = None
    if s.sy == '=':
        s.next()
2606
        value = p_test(s)
2607
    items.append(Nodes.CEnumDefItemNode(pos,
William Stein's avatar
William Stein committed
2608 2609
        name = name, cname = cname, value = value))

2610
def p_c_struct_or_union_definition(s, pos, ctx):
2611 2612 2613 2614
    packed = False
    if s.systring == 'packed':
        packed = True
        s.next()
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
2615
        if s.sy != 'IDENT' or s.systring != 'struct':
2616
            s.expected('struct')
William Stein's avatar
William Stein committed
2617 2618 2619 2620 2621
    # s.sy == ident 'struct' or 'union'
    kind = s.systring
    s.next()
    name = p_ident(s)
    cname = p_opt_cname(s)
2622 2623
    if cname is None and ctx.namespace is not None:
        cname = ctx.namespace + "::" + name
William Stein's avatar
William Stein committed
2624 2625 2626 2627 2628 2629
    attributes = None
    if s.sy == ':':
        s.next()
        s.expect('NEWLINE')
        s.expect_indent()
        attributes = []
2630
        body_ctx = Ctx()
Stefan Behnel's avatar
Stefan Behnel committed
2631 2632
        while s.sy != 'DEDENT':
            if s.sy != 'pass':
William Stein's avatar
William Stein committed
2633
                attributes.append(
2634
                    p_c_func_or_var_declaration(s, s.position(), body_ctx))
William Stein's avatar
William Stein committed
2635 2636 2637 2638 2639 2640
            else:
                s.next()
                s.expect_newline("Expected a newline")
        s.expect_dedent()
    else:
        s.expect_newline("Syntax error in struct or union definition")
Robert Bradshaw's avatar
Robert Bradshaw committed
2641
    return Nodes.CStructOrUnionDefNode(pos,
William Stein's avatar
William Stein committed
2642
        name = name, cname = cname, kind = kind, attributes = attributes,
2643
        typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2644
        api = ctx.api, in_pxd = ctx.level == 'module_pxd', packed = packed)
William Stein's avatar
William Stein committed
2645

Mark Florisson's avatar
Mark Florisson committed
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
def p_fused_definition(s, pos, ctx):
    """
    c(type)def fused my_fused_type:
        ...
    """
    # s.systring == 'fused'

    if ctx.level not in ('module', 'module_pxd'):
        error(pos, "Fused type definition not allowed here")

    s.next()
    name = p_ident(s)

    s.expect(":")
    s.expect_newline()
    s.expect_indent()

    types = []
    while s.sy != 'DEDENT':
        if s.sy != 'pass':
            #types.append(p_c_declarator(s))
            types.append(p_c_base_type(s)) #, nonempty=1))
        else:
            s.next()

        s.expect_newline()

    s.expect_dedent()

    if not types:
        error(pos, "Need at least one type")

    return Nodes.FusedTypeNode(pos, name=name, types=types)

def p_struct_enum(s, pos, ctx):
    if s.systring == 'enum':
        return p_c_enum_definition(s, pos, ctx)
    else:
        return p_c_struct_or_union_definition(s, pos, ctx)

William Stein's avatar
William Stein committed
2686 2687 2688 2689 2690
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
2691
        if prev_visibility != 'private' and visibility != prev_visibility:
William Stein's avatar
William Stein committed
2692 2693 2694 2695
            s.error("Conflicting visibility options '%s' and '%s'"
                % (prev_visibility, visibility))
        s.next()
    return visibility
2696

2697
def p_c_modifiers(s):
2698
    if s.sy == 'IDENT' and s.systring in ('inline',):
2699
        modifier = s.systring
2700
        s.next()
2701 2702
        return [modifier] + p_c_modifiers(s)
    return []
William Stein's avatar
William Stein committed
2703

2704 2705
def p_c_func_or_var_declaration(s, pos, ctx):
    cmethod_flag = ctx.level in ('c_class', 'c_class_pxd')
2706
    modifiers = p_c_modifiers(s)
Danilo Freitas's avatar
Danilo Freitas committed
2707
    base_type = p_c_base_type(s, nonempty = 1, templates = ctx.templates)
2708 2709 2710
    declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
                                assignable = 1, nonempty = 1)
    declarator.overridable = ctx.overridable
Robert Bradshaw's avatar
Robert Bradshaw committed
2711 2712 2713 2714 2715
    if s.sy == 'IDENT' and s.systring == 'const' and ctx.level == 'cpp_class':
        s.next()
        is_const_method = 1
    else:
        is_const_method = 0
William Stein's avatar
William Stein committed
2716
    if s.sy == ':':
2717
        if ctx.level not in ('module', 'c_class', 'module_pxd', 'c_class_pxd', 'cpp_class') and not ctx.templates:
William Stein's avatar
William Stein committed
2718
            s.error("C function definition not allowed here")
2719
        doc, suite = p_suite(s, Ctx(level = 'function'), with_doc = 1)
William Stein's avatar
William Stein committed
2720
        result = Nodes.CFuncDefNode(pos,
2721
            visibility = ctx.visibility,
William Stein's avatar
William Stein committed
2722
            base_type = base_type,
2723
            declarator = declarator,
2724
            body = suite,
2725
            doc = doc,
2726
            modifiers = modifiers,
2727
            api = ctx.api,
Robert Bradshaw's avatar
Robert Bradshaw committed
2728 2729
            overridable = ctx.overridable,
            is_const_method = is_const_method)
William Stein's avatar
William Stein committed
2730
    else:
Stefan Behnel's avatar
Stefan Behnel committed
2731
        #if api:
2732
        #    s.error("'api' not allowed with variable declaration")
William Stein's avatar
William Stein committed
2733 2734 2735 2736 2737
        declarators = [declarator]
        while s.sy == ',':
            s.next()
            if s.sy == 'NEWLINE':
                break
2738 2739
            declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
                                        assignable = 1, nonempty = 1)
William Stein's avatar
William Stein committed
2740 2741
            declarators.append(declarator)
        s.expect_newline("Syntax error in C variable declaration")
2742
        result = Nodes.CVarDefNode(pos,
2743 2744
            visibility = ctx.visibility,
            base_type = base_type,
2745
            declarators = declarators,
2746
            in_pxd = ctx.level in ('module_pxd', 'c_class_pxd'),
2747
            api = ctx.api,
2748
            modifiers = modifiers,
2749
            overridable = ctx.overridable)
William Stein's avatar
William Stein committed
2750 2751
    return result

2752
def p_ctypedef_statement(s, ctx):
William Stein's avatar
William Stein committed
2753 2754 2755
    # s.sy == 'ctypedef'
    pos = s.position()
    s.next()
2756
    visibility = p_visibility(s, ctx.visibility)
2757
    api = p_api(s)
2758
    ctx = ctx(typedef_flag = 1, visibility = visibility)
2759 2760
    if api:
        ctx.api = 1
William Stein's avatar
William Stein committed
2761
    if s.sy == 'class':
2762
        return p_c_class_definition(s, pos, ctx)
Mark Florisson's avatar
Mark Florisson committed
2763 2764 2765 2766
    elif s.sy == 'IDENT' and s.systring in struct_enum_union:
        return p_struct_enum(s, pos, ctx)
    elif s.sy == 'IDENT' and s.systring == 'fused':
        return p_fused_definition(s, pos, ctx)
William Stein's avatar
William Stein committed
2767
    else:
2768
        base_type = p_c_base_type(s, nonempty = 1)
2769
        declarator = p_c_declarator(s, ctx, is_type = 1, nonempty = 1)
William Stein's avatar
William Stein committed
2770
        s.expect_newline("Syntax error in ctypedef statement")
2771 2772
        return Nodes.CTypeDefNode(
            pos, base_type = base_type,
Robert Bradshaw's avatar
Robert Bradshaw committed
2773
            declarator = declarator,
2774
            visibility = visibility, api = api,
2775
            in_pxd = ctx.level == 'module_pxd')
William Stein's avatar
William Stein committed
2776

2777 2778 2779 2780 2781
def p_decorators(s):
    decorators = []
    while s.sy == 'DECORATOR':
        pos = s.position()
        s.next()
2782 2783
        decstring = p_dotted_name(s, as_allowed=0)[2]
        names = decstring.split('.')
2784
        decorator = ExprNodes.NameNode(pos, name=EncodedString(names[0]))
2785 2786
        for name in names[1:]:
            decorator = ExprNodes.AttributeNode(pos,
2787
                                           attribute=EncodedString(name),
2788
                                           obj=decorator)
2789 2790 2791 2792 2793 2794 2795
        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
2796 2797 2798
    # s.sy == 'def'
    pos = s.position()
    s.next()
2799
    name = EncodedString( p_ident(s) )
William Stein's avatar
William Stein committed
2800
    s.expect('(');
Stefan Behnel's avatar
Stefan Behnel committed
2801 2802 2803
    args, star_arg, starstar_arg = p_varargslist(s, terminator=')')
    s.expect(')')
    if p_nogil(s):
2804
        error(pos, "Python function cannot be declared nogil")
2805 2806 2807
    return_type_annotation = None
    if s.sy == '->':
        s.next()
2808
        return_type_annotation = p_test(s)
Stefan Behnel's avatar
Stefan Behnel committed
2809
    doc, body = p_suite(s, Ctx(level = 'function'), with_doc = 1)
2810
    return Nodes.DefNode(pos, name = name, args = args,
Stefan Behnel's avatar
Stefan Behnel committed
2811
        star_arg = star_arg, starstar_arg = starstar_arg,
2812 2813
        doc = doc, body = body, decorators = decorators,
        return_type_annotation = return_type_annotation)
Stefan Behnel's avatar
Stefan Behnel committed
2814

2815 2816 2817
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
2818 2819 2820 2821
    star_arg = None
    starstar_arg = None
    if s.sy == '*':
        s.next()
2822
        if s.sy == 'IDENT':
2823
            star_arg = p_py_arg_decl(s, annotated=annotated)
William Stein's avatar
William Stein committed
2824 2825
        if s.sy == ',':
            s.next()
2826
            args.extend(p_c_arg_list(s, in_pyfunc = 1,
2827
                nonempty_declarators = 1, kw_only = 1, annotated = annotated))
Stefan Behnel's avatar
Stefan Behnel committed
2828
        elif s.sy != terminator:
2829 2830
            s.error("Syntax error in Python function argument list")
    if s.sy == '**':
William Stein's avatar
William Stein committed
2831
        s.next()
2832
        starstar_arg = p_py_arg_decl(s, annotated=annotated)
Stefan Behnel's avatar
Stefan Behnel committed
2833
    return (args, star_arg, starstar_arg)
William Stein's avatar
William Stein committed
2834

2835
def p_py_arg_decl(s, annotated = 1):
William Stein's avatar
William Stein committed
2836 2837
    pos = s.position()
    name = p_ident(s)
2838
    annotation = None
2839
    if annotated and s.sy == ':':
2840
        s.next()
2841
        annotation = p_test(s)
2842
    return Nodes.PyArgDeclNode(pos, name = name, annotation = annotation)
William Stein's avatar
William Stein committed
2843

2844
def p_class_statement(s, decorators):
William Stein's avatar
William Stein committed
2845 2846 2847
    # s.sy == 'class'
    pos = s.position()
    s.next()
2848
    class_name = EncodedString( p_ident(s) )
2849
    class_name.encoding = s.source_encoding
2850 2851 2852
    arg_tuple = None
    keyword_dict = None
    starstar_arg = None
William Stein's avatar
William Stein committed
2853
    if s.sy == '(':
2854
        positional_args, keyword_args, star_arg, starstar_arg = \
2855 2856
                            p_call_parse_args(s, allow_genexp = False)
        arg_tuple, keyword_dict = p_call_build_packed_args(
Stefan Behnel's avatar
Stefan Behnel committed
2857
            pos, positional_args, keyword_args, star_arg, None)
2858 2859 2860
    if arg_tuple is None:
        # XXX: empty arg_tuple
        arg_tuple = ExprNodes.TupleNode(pos, args = [])
2861
    doc, body = p_suite(s, Ctx(level = 'class'), with_doc = 1)
William Stein's avatar
William Stein committed
2862 2863
    return Nodes.PyClassDefNode(pos,
        name = class_name,
2864 2865 2866
        bases = arg_tuple,
        keyword_args = keyword_dict,
        starstar_arg = starstar_arg,
2867
        doc = doc, body = body, decorators = decorators)
William Stein's avatar
William Stein committed
2868

2869
def p_c_class_definition(s, pos,  ctx):
William Stein's avatar
William Stein committed
2870 2871 2872 2873 2874 2875 2876 2877
    # 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)
2878
    if module_path and ctx.visibility != 'extern':
William Stein's avatar
William Stein committed
2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900
        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 == '[':
2901 2902
        if ctx.visibility not in ('public', 'extern') and not ctx.api:
            error(s.position(), "Name options only allowed for 'public', 'api', or 'extern' C class")
William Stein's avatar
William Stein committed
2903 2904
        objstruct_name, typeobj_name = p_c_class_options(s)
    if s.sy == ':':
2905
        if ctx.level == 'module_pxd':
William Stein's avatar
William Stein committed
2906 2907 2908
            body_level = 'c_class_pxd'
        else:
            body_level = 'c_class'
2909
        doc, body = p_suite(s, Ctx(level = body_level), with_doc = 1)
William Stein's avatar
William Stein committed
2910 2911 2912 2913
    else:
        s.expect_newline("Syntax error in C class definition")
        doc = None
        body = None
2914
    if ctx.visibility == 'extern':
William Stein's avatar
William Stein committed
2915 2916 2917 2918
        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")
2919
    elif ctx.visibility == 'public':
William Stein's avatar
William Stein committed
2920 2921 2922 2923
        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")
2924 2925
    elif ctx.visibility == 'private':
        if ctx.api:
2926 2927 2928 2929
            if not objstruct_name:
                error(pos, "Object struct name specification required for 'api' C class")
            if not typeobj_name:
                error(pos, "Type object name specification required for 'api' C class")
2930
    else:
2931
        error(pos, "Invalid class visibility '%s'" % ctx.visibility)
William Stein's avatar
William Stein committed
2932
    return Nodes.CClassDefNode(pos,
2933 2934 2935
        visibility = ctx.visibility,
        typedef_flag = ctx.typedef_flag,
        api = ctx.api,
William Stein's avatar
William Stein committed
2936 2937 2938 2939 2940 2941 2942
        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,
2943
        in_pxd = ctx.level == 'module_pxd',
William Stein's avatar
William Stein committed
2944 2945 2946 2947 2948 2949 2950 2951
        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
2952
        if s.sy != 'IDENT':
William Stein's avatar
William Stein committed
2953 2954 2955 2956 2957 2958 2959
            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
2960
        if s.sy != ',':
William Stein's avatar
William Stein committed
2961 2962 2963 2964 2965 2966 2967 2968 2969
            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)
2970
    doc, body = p_suite(s, Ctx(level = 'property'), with_doc = 1)
William Stein's avatar
William Stein committed
2971 2972
    return Nodes.PropertyNode(pos, name = name, doc = doc, body = body)

2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
def p_doc_string(s):
    if s.sy == 'BEGIN_STRING':
        pos = s.position()
        kind, bytes_result, unicode_result = p_cat_string_literal(s)
        if s.sy != 'EOF':
            s.expect_newline("Syntax error in doc string")
        if kind in ('u', ''):
            return unicode_result
        warning(pos, "Python 3 requires docstrings to be unicode strings")
        return bytes_result
    else:
        return None

2986 2987
def p_code(s, level=None, ctx=Ctx):
    body = p_statement_list(s, ctx(level = level), first_statement = 1)
2988 2989 2990 2991
    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
2992

2993
COMPILER_DIRECTIVE_COMMENT_RE = re.compile(r"^#\s*cython\s*:\s*((\w|[.])+\s*=.*)$")
2994 2995

def p_compiler_directive_comments(s):
2996
    result = {}
2997 2998 2999
    while s.sy == 'commentline':
        m = COMPILER_DIRECTIVE_COMMENT_RE.match(s.systring)
        if m:
3000
            directives = m.group(1).strip()
3001
            try:
3002 3003
                result.update( Options.parse_directive_list(
                    directives, ignore_unknown=True) )
3004
            except ValueError, e:
3005
                s.error(e.args[0], fatal=False)
3006 3007 3008
        s.next()
    return result

3009
def p_module(s, pxd, full_module_name, ctx=Ctx):
William Stein's avatar
William Stein committed
3010
    pos = s.position()
3011

3012
    directive_comments = p_compiler_directive_comments(s)
3013 3014
    s.parse_comments = False

3015
    if 'language_level' in directive_comments:
Stefan Behnel's avatar
Stefan Behnel committed
3016
        s.context.set_language_level(directive_comments['language_level'])
3017

3018
    doc = p_doc_string(s)
William Stein's avatar
William Stein committed
3019 3020 3021 3022
    if pxd:
        level = 'module_pxd'
    else:
        level = 'module'
3023

3024
    body = p_statement_list(s, ctx(level=level), first_statement = 1)
Stefan Behnel's avatar
Stefan Behnel committed
3025
    if s.sy != 'EOF':
William Stein's avatar
William Stein committed
3026 3027
        s.error("Syntax error in statement [%s,%s]" % (
            repr(s.sy), repr(s.systring)))
3028 3029
    return ModuleNode(pos, doc = doc, body = body,
                      full_module_name = full_module_name,
3030
                      directive_comments = directive_comments)
William Stein's avatar
William Stein committed
3031

3032 3033 3034 3035 3036
def p_cpp_class_definition(s, pos,  ctx):
    # s.sy == 'cppclass'
    s.next()
    module_path = []
    class_name = p_ident(s)
3037 3038 3039
    cname = p_opt_cname(s)
    if cname is None and ctx.namespace is not None:
        cname = ctx.namespace + "::" + class_name
3040
    if s.sy == '.':
3041
        error(pos, "Qualified class name not allowed C++ class")
Danilo Freitas's avatar
Danilo Freitas committed
3042 3043
    if s.sy == '[':
        s.next()
3044
        templates = [p_ident(s)]
Danilo Freitas's avatar
Danilo Freitas committed
3045 3046
        while s.sy == ',':
            s.next()
3047
            templates.append(p_ident(s))
Danilo Freitas's avatar
Danilo Freitas committed
3048
        s.expect(']')
3049 3050
    else:
        templates = None
3051
    if s.sy == '(':
3052
        s.next()
3053
        base_classes = [p_c_base_type(s, templates = templates)]
3054
        while s.sy == ',':
3055
            s.next()
3056
            base_classes.append(p_c_base_type(s, templates = templates))
3057
        s.expect(')')
3058 3059
    else:
        base_classes = []
3060
    if s.sy == '[':
3061
        error(s.position(), "Name options not allowed for C++ class")
3062
    if s.sy == ':':
3063 3064 3065 3066
        s.next()
        s.expect('NEWLINE')
        s.expect_indent()
        attributes = []
3067
        body_ctx = Ctx(visibility = ctx.visibility, level='cpp_class')
Danilo Freitas's avatar
Danilo Freitas committed
3068
        body_ctx.templates = templates
3069
        while s.sy != 'DEDENT':
Robert Bradshaw's avatar
Robert Bradshaw committed
3070 3071 3072 3073
            if s.systring == 'cppclass':
                attributes.append(
                    p_cpp_class_definition(s, s.position(), body_ctx))
            elif s.sy != 'pass':
3074 3075 3076 3077 3078 3079
                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()
3080
    else:
3081
        attributes = None
3082 3083 3084
        s.expect_newline("Syntax error in C++ class definition")
    return Nodes.CppClassNode(pos,
        name = class_name,
3085
        cname = cname,
3086
        base_classes = base_classes,
3087 3088
        visibility = ctx.visibility,
        in_pxd = ctx.level == 'module_pxd',
Danilo Freitas's avatar
Danilo Freitas committed
3089 3090
        attributes = attributes,
        templates = templates)
3091 3092 3093



William Stein's avatar
William Stein committed
3094 3095 3096 3097 3098 3099
#----------------------------------------------
#
#   Debugging
#
#----------------------------------------------

Stefan Behnel's avatar
Stefan Behnel committed
3100
def print_parse_tree(f, node, level, key = None):
Stefan Behnel's avatar
Stefan Behnel committed
3101
    from types import ListType, TupleType
3102
    from Nodes import Node
William Stein's avatar
William Stein committed
3103 3104 3105 3106 3107 3108
    ind = "  " * level
    if node:
        f.write(ind)
        if key:
            f.write("%s: " % key)
        t = type(node)
Stefan Behnel's avatar
Stefan Behnel committed
3109
        if t is tuple:
William Stein's avatar
William Stein committed
3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121
            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
3122
                if name != 'tag' and name != 'pos':
William Stein's avatar
William Stein committed
3123 3124
                    print_parse_tree(f, value, level+1, name)
            return
Stefan Behnel's avatar
Stefan Behnel committed
3125
        elif t is list:
William Stein's avatar
William Stein committed
3126 3127 3128 3129 3130 3131
            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))