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

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

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

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
class Ctx(object):
    #  Parsing context
    level = 'other'
    visibility = 'private'
    cdef_flag = 0
    typedef_flag = 0
    api = 0
    overridable = 0
    nogil = 0

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

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

def p_binop_expr(s, ops, p_sub_expr):
    n1 = p_sub_expr(s)
    while s.sy in ops:
        op = s.sy
        pos = s.position()
        s.next()
        n2 = p_sub_expr(s)
        n1 = ExprNodes.binop_node(pos, op, n1, n2)
    return n1

Robert Bradshaw's avatar
Robert Bradshaw committed
78
#expression: or_test [if or_test else test] | lambda_form
William Stein's avatar
William Stein committed
79 80

def p_simple_expr(s):
Robert Bradshaw's avatar
Robert Bradshaw committed
81 82 83 84 85
    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
86 87 88
        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
89 90 91 92 93 94 95 96 97 98 99
    else:
        return expr
        
#test: or_test | lambda_form
        
def p_test(s):
    return p_or_test(s)

#or_test: and_test ('or' and_test)*

def p_or_test(s):
William Stein's avatar
William Stein committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    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):
132
    n1 = p_starred_expr(s)
William Stein's avatar
William Stein committed
133 134 135
    if s.sy in comparison_ops:
        pos = s.position()
        op = p_cmp_op(s)
136
        n2 = p_starred_expr(s)
William Stein's avatar
William Stein committed
137 138 139 140 141 142
        n1 = ExprNodes.PrimaryCmpNode(pos, 
            operator = op, operand1 = n1, operand2 = n2)
        if s.sy in comparison_ops:
            n1.cascade = p_cascaded_cmp(s)
    return n1

143
def p_starred_expr(s):
144
    pos = s.position()
145 146 147 148 149 150
    if s.sy == '*':
        starred = True
        s.next()
    else:
        starred = False
    expr = p_bit_expr(s)
151 152
    if starred:
        expr = ExprNodes.StarredTargetNode(pos, expr)
153 154
    return expr

William Stein's avatar
William Stein committed
155 156 157
def p_cascaded_cmp(s):
    pos = s.position()
    op = p_cmp_op(s)
158
    n2 = p_starred_expr(s)
William Stein's avatar
William Stein committed
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    result = ExprNodes.CascadedCmpNode(pos, 
        operator = op, operand2 = n2)
    if s.sy in comparison_ops:
        result.cascade = p_cascaded_cmp(s)
    return result

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

#expr: xor_expr ('|' xor_expr)*

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

#xor_expr: and_expr ('^' and_expr)*

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

#and_expr: shift_expr ('&' shift_expr)*

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

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

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

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

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

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

def p_term(s):
Robert Bradshaw's avatar
Robert Bradshaw committed
217
    return p_binop_expr(s, ('*', '/', '%', '//'), p_factor)
William Stein's avatar
William Stein committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244

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

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

def p_typecast(s):
    # s.sy == "<"
    pos = s.position()
    s.next()
    base_type = p_c_base_type(s)
245 246
    if base_type.name is None:
        s.error("Unknown type")
William Stein's avatar
William Stein committed
247
    declarator = p_c_declarator(s, empty = 1)
248 249 250 251 252
    if s.sy == '?':
        s.next()
        typecheck = 1
    else:
        typecheck = 0
William Stein's avatar
William Stein committed
253 254 255 256 257
    s.expect(">")
    operand = p_factor(s)
    return ExprNodes.TypecastNode(pos, 
        base_type = base_type, 
        declarator = declarator,
258 259
        operand = operand,
        typecheck = typecheck)
William Stein's avatar
William Stein committed
260 261 262 263 264 265

def p_sizeof(s):
    # s.sy == ident "sizeof"
    pos = s.position()
    s.next()
    s.expect('(')
266 267 268
    # Here we decide if we are looking at an expression or type
    # If it is actually a type, but parsable as an expression, 
    # we treat it as an expression here. 
269 270 271 272
    if looking_at_expr(s):
        operand = p_simple_expr(s)
        node = ExprNodes.SizeofVarNode(pos, operand = operand)
    else:
William Stein's avatar
William Stein committed
273 274 275 276 277 278 279
        base_type = p_c_base_type(s)
        declarator = p_c_declarator(s, empty = 1)
        node = ExprNodes.SizeofTypeNode(pos, 
            base_type = base_type, declarator = declarator)
    s.expect(')')
    return node

280 281 282 283 284 285 286 287 288
def p_yield_expression(s):
    # s.sy == "yield"
    pos = s.position()
    s.next()
    if s.sy not in ('EOF', 'NEWLINE', ')'):
        expr = p_expr(s)
    s.error("generators ('yield') are not currently supported")
    return Nodes.PassStatNode(pos)

William Stein's avatar
William Stein committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
#power: atom trailer* ('**' factor)*

def p_power(s):
    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

#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()
312
        name = EncodedString( p_ident(s) )
William Stein's avatar
William Stein committed
313 314 315 316 317 318 319 320 321 322 323 324 325 326
        return ExprNodes.AttributeNode(pos, 
            obj = node1, attribute = name)

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

def p_call(s, function):
    # s.sy == '('
    pos = s.position()
    s.next()
    positional_args = []
    keyword_args = []
    star_arg = None
    starstar_arg = None
327 328 329 330 331
    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
332
            s.next()
333
            star_arg = p_simple_expr(s)
William Stein's avatar
William Stein committed
334
        else:
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
            arg = p_simple_expr(s)
            if s.sy == '=':
                s.next()
                if not arg.is_name:
                    s.error("Expected an identifier before '='",
                        pos = arg.pos)
                encoded_name = EncodedString(arg.name)
                keyword = ExprNodes.IdentifierStringNode(arg.pos, 
                    value = encoded_name)
                arg = p_simple_expr(s)
                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
354
        if s.sy != ',':
William Stein's avatar
William Stein committed
355 356
            break
        s.next()
357

William Stein's avatar
William Stein committed
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    if s.sy == '**':
        s.next()
        starstar_arg = p_simple_expr(s)
        if s.sy == ',':
            s.next()
    s.expect(')')
    if not (keyword_args or star_arg or starstar_arg):
        return ExprNodes.SimpleCallNode(pos,
            function = function,
            args = positional_args)
    else:
        arg_tuple = None
        keyword_dict = None
        if positional_args or not star_arg:
            arg_tuple = ExprNodes.TupleNode(pos, 
                args = positional_args)
        if star_arg:
            star_arg_tuple = ExprNodes.AsTupleNode(pos, arg = star_arg)
            if arg_tuple:
                arg_tuple = ExprNodes.binop_node(pos, 
                    operator = '+', operand1 = arg_tuple,
                    operand2 = star_arg_tuple)
            else:
                arg_tuple = star_arg_tuple
        if keyword_args:
383 384
            keyword_args = [ExprNodes.DictItemNode(pos=key.pos, key=key, value=value) 
                              for key, value in keyword_args]
William Stein's avatar
William Stein committed
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
            keyword_dict = ExprNodes.DictNode(pos,
                key_value_pairs = keyword_args)
        return ExprNodes.GeneralCallNode(pos, 
            function = function,
            positional_args = arg_tuple,
            keyword_args = keyword_dict,
            starstar_arg = starstar_arg)

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

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

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

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

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

def p_subscript(s):
    # Parse a subscript and return a list of
    # 1, 2 or 3 ExprNodes, depending on how
    # many slice elements were encountered.
    pos = s.position()
    if s.sy == '.':
        expect_ellipsis(s)
        return [ExprNodes.EllipsisNode(pos)]
    else:
        start = p_slice_element(s, (':',))
Stefan Behnel's avatar
Stefan Behnel committed
438
        if s.sy != ':':
William Stein's avatar
William Stein committed
439 440 441
            return [start]
        s.next()
        stop = p_slice_element(s, (':', ',', ']'))
Stefan Behnel's avatar
Stefan Behnel committed
442
        if s.sy != ':':
William Stein's avatar
William Stein committed
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
            return [start, stop]
        s.next()
        step = p_slice_element(s, (':', ',', ']'))
        return [start, stop, step]

def p_slice_element(s, follow_set):
    # Simple expression which may be missing iff
    # it is followed by something in follow_set.
    if s.sy not in follow_set:
        return p_simple_expr(s)
    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)

484
#atom: '(' [testlist] ')' | '[' [listmaker] ']' | '{' [dict_or_set_maker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+
William Stein's avatar
William Stein committed
485 486 487 488 489 490 491 492

def p_atom(s):
    pos = s.position()
    sy = s.sy
    if sy == '(':
        s.next()
        if s.sy == ')':
            result = ExprNodes.TupleNode(pos, args = [])
493 494
        elif s.sy == 'yield':
            result = p_yield_expression(s)
William Stein's avatar
William Stein committed
495 496 497 498 499 500 501
        else:
            result = p_expr(s)
        s.expect(')')
        return result
    elif sy == '[':
        return p_list_maker(s)
    elif sy == '{':
502
        return p_dict_or_set_maker(s)
William Stein's avatar
William Stein committed
503 504 505
    elif sy == '`':
        return p_backquote_expr(s)
    elif sy == 'INT':
506
        value = s.systring
William Stein's avatar
William Stein committed
507
        s.next()
508 509 510 511 512 513 514 515 516 517 518 519
        unsigned = ""
        longness = ""
        while value[-1] in "UuLl":
            if value[-1] in "Ll":
                longness += "L"
            else:
                unsigned += "U"
            value = value[:-1]
        return ExprNodes.IntNode(pos, 
                                 value = value,
                                 unsigned = unsigned,
                                 longness = longness)
William Stein's avatar
William Stein committed
520 521 522 523 524 525 526 527
    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)
528
    elif sy == 'BEGIN_STRING':
William Stein's avatar
William Stein committed
529 530 531
        kind, value = p_cat_string_literal(s)
        if kind == 'c':
            return ExprNodes.CharNode(pos, value = value)
532 533
        elif kind == 'u':
            return ExprNodes.UnicodeNode(pos, value = value)
