1 # cython: auto_cpdef=True, infer_types=True
6 # This should be done automatically
8 cython.declare(Nodes=object, ExprNodes=object, EncodedString=object)
14 from Cython.Compiler.Scanning import PyrexScanner, FileSourceDescriptor
18 from StringEncoding import EncodedString, BytesLiteral, _unicode, _bytes
19 from ModuleNode import ModuleNode
20 from Errors import error, warning, InternalError
21 from Cython import Utils
28 visibility = 'private'
37 def __init__(self, **kwds):
38 self.__dict__.update(kwds)
40 def __call__(self, **kwds):
43 d.update(self.__dict__)
47 def p_ident(s, message = "Expected an identifier"):
57 while s.sy == 'IDENT':
58 names.append(s.systring)
65 #------------------------------------------
69 #------------------------------------------
71 def p_binop_operator(s):
77 def p_binop_expr(s, ops, p_sub_expr):
80 op, pos = p_binop_operator(s)
82 n1 = ExprNodes.binop_node(pos, op, n1, n2)
84 if Future.division in s.context.future_directives:
85 n1.truedivision = True
87 n1.truedivision = None # unknown
90 #lambdef: 'lambda' [varargslist] ':' test
92 def p_lambdef(s, allow_conditional=True):
98 star_arg = starstar_arg = None
100 args, star_arg, starstar_arg = p_varargslist(
101 s, terminator=':', annotated=False)
103 if allow_conditional:
106 expr = p_test_nocond(s)
107 return ExprNodes.LambdaNode(
109 star_arg = star_arg, starstar_arg = starstar_arg,
112 #lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
114 def p_lambdef_nocond(s):
115 return p_lambdef(s, allow_conditional=False)
117 #test: or_test ['if' or_test 'else' test] | lambdef
129 return ExprNodes.CondExprNode(pos, test=test, true_val=expr, false_val=other)
133 #test_nocond: or_test | lambdef_nocond
135 def p_test_nocond(s):
137 return p_lambdef_nocond(s)
141 #or_test: and_test ('or' and_test)*
144 return p_rassoc_binop_expr(s, ('or',), p_and_test)
146 def p_rassoc_binop_expr(s, ops, p_subexpr):
152 n2 = p_rassoc_binop_expr(s, ops, p_subexpr)
153 n1 = ExprNodes.binop_node(pos, op, n1, n2)
156 #and_test: not_test ('and' not_test)*
159 #return p_binop_expr(s, ('and',), p_not_test)
160 return p_rassoc_binop_expr(s, ('and',), p_not_test)
162 #not_test: 'not' not_test | comparison
168 return ExprNodes.NotNode(pos, operand = p_not_test(s))
170 return p_comparison(s)
172 #comparison: expr (comp_op expr)*
173 #comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
176 n1 = p_starred_expr(s)
177 if s.sy in comparison_ops:
180 n2 = p_starred_expr(s)
181 n1 = ExprNodes.PrimaryCmpNode(pos,
182 operator = op, operand1 = n1, operand2 = n2)
183 if s.sy in comparison_ops:
184 n1.cascade = p_cascaded_cmp(s)
187 def p_test_or_starred_expr(s):
189 return p_starred_expr(s)
193 def p_starred_expr(s):
202 expr = ExprNodes.StarredTargetNode(pos, expr)
205 def p_cascaded_cmp(s):
208 n2 = p_starred_expr(s)
209 result = ExprNodes.CascadedCmpNode(pos,
210 operator = op, operand2 = n2)
211 if s.sy in comparison_ops:
212 result.cascade = p_cascaded_cmp(s)
235 '<', '>', '==', '>=', '<=', '<>', '!=',
239 #expr: xor_expr ('|' xor_expr)*
242 return p_binop_expr(s, ('|',), p_xor_expr)
244 #xor_expr: and_expr ('^' and_expr)*
247 return p_binop_expr(s, ('^',), p_and_expr)
249 #and_expr: shift_expr ('&' shift_expr)*
252 return p_binop_expr(s, ('&',), p_shift_expr)
254 #shift_expr: arith_expr (('<<'|'>>') arith_expr)*
257 return p_binop_expr(s, ('<<', '>>'), p_arith_expr)
259 #arith_expr: term (('+'|'-') term)*
262 return p_binop_expr(s, ('+', '-'), p_term)
264 #term: factor (('*'|'/'|'%') factor)*
267 return p_binop_expr(s, ('*', '/', '%', '//'), p_factor)
269 #factor: ('+'|'-'|'~'|'&'|typecast|sizeof) factor | power
273 if sy in ('+', '-', '~'):
277 return ExprNodes.unop_node(pos, op, p_factor(s))
282 return ExprNodes.AmpersandNode(pos, operand = arg)
285 elif sy == 'IDENT' and s.systring == "sizeof":
294 base_type = p_c_base_type(s)
295 if base_type.name is None:
296 s.error("Unknown type")
297 declarator = p_c_declarator(s, empty = 1)
304 operand = p_factor(s)
305 return ExprNodes.TypecastNode(pos,
306 base_type = base_type,
307 declarator = declarator,
309 typecheck = typecheck)
312 # s.sy == ident "sizeof"
316 # Here we decide if we are looking at an expression or type
317 # If it is actually a type, but parsable as an expression,
318 # we treat it as an expression here.
319 if looking_at_expr(s):
321 node = ExprNodes.SizeofVarNode(pos, operand = operand)
323 base_type = p_c_base_type(s)
324 declarator = p_c_declarator(s, empty = 1)
325 node = ExprNodes.SizeofTypeNode(pos,
326 base_type = base_type, declarator = declarator)
330 def p_yield_expression(s):
334 if s.sy != ')' and s.sy not in statement_terminators:
338 return ExprNodes.YieldExprNode(pos, arg=arg)
340 def p_yield_statement(s):
342 yield_expr = p_yield_expression(s)
343 return Nodes.ExprStatNode(yield_expr.pos, expr=yield_expr)
345 #power: atom trailer* ('**' factor)*
348 if s.systring == 'new' and s.peek()[0] == 'IDENT':
351 while s.sy in ('(', '[', '.'):
352 n1 = p_trailer(s, n1)
357 n1 = ExprNodes.binop_node(pos, '**', n1, n2)
361 # s.systring == 'new'.
364 cppclass = p_c_base_type(s)
365 return p_call(s, ExprNodes.NewExprNode(pos, cppclass = cppclass))
367 #trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
369 def p_trailer(s, node1):
372 return p_call(s, node1)
374 return p_index(s, node1)
377 name = EncodedString( p_ident(s) )
378 return ExprNodes.AttributeNode(pos,
379 obj = node1, attribute = name)
381 # arglist: argument (',' argument)* [',']
382 # argument: [test '='] test # Really [keyword '='] test
384 def p_call_parse_args(s, allow_genexp = True):
392 while s.sy not in ('**', ')'):
395 s.error("only one star-arg parameter allowed",
404 s.error("Expected an identifier before '='",
406 encoded_name = EncodedString(arg.name)
407 keyword = ExprNodes.IdentifierStringNode(arg.pos, value = encoded_name)
409 keyword_args.append((keyword, arg))
412 s.error("Non-keyword arg following keyword arg",
415 s.error("Non-keyword arg following star-arg",
417 positional_args.append(arg)
423 if len(positional_args) == 1 and not star_arg:
424 positional_args = [ p_genexp(s, positional_args[0]) ]
427 starstar_arg = p_test(s)
431 return positional_args, keyword_args, star_arg, starstar_arg
433 def p_call_build_packed_args(pos, positional_args, keyword_args, star_arg):
436 if positional_args or not star_arg:
437 arg_tuple = ExprNodes.TupleNode(pos,
438 args = positional_args)
440 star_arg_tuple = ExprNodes.AsTupleNode(pos, arg = star_arg)
442 arg_tuple = ExprNodes.binop_node(pos,
443 operator = '+', operand1 = arg_tuple,
444 operand2 = star_arg_tuple)
446 arg_tuple = star_arg_tuple
448 keyword_args = [ExprNodes.DictItemNode(pos=key.pos, key=key, value=value)
449 for key, value in keyword_args]
450 keyword_dict = ExprNodes.DictNode(pos,
451 key_value_pairs = keyword_args)
452 return arg_tuple, keyword_dict
454 def p_call(s, function):
458 positional_args, keyword_args, star_arg, starstar_arg = \
461 if not (keyword_args or star_arg or starstar_arg):
462 return ExprNodes.SimpleCallNode(pos,
464 args = positional_args)
466 arg_tuple, keyword_dict = p_call_build_packed_args(
467 pos, positional_args, keyword_args, star_arg)
468 return ExprNodes.GeneralCallNode(pos,
470 positional_args = arg_tuple,
471 keyword_args = keyword_dict,
472 starstar_arg = starstar_arg)
474 #lambdef: 'lambda' [varargslist] ':' test
476 #subscriptlist: subscript (',' subscript)* [',']
478 def p_index(s, base):
482 subscripts = p_subscript_list(s)
483 if len(subscripts) == 1 and len(subscripts[0]) == 2:
484 start, stop = subscripts[0]
485 result = ExprNodes.SliceIndexNode(pos,
486 base = base, start = start, stop = stop)
488 indexes = make_slice_nodes(pos, subscripts)
489 if len(indexes) == 1:
492 index = ExprNodes.TupleNode(pos, args = indexes)
493 result = ExprNodes.IndexNode(pos,
494 base = base, index = index)
498 def p_subscript_list(s):
499 items = [p_subscript(s)]
504 items.append(p_subscript(s))
507 #subscript: '.' '.' '.' | test | [test] ':' [test] [':' [test]]
510 # Parse a subscript and return a list of
511 # 1, 2 or 3 ExprNodes, depending on how
512 # many slice elements were encountered.
514 start = p_slice_element(s, (':',))
518 stop = p_slice_element(s, (':', ',', ']'))
522 step = p_slice_element(s, (':', ',', ']'))
523 return [start, stop, step]
525 def p_slice_element(s, follow_set):
526 # Simple expression which may be missing iff
527 # it is followed by something in follow_set.
528 if s.sy not in follow_set:
533 def expect_ellipsis(s):
538 def make_slice_nodes(pos, subscripts):
539 # Convert a list of subscripts as returned
540 # by p_subscript_list into a list of ExprNodes,
541 # creating SliceNodes for elements with 2 or
544 for subscript in subscripts:
545 if len(subscript) == 1:
546 result.append(subscript[0])
548 result.append(make_slice_node(pos, *subscript))
551 def make_slice_node(pos, start, stop = None, step = None):
553 start = ExprNodes.NoneNode(pos)
555 stop = ExprNodes.NoneNode(pos)
557 step = ExprNodes.NoneNode(pos)
558 return ExprNodes.SliceNode(pos,
559 start = start, stop = stop, step = step)
561 #atom: '(' [yield_expr|testlist_comp] ')' | '[' [listmaker] ']' | '{' [dict_or_set_maker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+
569 result = ExprNodes.TupleNode(pos, args = [])
570 elif s.sy == 'yield':
571 result = p_yield_expression(s)
573 result = p_testlist_comp(s)
577 return p_list_maker(s)
579 return p_dict_or_set_maker(s)
581 return p_backquote_expr(s)
584 return ExprNodes.EllipsisNode(pos)
586 return p_int_literal(s)
590 return ExprNodes.FloatNode(pos, value = value)
592 value = s.systring[:-1]
594 return ExprNodes.ImagNode(pos, value = value)
595 elif sy == 'BEGIN_STRING':
596 kind, bytes_value, unicode_value = p_cat_string_literal(s)
598 return ExprNodes.CharNode(pos, value = bytes_value)
600 return ExprNodes.UnicodeNode(pos, value = unicode_value, bytes_value = bytes_value)
602 return ExprNodes.BytesNode(pos, value = bytes_value)
604 return ExprNodes.StringNode(pos, value = bytes_value, unicode_value = unicode_value)
606 name = EncodedString( s.systring )
609 return ExprNodes.NoneNode(pos)
611 return ExprNodes.BoolNode(pos, value=True)
612 elif name == "False":
613 return ExprNodes.BoolNode(pos, value=False)
615 return ExprNodes.NullNode(pos)
617 return p_name(s, name)
619 s.error("Expected an identifier or literal")
621 def p_int_literal(s):
627 while value[-1] in u"UuLl":
628 if value[-1] in u"Ll":
633 # '3L' is ambiguous in Py2 but not in Py3. '3U' and '3LL' are
634 # illegal in Py2 Python files. All suffixes are illegal in Py3
640 if longness == 'LL' or s.context.language_level >= 3:
644 error(pos, "illegal integer literal syntax in Python source file")
646 return ExprNodes.IntNode(pos,
647 is_c_literal = is_c_literal,
654 if not s.compile_time_expr and name in s.compile_time_env:
655 value = s.compile_time_env.lookup_here(name)
657 if isinstance(value, bool):
658 return ExprNodes.BoolNode(pos, value = value)
659 elif isinstance(value, int):
660 return ExprNodes.IntNode(pos, value = rep)
661 elif isinstance(value, long):
662 return ExprNodes.IntNode(pos, value = rep, longness = "L")
663 elif isinstance(value, float):
664 return ExprNodes.FloatNode(pos, value = rep)
665 elif isinstance(value, _unicode):
666 return ExprNodes.UnicodeNode(pos, value = value)
667 elif isinstance(value, _bytes):
668 return ExprNodes.BytesNode(pos, value = value)
670 error(pos, "Invalid type for compile-time constant: %s"
671 % value.__class__.__name__)
672 return ExprNodes.NameNode(pos, name = name)
674 def p_cat_string_literal(s):
675 # A sequence of one or more adjacent string literals.
676 # Returns (kind, bytes_value, unicode_value)
677 # where kind in ('b', 'c', 'u', '')
678 kind, bytes_value, unicode_value = p_string_literal(s)
679 if kind == 'c' or s.sy != 'BEGIN_STRING':
680 return kind, bytes_value, unicode_value
681 bstrings, ustrings = [bytes_value], [unicode_value]
682 bytes_value = unicode_value = None
683 while s.sy == 'BEGIN_STRING':
685 next_kind, next_bytes_value, next_unicode_value = p_string_literal(s)
687 error(pos, "Cannot concatenate char literal with another string or char literal")
688 elif next_kind != kind:
689 error(pos, "Cannot mix string literals of different types, expected %s'', got %s''" %
692 bstrings.append(next_bytes_value)
693 ustrings.append(next_unicode_value)
694 # join and rewrap the partial literals
695 if kind in ('b', 'c', '') or kind == 'u' and None not in bstrings:
696 # Py3 enforced unicode literals are parsed as bytes/unicode combination
697 bytes_value = BytesLiteral( StringEncoding.join_bytes(bstrings) )
698 bytes_value.encoding = s.source_encoding
699 if kind in ('u', ''):
700 unicode_value = EncodedString( u''.join([ u for u in ustrings if u is not None ]) )
701 return kind, bytes_value, unicode_value
703 def p_opt_string_literal(s, required_type='u'):
704 if s.sy == 'BEGIN_STRING':
705 kind, bytes_value, unicode_value = p_string_literal(s, required_type)
706 if required_type == 'u':
708 elif required_type == 'b':
711 s.error("internal parser configuration error")
715 def check_for_non_ascii_characters(string):
721 def p_string_literal(s, kind_override=None):
722 # A single string or char literal. Returns (kind, bvalue, uvalue)
723 # where kind in ('b', 'c', 'u', ''). The 'bvalue' is the source
724 # code byte sequence of the string literal, 'uvalue' is the
725 # decoded Unicode string. Either of the two may be None depending
726 # on the 'kind' of string, only unprefixed strings have both
729 # s.sy == 'BEGIN_STRING'
732 is_python3_source = s.context.language_level >= 3
733 has_non_ASCII_literal_characters = False
734 kind = s.systring[:1].lower()
739 is_raw = s.systring[1:2].lower() == 'r'
742 if kind == '' and kind_override is None and Future.unicode_literals in s.context.future_directives:
743 chars = StringEncoding.StrLiteralBuilder(s.source_encoding)
746 if kind_override is not None and kind_override in 'ub':
749 chars = StringEncoding.UnicodeLiteralBuilder()
751 chars = StringEncoding.StrLiteralBuilder(s.source_encoding)
753 chars = StringEncoding.BytesLiteralBuilder(s.source_encoding)
758 #print "p_string_literal: sy =", sy, repr(s.systring) ###
761 if is_python3_source and not has_non_ASCII_literal_characters and check_for_non_ascii_characters(systr):
762 has_non_ASCII_literal_characters = True
766 chars.append(u'\\\n')
767 elif systr == u'\\\"':
769 elif systr == u'\\\'':
773 if is_python3_source and not has_non_ASCII_literal_characters \
774 and check_for_non_ascii_characters(systr):
775 has_non_ASCII_literal_characters = True
779 chars.append_charval( int(systr[1:], 8) )
782 elif c in u"abfnrtv":
784 StringEncoding.char_from_escape_sequence(systr))
788 chars.append_charval( int(systr[2:], 16) )
790 if kind in ('u', ''):
791 chrval = int(systr[2:], 16)
792 if chrval > 1114111: # sys.maxunicode:
793 s.error("Invalid unicode escape '%s'" % systr,
796 # unicode escapes in plain byte strings are not unescaped
798 chars.append_uescape(chrval, systr)
800 chars.append(u'\\' + systr[1:])
801 if is_python3_source and not has_non_ASCII_literal_characters \
802 and check_for_non_ascii_characters(systr):
803 has_non_ASCII_literal_characters = True
804 elif sy == 'NEWLINE':
806 elif sy == 'END_STRING':
809 s.error("Unclosed string literal", pos = pos)
812 "Unexpected token %r:%r in string literal" %
816 bytes_value = chars.getchar()
817 if len(bytes_value) != 1:
818 error(pos, u"invalid character literal: %r" % bytes_value)
820 bytes_value, unicode_value = chars.getstrings()
821 if is_python3_source and has_non_ASCII_literal_characters:
822 # Python 3 forbids literal non-ASCII characters in byte strings
824 s.error("bytes can only contain ASCII literal characters.", pos = pos)
827 return (kind, bytes_value, unicode_value)
829 # list_display ::= "[" [listmaker] "]"
830 # listmaker ::= expression ( comp_for | ( "," expression )* [","] )
831 # comp_iter ::= comp_for | comp_if
832 # comp_for ::= "for" expression_list "in" testlist [comp_iter]
833 # comp_if ::= "if" test [comp_iter]
841 return ExprNodes.ListNode(pos, args = [])
844 target = ExprNodes.ListNode(pos, args = [])
845 append = ExprNodes.ComprehensionAppendNode(
846 pos, expr=expr, target=ExprNodes.CloneNode(target))
847 loop = p_comp_for(s, append)
849 return ExprNodes.ComprehensionNode(
850 pos, loop=loop, append=append, target=target,
851 # list comprehensions leak their loop variable in Py2
852 has_local_scope = s.context.language_level >= 3)
856 exprs = p_simple_expr_list(s, expr)
860 return ExprNodes.ListNode(pos, args = exprs)
862 def p_comp_iter(s, body):
864 return p_comp_for(s, body)
866 return p_comp_if(s, body)
868 # insert the 'append' operation into the loop
871 def p_comp_for(s, body):
875 kw = p_for_bounds(s, allow_testlist=False)
876 kw['else_clause'] = None
877 kw['body'] = p_comp_iter(s, body)
878 return Nodes.ForStatNode(pos, **kw)
880 def p_comp_if(s, body):
884 test = p_test_nocond(s)
885 return Nodes.IfStatNode(pos,
886 if_clauses = [Nodes.IfClauseNode(pos, condition = test,
887 body = p_comp_iter(s, body))],
890 #dictmaker: test ':' test (',' test ':' test)* [',']
892 def p_dict_or_set_maker(s):
898 return ExprNodes.DictNode(pos, key_value_pairs = [])
900 if s.sy == ',' or s.sy == '}':
907 values.append( p_test(s) )
909 return ExprNodes.SetNode(pos, args=values)
912 target = ExprNodes.SetNode(pos, args=[])
913 append = ExprNodes.ComprehensionAppendNode(
914 item.pos, expr=item, target=ExprNodes.CloneNode(target))
915 loop = p_comp_for(s, append)
917 return ExprNodes.ComprehensionNode(
918 pos, loop=loop, append=append, target=target)
920 # dict literal or comprehension
926 target = ExprNodes.DictNode(pos, key_value_pairs = [])
927 append = ExprNodes.DictComprehensionAppendNode(
928 item.pos, key_expr=key, value_expr=value,
929 target=ExprNodes.CloneNode(target))
930 loop = p_comp_for(s, append)
932 return ExprNodes.ComprehensionNode(
933 pos, loop=loop, append=append, target=target)
936 items = [ExprNodes.DictItemNode(key.pos, key=key, value=value)]
945 ExprNodes.DictItemNode(key.pos, key=key, value=value))
947 return ExprNodes.DictNode(pos, key_value_pairs=items)
951 return ExprNodes.DictNode(pos, key_value_pairs = [])
953 # NOTE: no longer in Py3 :)
954 def p_backquote_expr(s):
961 args.append(p_test(s))
966 arg = ExprNodes.TupleNode(pos, args = args)
967 return ExprNodes.BackquoteNode(pos, arg = arg)
969 def p_simple_expr_list(s, expr=None):
970 exprs = expr is not None and [expr] or []
971 while s.sy not in expr_terminators:
972 exprs.append( p_test(s) )
978 def p_test_or_starred_expr_list(s, expr=None):
979 exprs = expr is not None and [expr] or []
980 while s.sy not in expr_terminators:
981 exprs.append( p_test_or_starred_expr(s) )
988 #testlist: test (',' test)* [',']
995 exprs = p_simple_expr_list(s, expr)
996 return ExprNodes.TupleNode(pos, args = exprs)
1000 # testlist_star_expr: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
1002 def p_testlist_star_expr(s):
1004 expr = p_test_or_starred_expr(s)
1007 exprs = p_test_or_starred_expr_list(s, expr)
1008 return ExprNodes.TupleNode(pos, args = exprs)
1012 # testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
1014 def p_testlist_comp(s):
1016 expr = p_test_or_starred_expr(s)
1019 exprs = p_test_or_starred_expr_list(s, expr)
1020 return ExprNodes.TupleNode(pos, args = exprs)
1022 return p_genexp(s, expr)
1026 def p_genexp(s, expr):
1028 loop = p_comp_for(s, Nodes.ExprStatNode(
1029 expr.pos, expr = ExprNodes.YieldExprNode(expr.pos, arg=expr)))
1030 return ExprNodes.GeneratorExpressionNode(expr.pos, loop=loop)
1032 expr_terminators = (')', ']', '}', ':', '=', 'NEWLINE')
1034 #-------------------------------------------------------
1038 #-------------------------------------------------------
1040 def p_global_statement(s):
1041 # assume s.sy == 'global'
1044 names = p_ident_list(s)
1045 return Nodes.GlobalNode(pos, names = names)
1047 def p_expression_or_assignment(s):
1048 expr_list = [p_testlist_star_expr(s)]
1052 expr = p_yield_expression(s)
1054 expr = p_testlist_star_expr(s)
1055 expr_list.append(expr)
1056 if len(expr_list) == 1:
1057 if re.match(r"([+*/\%^\&|-]|<<|>>|\*\*|//)=", s.sy):
1059 if not isinstance(lhs, (ExprNodes.AttributeNode, ExprNodes.IndexNode, ExprNodes.NameNode) ):
1060 error(lhs.pos, "Illegal operand for inplace operation.")
1061 operator = s.sy[:-1]
1064 rhs = p_yield_expression(s)
1067 return Nodes.InPlaceAssignmentNode(lhs.pos, operator = operator, lhs = lhs, rhs = rhs)
1069 if isinstance(expr, (ExprNodes.UnicodeNode, ExprNodes.StringNode, ExprNodes.BytesNode)):
1070 return Nodes.PassStatNode(expr.pos)
1072 return Nodes.ExprStatNode(expr.pos, expr = expr)
1075 if len(expr_list) == 2:
1076 return Nodes.SingleAssignmentNode(rhs.pos,
1077 lhs = expr_list[0], rhs = rhs)
1079 return Nodes.CascadedAssignmentNode(rhs.pos,
1080 lhs_list = expr_list[:-1], rhs = rhs)
1082 def p_print_statement(s):
1092 ends_with_comma = s.sy in ('NEWLINE', 'EOF')
1096 if s.sy not in ('NEWLINE', 'EOF'):
1097 args.append(p_test(s))
1100 if s.sy in ('NEWLINE', 'EOF'):
1103 args.append(p_test(s))
1104 arg_tuple = ExprNodes.TupleNode(pos, args = args)
1105 return Nodes.PrintStatNode(pos,
1106 arg_tuple = arg_tuple, stream = stream,
1107 append_newline = not ends_with_comma)
1109 def p_exec_statement(s):
1113 args = [ p_bit_expr(s) ]
1116 args.append(p_test(s))
1119 args.append(p_test(s))
1121 error(pos, "'exec' currently requires a target mapping (globals/locals)")
1122 return Nodes.ExecStatNode(pos, args = args)
1124 def p_del_statement(s):
1128 # FIXME: 'exprlist' in Python
1129 args = p_simple_expr_list(s)
1130 return Nodes.DelStatNode(pos, args = args)
1132 def p_pass_statement(s, with_newline = 0):
1136 s.expect_newline("Expected a newline")
1137 return Nodes.PassStatNode(pos)
1139 def p_break_statement(s):
1143 return Nodes.BreakStatNode(pos)
1145 def p_continue_statement(s):
1146 # s.sy == 'continue'
1149 return Nodes.ContinueStatNode(pos)
1151 def p_return_statement(s):
1155 if s.sy not in statement_terminators:
1156 value = p_testlist(s)
1159 return Nodes.ReturnStatNode(pos, value = value)
1161 def p_raise_statement(s):
1168 if s.sy not in statement_terminators:
1169 exc_type = p_test(s)
1172 exc_value = p_test(s)
1176 if exc_type or exc_value or exc_tb:
1177 return Nodes.RaiseStatNode(pos,
1178 exc_type = exc_type,
1179 exc_value = exc_value,
1182 return Nodes.ReraiseStatNode(pos)
1184 def p_import_statement(s):
1185 # s.sy in ('import', 'cimport')
1189 items = [p_dotted_name(s, as_allowed = 1)]
1192 items.append(p_dotted_name(s, as_allowed = 1))
1194 for pos, target_name, dotted_name, as_name in items:
1195 dotted_name = EncodedString(dotted_name)
1196 if kind == 'cimport':
1197 stat = Nodes.CImportStatNode(pos,
1198 module_name = dotted_name,
1201 if as_name and "." in dotted_name:
1202 name_list = ExprNodes.ListNode(pos, args = [
1203 ExprNodes.IdentifierStringNode(pos, value = EncodedString("*"))])
1206 stat = Nodes.SingleAssignmentNode(pos,
1207 lhs = ExprNodes.NameNode(pos,
1208 name = as_name or target_name),
1209 rhs = ExprNodes.ImportNode(pos,
1210 module_name = ExprNodes.IdentifierStringNode(
1211 pos, value = dotted_name),
1212 name_list = name_list))
1214 return Nodes.StatListNode(pos, stats = stats)
1216 def p_from_import_statement(s, first_statement = 0):
1220 (dotted_name_pos, _, dotted_name, _) = \
1221 p_dotted_name(s, as_allowed = 0)
1222 if s.sy in ('import', 'cimport'):
1226 s.error("Expected 'import' or 'cimport'")
1227 is_cimport = kind == 'cimport'
1228 is_parenthesized = False
1230 imported_names = [(s.position(), "*", None, None)]
1234 is_parenthesized = True
1236 imported_names = [p_imported_name(s, is_cimport)]
1239 if is_parenthesized and s.sy == ')':
1241 imported_names.append(p_imported_name(s, is_cimport))
1242 if is_parenthesized:
1244 dotted_name = EncodedString(dotted_name)
1245 if dotted_name == '__future__':
1246 if not first_statement:
1247 s.error("from __future__ imports must occur at the beginning of the file")
1249 for (name_pos, name, as_name, kind) in imported_names:
1250 if name == "braces":
1251 s.error("not a chance", name_pos)
1254 directive = getattr(Future, name)
1255 except AttributeError:
1256 s.error("future feature %s is not defined" % name, name_pos)
1258 s.context.future_directives.add(directive)
1259 return Nodes.PassStatNode(pos)
1260 elif kind == 'cimport':
1261 return Nodes.FromCImportStatNode(pos,
1262 module_name = dotted_name,
1263 imported_names = imported_names)
1265 imported_name_strings = []
1267 for (name_pos, name, as_name, kind) in imported_names:
1268 encoded_name = EncodedString(name)
1269 imported_name_strings.append(
1270 ExprNodes.IdentifierStringNode(name_pos, value = encoded_name))
1273 ExprNodes.NameNode(name_pos,
1274 name = as_name or name)))
1275 import_list = ExprNodes.ListNode(
1276 imported_names[0][0], args = imported_name_strings)
1277 dotted_name = EncodedString(dotted_name)
1278 return Nodes.FromImportStatNode(pos,
1279 module = ExprNodes.ImportNode(dotted_name_pos,
1280 module_name = ExprNodes.IdentifierStringNode(pos, value = dotted_name),
1281 name_list = import_list),
1284 imported_name_kinds = ('class', 'struct', 'union')
1286 def p_imported_name(s, is_cimport):
1289 if is_cimport and s.systring in imported_name_kinds:
1293 as_name = p_as_name(s)
1294 return (pos, name, as_name, kind)
1296 def p_dotted_name(s, as_allowed):
1298 target_name = p_ident(s)
1300 names = [target_name]
1303 names.append(p_ident(s))
1305 as_name = p_as_name(s)
1306 return (pos, target_name, u'.'.join(names), as_name)
1309 if s.sy == 'IDENT' and s.systring == 'as':
1315 def p_assert_statement(s):
1325 return Nodes.AssertStatNode(pos, cond = cond, value = value)
1327 statement_terminators = (';', 'NEWLINE', 'EOF')
1329 def p_if_statement(s):
1333 if_clauses = [p_if_clause(s)]
1334 while s.sy == 'elif':
1336 if_clauses.append(p_if_clause(s))
1337 else_clause = p_else_clause(s)
1338 return Nodes.IfStatNode(pos,
1339 if_clauses = if_clauses, else_clause = else_clause)
1345 return Nodes.IfClauseNode(pos,
1346 condition = test, body = body)
1348 def p_else_clause(s):
1355 def p_while_statement(s):
1361 else_clause = p_else_clause(s)
1362 return Nodes.WhileStatNode(pos,
1363 condition = test, body = body,
1364 else_clause = else_clause)
1366 def p_for_statement(s):
1370 kw = p_for_bounds(s, allow_testlist=True)
1371 kw['body'] = p_suite(s)
1372 kw['else_clause'] = p_else_clause(s)
1373 return Nodes.ForStatNode(pos, **kw)
1375 def p_for_bounds(s, allow_testlist=True):
1376 target = p_for_target(s)
1379 iterator = p_for_iterator(s, allow_testlist)
1380 return { 'target': target, 'iterator': iterator }
1381 elif not s.in_python_file:
1384 bound1 = p_bit_expr(s)
1386 # Support shorter "for a <= x < b" syntax
1387 bound1, target = target, None
1388 rel1 = p_for_from_relation(s)
1389 name2_pos = s.position()
1391 rel2_pos = s.position()
1392 rel2 = p_for_from_relation(s)
1393 bound2 = p_bit_expr(s)
1394 step = p_for_from_step(s)
1396 target = ExprNodes.NameNode(name2_pos, name = name2)
1398 if not target.is_name:
1400 "Target of for-from statement must be a variable name")
1401 elif name2 != target.name:
1403 "Variable name in for-from range does not match target")
1404 if rel1[0] != rel2[0]:
1406 "Relation directions in for-from do not match")
1407 return {'target': target,
1417 def p_for_from_relation(s):
1418 if s.sy in inequality_relations:
1423 s.error("Expected one of '<', '<=', '>' '>='")
1425 def p_for_from_step(s):
1428 step = p_bit_expr(s)
1433 inequality_relations = ('<', '<=', '>', '>=')
1435 def p_target(s, terminator):
1437 expr = p_starred_expr(s)
1441 while s.sy != terminator:
1442 exprs.append(p_starred_expr(s))
1446 return ExprNodes.TupleNode(pos, args = exprs)
1450 def p_for_target(s):
1451 return p_target(s, 'in')
1453 def p_for_iterator(s, allow_testlist=True):
1456 expr = p_testlist(s)
1459 return ExprNodes.IteratorNode(pos, sequence = expr)
1461 def p_try_statement(s):
1468 if s.sy in ('except', 'else'):
1469 while s.sy == 'except':
1470 except_clauses.append(p_except_clause(s))
1473 else_clause = p_suite(s)
1474 body = Nodes.TryExceptStatNode(pos,
1475 body = body, except_clauses = except_clauses,
1476 else_clause = else_clause)
1477 if s.sy != 'finally':
1479 # try-except-finally is equivalent to nested try-except/try-finally
1480 if s.sy == 'finally':
1482 finally_clause = p_suite(s)
1483 return Nodes.TryFinallyStatNode(pos,
1484 body = body, finally_clause = finally_clause)
1486 s.error("Expected 'except' or 'finally'")
1488 def p_except_clause(s):
1495 exc_type = p_test(s)
1496 # normalise into list of single exception tests
1497 if isinstance(exc_type, ExprNodes.TupleNode):
1498 exc_type = exc_type.args
1500 exc_type = [exc_type]
1501 if s.sy == ',' or (s.sy == 'IDENT' and s.systring == 'as'):
1503 exc_value = p_test(s)
1504 elif s.sy == 'IDENT' and s.systring == 'as':
1505 # Py3 syntax requires a name here
1509 exc_value = ExprNodes.NameNode(pos2, name = name)
1511 return Nodes.ExceptClauseNode(pos,
1512 pattern = exc_type, target = exc_value, body = body)
1514 def p_include_statement(s, ctx):
1516 s.next() # 'include'
1517 unicode_include_file_name = p_string_literal(s, 'u')[2]
1518 s.expect_newline("Syntax error in include statement")
1519 if s.compile_time_eval:
1520 include_file_name = unicode_include_file_name
1521 include_file_path = s.context.find_include_file(include_file_name, pos)
1522 if include_file_path:
1523 s.included_files.append(include_file_name)
1524 f = Utils.open_source_file(include_file_path, mode="rU")
1525 source_desc = FileSourceDescriptor(include_file_path)
1526 s2 = PyrexScanner(f, source_desc, s, source_encoding=f.encoding, parse_comments=s.parse_comments)
1528 tree = p_statement_list(s2, ctx)
1535 return Nodes.PassStatNode(pos)
1537 def p_with_statement(s):
1539 if s.systring == 'template' and not s.in_python_file:
1540 node = p_with_template(s)
1542 node = p_with_items(s)
1545 def p_with_items(s):
1547 if not s.in_python_file and s.sy == 'IDENT' and s.systring == 'nogil':
1552 body = p_with_items(s)
1555 return Nodes.GILStatNode(pos, state = state, body = body)
1559 if s.sy == 'IDENT' and s.systring == 'as':
1561 target = p_starred_expr(s)
1564 body = p_with_items(s)
1567 return Nodes.WithStatNode(pos, manager = manager,
1568 target = target, body = body)
1570 def p_with_template(s):
1575 templates.append(s.systring)
1577 while s.systring == ',':
1579 templates.append(s.systring)
1584 s.expect_newline("Syntax error in template function declaration")
1587 body_ctx.templates = templates
1588 func_or_var = p_c_func_or_var_declaration(s, pos, body_ctx)
1592 error(pos, "Syntax error in template function declaration")
1594 def p_simple_statement(s, first_statement = 0):
1595 #print "p_simple_statement:", s.sy, s.systring ###
1596 if s.sy == 'global':
1597 node = p_global_statement(s)
1598 elif s.sy == 'print':
1599 node = p_print_statement(s)
1600 elif s.sy == 'exec':
1601 node = p_exec_statement(s)
1603 node = p_del_statement(s)
1604 elif s.sy == 'break':
1605 node = p_break_statement(s)
1606 elif s.sy == 'continue':
1607 node = p_continue_statement(s)
1608 elif s.sy == 'return':
1609 node = p_return_statement(s)
1610 elif s.sy == 'raise':
1611 node = p_raise_statement(s)
1612 elif s.sy in ('import', 'cimport'):
1613 node = p_import_statement(s)
1614 elif s.sy == 'from':
1615 node = p_from_import_statement(s, first_statement = first_statement)
1616 elif s.sy == 'yield':
1617 node = p_yield_statement(s)
1618 elif s.sy == 'assert':
1619 node = p_assert_statement(s)
1620 elif s.sy == 'pass':
1621 node = p_pass_statement(s)
1623 node = p_expression_or_assignment(s)
1626 def p_simple_statement_list(s, ctx, first_statement = 0):
1627 # Parse a series of simple statements on one line
1628 # separated by semicolons.
1629 stat = p_simple_statement(s, first_statement = first_statement)
1633 #print "p_simple_statement_list: maybe more to follow" ###
1635 if s.sy in ('NEWLINE', 'EOF'):
1637 stats.append(p_simple_statement(s))
1638 stat = Nodes.StatListNode(stats[0].pos, stats = stats)
1639 s.expect_newline("Syntax error in simple statement list")
1642 def p_compile_time_expr(s):
1643 old = s.compile_time_expr
1644 s.compile_time_expr = 1
1645 expr = p_testlist(s)
1646 s.compile_time_expr = old
1649 def p_DEF_statement(s):
1651 denv = s.compile_time_env
1655 expr = p_compile_time_expr(s)
1656 value = expr.compile_time_value(denv)
1657 #print "p_DEF_statement: %s = %r" % (name, value) ###
1658 denv.declare(name, value)
1660 return Nodes.PassStatNode(pos)
1662 def p_IF_statement(s, ctx):
1664 saved_eval = s.compile_time_eval
1665 current_eval = saved_eval
1666 denv = s.compile_time_env
1669 s.next() # 'IF' or 'ELIF'
1670 expr = p_compile_time_expr(s)
1671 s.compile_time_eval = current_eval and bool(expr.compile_time_value(denv))
1672 body = p_suite(s, ctx)
1673 if s.compile_time_eval:
1680 s.compile_time_eval = current_eval
1681 body = p_suite(s, ctx)
1685 result = Nodes.PassStatNode(pos)
1686 s.compile_time_eval = saved_eval
1689 def p_statement(s, ctx, first_statement = 0):
1690 cdef_flag = ctx.cdef_flag
1692 if s.sy == 'ctypedef':
1693 if ctx.level not in ('module', 'module_pxd'):
1694 s.error("ctypedef statement not allowed here")
1696 # error(s.position(), "'api' not allowed with 'ctypedef'")
1697 return p_ctypedef_statement(s, ctx)
1699 return p_DEF_statement(s)
1701 return p_IF_statement(s, ctx)
1702 elif s.sy == 'DECORATOR':
1703 if ctx.level not in ('module', 'class', 'c_class', 'function', 'property', 'module_pxd', 'c_class_pxd'):
1705 s.error('decorator not allowed here')
1707 decorators = p_decorators(s)
1708 if s.sy not in ('def', 'cdef', 'cpdef', 'class'):
1709 s.error("Decorators can only be followed by functions or classes")
1710 elif s.sy == 'pass' and cdef_flag:
1712 return p_pass_statement(s, with_newline = 1)
1718 elif s.sy == 'cpdef':
1723 if ctx.level not in ('module', 'module_pxd', 'function', 'c_class', 'c_class_pxd'):
1724 s.error('cdef statement not allowed here')
1726 node = p_cdef_statement(s, ctx(overridable = overridable))
1727 if decorators is not None:
1728 if not isinstance(node, (Nodes.CFuncDefNode, Nodes.CVarDefNode, Nodes.CClassDefNode)):
1729 s.error("Decorators can only be followed by functions or classes")
1730 node.decorators = decorators
1734 s.error("'api' not allowed with this statement")
1736 # def statements aren't allowed in pxd files, except
1737 # as part of a cdef class
1738 if ('pxd' in ctx.level) and (ctx.level != 'c_class_pxd'):
1739 s.error('def statement not allowed here')
1741 return p_def_statement(s, decorators)
1742 elif s.sy == 'class':
1743 if ctx.level != 'module':
1744 s.error("class definition not allowed here")
1745 return p_class_statement(s, decorators)
1746 elif s.sy == 'include':
1747 if ctx.level not in ('module', 'module_pxd'):
1748 s.error("include statement not allowed here")
1749 return p_include_statement(s, ctx)
1750 elif ctx.level == 'c_class' and s.sy == 'IDENT' and s.systring == 'property':
1751 return p_property_decl(s)
1752 elif s.sy == 'pass' and ctx.level != 'property':
1753 return p_pass_statement(s, with_newline = 1)
1755 if ctx.level in ('c_class_pxd', 'property'):
1756 s.error("Executable statement not allowed here")
1758 return p_if_statement(s)
1759 elif s.sy == 'while':
1760 return p_while_statement(s)
1762 return p_for_statement(s)
1764 return p_try_statement(s)
1765 elif s.sy == 'with':
1766 return p_with_statement(s)
1768 return p_simple_statement_list(
1769 s, ctx, first_statement = first_statement)
1771 def p_statement_list(s, ctx, first_statement = 0):
1772 # Parse a series of statements separated by newlines.
1775 while s.sy not in ('DEDENT', 'EOF'):
1776 stats.append(p_statement(s, ctx, first_statement = first_statement))
1781 return Nodes.StatListNode(pos, stats = stats)
1783 def p_suite(s, ctx = Ctx(), with_doc = 0, with_pseudo_doc = 0):
1788 if s.sy == 'NEWLINE':
1791 if with_doc or with_pseudo_doc:
1792 doc = p_doc_string(s)
1793 body = p_statement_list(s, ctx)
1797 s.error("'api' not allowed with this statement")
1798 if ctx.level in ('module', 'class', 'function', 'other'):
1799 body = p_simple_statement_list(s, ctx)
1801 body = p_pass_statement(s)
1802 s.expect_newline("Syntax error in declarations")
1808 def p_positional_and_keyword_args(s, end_sy_set, templates = None):
1810 Parses positional and keyword arguments. end_sy_set
1811 should contain any s.sy that terminate the argument list.
1812 Argument expansion (* and **) are not allowed.
1814 Returns: (positional_args, keyword_args)
1816 positional_args = []
1820 while s.sy not in end_sy_set:
1821 if s.sy == '*' or s.sy == '**':
1822 s.error('Argument expansion not allowed here.')
1825 if s.sy == 'IDENT' and s.peek()[0] == '=':
1827 s.next() # s.sy is '='
1829 if looking_at_expr(s):
1832 base_type = p_c_base_type(s, templates = templates)
1833 declarator = p_c_declarator(s, empty = 1)
1834 arg = Nodes.CComplexBaseTypeNode(base_type.pos,
1835 base_type = base_type, declarator = declarator)
1837 keyword_node = ExprNodes.IdentifierStringNode(
1838 arg.pos, value = EncodedString(ident))
1839 keyword_args.append((keyword_node, arg))
1843 if looking_at_expr(s):
1846 base_type = p_c_base_type(s, templates = templates)
1847 declarator = p_c_declarator(s, empty = 1)
1848 arg = Nodes.CComplexBaseTypeNode(base_type.pos,
1849 base_type = base_type, declarator = declarator)
1851 positional_args.append(arg)
1853 if len(keyword_args) > 0:
1854 s.error("Non-keyword arg following keyword arg",
1858 if s.sy not in end_sy_set:
1860 s.error("Unmatched %s" % " or ".join(end_sy_set))
1863 return positional_args, keyword_args
1865 def p_c_base_type(s, self_flag = 0, nonempty = 0, templates = None):
1866 # If self_flag is true, this is the base type for the
1867 # self argument of a C method of an extension type.
1869 return p_c_complex_base_type(s)
1871 return p_c_simple_base_type(s, self_flag, nonempty = nonempty, templates = templates)
1873 def p_calling_convention(s):
1874 if s.sy == 'IDENT' and s.systring in calling_convention_words:
1881 calling_convention_words = ("__stdcall", "__cdecl", "__fastcall")
1883 def p_c_complex_base_type(s):
1887 base_type = p_c_base_type(s)
1888 declarator = p_c_declarator(s, empty = 1)
1890 return Nodes.CComplexBaseTypeNode(pos,
1891 base_type = base_type, declarator = declarator)
1893 def p_c_simple_base_type(s, self_flag, nonempty, templates = None):
1894 #print "p_c_simple_base_type: self_flag =", self_flag, nonempty
1901 if not s.sy == 'IDENT':
1902 error(pos, "Expected an identifier, found '%s'" % s.sy)
1903 if looking_at_base_type(s):
1904 #print "p_c_simple_base_type: looking_at_base_type at", s.position()
1906 if s.sy == 'IDENT' and s.systring in special_basic_c_types:
1907 signed, longness = special_basic_c_types[s.systring]
1911 signed, longness = p_sign_and_longness(s)
1912 if s.sy == 'IDENT' and s.systring in basic_c_type_names:
1917 if s.sy == 'IDENT' and s.systring == 'complex':
1920 elif looking_at_dotted_name(s):
1921 #print "p_c_simple_base_type: looking_at_type_name at", s.position()
1925 module_path.append(name)
1931 if nonempty and s.sy != 'IDENT':
1932 # Make sure this is not a declaration of a variable or function.
1935 if s.sy == '*' or s.sy == '**' or s.sy == '&':
1936 s.put_back('(', '(')
1938 s.put_back('(', '(')
1939 s.put_back('IDENT', name)
1941 elif s.sy not in ('*', '**', '[', '&'):
1942 s.put_back('IDENT', name)
1945 type_node = Nodes.CSimpleBaseTypeNode(pos,
1946 name = name, module_path = module_path,
1947 is_basic_c_type = is_basic, signed = signed,
1948 complex = complex, longness = longness,
1949 is_self_arg = self_flag, templates = templates)
1952 type_node = p_buffer_or_template(s, type_node, templates)
1957 type_node = Nodes.CNestedBaseTypeNode(pos, base_type = type_node, name = name)
1961 def p_buffer_or_template(s, base_type_node, templates):
1965 # Note that buffer_positional_options_count=1, so the only positional argument is dtype.
1966 # For templated types, all parameters are types.
1967 positional_args, keyword_args = (
1968 p_positional_and_keyword_args(s, (']',), templates)
1972 keyword_dict = ExprNodes.DictNode(pos,
1974 ExprNodes.DictItemNode(pos=key.pos, key=key, value=value)
1975 for key, value in keyword_args
1977 result = Nodes.TemplatedTypeNode(pos,
1978 positional_args = positional_args,
1979 keyword_args = keyword_dict,
1980 base_type_node = base_type_node)
1984 def looking_at_name(s):
1985 return s.sy == 'IDENT' and not s.systring in calling_convention_words
1987 def looking_at_expr(s):
1988 if s.systring in base_type_start_words:
1990 elif s.sy == 'IDENT':
1997 dotted_path.append(s.systring)
1999 saved = s.sy, s.systring
2002 elif s.sy == '*' or s.sy == '**':
2004 is_type = s.sy == ')'
2008 is_type = s.sy == '*'
2012 is_type = s.sy == ']'
2014 dotted_path.reverse()
2015 for p in dotted_path:
2016 s.put_back('IDENT', p)
2017 s.put_back('.', '.')
2018 s.put_back('IDENT', name)
2023 def looking_at_base_type(s):
2024 #print "looking_at_base_type?", s.sy, s.systring, s.position()
2025 return s.sy == 'IDENT' and s.systring in base_type_start_words
2027 def looking_at_dotted_name(s):
2031 result = s.sy == '.'
2032 s.put_back('IDENT', name)
2037 basic_c_type_names = ("void", "char", "int", "float", "double", "bint")
2039 special_basic_c_types = {
2040 # name : (signed, longness)
2041 "Py_UNICODE" : (0, 0),
2042 "Py_ssize_t" : (2, 0),
2047 sign_and_longness_words = ("short", "long", "signed", "unsigned")
2049 base_type_start_words = \
2050 basic_c_type_names + sign_and_longness_words + tuple(special_basic_c_types)
2052 def p_sign_and_longness(s):
2055 while s.sy == 'IDENT' and s.systring in sign_and_longness_words:
2056 if s.systring == 'unsigned':
2058 elif s.systring == 'signed':
2060 elif s.systring == 'short':
2062 elif s.systring == 'long':
2065 return signed, longness
2068 literal = p_opt_string_literal(s, 'u')
2069 if literal is not None:
2070 cname = EncodedString(literal)
2071 cname.encoding = s.source_encoding
2076 def p_c_declarator(s, ctx = Ctx(), empty = 0, is_type = 0, cmethod_flag = 0,
2077 assignable = 0, nonempty = 0,
2078 calling_convention_allowed = 0):
2079 # If empty is true, the declarator must be empty. If nonempty is true,
2080 # the declarator must be nonempty. Otherwise we don't care.
2081 # If cmethod_flag is true, then if this declarator declares
2082 # a function, it's a C method of an extension type.
2086 if s.sy == ')' or looking_at_name(s):
2087 base = Nodes.CNameDeclaratorNode(pos, name = EncodedString(u""), cname = None)
2088 result = p_c_func_declarator(s, pos, ctx, base, cmethod_flag)
2090 result = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2091 cmethod_flag = cmethod_flag,
2092 nonempty = nonempty,
2093 calling_convention_allowed = 1)
2096 result = p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
2097 assignable, nonempty)
2098 if not calling_convention_allowed and result.calling_convention and s.sy != '(':
2099 error(s.position(), "%s on something that is not a function"
2100 % result.calling_convention)
2101 while s.sy in ('[', '('):
2104 result = p_c_array_declarator(s, result)
2107 result = p_c_func_declarator(s, pos, ctx, result, cmethod_flag)
2111 def p_c_array_declarator(s, base):
2119 return Nodes.CArrayDeclaratorNode(pos, base = base, dimension = dim)
2121 def p_c_func_declarator(s, pos, ctx, base, cmethod_flag):
2122 # Opening paren has already been skipped
2123 args = p_c_arg_list(s, ctx, cmethod_flag = cmethod_flag,
2124 nonempty_declarators = 0)
2125 ellipsis = p_optional_ellipsis(s)
2128 exc_val, exc_check = p_exception_value_clause(s)
2129 with_gil = p_with_gil(s)
2130 return Nodes.CFuncDeclaratorNode(pos,
2131 base = base, args = args, has_varargs = ellipsis,
2132 exception_value = exc_val, exception_check = exc_check,
2133 nogil = nogil or ctx.nogil or with_gil, with_gil = with_gil)
2135 supported_overloaded_operators = cython.set([
2136 '+', '-', '*', '/', '%',
2137 '++', '--', '~', '|', '&', '^', '<<', '>>', ',',
2138 '==', '!=', '>=', '>', '<=', '<',
2142 def p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
2143 assignable, nonempty):
2145 calling_convention = p_calling_convention(s)
2148 base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2149 cmethod_flag = cmethod_flag,
2150 assignable = assignable, nonempty = nonempty)
2151 result = Nodes.CPtrDeclaratorNode(pos,
2153 elif s.sy == '**': # scanner returns this as a single token
2155 base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2156 cmethod_flag = cmethod_flag,
2157 assignable = assignable, nonempty = nonempty)
2158 result = Nodes.CPtrDeclaratorNode(pos,
2159 base = Nodes.CPtrDeclaratorNode(pos,
2163 base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2164 cmethod_flag = cmethod_flag,
2165 assignable = assignable, nonempty = nonempty)
2166 result = Nodes.CReferenceDeclaratorNode(pos, base = base)
2170 name = EncodedString(s.systring)
2172 error(s.position(), "Declarator should be empty")
2174 cname = p_opt_cname(s)
2175 if name != 'operator' and s.sy == '=' and assignable:
2180 error(s.position(), "Empty declarator")
2183 if cname is None and ctx.namespace is not None and nonempty:
2184 cname = ctx.namespace + "::" + name
2185 if name == 'operator' and ctx.visibility == 'extern' and nonempty:
2187 if [c in '+-*/<=>!%&|([^~,' for c in op]:
2189 # Handle diphthong operators.
2196 if op in ['-', '+', '|', '&'] and s.sy == op:
2202 if op not in supported_overloaded_operators:
2203 s.error("Overloading operator '%s' not yet supported." % op)
2205 result = Nodes.CNameDeclaratorNode(pos,
2206 name = name, cname = cname, default = rhs)
2207 result.calling_convention = calling_convention
2211 if s.sy == 'IDENT' and s.systring == 'nogil':
2220 s.expect_keyword('gil')
2225 def p_exception_value_clause(s):
2228 if s.sy == 'except':
2239 exc_val = p_name(s, name)
2245 return exc_val, exc_check
2247 c_arg_list_terminators = ('*', '**', '.', ')')
2249 def p_c_arg_list(s, ctx = Ctx(), in_pyfunc = 0, cmethod_flag = 0,
2250 nonempty_declarators = 0, kw_only = 0, annotated = 1):
2251 # Comma-separated list of C argument declarations, possibly empty.
2252 # May have a trailing comma.
2254 is_self_arg = cmethod_flag
2255 while s.sy not in c_arg_list_terminators:
2256 args.append(p_c_arg_decl(s, ctx, in_pyfunc, is_self_arg,
2257 nonempty = nonempty_declarators, kw_only = kw_only,
2258 annotated = annotated))
2265 def p_optional_ellipsis(s):
2272 def p_c_arg_decl(s, ctx, in_pyfunc, cmethod_flag = 0, nonempty = 0,
2273 kw_only = 0, annotated = 1):
2275 not_none = or_none = 0
2278 if s.in_python_file:
2279 # empty type declaration
2280 base_type = Nodes.CSimpleBaseTypeNode(pos,
2281 name = None, module_path = [],
2282 is_basic_c_type = 0, signed = 0,
2283 complex = 0, longness = 0,
2284 is_self_arg = cmethod_flag, templates = None)
2286 base_type = p_c_base_type(s, cmethod_flag, nonempty = nonempty)
2287 declarator = p_c_declarator(s, ctx, nonempty = nonempty)
2288 if s.sy in ('not', 'or') and not s.in_python_file:
2291 if s.sy == 'IDENT' and s.systring == 'None':
2294 s.error("Expected 'None'")
2296 error(pos, "'%s None' only allowed in Python functions" % kind)
2297 or_none = kind == 'or'
2298 not_none = kind == 'not'
2299 if annotated and s.sy == ':':
2301 annotation = p_test(s)
2304 if 'pxd' in s.level:
2305 if s.sy not in ['*', '?']:
2306 error(pos, "default values cannot be specified in pxd files, use ? or *")
2307 default = ExprNodes.BoolNode(1)
2311 return Nodes.CArgDeclNode(pos,
2312 base_type = base_type,
2313 declarator = declarator,
2314 not_none = not_none,
2317 annotation = annotation,
2321 if s.sy == 'IDENT' and s.systring == 'api':
2327 def p_cdef_statement(s, ctx):
2329 ctx.visibility = p_visibility(s, ctx.visibility)
2330 ctx.api = ctx.api or p_api(s)
2332 if ctx.visibility not in ('private', 'public'):
2333 error(pos, "Cannot combine 'api' with '%s'" % ctx.visibility)
2334 if (ctx.visibility == 'extern') and s.sy == 'from':
2335 return p_cdef_extern_block(s, pos, ctx)
2336 elif s.sy == 'import':
2338 return p_cdef_extern_block(s, pos, ctx)
2342 error(pos, "cdef blocks cannot be declared cpdef")
2343 return p_cdef_block(s, ctx)
2346 error(pos, "cdef blocks cannot be declared cpdef")
2347 return p_cdef_block(s, ctx)
2348 elif s.sy == 'class':
2349 if ctx.level not in ('module', 'module_pxd'):
2350 error(pos, "Extension type definition not allowed here")
2352 error(pos, "Extension types cannot be declared cpdef")
2353 return p_c_class_definition(s, pos, ctx)
2354 elif s.sy == 'IDENT' and s.systring == 'cppclass':
2355 if ctx.visibility != 'extern':
2356 error(pos, "C++ classes need to be declared extern")
2357 return p_cpp_class_definition(s, pos, ctx)
2358 elif s.sy == 'IDENT' and s.systring in ("struct", "union", "enum", "packed"):
2359 if ctx.level not in ('module', 'module_pxd'):
2360 error(pos, "C struct/union/enum definition not allowed here")
2362 error(pos, "C struct/union/enum cannot be declared cpdef")
2363 if s.systring == "enum":
2364 return p_c_enum_definition(s, pos, ctx)
2366 return p_c_struct_or_union_definition(s, pos, ctx)
2368 return p_c_func_or_var_declaration(s, pos, ctx)
2370 def p_cdef_block(s, ctx):
2371 return p_suite(s, ctx(cdef_flag = 1))
2373 def p_cdef_extern_block(s, pos, ctx):
2375 error(pos, "cdef extern blocks cannot be declared cpdef")
2381 include_file = p_string_literal(s, 'u')[2]
2382 ctx = ctx(cdef_flag = 1, visibility = 'extern')
2383 if s.systring == "namespace":
2385 ctx.namespace = p_string_literal(s, 'u')[2]
2388 body = p_suite(s, ctx)
2389 return Nodes.CDefExternNode(pos,
2390 include_file = include_file,
2392 namespace = ctx.namespace)
2394 def p_c_enum_definition(s, pos, ctx):
2395 # s.sy == ident 'enum'
2400 cname = p_opt_cname(s)
2401 if cname is None and ctx.namespace is not None:
2402 cname = ctx.namespace + "::" + name
2409 if s.sy != 'NEWLINE':
2410 p_c_enum_line(s, ctx, items)
2412 s.next() # 'NEWLINE'
2414 while s.sy not in ('DEDENT', 'EOF'):
2415 p_c_enum_line(s, ctx, items)
2417 return Nodes.CEnumDefNode(
2418 pos, name = name, cname = cname, items = items,
2419 typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2420 in_pxd = ctx.level == 'module_pxd')
2422 def p_c_enum_line(s, ctx, items):
2424 p_c_enum_item(s, ctx, items)
2427 if s.sy in ('NEWLINE', 'EOF'):
2429 p_c_enum_item(s, ctx, items)
2432 s.expect_newline("Syntax error in enum item list")
2434 def p_c_enum_item(s, ctx, items):
2437 cname = p_opt_cname(s)
2438 if cname is None and ctx.namespace is not None:
2439 cname = ctx.namespace + "::" + name
2444 items.append(Nodes.CEnumDefItemNode(pos,
2445 name = name, cname = cname, value = value))
2447 def p_c_struct_or_union_definition(s, pos, ctx):
2449 if s.systring == 'packed':
2452 if s.sy != 'IDENT' or s.systring != 'struct':
2453 s.expected('struct')
2454 # s.sy == ident 'struct' or 'union'
2458 cname = p_opt_cname(s)
2459 if cname is None and ctx.namespace is not None:
2460 cname = ctx.namespace + "::" + name
2468 while s.sy != 'DEDENT':
2471 p_c_func_or_var_declaration(s, s.position(), body_ctx))
2474 s.expect_newline("Expected a newline")
2477 s.expect_newline("Syntax error in struct or union definition")
2478 return Nodes.CStructOrUnionDefNode(pos,
2479 name = name, cname = cname, kind = kind, attributes = attributes,
2480 typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2481 in_pxd = ctx.level == 'module_pxd', packed = packed)
2483 def p_visibility(s, prev_visibility):
2485 visibility = prev_visibility
2486 if s.sy == 'IDENT' and s.systring in ('extern', 'public', 'readonly'):
2487 visibility = s.systring
2488 if prev_visibility != 'private' and visibility != prev_visibility:
2489 s.error("Conflicting visibility options '%s' and '%s'"
2490 % (prev_visibility, visibility))
2494 def p_c_modifiers(s):
2495 if s.sy == 'IDENT' and s.systring in ('inline',):
2496 modifier = s.systring
2498 return [modifier] + p_c_modifiers(s)
2501 def p_c_func_or_var_declaration(s, pos, ctx):
2502 cmethod_flag = ctx.level in ('c_class', 'c_class_pxd')
2503 modifiers = p_c_modifiers(s)
2504 base_type = p_c_base_type(s, nonempty = 1, templates = ctx.templates)
2505 declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
2506 assignable = 1, nonempty = 1)
2507 declarator.overridable = ctx.overridable
2509 if ctx.level not in ('module', 'c_class', 'module_pxd', 'c_class_pxd') and not ctx.templates:
2510 s.error("C function definition not allowed here")
2511 doc, suite = p_suite(s, Ctx(level = 'function'), with_doc = 1)
2512 result = Nodes.CFuncDefNode(pos,
2513 visibility = ctx.visibility,
2514 base_type = base_type,
2515 declarator = declarator,
2518 modifiers = modifiers,
2520 overridable = ctx.overridable)
2523 # s.error("'api' not allowed with variable declaration")
2524 declarators = [declarator]
2527 if s.sy == 'NEWLINE':
2529 declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
2530 assignable = 1, nonempty = 1)
2531 declarators.append(declarator)
2532 s.expect_newline("Syntax error in C variable declaration")
2533 result = Nodes.CVarDefNode(pos,
2534 visibility = ctx.visibility,
2535 base_type = base_type,
2536 declarators = declarators,
2537 in_pxd = ctx.level == 'module_pxd',
2539 overridable = ctx.overridable)
2542 def p_ctypedef_statement(s, ctx):
2543 # s.sy == 'ctypedef'
2546 visibility = p_visibility(s, ctx.visibility)
2548 ctx = ctx(typedef_flag = 1, visibility = visibility)
2552 return p_c_class_definition(s, pos, ctx)
2553 elif s.sy == 'IDENT' and s.systring in ('packed', 'struct', 'union', 'enum'):
2554 if s.systring == 'enum':
2555 return p_c_enum_definition(s, pos, ctx)
2557 return p_c_struct_or_union_definition(s, pos, ctx)
2559 base_type = p_c_base_type(s, nonempty = 1)
2560 if base_type.name is None:
2561 s.error("Syntax error in ctypedef statement")
2562 declarator = p_c_declarator(s, ctx, is_type = 1, nonempty = 1)
2563 s.expect_newline("Syntax error in ctypedef statement")
2564 return Nodes.CTypeDefNode(
2565 pos, base_type = base_type,
2566 declarator = declarator, visibility = visibility,
2567 in_pxd = ctx.level == 'module_pxd')
2569 def p_decorators(s):
2571 while s.sy == 'DECORATOR':
2574 decstring = p_dotted_name(s, as_allowed=0)[2]
2575 names = decstring.split('.')
2576 decorator = ExprNodes.NameNode(pos, name=EncodedString(names[0]))
2577 for name in names[1:]:
2578 decorator = ExprNodes.AttributeNode(pos,
2579 attribute=EncodedString(name),
2582 decorator = p_call(s, decorator)
2583 decorators.append(Nodes.DecoratorNode(pos, decorator=decorator))
2584 s.expect_newline("Expected a newline after decorator")
2587 def p_def_statement(s, decorators=None):
2591 name = EncodedString( p_ident(s) )
2593 args, star_arg, starstar_arg = p_varargslist(s, terminator=')')
2596 error(pos, "Python function cannot be declared nogil")
2597 return_type_annotation = None
2600 return_type_annotation = p_test(s)
2601 doc, body = p_suite(s, Ctx(level = 'function'), with_doc = 1)
2602 return Nodes.DefNode(pos, name = name, args = args,
2603 star_arg = star_arg, starstar_arg = starstar_arg,
2604 doc = doc, body = body, decorators = decorators,
2605 return_type_annotation = return_type_annotation)
2607 def p_varargslist(s, terminator=')', annotated=1):
2608 args = p_c_arg_list(s, in_pyfunc = 1, nonempty_declarators = 1,
2609 annotated = annotated)
2615 star_arg = p_py_arg_decl(s, annotated=annotated)
2618 args.extend(p_c_arg_list(s, in_pyfunc = 1,
2619 nonempty_declarators = 1, kw_only = 1, annotated = annotated))
2620 elif s.sy != terminator:
2621 s.error("Syntax error in Python function argument list")
2624 starstar_arg = p_py_arg_decl(s, annotated=annotated)
2625 return (args, star_arg, starstar_arg)
2627 def p_py_arg_decl(s, annotated = 1):
2631 if annotated and s.sy == ':':
2633 annotation = p_test(s)
2634 return Nodes.PyArgDeclNode(pos, name = name, annotation = annotation)
2636 def p_class_statement(s, decorators):
2640 class_name = EncodedString( p_ident(s) )
2641 class_name.encoding = s.source_encoding
2646 positional_args, keyword_args, star_arg, starstar_arg = \
2647 p_call_parse_args(s, allow_genexp = False)
2648 arg_tuple, keyword_dict = p_call_build_packed_args(
2649 pos, positional_args, keyword_args, star_arg)
2650 if arg_tuple is None:
2651 # XXX: empty arg_tuple
2652 arg_tuple = ExprNodes.TupleNode(pos, args = [])
2653 doc, body = p_suite(s, Ctx(level = 'class'), with_doc = 1)
2654 return Nodes.PyClassDefNode(pos,
2657 keyword_args = keyword_dict,
2658 starstar_arg = starstar_arg,
2659 doc = doc, body = body, decorators = decorators)
2661 def p_c_class_definition(s, pos, ctx):
2665 class_name = p_ident(s)
2668 module_path.append(class_name)
2669 class_name = p_ident(s)
2670 if module_path and ctx.visibility != 'extern':
2671 error(pos, "Qualified class name only allowed for 'extern' C class")
2672 if module_path and s.sy == 'IDENT' and s.systring == 'as':
2674 as_name = p_ident(s)
2676 as_name = class_name
2677 objstruct_name = None
2679 base_class_module = None
2680 base_class_name = None
2683 base_class_path = [p_ident(s)]
2686 base_class_path.append(p_ident(s))
2688 s.error("C class may only have one base class")
2690 base_class_module = ".".join(base_class_path[:-1])
2691 base_class_name = base_class_path[-1]
2693 if ctx.visibility not in ('public', 'extern'):
2694 error(s.position(), "Name options only allowed for 'public' or 'extern' C class")
2695 objstruct_name, typeobj_name = p_c_class_options(s)
2697 if ctx.level == 'module_pxd':
2698 body_level = 'c_class_pxd'
2700 body_level = 'c_class'
2701 doc, body = p_suite(s, Ctx(level = body_level), with_doc = 1)
2703 s.expect_newline("Syntax error in C class definition")
2706 if ctx.visibility == 'extern':
2708 error(pos, "Module name required for 'extern' C class")
2710 error(pos, "Type object name specification not allowed for 'extern' C class")
2711 elif ctx.visibility == 'public':
2712 if not objstruct_name:
2713 error(pos, "Object struct name specification required for 'public' C class")
2714 if not typeobj_name:
2715 error(pos, "Type object name specification required for 'public' C class")
2716 elif ctx.visibility == 'private':
2718 error(pos, "Only 'public' C class can be declared 'api'")
2720 error(pos, "Invalid class visibility '%s'" % ctx.visibility)
2721 return Nodes.CClassDefNode(pos,
2722 visibility = ctx.visibility,
2723 typedef_flag = ctx.typedef_flag,
2725 module_name = ".".join(module_path),
2726 class_name = class_name,
2728 base_class_module = base_class_module,
2729 base_class_name = base_class_name,
2730 objstruct_name = objstruct_name,
2731 typeobj_name = typeobj_name,
2732 in_pxd = ctx.level == 'module_pxd',
2736 def p_c_class_options(s):
2737 objstruct_name = None
2743 if s.systring == 'object':
2745 objstruct_name = p_ident(s)
2746 elif s.systring == 'type':
2748 typeobj_name = p_ident(s)
2752 s.expect(']', "Expected 'object' or 'type'")
2753 return objstruct_name, typeobj_name
2755 def p_property_decl(s):
2757 s.next() # 'property'
2759 doc, body = p_suite(s, Ctx(level = 'property'), with_doc = 1)
2760 return Nodes.PropertyNode(pos, name = name, doc = doc, body = body)
2762 def p_doc_string(s):
2763 if s.sy == 'BEGIN_STRING':
2765 kind, bytes_result, unicode_result = p_cat_string_literal(s)
2767 s.expect_newline("Syntax error in doc string")
2768 if kind in ('u', ''):
2769 return unicode_result
2770 warning(pos, "Python 3 requires docstrings to be unicode strings")
2775 def p_code(s, level=None):
2776 body = p_statement_list(s, Ctx(level = level), first_statement = 1)
2778 s.error("Syntax error in statement [%s,%s]" % (
2779 repr(s.sy), repr(s.systring)))
2782 COMPILER_DIRECTIVE_COMMENT_RE = re.compile(r"^#\s*cython:\s*((\w|[.])+\s*=.*)$")
2784 def p_compiler_directive_comments(s):
2786 while s.sy == 'commentline':
2787 m = COMPILER_DIRECTIVE_COMMENT_RE.match(s.systring)
2789 directives = m.group(1).strip()
2791 result.update( Options.parse_directive_list(
2792 directives, ignore_unknown=True) )
2793 except ValueError, e:
2794 s.error(e.args[0], fatal=False)
2798 def p_module(s, pxd, full_module_name):
2801 directive_comments = p_compiler_directive_comments(s)
2802 s.parse_comments = False
2804 if 'language_level' in directive_comments:
2805 s.context.set_language_level(directive_comments['language_level'])
2807 doc = p_doc_string(s)
2809 level = 'module_pxd'
2813 body = p_statement_list(s, Ctx(level = level), first_statement = 1)
2815 s.error("Syntax error in statement [%s,%s]" % (
2816 repr(s.sy), repr(s.systring)))
2817 return ModuleNode(pos, doc = doc, body = body,
2818 full_module_name = full_module_name,
2819 directive_comments = directive_comments)
2821 def p_cpp_class_definition(s, pos, ctx):
2822 # s.sy == 'cppclass'
2825 class_name = p_ident(s)
2826 cname = p_opt_cname(s)
2827 if cname is None and ctx.namespace is not None:
2828 cname = ctx.namespace + "::" + class_name
2830 error(pos, "Qualified class name not allowed C++ class")
2833 templates = [p_ident(s)]
2836 templates.append(p_ident(s))
2842 base_classes = [p_dotted_name(s, False)[2]]
2845 base_classes.append(p_dotted_name(s, False)[2])
2850 error(s.position(), "Name options not allowed for C++ class")
2856 body_ctx = Ctx(visibility = ctx.visibility)
2857 body_ctx.templates = templates
2858 while s.sy != 'DEDENT':
2859 if s.systring == 'cppclass':
2861 p_cpp_class_definition(s, s.position(), body_ctx))
2862 elif s.sy != 'pass':
2864 p_c_func_or_var_declaration(s, s.position(), body_ctx))
2867 s.expect_newline("Expected a newline")
2871 s.expect_newline("Syntax error in C++ class definition")
2872 return Nodes.CppClassNode(pos,
2875 base_classes = base_classes,
2876 visibility = ctx.visibility,
2877 in_pxd = ctx.level == 'module_pxd',
2878 attributes = attributes,
2879 templates = templates)
2883 #----------------------------------------------
2887 #----------------------------------------------
2889 def print_parse_tree(f, node, level, key = None):
2890 from types import ListType, TupleType
2891 from Nodes import Node
2896 f.write("%s: " % key)
2899 f.write("(%s @ %s\n" % (node[0], node[1]))
2900 for i in xrange(2, len(node)):
2901 print_parse_tree(f, node[i], level+1)
2902 f.write("%s)\n" % ind)
2904 elif isinstance(node, Node):
2907 except AttributeError:
2908 tag = node.__class__.__name__
2909 f.write("%s @ %s\n" % (tag, node.pos))
2910 for name, value in node.__dict__.items():
2911 if name != 'tag' and name != 'pos':
2912 print_parse_tree(f, value, level+1, name)
2916 for i in xrange(len(node)):
2917 print_parse_tree(f, node[i], level+1)
2918 f.write("%s]\n" % ind)
2920 f.write("%s%s\n" % (ind, node))