William Stein's avatar
William Stein committed
534 535 536
        else:
            return ExprNodes.StringNode(pos, value = value)
    elif sy == 'IDENT':
537
        name = EncodedString( s.systring )
William Stein's avatar
William Stein committed
538 539 540
        s.next()
        if name == "None":
            return ExprNodes.NoneNode(pos)
541
        elif name == "True":
542
            return ExprNodes.BoolNode(pos, value=True)
543
        elif name == "False":
544
            return ExprNodes.BoolNode(pos, value=False)
545 546
        elif name == "NULL":
            return ExprNodes.NullNode(pos)
William Stein's avatar
William Stein committed
547
        else:
548
            return p_name(s, name)
William Stein's avatar
William Stein committed
549 550 551
    else:
        s.error("Expected an identifier or literal")

552 553
def p_name(s, name):
    pos = s.position()
554 555 556 557 558 559 560 561 562 563 564 565 566
    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)
        elif isinstance(value, (str, unicode)):
            return ExprNodes.StringNode(pos, value = value)
567
        else:
568 569
            error(pos, "Invalid type for compile-time constant: %s"
                % value.__class__.__name__)
570 571
    return ExprNodes.NameNode(pos, name = name)

William Stein's avatar
William Stein committed
572 573
def p_cat_string_literal(s):
    # A sequence of one or more adjacent string literals.
574
    # Returns (kind, value) where kind in ('b', 'c', 'u')
William Stein's avatar
William Stein committed
575
    kind, value = p_string_literal(s)
Stefan Behnel's avatar
Stefan Behnel committed
576
    if kind != 'c':
William Stein's avatar
William Stein committed
577
        strings = [value]
578
        while s.sy == 'BEGIN_STRING':
William Stein's avatar
William Stein committed
579 580
            next_kind, next_value = p_string_literal(s)
            if next_kind == 'c':
581 582
                error(s.position(),
                      "Cannot concatenate char literal with another string or char literal")
583 584 585 586 587 588 589 590
            elif next_kind != kind:
                # we have to switch to unicode now
                if kind == 'b':
                    # concatenating a unicode string to byte strings
                    strings = [u''.join([s.decode(s.encoding) for s in strings])]
                elif kind == 'u':
                    # concatenating a byte string to unicode strings
                    strings.append(next_value.decode(next_value.encoding))
591
                kind = 'u'
592 593 594 595 596
            else:
                strings.append(next_value)
        if kind == 'u':
            value = EncodedString( u''.join(strings) )
        else:
Stefan Behnel's avatar
Stefan Behnel committed
597
            value = BytesLiteral( StringEncoding.join_bytes(strings) )
598
            value.encoding = s.source_encoding
William Stein's avatar
William Stein committed
599 600 601
    return kind, value

def p_opt_string_literal(s):
602
    if s.sy == 'BEGIN_STRING':
William Stein's avatar
William Stein committed
603 604 605 606 607 608
        return p_string_literal(s)
    else:
        return None

def p_string_literal(s):
    # A single string or char literal.
609
    # Returns (kind, value) where kind in ('b', 'c', 'u')
William Stein's avatar
William Stein committed
610 611
    # s.sy == 'BEGIN_STRING'
    pos = s.position()
612
    is_raw = 0
William Stein's avatar
William Stein committed
613
    kind = s.systring[:1].lower()
614 615 616 617 618 619
    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
620
        kind = ''
Stefan Behnel's avatar
Stefan Behnel committed
621 622 623
    if Future.unicode_literals in s.context.future_directives:
        if kind == '':
            kind = 'u'
624 625
    elif kind == '':
        kind = 'b'
626 627 628 629
    if kind == 'u':
        chars = StringEncoding.UnicodeLiteralBuilder()
    else:
        chars = StringEncoding.BytesLiteralBuilder(s.source_encoding)
William Stein's avatar
William Stein committed
630 631 632 633 634
    while 1:
        s.next()
        sy = s.sy
        #print "p_string_literal: sy =", sy, repr(s.systring) ###
        if sy == 'CHARS':
635
            chars.append(s.systring)
William Stein's avatar
William Stein committed
636
        elif sy == 'ESCAPE':
637
            has_escape = True
William Stein's avatar
William Stein committed
638
            systr = s.systring
639
            if is_raw:
640 641 642 643 644 645
                if systr == u'\\\n':
                    chars.append(u'\\\n')
                elif systr == u'\\\"':
                    chars.append(u'"')
                elif systr == u'\\\'':
                    chars.append(u"'")
William Stein's avatar
William Stein committed
646
                else:
647
                    chars.append(systr)
William Stein's avatar
William Stein committed
648 649
            else:
                c = systr[1]
650 651 652
                if c in u"01234567":
                    chars.append_charval( int(systr[1:], 8) )
                elif c in u"'\"\\":
653
                    chars.append(c)
654 655 656 657
                elif c in u"abfnrtv":
                    chars.append(
                        StringEncoding.char_from_escape_sequence(systr))
                elif c == u'\n':
William Stein's avatar
William Stein committed
658
                    pass
659
                elif c in u'Uux':
660 661
                    if kind == 'u' or c == 'x':
                        chrval = int(systr[2:], 16)
662
                        if chrval > 1114111: # sys.maxunicode:
663 664
                            s.error("Invalid unicode escape '%s'" % systr,
                                    pos = pos)
665 666 667 668 669
                        elif chrval > 65535:
                            warning(s.position(),
                                    "Unicode characters above 65535 are not "
                                    "necessarily portable across Python installations", 1)
                        chars.append_charval(chrval)
670
                    else:
671
                        # unicode escapes in plain byte strings are not unescaped
672
                        chars.append(systr)
William Stein's avatar
William Stein committed
673
                else:
674
                    chars.append(u'\\' + systr[1:])
William Stein's avatar
William Stein committed
675
        elif sy == 'NEWLINE':
676
            chars.append(u'\n')
William Stein's avatar
William Stein committed
677 678 679 680 681 682 683 684
        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))
685 686 687 688 689 690
    if kind == 'c':
        value = chars.getchar()
        if len(value) != 1:
            error(pos, u"invalid character literal: %r" % value)
    else:
        value = chars.getstring()
William Stein's avatar
William Stein committed
691 692 693 694
    s.next()
    #print "p_string_literal: value =", repr(value) ###
    return kind, value

Robert Bradshaw's avatar
Robert Bradshaw committed
695 696 697 698 699
# list_display      ::=      "[" [listmaker] "]"
# listmaker     ::=     expression ( list_for | ( "," expression )* [","] )
# list_iter     ::=     list_for | list_if
# list_for     ::=     "for" expression_list "in" testlist [list_iter]
# list_if     ::=     "if" test [list_iter]
Robert Bradshaw's avatar
Robert Bradshaw committed
700
        
William Stein's avatar
William Stein committed
701 702 703 704
def p_list_maker(s):
    # s.sy == '['
    pos = s.position()
    s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
705 706 707 708 709
    if s.sy == ']':
        s.expect(']')
        return ExprNodes.ListNode(pos, args = [])
    expr = p_simple_expr(s)
    if s.sy == 'for':
710 711 712 713
        target = ExprNodes.ListNode(pos, args = [])
        append = ExprNodes.ComprehensionAppendNode(
            pos, expr=expr, target=ExprNodes.CloneNode(target))
        loop = p_list_for(s, Nodes.ExprStatNode(append.pos, expr=append))
Robert Bradshaw's avatar
Robert Bradshaw committed
714
        s.expect(']')
715 716
        return ExprNodes.ComprehensionNode(
            pos, loop=loop, append=append, target=target)
Robert Bradshaw's avatar
Robert Bradshaw committed
717 718 719 720 721 722 723 724
    else:
        exprs = [expr]
        if s.sy == ',':
            s.next()
            exprs += p_simple_expr_list(s)
        s.expect(']')
        return ExprNodes.ListNode(pos, args = exprs)
        
725
def p_list_iter(s, body):
Robert Bradshaw's avatar
Robert Bradshaw committed
726
    if s.sy == 'for':
727
        return p_list_for(s, body)
Robert Bradshaw's avatar
Robert Bradshaw committed
728
    elif s.sy == 'if':
729
        return p_list_if(s, body)
Robert Bradshaw's avatar
Robert Bradshaw committed
730
    else:
731 732
        # insert the 'append' operation into the loop
        return body
William Stein's avatar
William Stein committed
733

734
def p_list_for(s, body):
Robert Bradshaw's avatar
Robert Bradshaw committed
735 736 737 738 739
    # s.sy == 'for'
    pos = s.position()
    s.next()
    kw = p_for_bounds(s)
    kw['else_clause'] = None
740
    kw['body'] = p_list_iter(s, body)
Robert Bradshaw's avatar
Robert Bradshaw committed
741 742
    return Nodes.ForStatNode(pos, **kw)
        
743
def p_list_if(s, body):
Robert Bradshaw's avatar
Robert Bradshaw committed
744 745 746
    # s.sy == 'if'
    pos = s.position()
    s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
747
    test = p_test(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
748
    return Nodes.IfStatNode(pos, 
749 750
        if_clauses = [Nodes.IfClauseNode(pos, condition = test,
                                         body = p_list_iter(s, body))],
Robert Bradshaw's avatar
Robert Bradshaw committed
751
        else_clause = None )
752

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

755
def p_dict_or_set_maker(s):
William Stein's avatar
William Stein committed
756 757 758
    # s.sy == '{'
    pos = s.position()
    s.next()
759
    if s.sy == '}':
William Stein's avatar
William Stein committed
760
        s.next()
761 762 763 764 765 766 767
        return ExprNodes.DictNode(pos, key_value_pairs = [])
    item = p_simple_expr(s)
    if s.sy == ',' or s.sy == '}':
        # set literal
        values = [item]
        while s.sy == ',':
            s.next()
768 769
            if s.sy == '}':
                break
770 771 772 773 774
            values.append( p_simple_expr(s) )
        s.expect('}')
        return ExprNodes.SetNode(pos, args=values)
    elif s.sy == 'for':
        # set comprehension
775 776 777 778
        target = ExprNodes.SetNode(pos, args=[])
        append = ExprNodes.ComprehensionAppendNode(
            item.pos, expr=item, target=ExprNodes.CloneNode(target))
        loop = p_list_for(s, Nodes.ExprStatNode(append.pos, expr=append))
779
        s.expect('}')
780 781
        return ExprNodes.ComprehensionNode(
            pos, loop=loop, append=append, target=target)
782 783 784 785 786 787 788
    elif s.sy == ':':
        # dict literal or comprehension
        key = item
        s.next()
        value = p_simple_expr(s)
        if s.sy == 'for':
            # dict comprehension
789
            target = ExprNodes.DictNode(pos, key_value_pairs = [])
790
            append = ExprNodes.DictComprehensionAppendNode(
791 792 793 794 795 796
                item.pos, key_expr=key, value_expr=value,
                target=ExprNodes.CloneNode(target))
            loop = p_list_for(s, Nodes.ExprStatNode(append.pos, expr=append))
            s.expect('}')
            return ExprNodes.ComprehensionNode(
                pos, loop=loop, append=append, target=target)
797 798 799 800 801
        else:
            # dict literal
            items = [ExprNodes.DictItemNode(key.pos, key=key, value=value)]
            while s.sy == ',':
                s.next()
802 803
                if s.sy == '}':
                    break
804 805 806 807 808 809 810 811 812 813 814
                key = p_simple_expr(s)
                s.expect(':')
                value = p_simple_expr(s)
                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
815 816 817 818 819 820 821 822 823 824 825 826

def p_backquote_expr(s):
    # s.sy == '`'
    pos = s.position()
    s.next()
    arg = p_expr(s)
    s.expect('`')
    return ExprNodes.BackquoteNode(pos, arg = arg)

def p_simple_expr_list(s):
    exprs = []
    while s.sy not in expr_terminators:
827 828
        expr = p_simple_expr(s)
        exprs.append(expr)
Stefan Behnel's avatar
Stefan Behnel committed
829
        if s.sy != ',':
William Stein's avatar
William Stein committed
830 831 832 833 834 835 836 837 838 839 840 841 842 843
            break
        s.next()
    return exprs

def p_expr(s):
    pos = s.position()
    expr = p_simple_expr(s)
    if s.sy == ',':
        s.next()
        exprs = [expr] + p_simple_expr_list(s)
        return ExprNodes.TupleNode(pos, args = exprs)
    else:
        return expr

Robert Bradshaw's avatar
Robert Bradshaw committed
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859

#testlist: test (',' test)* [',']
# differs from p_expr only in the fact that it cannot contain conditional expressions

def p_testlist(s):
    pos = s.position()
    expr = p_test(s)
    if s.sy == ',':
        exprs = [expr]
        while s.sy == ',':
            s.next()
            exprs.append(p_test(s))
        return ExprNodes.TupleNode(pos, args = exprs)
    else:
        return expr
        
William Stein's avatar
William Stein committed
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
expr_terminators = (')', ']', '}', ':', '=', 'NEWLINE')

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

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

def p_expression_or_assignment(s):
    expr_list = [p_expr(s)]
    while s.sy == '=':
        s.next()
        expr_list.append(p_expr(s))
    if len(expr_list) == 1:
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
881
        if re.match(r"([+*/\%^\&|-]|<<|>>|\*\*|//)=", s.sy):
882 883 884
            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
885
            operator = s.sy[:-1]
886 887 888
            s.next()
            rhs = p_expr(s)
            return Nodes.InPlaceAssignmentNode(lhs.pos, operator = operator, lhs = lhs, rhs = rhs)
889 890 891
        expr = expr_list[0]
        if isinstance(expr, ExprNodes.StringNode):
            return Nodes.PassStatNode(expr.pos)
892 893
        else:
            return Nodes.ExprStatNode(expr.pos, expr = expr)
William Stein's avatar
William Stein committed
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    else:
        expr_list_list = []
        flatten_parallel_assignments(expr_list, expr_list_list)
        nodes = []
        for expr_list in expr_list_list:
            lhs_list = expr_list[:-1]
            rhs = expr_list[-1]
            if len(lhs_list) == 1:
                node = Nodes.SingleAssignmentNode(rhs.pos, 
                    lhs = lhs_list[0], rhs = rhs)
            else:
                node = Nodes.CascadedAssignmentNode(rhs.pos,
                    lhs_list = lhs_list, rhs = rhs)
            nodes.append(node)
        if len(nodes) == 1:
            return nodes[0]
        else:
            return Nodes.ParallelAssignmentNode(nodes[0].pos, stats = nodes)

def flatten_parallel_assignments(input, output):
914 915 916 917 918 919 920 921
    #  The input is a list of expression nodes, representing the LHSs
    #  and RHS of one (possibly cascaded) assignment statement.  For
    #  sequence constructors, rearranges the matching parts of both
    #  sides into a list of equivalent assignments between the
    #  individual elements.  This transformation is applied
    #  recursively, so that nested structures get matched as well.
    rhs = input[-1]
    if not rhs.is_sequence_constructor:
William Stein's avatar
William Stein committed
922
        output.append(input)
923
        return
William Stein's avatar
William Stein committed
924 925

    rhs_size = len(rhs.args)
926 927
    lhs_targets = [ [] for _ in range(rhs_size) ]
    starred_assignments = []
William Stein's avatar
William Stein committed
928
    for lhs in input[:-1]:
929 930 931
        if not lhs.is_sequence_constructor:
            if lhs.is_starred:
                error(lhs.pos, "starred assignment target must be in a list or tuple")
932
            output.append([lhs,rhs])
933
            continue
William Stein's avatar
William Stein committed
934
        lhs_size = len(lhs.args)
935 936 937 938
        starred_targets = sum([1 for expr in lhs.args if expr.is_starred])
        if starred_targets:
            if starred_targets > 1:
                error(lhs.pos, "more than 1 starred expression in assignment")
939 940
                output.append([lhs,rhs])
                continue
941 942 943
            elif lhs_size - starred_targets > rhs_size:
                error(lhs.pos, "need more than %d value%s to unpack"
                      % (rhs_size, (rhs_size != 1) and 's' or ''))
944 945
                output.append([lhs,rhs])
                continue
946 947 948 949 950 951
            map_starred_assignment(lhs_targets, starred_assignments,
                                   lhs.args, rhs.args)
        else:
            if lhs_size > rhs_size:
                error(lhs.pos, "need more than %d value%s to unpack"
                      % (rhs_size, (rhs_size != 1) and 's' or ''))
952 953
                output.append([lhs,rhs])
                continue
954 955 956
            elif lhs_size < rhs_size:
                error(lhs.pos, "too many values to unpack (expected %d, got %d)"
                      % (lhs_size, rhs_size))
957 958
                output.append([lhs,rhs])
                continue
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
            else:
                for targets, expr in zip(lhs_targets, lhs.args):
                    targets.append(expr)

    # recursively flatten partial assignments
    for cascade, rhs in zip(lhs_targets, rhs.args):
        if cascade:
            cascade.append(rhs)
            flatten_parallel_assignments(cascade, output)

    # recursively flatten starred assignments
    for cascade in starred_assignments:
        if cascade[0].is_sequence_constructor:
            flatten_parallel_assignments(cascade, output)
        else:
            output.append(cascade)

def map_starred_assignment(lhs_targets, starred_assignments, lhs_args, rhs_args):
    # Appends the fixed-position LHS targets to the target list that
    # appear left and right of the starred argument.
    #
    # The starred_assignments list receives a new tuple
    # (lhs_target, rhs_values_list) that maps the remaining arguments
    # (those that match the starred target) to a list.

    # left side of the starred target
    for i, (targets, expr) in enumerate(zip(lhs_targets, lhs_args)):
        if expr.is_starred:
            starred = i
            lhs_remaining = len(lhs_args) - i - 1
            break
        targets.append(expr)
    else:
        raise InternalError("no starred arg found when splitting starred assignment")

    # right side of the starred target
    for i, (targets, expr) in enumerate(zip(lhs_targets[-lhs_remaining:],
                                            lhs_args[-lhs_remaining:])):
        targets.append(expr)

    # the starred target itself, must be assigned a (potentially empty) list
1000
    target = lhs_args[starred].target # unpack starred node
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    starred_rhs = rhs_args[starred:]
    if lhs_remaining:
        starred_rhs = starred_rhs[:-lhs_remaining]
    if starred_rhs:
        pos = starred_rhs[0].pos
    else:
        pos = target.pos
    starred_assignments.append([
        target, ExprNodes.ListNode(pos=pos, args=starred_rhs)])

William Stein's avatar
William Stein committed
1011 1012 1013 1014 1015 1016 1017 1018

def p_print_statement(s):
    # s.sy == 'print'
    pos = s.position()
    s.next()
    if s.sy == '>>':
        s.error("'print >>' not yet implemented")
    args = []
1019
    ends_with_comma = 0
William Stein's avatar
William Stein committed
1020 1021 1022 1023 1024
    if s.sy not in ('NEWLINE', 'EOF'):
        args.append(p_simple_expr(s))
        while s.sy == ',':
            s.next()
            if s.sy in ('NEWLINE', 'EOF'):
1025
                ends_with_comma = 1
William Stein's avatar
William Stein committed
1026 1027
                break
            args.append(p_simple_expr(s))
1028
    arg_tuple = ExprNodes.TupleNode(pos, args = args)
1029 1030
    return Nodes.PrintStatNode(pos,
        arg_tuple = arg_tuple, append_newline = not ends_with_comma)
William Stein's avatar
William Stein committed
1031

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
def p_exec_statement(s):
    # s.sy == 'exec'
    pos = s.position()
    s.next()
    args = [ p_bit_expr(s) ]
    if s.sy == 'in':
        s.next()
        args.append(p_simple_expr(s))
        if s.sy == ',':
            s.next()
            args.append(p_simple_expr(s))
    else:
        error(pos, "'exec' currently requires a target mapping (globals/locals)")
    return Nodes.ExecStatNode(pos, args = args)

William Stein's avatar
William Stein committed
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
def p_del_statement(s):
    # s.sy == 'del'
    pos = s.position()
    s.next()
    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:
        value = p_expr(s)
    else:
        value = None
    return Nodes.ReturnStatNode(pos, value = value)

def p_raise_statement(s):
    # s.sy == 'raise'
    pos = s.position()
    s.next()
    exc_type = None
    exc_value = None
    exc_tb = None
    if s.sy not in statement_terminators:
        exc_type = p_simple_expr(s)
        if s.sy == ',':
            s.next()
            exc_value = p_simple_expr(s)
            if s.sy == ',':
                s.next()
                exc_tb = p_simple_expr(s)
1098 1099 1100 1101 1102 1103 1104
    if exc_type or exc_value or exc_tb:
        return Nodes.RaiseStatNode(pos, 
            exc_type = exc_type,
            exc_value = exc_value,
            exc_tb = exc_tb)
    else:
        return Nodes.ReraiseStatNode(pos)
William Stein's avatar
William Stein committed
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116

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:
1117
        dotted_name = EncodedString(dotted_name)
William Stein's avatar
William Stein committed
1118 1119 1120 1121 1122
        if kind == 'cimport':
            stat = Nodes.CImportStatNode(pos, 
                module_name = dotted_name,
                as_name = as_name)
        else:
1123 1124
            if as_name and "." in dotted_name:
                name_list = ExprNodes.ListNode(pos, args = [
1125 1126
                        ExprNodes.IdentifierStringNode(
                            pos, value = EncodedString("*"))])
1127 1128
            else:
                name_list = None
William Stein's avatar
William Stein committed
1129 1130 1131 1132
            stat = Nodes.SingleAssignmentNode(pos,
                lhs = ExprNodes.NameNode(pos, 
                    name = as_name or target_name),
                rhs = ExprNodes.ImportNode(pos, 
1133 1134
                    module_name = ExprNodes.IdentifierStringNode(
                        pos, value = dotted_name),
1135
                    name_list = name_list))
William Stein's avatar
William Stein committed
1136 1137 1138
        stats.append(stat)
    return Nodes.StatListNode(pos, stats = stats)

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

1205 1206 1207
imported_name_kinds = ('class', 'struct', 'union')

def p_imported_name(s, is_cimport):
William Stein's avatar
William Stein committed
1208
    pos = s.position()
1209 1210 1211 1212
    kind = None
    if is_cimport and s.systring in imported_name_kinds:
        kind = s.systring
        s.next()
William Stein's avatar
William Stein committed
1213 1214
    name = p_ident(s)
    as_name = p_as_name(s)
1215
    return (pos, name, as_name, kind)
William Stein's avatar
William Stein committed
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226

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
1227
    return (pos, target_name, u'.'.join(names), as_name)
William Stein's avatar
William Stein committed
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290

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()
    cond = p_simple_expr(s)
    if s.sy == ',':
        s.next()
        value = p_simple_expr(s)
    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()
    test = p_simple_expr(s)
    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()
    test = p_simple_expr(s)
    body = p_suite(s)
    else_clause = p_else_clause(s)
    return Nodes.WhileStatNode(pos, 
        condition = test, body = body, 
        else_clause = else_clause)

def p_for_statement(s):
    # s.sy == 'for'
    pos = s.position()
    s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
1291 1292 1293 1294 1295 1296
    kw = p_for_bounds(s)
    kw['body'] = p_suite(s)
    kw['else_clause'] = p_else_clause(s)
    return Nodes.ForStatNode(pos, **kw)
            
def p_for_bounds(s):
William Stein's avatar
William Stein committed
1297 1298 1299 1300
    target = p_for_target(s)
    if s.sy == 'in':
        s.next()
        iterator = p_for_iterator(s)
Robert Bradshaw's avatar
Robert Bradshaw committed
1301
        return { 'target': target, 'iterator': iterator }
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1302 1303 1304 1305 1306 1307 1308
    else:
        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
1309 1310 1311 1312 1313 1314
        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)
1315
        step = p_for_from_step(s)
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1316 1317 1318 1319 1320 1321 1322 1323 1324
        if target is None:
            target = ExprNodes.NameNode(name2_pos, name = name2)
        else:
            if not target.is_name:
                error(target.pos, 
                    "Target of for-from statement must be a variable name")
            elif name2 != target.name:
                error(name2_pos,
                    "Variable name in for-from range does not match target")
Stefan Behnel's avatar
Stefan Behnel committed
1325
        if rel1[0] != rel2[0]:
William Stein's avatar
William Stein committed
1326 1327
            error(rel2_pos,
                "Relation directions in for-from do not match")
Robert Bradshaw's avatar
Robert Bradshaw committed
1328 1329 1330 1331
        return {'target': target, 
                'bound1': bound1, 
                'relation1': rel1, 
                'relation2': rel2,
1332 1333
                'bound2': bound2,
                'step': step }
William Stein's avatar
William Stein committed
1334 1335 1336 1337 1338 1339 1340 1341

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

1343 1344 1345 1346 1347 1348 1349
def p_for_from_step(s):
    if s.sy == 'by':
        s.next()
        step = p_bit_expr(s)
        return step
    else:
        return None
William Stein's avatar
William Stein committed
1350 1351 1352

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

1353
def p_target(s, terminator):
William Stein's avatar
William Stein committed
1354
    pos = s.position()
1355
    expr = p_starred_expr(s)
William Stein's avatar
William Stein committed
1356 1357 1358
    if s.sy == ',':
        s.next()
        exprs = [expr]
1359
        while s.sy != terminator:
1360
            exprs.append(p_starred_expr(s))
Stefan Behnel's avatar
Stefan Behnel committed
1361
            if s.sy != ',':
William Stein's avatar
William Stein committed
1362 1363 1364 1365 1366 1367
                break
            s.next()
        return ExprNodes.TupleNode(pos, args = exprs)
    else:
        return expr

1368 1369 1370
def p_for_target(s):
    return p_target(s, 'in')

William Stein's avatar
William Stein committed
1371 1372
def p_for_iterator(s):
    pos = s.position()
Robert Bradshaw's avatar
Robert Bradshaw committed
1373
    expr = p_testlist(s)
William Stein's avatar
William Stein committed
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
    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)
1389
        body = Nodes.TryExceptStatNode(pos,
William Stein's avatar
William Stein committed
1390 1391
            body = body, except_clauses = except_clauses,
            else_clause = else_clause)
1392 1393 1394 1395
        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
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
        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
1409
    if s.sy != ':':
William Stein's avatar
William Stein committed
1410 1411 1412 1413 1414 1415 1416 1417
        exc_type = p_simple_expr(s)
        if s.sy == ',':
            s.next()
            exc_value = p_simple_expr(s)
    body = p_suite(s)
    return Nodes.ExceptClauseNode(pos,
        pattern = exc_type, target = exc_value, body = body)

1418
def p_include_statement(s, ctx):
William Stein's avatar
William Stein committed
1419 1420 1421 1422
    pos = s.position()
    s.next() # 'include'
    _, include_file_name = p_string_literal(s)
    s.expect_newline("Syntax error in include statement")
1423 1424 1425
    if s.compile_time_eval:
        include_file_path = s.context.find_include_file(include_file_name, pos)
        if include_file_path:
1426
            s.included_files.append(include_file_name)
1427
            f = Utils.open_source_file(include_file_path, mode="rU")
1428
            source_desc = FileSourceDescriptor(include_file_path)
1429
            s2 = PyrexScanner(f, source_desc, s, source_encoding=f.encoding, parse_comments=s.parse_comments)
1430
            try:
1431
                tree = p_statement_list(s2, ctx)
1432 1433 1434 1435 1436
            finally:
                f.close()
            return tree
        else:
            return None
William Stein's avatar
William Stein committed
1437
    else:
1438 1439 1440 1441 1442
        return Nodes.PassStatNode(pos)

def p_with_statement(s):
    pos = s.position()
    s.next() # 'with'
Robert Bradshaw's avatar
Robert Bradshaw committed
1443
#    if s.sy == 'IDENT' and s.systring in ('gil', 'nogil'):
1444 1445 1446 1447 1448 1449
    if s.sy == 'IDENT' and s.systring == 'nogil':
        state = s.systring
        s.next()
        body = p_suite(s)
        return Nodes.GILStatNode(pos, state = state, body = body)
    else:
1450 1451 1452 1453 1454 1455 1456 1457 1458
        manager = p_expr(s)
        target = None
        if s.sy == 'IDENT' and s.systring == 'as':
            s.next()
            allow_multi = (s.sy == '(')
            target = p_target(s, ':')
            if not allow_multi and isinstance(target, ExprNodes.TupleNode):
                s.error("Multiple with statement target values not allowed without paranthesis")
        body = p_suite(s)
1459
    return Nodes.WithStatNode(pos, manager = manager, 
Robert Bradshaw's avatar
Robert Bradshaw committed
1460
                              target = target, body = body)
William Stein's avatar
William Stein committed
1461
    
Stefan Behnel's avatar
Stefan Behnel committed
1462
def p_simple_statement(s, first_statement = 0):
William Stein's avatar
William Stein committed
1463 1464 1465 1466 1467
    #print "p_simple_statement:", s.sy, s.systring ###
    if s.sy == 'global':
        node = p_global_statement(s)
    elif s.sy == 'print':
        node = p_print_statement(s)
1468 1469
    elif s.sy == 'exec':
        node = p_exec_statement(s)
William Stein's avatar
William Stein committed
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
    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
1483
        node = p_from_import_statement(s, first_statement = first_statement)
1484 1485
    elif s.sy == 'yield':
        node = p_yield_expression(s)
William Stein's avatar
William Stein committed
1486 1487 1488 1489 1490 1491 1492 1493
    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

1494
def p_simple_statement_list(s, ctx, first_statement = 0):
William Stein's avatar
William Stein committed
1495 1496
    # Parse a series of simple statements on one line
    # separated by semicolons.
Stefan Behnel's avatar
Stefan Behnel committed
1497
    stat = p_simple_statement(s, first_statement = first_statement)
William Stein's avatar
William Stein committed
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
    if s.sy == ';':
        stats = [stat]
        while s.sy == ';':
            #print "p_simple_statement_list: maybe more to follow" ###
            s.next()
            if s.sy in ('NEWLINE', 'EOF'):
                break
            stats.append(p_simple_statement(s))
        stat = Nodes.StatListNode(stats[0].pos, stats = stats)
    s.expect_newline("Syntax error in simple statement list")
    return stat

1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
def p_compile_time_expr(s):
    old = s.compile_time_expr
    s.compile_time_expr = 1
    expr = p_expr(s)
    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)

1530
def p_IF_statement(s, ctx):
Dag Sverre Seljebotn's avatar
Merge  
Dag Sverre Seljebotn committed
1531
    pos = s.position()
1532 1533 1534 1535 1536 1537 1538 1539
    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))
1540
        body = p_suite(s, ctx)
1541 1542 1543
        if s.compile_time_eval:
            result = body
            current_eval = 0
Stefan Behnel's avatar
Stefan Behnel committed
1544
        if s.sy != 'ELIF':
1545 1546 1547 1548
            break
    if s.sy == 'ELSE':
        s.next()
        s.compile_time_eval = current_eval
1549
        body = p_suite(s, ctx)
1550 1551 1552
        if current_eval:
            result = body
    if not result:
Stefan Behnel's avatar
Stefan Behnel committed
1553
        result = Nodes.PassStatNode(pos)
1554 1555 1556
    s.compile_time_eval = saved_eval
    return result

1557 1558
def p_statement(s, ctx, first_statement = 0):
    cdef_flag = ctx.cdef_flag
Robert Bradshaw's avatar
Robert Bradshaw committed
1559
    decorators = None
William Stein's avatar
William Stein committed
1560
    if s.sy == 'ctypedef':
1561
        if ctx.level not in ('module', 'module_pxd'):
William Stein's avatar
William Stein committed
1562
            s.error("ctypedef statement not allowed here")
1563 1564
        #if ctx.api:
        #    error(s.position(), "'api' not allowed with 'ctypedef'")
1565
        return p_ctypedef_statement(s, ctx)
1566 1567 1568
    elif s.sy == 'DEF':
        return p_DEF_statement(s)
    elif s.sy == 'IF':
1569
        return p_IF_statement(s, ctx)
1570
    elif s.sy == 'DECORATOR':
1571 1572
        if ctx.level not in ('module', 'class', 'c_class', 'property', 'module_pxd', 'c_class_pxd'):
            print ctx.level
1573 1574 1575
            s.error('decorator not allowed here')
        s.level = ctx.level
        decorators = p_decorators(s)
1576 1577
        if s.sy not in ('def', 'cdef', 'cpdef', 'class'):
            s.error("Decorators can only be followed by functions or classes")
1578 1579 1580
    elif s.sy == 'pass' and cdef_flag:
        # empty cdef block
        return p_pass_statement(s, with_newline = 1)
1581 1582 1583 1584 1585

    overridable = 0
    if s.sy == 'cdef':
        cdef_flag = 1
        s.next()
1586
    elif s.sy == 'cpdef':
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
        cdef_flag = 1
        overridable = 1
        s.next()
    if cdef_flag:
        if ctx.level not in ('module', 'module_pxd', 'function', 'c_class', 'c_class_pxd'):
            s.error('cdef statement not allowed here')
        s.level = ctx.level
        node = p_cdef_statement(s, ctx(overridable = overridable))
        if decorators is not None:
            if not isinstance(node, (Nodes.CFuncDefNode, Nodes.CVarDefNode)):
1597
                s.error("Decorators can only be followed by functions or Python classes")
1598 1599
            node.decorators = decorators
        return node
William Stein's avatar
William Stein committed
1600
    else:
1601 1602 1603 1604 1605
        if ctx.api:
            error(s.pos, "'api' not allowed with this statement")
        elif s.sy == 'def':
            if ctx.level not in ('module', 'class', 'c_class', 'c_class_pxd', 'property'):
                s.error('def statement not allowed here')
1606
            s.level = ctx.level
1607 1608 1609 1610
            return p_def_statement(s, decorators)
        elif s.sy == 'class':
            if ctx.level != 'module':
                s.error("class definition not allowed here")
1611
            return p_class_statement(s, decorators)
1612 1613 1614 1615 1616 1617 1618 1619
        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
1620
        else:
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
            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)
1633
            else:
1634 1635
                return p_simple_statement_list(
                    s, ctx, first_statement = first_statement)
William Stein's avatar
William Stein committed
1636

1637
def p_statement_list(s, ctx, first_statement = 0):
William Stein's avatar
William Stein committed
1638 1639 1640 1641
    # Parse a series of statements separated by newlines.
    pos = s.position()
    stats = []
    while s.sy not in ('DEDENT', 'EOF'):
1642
        stats.append(p_statement(s, ctx, first_statement = first_statement))
Stefan Behnel's avatar
Stefan Behnel committed
1643
        first_statement = 0
1644 1645 1646 1647
    if len(stats) == 1:
        return stats[0]
    else:
        return Nodes.StatListNode(pos, stats = stats)
William Stein's avatar
William Stein committed
1648

1649
def p_suite(s, ctx = Ctx(), with_doc = 0, with_pseudo_doc = 0):
William Stein's avatar
William Stein committed
1650 1651 1652 1653 1654 1655 1656
    pos = s.position()
    s.expect(':')
    doc = None
    stmts = []
    if s.sy == 'NEWLINE':
        s.next()
        s.expect_indent()
1657
        if with_doc or with_pseudo_doc:
William Stein's avatar
William Stein committed
1658
            doc = p_doc_string(s)
1659
        body = p_statement_list(s, ctx)
William Stein's avatar
William Stein committed
1660 1661
        s.expect_dedent()
    else:
1662
        if ctx.api:
1663
            error(s.pos, "'api' not allowed with this statement")
1664 1665
        if ctx.level in ('module', 'class', 'function', 'other'):
            body = p_simple_statement_list(s, ctx)
William Stein's avatar
William Stein committed
1666 1667 1668 1669 1670 1671 1672 1673
        else:
            body = p_pass_statement(s)
            s.expect_newline("Syntax error in declarations")
    if with_doc:
        return doc, body
    else:
        return body

1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
def p_positional_and_keyword_args(s, end_sy_set, type_positions=(), type_keywords=()):
    """
    Parses positional and keyword arguments. end_sy_set
    should contain any s.sy that terminate the argument list.
    Argument expansion (* and **) are not allowed.

    type_positions and type_keywords specifies which argument
    positions and/or names which should be interpreted as
    types. Other arguments will be treated as expressions.

    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.')

        was_keyword = False
        parsed_type = False
        if s.sy == 'IDENT':
            # Since we can have either types or expressions as positional args,
            # we use a strategy of looking an extra step forward for a '=' and
            # if it is a positional arg we backtrack.
            ident = s.systring
            s.next()
            if s.sy == '=':
                s.next()
                # Is keyword arg
                if ident in type_keywords:
                    arg = p_c_base_type(s)
                    parsed_type = True
                else:
                    arg = p_simple_expr(s)
                keyword_node = ExprNodes.IdentifierStringNode(arg.pos,
1711
                                value = EncodedString(ident))
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
                keyword_args.append((keyword_node, arg))
                was_keyword = True
            else:
                s.put_back('IDENT', ident)
                
        if not was_keyword:
            if pos_idx in type_positions:
                arg = p_c_base_type(s)
                parsed_type = True
            else:
                arg = p_simple_expr(s)
            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:
                    s.error("Expected: type")
                else:
                    s.error("Expected: expression")
            break
        s.next()
    return positional_args, keyword_args

1739
def p_c_base_type(s, self_flag = 0, nonempty = 0):
William Stein's avatar
William Stein committed
1740 1741 1742 1743 1744
    # 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:
1745
        return p_c_simple_base_type(s, self_flag, nonempty = nonempty)
William Stein's avatar
William Stein committed
1746

1747 1748 1749 1750 1751 1752 1753 1754
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 ""

1755
calling_convention_words = ("__stdcall", "__cdecl", "__fastcall")
1756

William Stein's avatar
William Stein committed
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
def p_c_complex_base_type(s):
    # s.sy == '('
    pos = s.position()
    s.next()
    base_type = p_c_base_type(s)
    declarator = p_c_declarator(s, empty = 1)
    s.expect(')')
    return Nodes.CComplexBaseTypeNode(pos, 
        base_type = base_type, declarator = declarator)

1767
def p_c_simple_base_type(s, self_flag, nonempty):
1768
    #print "p_c_simple_base_type: self_flag =", self_flag, nonempty
William Stein's avatar
William Stein committed
1769 1770 1771
    is_basic = 0
    signed = 1
    longness = 0
1772
    complex = 0
William Stein's avatar
William Stein committed
1773
    module_path = []
1774
    pos = s.position()
1775 1776
    if not s.sy == 'IDENT':
        error(pos, "Expected an identifier, found '%s'" % s.sy)
William Stein's avatar
William Stein committed
1777 1778 1779
    if looking_at_base_type(s):
        #print "p_c_simple_base_type: looking_at_base_type at", s.position()
        is_basic = 1
1780 1781
        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
1782 1783 1784
            name = s.systring
            s.next()
        else:
1785 1786 1787 1788 1789 1790
            signed, longness = p_sign_and_longness(s)
            if s.sy == 'IDENT' and s.systring in basic_c_type_names:
                name = s.systring
                s.next()
            else:
                name = 'int'
1791 1792 1793
        if s.sy == 'IDENT' and s.systring == 'complex':
            complex = 1
            s.next()
1794 1795 1796 1797 1798 1799 1800 1801
    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)
1802
    else:
1803 1804 1805
        name = s.systring
        s.next()
        if nonempty and s.sy != 'IDENT':
1806
            # Make sure this is not a declaration of a variable or function.  
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
            if s.sy == '(':
                s.next()
                if s.sy == '*' or s.sy == '**':
                    s.put_back('(', '(')
                else:
                    s.put_back('(', '(')
                    s.put_back('IDENT', name)
                    name = None
            elif s.sy not in ('*', '**', '['):
                s.put_back('IDENT', name)
                name = None
1818
    
1819
    type_node = Nodes.CSimpleBaseTypeNode(pos, 
William Stein's avatar
William Stein committed
1820 1821
        name = name, module_path = module_path,
        is_basic_c_type = is_basic, signed = signed,
1822 1823
        complex = complex, longness = longness, 
        is_self_arg = self_flag)
William Stein's avatar
William Stein committed
1824

1825

1826 1827 1828 1829 1830 1831 1832
    # Treat trailing [] on type as buffer access if it appears in a context
    # where declarator names are required (so that it cannot mean int[] or
    # sizeof(int[SIZE]))...
    #
    # (This means that buffers cannot occur where there can be empty declarators,
    # which is an ok restriction to make.)
    if nonempty and s.sy == '[':
1833
        return p_buffer_access(s, type_node)
1834 1835 1836
    else:
        return type_node

1837
def p_buffer_access(s, base_type_node):
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
    # s.sy == '['
    pos = s.position()
    s.next()
    positional_args, keyword_args = (
        p_positional_and_keyword_args(s, (']',), (0,), ('dtype',))
    )
    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
        ])

    result = Nodes.CBufferAccessTypeNode(pos,
        positional_args = positional_args,
        keyword_args = keyword_dict,
1855
        base_type_node = base_type_node)
1856 1857 1858
    return result
    

1859
def looking_at_name(s):
1860 1861
    return s.sy == 'IDENT' and not s.systring in calling_convention_words

1862
def looking_at_expr(s):
1863
    if s.systring in base_type_start_words:
1864
        return False
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
    elif s.sy == 'IDENT':
        is_type = False
        name = s.systring
        dotted_path = []
        s.next()
        while s.sy == '.':
            s.next()
            dotted_path.append(s.systring)
            s.expect('IDENT')
        saved = s.sy, s.systring
1875 1876 1877
        if s.sy == 'IDENT':
            is_type = True
        elif s.sy == '*' or s.sy == '**':
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
            s.next()
            is_type = s.sy == ')'
            s.put_back(*saved)
        elif s.sy == '(':
            s.next()
            is_type = s.sy == '*'
            s.put_back(*saved)
        elif s.sy == '[':
            s.next()
            is_type = s.sy == ']'
            s.put_back(*saved)
        dotted_path.reverse()
        for p in dotted_path:
            s.put_back('IDENT', p)
            s.put_back('.', '.')
        s.put_back('IDENT', name)
1894
        return not is_type
1895
    else:
1896
        return True
William Stein's avatar
William Stein committed
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910

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
1911

1912 1913 1914 1915 1916 1917 1918
basic_c_type_names = ("void", "char", "int", "float", "double", "bint")

special_basic_c_types = {
    # name : (signed, longness)
    "Py_ssize_t" : (2, 0),
    "size_t"     : (0, 0),
}
William Stein's avatar
William Stein committed
1919 1920 1921

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

1922
base_type_start_words = \
1923
    basic_c_type_names + sign_and_longness_words + tuple(special_basic_c_types)
William Stein's avatar
William Stein committed
1924 1925 1926 1927 1928 1929 1930

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
1931 1932
        elif s.systring == 'signed':
            signed = 2
William Stein's avatar
William Stein committed
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
        elif s.systring == 'short':
            longness = -1
        elif s.systring == 'long':
            longness += 1
        s.next()
    return signed, longness

def p_opt_cname(s):
    literal = p_opt_string_literal(s)
    if literal:
        _, cname = literal
    else:
        cname = None
    return cname

1948 1949 1950
def p_c_declarator(s, ctx = Ctx(), empty = 0, is_type = 0, cmethod_flag = 0,
                   assignable = 0, nonempty = 0,
                   calling_convention_allowed = 0):
1951 1952
    # 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
1953 1954 1955
    # If cmethod_flag is true, then if this declarator declares
    # a function, it's a C method of an extension type.
    pos = s.position()
1956 1957
    if s.sy == '(':
        s.next()
1958
        if s.sy == ')' or looking_at_name(s):
1959
            base = Nodes.CNameDeclaratorNode(pos, name = EncodedString(u""), cname = None)
1960
            result = p_c_func_declarator(s, pos, ctx, base, cmethod_flag)
1961
        else:
1962 1963 1964 1965
            result = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
                                    cmethod_flag = cmethod_flag,
                                    nonempty = nonempty,
                                    calling_convention_allowed = 1)
1966 1967
            s.expect(')')
    else:
1968 1969
        result = p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
                                       assignable, nonempty)
Stefan Behnel's avatar
Stefan Behnel committed
1970
    if not calling_convention_allowed and result.calling_convention and s.sy != '(':
1971 1972 1973 1974 1975 1976 1977 1978
        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()
1979
            result = p_c_func_declarator(s, pos, ctx, result, cmethod_flag)
1980 1981 1982 1983 1984 1985
        cmethod_flag = 0
    return result

def p_c_array_declarator(s, base):
    pos = s.position()
    s.next() # '['
Stefan Behnel's avatar
Stefan Behnel committed
1986
    if s.sy != ']':
1987 1988 1989 1990 1991 1992
        dim = p_expr(s)
    else:
        dim = None
    s.expect(']')
    return Nodes.CArrayDeclaratorNode(pos, base = base, dimension = dim)

1993
def p_c_func_declarator(s, pos, ctx, base, cmethod_flag):
1994
    #  Opening paren has already been skipped
1995 1996
    args = p_c_arg_list(s, ctx, cmethod_flag = cmethod_flag,
                        nonempty_declarators = 0)
1997 1998 1999 2000 2001 2002 2003 2004
    ellipsis = p_optional_ellipsis(s)
    s.expect(')')
    nogil = p_nogil(s)
    exc_val, exc_check = p_exception_value_clause(s)
    with_gil = p_with_gil(s)
    return Nodes.CFuncDeclaratorNode(pos, 
        base = base, args = args, has_varargs = ellipsis,
        exception_value = exc_val, exception_check = exc_check,
2005
        nogil = nogil or ctx.nogil or with_gil, with_gil = with_gil)
2006

2007 2008
def p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
                          assignable, nonempty):
2009 2010
    pos = s.position()
    calling_convention = p_calling_convention(s)
William Stein's avatar
William Stein committed
2011 2012
    if s.sy == '*':
        s.next()
2013 2014 2015
        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
2016 2017 2018 2019
        result = Nodes.CPtrDeclaratorNode(pos, 
            base = base)
    elif s.sy == '**': # scanner returns this as a single token
        s.next()
2020 2021 2022
        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
2023 2024 2025 2026
        result = Nodes.CPtrDeclaratorNode(pos,
            base = Nodes.CPtrDeclaratorNode(pos,
                base = base))
    else:
2027 2028
        rhs = None
        if s.sy == 'IDENT':
2029
            name = EncodedString(s.systring)
2030 2031
            if empty:
                error(s.position(), "Declarator should be empty")
William Stein's avatar
William Stein committed
2032
            s.next()
2033
            cname = p_opt_cname(s)
2034 2035 2036
            if s.sy == '=' and assignable:
                s.next()
                rhs = p_simple_expr(s)
William Stein's avatar
William Stein committed
2037
        else:
2038 2039 2040 2041 2042
            if nonempty:
                error(s.position(), "Empty declarator")
            name = ""
            cname = None
        result = Nodes.CNameDeclaratorNode(pos,
Robert Bradshaw's avatar
Robert Bradshaw committed
2043
            name = name, cname = cname, default = rhs)
2044
    result.calling_convention = calling_convention
William Stein's avatar
William Stein committed
2045 2046
    return result

2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
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
2062 2063 2064 2065 2066 2067 2068 2069
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
2070 2071 2072
        elif s.sy == '+':
            exc_check = '+'
            s.next()
Robert Bradshaw's avatar
Robert Bradshaw committed
2073 2074 2075 2076
            if s.sy == 'IDENT':
                name = s.systring
                s.next()
                exc_val = p_name(s, name)
William Stein's avatar
William Stein committed
2077 2078 2079 2080
        else:
            if s.sy == '?':
                exc_check = 1
                s.next()
2081
            exc_val = p_simple_expr(s)
William Stein's avatar
William Stein committed
2082 2083 2084 2085
    return exc_val, exc_check

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

2086 2087
def p_c_arg_list(s, ctx = Ctx(), in_pyfunc = 0, cmethod_flag = 0,
                 nonempty_declarators = 0, kw_only = 0):
2088 2089
    #  Comma-separated list of C argument declarations, possibly empty.
    #  May have a trailing comma.
William Stein's avatar
William Stein committed
2090
    args = []
2091 2092
    is_self_arg = cmethod_flag
    while s.sy not in c_arg_list_terminators:
2093
        args.append(p_c_arg_decl(s, ctx, in_pyfunc, is_self_arg,
2094 2095 2096 2097 2098
            nonempty = nonempty_declarators, kw_only = kw_only))
        if s.sy != ',':
            break
        s.next()
        is_self_arg = 0
William Stein's avatar
William Stein committed
2099 2100 2101 2102 2103 2104 2105 2106 2107
    return args

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

2108
def p_c_arg_decl(s, ctx, in_pyfunc, cmethod_flag = 0, nonempty = 0, kw_only = 0):
William Stein's avatar
William Stein committed
2109 2110 2111
    pos = s.position()
    not_none = 0
    default = None
2112
    base_type = p_c_base_type(s, cmethod_flag, nonempty = nonempty)
2113
    declarator = p_c_declarator(s, ctx, nonempty = nonempty)
William Stein's avatar
William Stein committed
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
    if s.sy == 'not':
        s.next()
        if s.sy == 'IDENT' and s.systring == 'None':
            s.next()
        else:
            s.error("Expected 'None'")
        if not in_pyfunc:
            error(pos, "'not None' only allowed in Python functions")
        not_none = 1
    if s.sy == '=':
        s.next()
2125 2126 2127
        if 'pxd' in s.level:
            if s.sy not in ['*', '?']:
                error(pos, "default values cannot be specified in pxd files, use ? or *")
Robert Bradshaw's avatar
Robert Bradshaw committed
2128
            default = ExprNodes.BoolNode(1)
2129 2130 2131
            s.next()
        else:
            default = p_simple_expr(s)
William Stein's avatar
William Stein committed
2132 2133 2134 2135
    return Nodes.CArgDeclNode(pos,
        base_type = base_type,
        declarator = declarator,
        not_none = not_none,
2136 2137
        default = default,
        kw_only = kw_only)
William Stein's avatar
William Stein committed
2138

2139 2140 2141 2142 2143 2144 2145
def p_api(s):
    if s.sy == 'IDENT' and s.systring == 'api':
        s.next()
        return 1
    else:
        return 0

2146
def p_cdef_statement(s, ctx):
William Stein's avatar
William Stein committed
2147
    pos = s.position()
2148 2149 2150 2151 2152 2153 2154
    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
2155 2156
    elif s.sy == 'import':
        s.next()
2157
        return p_cdef_extern_block(s, pos, ctx)
2158
    elif p_nogil(s):
2159
        ctx.nogil = 1
2160 2161 2162 2163 2164 2165
        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")
2166
        return p_cdef_block(s, ctx)
William Stein's avatar
William Stein committed
2167
    elif s.sy == 'class':
2168
        if ctx.level not in ('module', 'module_pxd'):
William Stein's avatar
William Stein committed
2169
            error(pos, "Extension type definition not allowed here")
2170 2171
        if ctx.overridable:
            error(pos, "Extension types cannot be declared cpdef")
2172
        return p_c_class_definition(s, pos, ctx)
2173
    elif s.sy == 'IDENT' and s.systring in ("struct", "union", "enum", "packed"):
2174
        if ctx.level not in ('module', 'module_pxd'):
William Stein's avatar
William Stein committed
2175
            error(pos, "C struct/union/enum definition not allowed here")
2176 2177
        if ctx.overridable:
            error(pos, "C struct/union/enum cannot be declared cpdef")
William Stein's avatar
William Stein committed
2178
        if s.systring == "enum":
2179
            return p_c_enum_definition(s, pos, ctx)
William Stein's avatar
William Stein committed
2180
        else:
2181
            return p_c_struct_or_union_definition(s, pos, ctx)
William Stein's avatar
William Stein committed
2182
    else:
2183
        return p_c_func_or_var_declaration(s, pos, ctx)
2184

2185 2186
def p_cdef_block(s, ctx):
    return p_suite(s, ctx(cdef_flag = 1))
William Stein's avatar
William Stein committed
2187

2188
def p_cdef_extern_block(s, pos, ctx):
2189 2190
    if ctx.overridable:
        error(pos, "cdef extern blocks cannot be declared cpdef")
William Stein's avatar
William Stein committed
2191 2192 2193 2194 2195 2196
    include_file = None
    s.expect('from')
    if s.sy == '*':
        s.next()
    else:
        _, include_file = p_string_literal(s)
2197 2198 2199 2200
    ctx = ctx(cdef_flag = 1, visibility = 'extern')
    if p_nogil(s):
        ctx.nogil = 1
    body = p_suite(s, ctx)
William Stein's avatar
William Stein committed
2201 2202 2203 2204
    return Nodes.CDefExternNode(pos,
        include_file = include_file,
        body = body)

2205
def p_c_enum_definition(s, pos, ctx):
William Stein's avatar
William Stein committed
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
    # s.sy == ident 'enum'
    s.next()
    if s.sy == 'IDENT':
        name = s.systring
        s.next()
        cname = p_opt_cname(s)
    else:
        name = None
        cname = None
    items = None
    s.expect(':')
    items = []
Stefan Behnel's avatar
Stefan Behnel committed
2218
    if s.sy != 'NEWLINE':
William Stein's avatar
William Stein committed
2219 2220 2221 2222 2223 2224 2225
        p_c_enum_line(s, items)
    else:
        s.next() # 'NEWLINE'
        s.expect_indent()
        while s.sy not in ('DEDENT', 'EOF'):
            p_c_enum_line(s, items)
        s.expect_dedent()
2226 2227 2228 2229
    return Nodes.CEnumDefNode(
        pos, name = name, cname = cname, items = items,
        typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
        in_pxd = ctx.level == 'module_pxd')
William Stein's avatar
William Stein committed
2230 2231

def p_c_enum_line(s, items):
Stefan Behnel's avatar
Stefan Behnel committed
2232
    if s.sy != 'pass':
William Stein's avatar
William Stein committed
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
        p_c_enum_item(s, items)
        while s.sy == ',':
            s.next()
            if s.sy in ('NEWLINE', 'EOF'):
                break
            p_c_enum_item(s, items)
    else:
        s.next()
    s.expect_newline("Syntax error in enum item list")

def p_c_enum_item(s, items):
    pos = s.position()
    name = p_ident(s)
    cname = p_opt_cname(s)
    value = None
    if s.sy == '=':
        s.next()
        value = p_simple_expr(s)
    items.append(Nodes.CEnumDefItemNode(pos, 
        name = name, cname = cname, value = value))

2254
def p_c_struct_or_union_definition(s, pos, ctx):
2255 2256 2257 2258
    packed = False
    if s.systring == 'packed':
        packed = True
        s.next()
Dag Sverre Seljebotn's avatar
Dag Sverre Seljebotn committed
2259
        if s.sy != 'IDENT' or s.systring != 'struct':
2260
            s.expected('struct')
William Stein's avatar
William Stein committed
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
    # s.sy == ident 'struct' or 'union'
    kind = s.systring
    s.next()
    name = p_ident(s)
    cname = p_opt_cname(s)
    attributes = None
    if s.sy == ':':
        s.next()
        s.expect('NEWLINE')
        s.expect_indent()
        attributes = []
2272
        body_ctx = Ctx()
Stefan Behnel's avatar
Stefan Behnel committed
2273 2274
        while s.sy != 'DEDENT':
            if s.sy != 'pass':
William Stein's avatar
William Stein committed
2275
                attributes.append(
2276
                    p_c_func_or_var_declaration(s, s.position(), body_ctx))
William Stein's avatar
William Stein committed
2277 2278 2279 2280 2281 2282 2283 2284
            else:
                s.next()
                s.expect_newline("Expected a newline")
        s.expect_dedent()
    else:
        s.expect_newline("Syntax error in struct or union definition")
    return Nodes.CStructOrUnionDefNode(pos, 
        name = name, cname = cname, kind = kind, attributes = attributes,
2285
        typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2286
        in_pxd = ctx.level == 'module_pxd', packed = packed)
William Stein's avatar
William Stein committed
2287 2288 2289 2290 2291 2292

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
2293
        if prev_visibility != 'private' and visibility != prev_visibility:
William Stein's avatar
William Stein committed
2294 2295 2296 2297
            s.error("Conflicting visibility options '%s' and '%s'"
                % (prev_visibility, visibility))
        s.next()
    return visibility
2298 2299
    
def p_c_modifiers(s):
2300
    if s.sy == 'IDENT' and s.systring in ('inline',):
2301
        modifier = s.systring
2302
        s.next()
2303 2304
        return [modifier] + p_c_modifiers(s)
    return []
William Stein's avatar
William Stein committed
2305

2306 2307
def p_c_func_or_var_declaration(s, pos, ctx):
    cmethod_flag = ctx.level in ('c_class', 'c_class_pxd')
2308
    modifiers = p_c_modifiers(s)
2309
    base_type = p_c_base_type(s, nonempty = 1)
2310 2311 2312
    declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
                                assignable = 1, nonempty = 1)
    declarator.overridable = ctx.overridable
William Stein's avatar
William Stein committed
2313
    if s.sy == ':':
2314
        if ctx.level not in ('module', 'c_class', 'module_pxd', 'c_class_pxd'):
William Stein's avatar
William Stein committed
2315
            s.error("C function definition not allowed here")
2316
        doc, suite = p_suite(s, Ctx(level = 'function'), with_doc = 1)
William Stein's avatar
William Stein committed
2317
        result = Nodes.CFuncDefNode(pos,
2318
            visibility = ctx.visibility,
William Stein's avatar
William Stein committed
2319 2320
            base_type = base_type,
            declarator = declarator, 
2321
            body = suite,
2322
            doc = doc,
2323
            modifiers = modifiers,
2324 2325
            api = ctx.api,
            overridable = ctx.overridable)
William Stein's avatar
William Stein committed
2326
    else:
Stefan Behnel's avatar
Stefan Behnel committed
2327 2328
        #if api:
        #    error(s.pos, "'api' not allowed with variable declaration")
William Stein's avatar
William Stein committed
2329 2330 2331 2332 2333
        declarators = [declarator]
        while s.sy == ',':
            s.next()
            if s.sy == 'NEWLINE':
                break
2334 2335
            declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
                                        assignable = 1, nonempty = 1)
William Stein's avatar
William Stein committed
2336 2337 2338
            declarators.append(declarator)
        s.expect_newline("Syntax error in C variable declaration")
        result = Nodes.CVarDefNode(pos, 
2339 2340
            visibility = ctx.visibility,
            base_type = base_type,
2341
            declarators = declarators,
2342 2343 2344
            in_pxd = ctx.level == 'module_pxd',
            api = ctx.api,
            overridable = ctx.overridable)
William Stein's avatar
William Stein committed
2345 2346
    return result

2347
def p_ctypedef_statement(s, ctx):
William Stein's avatar
William Stein committed
2348 2349 2350
    # s.sy == 'ctypedef'
    pos = s.position()
    s.next()
2351
    visibility = p_visibility(s, ctx.visibility)
2352
    api = p_api(s)
2353
    ctx = ctx(typedef_flag = 1, visibility = visibility)
2354 2355
    if api:
        ctx.api = 1
William Stein's avatar
William Stein committed
2356
    if s.sy == 'class':
2357
        return p_c_class_definition(s, pos, ctx)
2358
    elif s.sy == 'IDENT' and s.systring in ('packed', 'struct', 'union', 'enum'):
William Stein's avatar
William Stein committed
2359
        if s.systring == 'enum':
2360
            return p_c_enum_definition(s, pos, ctx)
William Stein's avatar
William Stein committed
2361
        else:
2362
            return p_c_struct_or_union_definition(s, pos, ctx)
William Stein's avatar
William Stein committed
2363
    else:
2364
        base_type = p_c_base_type(s, nonempty = 1)
2365 2366
        if base_type.name is None:
            s.error("Syntax error in ctypedef statement")
2367
        declarator = p_c_declarator(s, ctx, is_type = 1, nonempty = 1)
William Stein's avatar
William Stein committed
2368
        s.expect_newline("Syntax error in ctypedef statement")
2369 2370 2371 2372
        return Nodes.CTypeDefNode(
            pos, base_type = base_type,
            declarator = declarator, visibility = visibility,
            in_pxd = ctx.level == 'module_pxd')
William Stein's avatar
William Stein committed
2373

2374 2375 2376 2377 2378
def p_decorators(s):
    decorators = []
    while s.sy == 'DECORATOR':
        pos = s.position()
        s.next()
2379 2380
        decstring = p_dotted_name(s, as_allowed=0)[2]
        names = decstring.split('.')
2381
        decorator = ExprNodes.NameNode(pos, name=EncodedString(names[0]))
2382 2383
        for name in names[1:]:
            decorator = ExprNodes.AttributeNode(pos,
2384
                                           attribute=EncodedString(name),
2385
                                           obj=decorator)
2386 2387 2388 2389 2390 2391 2392
        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
2393 2394 2395
    # s.sy == 'def'
    pos = s.position()
    s.next()
2396
    name = EncodedString( p_ident(s) )
2397
    #args = []
William Stein's avatar
William Stein committed
2398
    s.expect('(');
2399
    args = p_c_arg_list(s, in_pyfunc = 1, nonempty_declarators = 1)
William Stein's avatar
William Stein committed
2400 2401 2402 2403
    star_arg = None
    starstar_arg = None
    if s.sy == '*':
        s.next()
2404 2405
        if s.sy == 'IDENT':
            star_arg = p_py_arg_decl(s)
William Stein's avatar
William Stein committed
2406 2407
        if s.sy == ',':
            s.next()
2408 2409 2410 2411 2412
            args.extend(p_c_arg_list(s, in_pyfunc = 1,
                nonempty_declarators = 1, kw_only = 1))
        elif s.sy != ')':
            s.error("Syntax error in Python function argument list")
    if s.sy == '**':
William Stein's avatar
William Stein committed
2413 2414 2415
        s.next()
        starstar_arg = p_py_arg_decl(s)
    s.expect(')')
2416 2417
    if p_nogil(s):
        error(s.pos, "Python function cannot be declared nogil")
2418
    doc, body = p_suite(s, Ctx(level = 'function'), with_doc = 1)
William Stein's avatar
William Stein committed
2419 2420
    return Nodes.DefNode(pos, name = name, args = args, 
        star_arg = star_arg, starstar_arg = starstar_arg,
2421
        doc = doc, body = body, decorators = decorators)
William Stein's avatar
William Stein committed
2422 2423 2424 2425 2426 2427

def p_py_arg_decl(s):
    pos = s.position()
    name = p_ident(s)
    return Nodes.PyArgDeclNode(pos, name = name)

2428
def p_class_statement(s, decorators):
William Stein's avatar
William Stein committed
2429 2430 2431
    # s.sy == 'class'
    pos = s.position()
    s.next()
2432
    class_name = EncodedString( p_ident(s) )
2433
    class_name.encoding = s.source_encoding
William Stein's avatar
William Stein committed
2434 2435 2436 2437 2438 2439
    if s.sy == '(':
        s.next()
        base_list = p_simple_expr_list(s)
        s.expect(')')
    else:
        base_list = []
2440
    doc, body = p_suite(s, Ctx(level = 'class'), with_doc = 1)
William Stein's avatar
William Stein committed
2441 2442 2443
    return Nodes.PyClassDefNode(pos,
        name = class_name,
        bases = ExprNodes.TupleNode(pos, args = base_list),
2444
        doc = doc, body = body, decorators = decorators)
William Stein's avatar
William Stein committed
2445

2446
def p_c_class_definition(s, pos,  ctx):
William Stein's avatar
William Stein committed
2447 2448 2449 2450 2451 2452 2453 2454
    # 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)
2455
    if module_path and ctx.visibility != 'extern':
William Stein's avatar
William Stein committed
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
        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 == '[':
2478
        if ctx.visibility not in ('public', 'extern'):
William Stein's avatar
William Stein committed
2479 2480 2481
            error(s.position(), "Name options only allowed for 'public' or 'extern' C class")
        objstruct_name, typeobj_name = p_c_class_options(s)
    if s.sy == ':':
2482
        if ctx.level == 'module_pxd':
William Stein's avatar
William Stein committed
2483 2484 2485
            body_level = 'c_class_pxd'
        else:
            body_level = 'c_class'
2486
        doc, body = p_suite(s, Ctx(level = body_level), with_doc = 1)
William Stein's avatar
William Stein committed
2487 2488 2489 2490
    else:
        s.expect_newline("Syntax error in C class definition")
        doc = None
        body = None
2491
    if ctx.visibility == 'extern':
William Stein's avatar
William Stein committed
2492 2493 2494 2495
        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")
2496
    elif ctx.visibility == 'public':
William Stein's avatar
William Stein committed
2497 2498 2499 2500
        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")
2501 2502
    elif ctx.visibility == 'private':
        if ctx.api:
Stefan Behnel's avatar
Stefan Behnel committed
2503
            error(pos, "Only 'public' C class can be declared 'api'")
2504
    else:
2505
        error(pos, "Invalid class visibility '%s'" % ctx.visibility)
William Stein's avatar
William Stein committed
2506
    return Nodes.CClassDefNode(pos,
2507 2508 2509
        visibility = ctx.visibility,
        typedef_flag = ctx.typedef_flag,
        api = ctx.api,
William Stein's avatar
William Stein committed
2510 2511 2512 2513 2514 2515 2516
        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,
2517
        in_pxd = ctx.level == 'module_pxd',
William Stein's avatar
William Stein committed
2518 2519 2520 2521 2522 2523 2524 2525
        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
2526
        if s.sy != 'IDENT':
William Stein's avatar
William Stein committed
2527 2528 2529 2530 2531 2532 2533
            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
2534
        if s.sy != ',':
William Stein's avatar
William Stein committed
2535 2536 2537 2538 2539 2540 2541 2542 2543
            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)
2544
    doc, body = p_suite(s, Ctx(level = 'property'), with_doc = 1)
William Stein's avatar
William Stein committed
2545 2546 2547
    return Nodes.PropertyNode(pos, name = name, doc = doc, body = body)

def p_doc_string(s):
2548
    if s.sy == 'BEGIN_STRING':
2549 2550
        pos = s.position()
        kind, result = p_cat_string_literal(s)
Stefan Behnel's avatar
Stefan Behnel committed
2551
        if s.sy != 'EOF':
William Stein's avatar
William Stein committed
2552
            s.expect_newline("Syntax error in doc string")
2553 2554 2555 2556
        if kind != 'u':
            # warning(pos, "Python 3 requires docstrings to be unicode strings")
            if kind == 'b':
                result.encoding = None # force a unicode string
William Stein's avatar
William Stein committed
2557 2558 2559
        return result
    else:
        return None
2560 2561 2562 2563 2564 2565 2566
        
def p_code(s, level=None):
    body = p_statement_list(s, Ctx(level = level), first_statement = 1)
    if s.sy != 'EOF':
        s.error("Syntax error in statement [%s,%s]" % (
            repr(s.sy), repr(s.systring)))
    return body
William Stein's avatar
William Stein committed
2567

2568
COMPILER_DIRECTIVE_COMMENT_RE = re.compile(r"^#\s*cython:\s*(\w+)\s*=(.*)$")
2569 2570

def p_compiler_directive_comments(s):
2571
    result = {}
2572 2573 2574 2575 2576 2577
    while s.sy == 'commentline':
        m = COMPILER_DIRECTIVE_COMMENT_RE.match(s.systring)
        if m:
            name = m.group(1)
            try:
                value = Options.parse_option_value(str(name), str(m.group(2).strip()))
2578 2579
                if value is not None: # can be False!
                    result[name] = value
2580
            except ValueError, e:
2581
                s.error(e.args[0], fatal=False)
2582 2583 2584
        s.next()
    return result

2585
def p_module(s, pxd, full_module_name):
William Stein's avatar
William Stein committed
2586
    pos = s.position()
2587 2588 2589 2590

    option_comments = p_compiler_directive_comments(s)
    s.parse_comments = False

William Stein's avatar
William Stein committed
2591 2592 2593 2594 2595
    doc = p_doc_string(s)
    if pxd:
        level = 'module_pxd'
    else:
        level = 'module'
2596

2597
    body = p_statement_list(s, Ctx(level = level), first_statement = 1)
Stefan Behnel's avatar
Stefan Behnel committed
2598
    if s.sy != 'EOF':
William Stein's avatar
William Stein committed
2599 2600
        s.error("Syntax error in statement [%s,%s]" % (
            repr(s.sy), repr(s.systring)))
2601 2602 2603
    return ModuleNode(pos, doc = doc, body = body,
                      full_module_name = full_module_name,
                      option_comments = option_comments)
William Stein's avatar
William Stein committed
2604 2605 2606 2607 2608 2609 2610

#----------------------------------------------
#
#   Debugging
#
#----------------------------------------------

Stefan Behnel's avatar
Stefan Behnel committed
2611
def print_parse_tree(f, node, level, key = None):
2612
    from Nodes import Node
William Stein's avatar
William Stein committed
2613 2614 2615 2616 2617 2618
    ind = "  " * level
    if node:
        f.write(ind)
        if key:
            f.write("%s: " % key)
        t = type(node)
Stefan Behnel's avatar
Stefan Behnel committed
2619
        if t is tuple:
William Stein's avatar
William Stein committed
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631
            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
2632
                if name != 'tag' and name != 'pos':
William Stein's avatar
William Stein committed
2633 2634
                    print_parse_tree(f, value, level+1, name)
            return
Stefan Behnel's avatar
Stefan Behnel committed
2635
        elif t is list:
William Stein's avatar
William Stein committed
2636 2637 2638 2639 2640 2641 2642
            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))