1 # cython: auto_cpdef=True, infer_types=True
6 # This should be done automatically
8 cython.declare(Nodes=object, ExprNodes=object, EncodedString=object)
15 from __builtin__ import set
16 except (ImportError, AttributeError):
18 from builtins import set
19 except (ImportError, AttributeError):
20 from sets import Set as set
22 from Cython.Compiler.Scanning import PyrexScanner, FileSourceDescriptor
26 from StringEncoding import EncodedString, BytesLiteral, _unicode, _bytes
27 from ModuleNode import ModuleNode
28 from Errors import error, warning, InternalError
29 from Cython import Utils
36 visibility = 'private'
45 def __init__(self, **kwds):
46 self.__dict__.update(kwds)
48 def __call__(self, **kwds):
51 d.update(self.__dict__)
55 def p_ident(s, message = "Expected an identifier"):
65 while s.sy == 'IDENT':
66 names.append(s.systring)
73 #------------------------------------------
77 #------------------------------------------
79 def p_binop_operator(s):
85 def p_binop_expr(s, ops, p_sub_expr):
88 op, pos = p_binop_operator(s)
90 n1 = ExprNodes.binop_node(pos, op, n1, n2)
92 if Future.division in s.context.future_directives:
93 n1.truedivision = True
95 n1.truedivision = None # unknown
98 #expression: or_test [if or_test else test] | lambda_form
101 #test: or_test ['if' or_test 'else' test] | lambdef
103 def p_simple_expr(s):
113 return ExprNodes.CondExprNode(pos, test=test, true_val=expr, false_val=other)
117 #lambdef: 'lambda' [varargslist] ':' test
119 def p_lambdef(s, allow_conditional=True):
125 star_arg = starstar_arg = None
127 args, star_arg, starstar_arg = p_varargslist(
128 s, terminator=':', annotated=False)
130 if allow_conditional:
131 expr = p_simple_expr(s)
133 expr = p_test_nocond(s)
134 return ExprNodes.LambdaNode(
136 star_arg = star_arg, starstar_arg = starstar_arg,
139 #lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
141 def p_lambdef_nocond(s):
142 return p_lambdef(s, allow_conditional=False)
144 #test: or_test | lambdef
149 #test_nocond: or_test | lambdef_nocond
151 def p_test_nocond(s):
153 return p_lambdef_nocond(s)
157 #or_test: and_test ('or' and_test)*
160 return p_rassoc_binop_expr(s, ('or',), p_and_test)
162 def p_rassoc_binop_expr(s, ops, p_subexpr):
168 n2 = p_rassoc_binop_expr(s, ops, p_subexpr)
169 n1 = ExprNodes.binop_node(pos, op, n1, n2)
172 #and_test: not_test ('and' not_test)*
175 #return p_binop_expr(s, ('and',), p_not_test)
176 return p_rassoc_binop_expr(s, ('and',), p_not_test)
178 #not_test: 'not' not_test | comparison
184 return ExprNodes.NotNode(pos, operand = p_not_test(s))
186 return p_comparison(s)
188 #comparison: expr (comp_op expr)*
189 #comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
192 n1 = p_starred_expr(s)
193 if s.sy in comparison_ops:
196 n2 = p_starred_expr(s)
197 n1 = ExprNodes.PrimaryCmpNode(pos,
198 operator = op, operand1 = n1, operand2 = n2)
199 if s.sy in comparison_ops:
200 n1.cascade = p_cascaded_cmp(s)
203 def p_starred_expr(s):
212 expr = ExprNodes.StarredTargetNode(pos, expr)
215 def p_cascaded_cmp(s):
218 n2 = p_starred_expr(s)
219 result = ExprNodes.CascadedCmpNode(pos,
220 operator = op, operand2 = n2)
221 if s.sy in comparison_ops:
222 result.cascade = p_cascaded_cmp(s)
245 '<', '>', '==', '>=', '<=', '<>', '!=',
249 #expr: xor_expr ('|' xor_expr)*
252 return p_binop_expr(s, ('|',), p_xor_expr)
254 #xor_expr: and_expr ('^' and_expr)*
257 return p_binop_expr(s, ('^',), p_and_expr)
259 #and_expr: shift_expr ('&' shift_expr)*
262 return p_binop_expr(s, ('&',), p_shift_expr)
264 #shift_expr: arith_expr (('<<'|'>>') arith_expr)*
267 return p_binop_expr(s, ('<<', '>>'), p_arith_expr)
269 #arith_expr: term (('+'|'-') term)*
272 return p_binop_expr(s, ('+', '-'), p_term)
274 #term: factor (('*'|'/'|'%') factor)*
277 return p_binop_expr(s, ('*', '/', '%', '//'), p_factor)
279 #factor: ('+'|'-'|'~'|'&'|typecast|sizeof) factor | power
283 if sy in ('+', '-', '~'):
287 return ExprNodes.unop_node(pos, op, p_factor(s))
292 return ExprNodes.AmpersandNode(pos, operand = arg)
295 elif sy == 'IDENT' and s.systring == "sizeof":
304 base_type = p_c_base_type(s)
305 if base_type.name is None:
306 s.error("Unknown type")
307 declarator = p_c_declarator(s, empty = 1)
314 operand = p_factor(s)
315 return ExprNodes.TypecastNode(pos,
316 base_type = base_type,
317 declarator = declarator,
319 typecheck = typecheck)
322 # s.sy == ident "sizeof"
326 # Here we decide if we are looking at an expression or type
327 # If it is actually a type, but parsable as an expression,
328 # we treat it as an expression here.
329 if looking_at_expr(s):
330 operand = p_simple_expr(s)
331 node = ExprNodes.SizeofVarNode(pos, operand = operand)
333 base_type = p_c_base_type(s)
334 declarator = p_c_declarator(s, empty = 1)
335 node = ExprNodes.SizeofTypeNode(pos,
336 base_type = base_type, declarator = declarator)
340 def p_yield_expression(s):
344 if s.sy != ')' and s.sy not in statement_terminators:
348 return ExprNodes.YieldExprNode(pos, arg=arg)
350 def p_yield_statement(s):
352 yield_expr = p_yield_expression(s)
353 return Nodes.ExprStatNode(yield_expr.pos, expr=yield_expr)
355 #power: atom trailer* ('**' factor)*
358 if s.systring == 'new' and s.peek()[0] == 'IDENT':
361 while s.sy in ('(', '[', '.'):
362 n1 = p_trailer(s, n1)
367 n1 = ExprNodes.binop_node(pos, '**', n1, n2)
371 # s.systring == 'new'.
374 cppclass = p_c_base_type(s)
375 return p_call(s, ExprNodes.NewExprNode(pos, cppclass = cppclass))
377 #trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
379 def p_trailer(s, node1):
382 return p_call(s, node1)
384 return p_index(s, node1)
387 name = EncodedString( p_ident(s) )
388 return ExprNodes.AttributeNode(pos,
389 obj = node1, attribute = name)
391 # arglist: argument (',' argument)* [',']
392 # argument: [test '='] test # Really [keyword '='] test
394 def p_call(s, function):
402 while s.sy not in ('**', ')'):
405 s.error("only one star-arg parameter allowed",
408 star_arg = p_simple_expr(s)
410 arg = p_simple_expr(s)
414 s.error("Expected an identifier before '='",
416 encoded_name = EncodedString(arg.name)
417 keyword = ExprNodes.IdentifierStringNode(arg.pos, value = encoded_name)
418 arg = p_simple_expr(s)
419 keyword_args.append((keyword, arg))
422 s.error("Non-keyword arg following keyword arg",
425 s.error("Non-keyword arg following star-arg",
427 positional_args.append(arg)
434 starstar_arg = p_simple_expr(s)
438 if not (keyword_args or star_arg or starstar_arg):
439 return ExprNodes.SimpleCallNode(pos,
441 args = positional_args)
445 if positional_args or not star_arg:
446 arg_tuple = ExprNodes.TupleNode(pos,
447 args = positional_args)
449 star_arg_tuple = ExprNodes.AsTupleNode(pos, arg = star_arg)
451 arg_tuple = ExprNodes.binop_node(pos,
452 operator = '+', operand1 = arg_tuple,
453 operand2 = star_arg_tuple)
455 arg_tuple = star_arg_tuple
457 keyword_args = [ExprNodes.DictItemNode(pos=key.pos, key=key, value=value)
458 for key, value in keyword_args]
459 keyword_dict = ExprNodes.DictNode(pos,
460 key_value_pairs = keyword_args)
461 return ExprNodes.GeneralCallNode(pos,
463 positional_args = arg_tuple,
464 keyword_args = keyword_dict,
465 starstar_arg = starstar_arg)
467 #lambdef: 'lambda' [varargslist] ':' test
469 #subscriptlist: subscript (',' subscript)* [',']
471 def p_index(s, base):
475 subscripts = p_subscript_list(s)
476 if len(subscripts) == 1 and len(subscripts[0]) == 2:
477 start, stop = subscripts[0]
478 result = ExprNodes.SliceIndexNode(pos,
479 base = base, start = start, stop = stop)
481 indexes = make_slice_nodes(pos, subscripts)
482 if len(indexes) == 1:
485 index = ExprNodes.TupleNode(pos, args = indexes)
486 result = ExprNodes.IndexNode(pos,
487 base = base, index = index)
491 def p_subscript_list(s):
492 items = [p_subscript(s)]
497 items.append(p_subscript(s))
500 #subscript: '.' '.' '.' | test | [test] ':' [test] [':' [test]]
503 # Parse a subscript and return a list of
504 # 1, 2 or 3 ExprNodes, depending on how
505 # many slice elements were encountered.
509 return [ExprNodes.EllipsisNode(pos)]
511 start = p_slice_element(s, (':',))
515 stop = p_slice_element(s, (':', ',', ']'))
519 step = p_slice_element(s, (':', ',', ']'))
520 return [start, stop, step]
522 def p_slice_element(s, follow_set):
523 # Simple expression which may be missing iff
524 # it is followed by something in follow_set.
525 if s.sy not in follow_set:
526 return p_simple_expr(s)
530 def expect_ellipsis(s):
535 def make_slice_nodes(pos, subscripts):
536 # Convert a list of subscripts as returned
537 # by p_subscript_list into a list of ExprNodes,
538 # creating SliceNodes for elements with 2 or
541 for subscript in subscripts:
542 if len(subscript) == 1:
543 result.append(subscript[0])
545 result.append(make_slice_node(pos, *subscript))
548 def make_slice_node(pos, start, stop = None, step = None):
550 start = ExprNodes.NoneNode(pos)
552 stop = ExprNodes.NoneNode(pos)
554 step = ExprNodes.NoneNode(pos)
555 return ExprNodes.SliceNode(pos,
556 start = start, stop = stop, step = step)
558 #atom: '(' [testlist] ')' | '[' [listmaker] ']' | '{' [dict_or_set_maker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+
566 result = ExprNodes.TupleNode(pos, args = [])
567 elif s.sy == 'yield':
568 result = p_yield_expression(s)
574 return p_list_maker(s)
576 return p_dict_or_set_maker(s)
578 return p_backquote_expr(s)
584 while value[-1] in "UuLl":
585 if value[-1] in "Ll":
590 return ExprNodes.IntNode(pos,
597 return ExprNodes.FloatNode(pos, value = value)
599 value = s.systring[:-1]
601 return ExprNodes.ImagNode(pos, value = value)
602 elif sy == 'BEGIN_STRING':
603 kind, value = p_cat_string_literal(s)
605 return ExprNodes.CharNode(pos, value = value)
607 return ExprNodes.UnicodeNode(pos, value = value)
609 return ExprNodes.BytesNode(pos, value = value)
611 return ExprNodes.StringNode(pos, value = value)
613 name = EncodedString( s.systring )
616 return ExprNodes.NoneNode(pos)
618 return ExprNodes.BoolNode(pos, value=True)
619 elif name == "False":
620 return ExprNodes.BoolNode(pos, value=False)
622 return ExprNodes.NullNode(pos)
624 return p_name(s, name)
626 s.error("Expected an identifier or literal")
630 if not s.compile_time_expr and name in s.compile_time_env:
631 value = s.compile_time_env.lookup_here(name)
633 if isinstance(value, bool):
634 return ExprNodes.BoolNode(pos, value = value)
635 elif isinstance(value, int):
636 return ExprNodes.IntNode(pos, value = rep)
637 elif isinstance(value, long):
638 return ExprNodes.IntNode(pos, value = rep, longness = "L")
639 elif isinstance(value, float):
640 return ExprNodes.FloatNode(pos, value = rep)
641 elif isinstance(value, _unicode):
642 return ExprNodes.UnicodeNode(pos, value = value)
643 elif isinstance(value, _bytes):
644 return ExprNodes.BytesNode(pos, value = value)
646 error(pos, "Invalid type for compile-time constant: %s"
647 % value.__class__.__name__)
648 return ExprNodes.NameNode(pos, name = name)
650 def p_cat_string_literal(s):
651 # A sequence of one or more adjacent string literals.
652 # Returns (kind, value) where kind in ('b', 'c', 'u', '')
653 kind, value = p_string_literal(s)
654 if s.sy != 'BEGIN_STRING':
658 while s.sy == 'BEGIN_STRING':
660 next_kind, next_value = p_string_literal(s)
662 error(pos, "Cannot concatenate char literal with another string or char literal")
663 elif next_kind != kind:
664 error(pos, "Cannot mix string literals of different types, expected %s'', got %s''" %
667 strings.append(next_value)
669 value = EncodedString( u''.join(strings) )
671 value = BytesLiteral( StringEncoding.join_bytes(strings) )
672 value.encoding = s.source_encoding
675 def p_opt_string_literal(s):
676 if s.sy == 'BEGIN_STRING':
677 return p_string_literal(s)
681 def p_string_literal(s):
682 # A single string or char literal.
683 # Returns (kind, value) where kind in ('b', 'c', 'u')
684 # s.sy == 'BEGIN_STRING'
687 kind = s.systring[:1].lower()
692 is_raw = s.systring[1:2].lower() == 'r'
695 if Future.unicode_literals in s.context.future_directives:
699 chars = StringEncoding.UnicodeLiteralBuilder()
701 chars = StringEncoding.BytesLiteralBuilder(s.source_encoding)
705 #print "p_string_literal: sy =", sy, repr(s.systring) ###
707 chars.append(s.systring)
713 chars.append(u'\\\n')
714 elif systr == u'\\\"':
716 elif systr == u'\\\'':
723 chars.append_charval( int(systr[1:], 8) )
726 elif c in u"abfnrtv":
728 StringEncoding.char_from_escape_sequence(systr))
732 if kind == 'u' or c == 'x':
733 chrval = int(systr[2:], 16)
734 if chrval > 1114111: # sys.maxunicode:
735 s.error("Invalid unicode escape '%s'" % systr,
738 warning(s.position(),
739 "Unicode characters above 65535 are not "
740 "necessarily portable across Python installations", 1)
741 chars.append_charval(chrval)
743 # unicode escapes in plain byte strings are not unescaped
746 chars.append(u'\\' + systr[1:])
747 elif sy == 'NEWLINE':
749 elif sy == 'END_STRING':
752 s.error("Unclosed string literal", pos = pos)
755 "Unexpected token %r:%r in string literal" %
758 value = chars.getchar()
760 error(pos, u"invalid character literal: %r" % value)
762 value = chars.getstring()
764 #print "p_string_literal: value =", repr(value) ###
767 # list_display ::= "[" [listmaker] "]"
768 # listmaker ::= expression ( comp_for | ( "," expression )* [","] )
769 # comp_iter ::= comp_for | comp_if
770 # comp_for ::= "for" expression_list "in" testlist [comp_iter]
771 # comp_if ::= "if" test [comp_iter]
779 return ExprNodes.ListNode(pos, args = [])
780 expr = p_simple_expr(s)
782 target = ExprNodes.ListNode(pos, args = [])
783 append = ExprNodes.ComprehensionAppendNode(
784 pos, expr=expr, target=ExprNodes.CloneNode(target))
785 loop = p_comp_for(s, Nodes.ExprStatNode(append.pos, expr=append))
787 return ExprNodes.ComprehensionNode(
788 pos, loop=loop, append=append, target=target)
793 exprs += p_simple_expr_list(s)
795 return ExprNodes.ListNode(pos, args = exprs)
797 def p_comp_iter(s, body):
799 return p_comp_for(s, body)
801 return p_comp_if(s, body)
803 # insert the 'append' operation into the loop
806 def p_comp_for(s, body):
811 kw['else_clause'] = None
812 kw['body'] = p_comp_iter(s, body)
813 return Nodes.ForStatNode(pos, **kw)
815 def p_comp_if(s, body):
819 test = p_test_nocond(s)
820 return Nodes.IfStatNode(pos,
821 if_clauses = [Nodes.IfClauseNode(pos, condition = test,
822 body = p_comp_iter(s, body))],
825 #dictmaker: test ':' test (',' test ':' test)* [',']
827 def p_dict_or_set_maker(s):
833 return ExprNodes.DictNode(pos, key_value_pairs = [])
834 item = p_simple_expr(s)
835 if s.sy == ',' or s.sy == '}':
842 values.append( p_simple_expr(s) )
844 return ExprNodes.SetNode(pos, args=values)
847 target = ExprNodes.SetNode(pos, args=[])
848 append = ExprNodes.ComprehensionAppendNode(
849 item.pos, expr=item, target=ExprNodes.CloneNode(target))
850 loop = p_comp_for(s, Nodes.ExprStatNode(append.pos, expr=append))
852 return ExprNodes.ComprehensionNode(
853 pos, loop=loop, append=append, target=target)
855 # dict literal or comprehension
858 value = p_simple_expr(s)
861 target = ExprNodes.DictNode(pos, key_value_pairs = [])
862 append = ExprNodes.DictComprehensionAppendNode(
863 item.pos, key_expr=key, value_expr=value,
864 target=ExprNodes.CloneNode(target))
865 loop = p_comp_for(s, Nodes.ExprStatNode(append.pos, expr=append))
867 return ExprNodes.ComprehensionNode(
868 pos, loop=loop, append=append, target=target)
871 items = [ExprNodes.DictItemNode(key.pos, key=key, value=value)]
876 key = p_simple_expr(s)
878 value = p_simple_expr(s)
880 ExprNodes.DictItemNode(key.pos, key=key, value=value))
882 return ExprNodes.DictNode(pos, key_value_pairs=items)
886 return ExprNodes.DictNode(pos, key_value_pairs = [])
888 def p_backquote_expr(s):
894 return ExprNodes.BackquoteNode(pos, arg = arg)
896 def p_simple_expr_list(s):
898 while s.sy not in expr_terminators:
899 expr = p_simple_expr(s)
908 expr = p_simple_expr(s)
911 exprs = [expr] + p_simple_expr_list(s)
912 return ExprNodes.TupleNode(pos, args = exprs)
917 #testlist: test (',' test)* [',']
918 # differs from p_expr only in the fact that it cannot contain conditional expressions
927 exprs.append(p_test(s))
928 return ExprNodes.TupleNode(pos, args = exprs)
932 expr_terminators = (')', ']', '}', ':', '=', 'NEWLINE')
934 #-------------------------------------------------------
938 #-------------------------------------------------------
940 def p_global_statement(s):
941 # assume s.sy == 'global'
944 names = p_ident_list(s)
945 return Nodes.GlobalNode(pos, names = names)
947 def p_expression_or_assignment(s):
948 expr_list = [p_expr(s)]
951 expr_list.append(p_expr(s))
952 if len(expr_list) == 1:
953 if re.match(r"([+*/\%^\&|-]|<<|>>|\*\*|//)=", s.sy):
955 if not isinstance(lhs, (ExprNodes.AttributeNode, ExprNodes.IndexNode, ExprNodes.NameNode) ):
956 error(lhs.pos, "Illegal operand for inplace operation.")
960 return Nodes.InPlaceAssignmentNode(lhs.pos, operator = operator, lhs = lhs, rhs = rhs)
962 if isinstance(expr, (ExprNodes.UnicodeNode, ExprNodes.StringNode, ExprNodes.BytesNode)):
963 return Nodes.PassStatNode(expr.pos)
965 return Nodes.ExprStatNode(expr.pos, expr = expr)
968 if len(expr_list) == 2:
969 return Nodes.SingleAssignmentNode(rhs.pos,
970 lhs = expr_list[0], rhs = rhs)
972 return Nodes.CascadedAssignmentNode(rhs.pos,
973 lhs_list = expr_list[:-1], rhs = rhs)
975 def p_print_statement(s):
982 stream = p_simple_expr(s)
985 ends_with_comma = s.sy in ('NEWLINE', 'EOF')
989 if s.sy not in ('NEWLINE', 'EOF'):
990 args.append(p_simple_expr(s))
993 if s.sy in ('NEWLINE', 'EOF'):
996 args.append(p_simple_expr(s))
997 arg_tuple = ExprNodes.TupleNode(pos, args = args)
998 return Nodes.PrintStatNode(pos,
999 arg_tuple = arg_tuple, stream = stream,
1000 append_newline = not ends_with_comma)
1002 def p_exec_statement(s):
1006 args = [ p_bit_expr(s) ]
1009 args.append(p_simple_expr(s))
1012 args.append(p_simple_expr(s))
1014 error(pos, "'exec' currently requires a target mapping (globals/locals)")
1015 return Nodes.ExecStatNode(pos, args = args)
1017 def p_del_statement(s):
1021 args = p_simple_expr_list(s)
1022 return Nodes.DelStatNode(pos, args = args)
1024 def p_pass_statement(s, with_newline = 0):
1028 s.expect_newline("Expected a newline")
1029 return Nodes.PassStatNode(pos)
1031 def p_break_statement(s):
1035 return Nodes.BreakStatNode(pos)
1037 def p_continue_statement(s):
1038 # s.sy == 'continue'
1041 return Nodes.ContinueStatNode(pos)
1043 def p_return_statement(s):
1047 if s.sy not in statement_terminators:
1051 return Nodes.ReturnStatNode(pos, value = value)
1053 def p_raise_statement(s):
1060 if s.sy not in statement_terminators:
1061 exc_type = p_simple_expr(s)
1064 exc_value = p_simple_expr(s)
1067 exc_tb = p_simple_expr(s)
1068 if exc_type or exc_value or exc_tb:
1069 return Nodes.RaiseStatNode(pos,
1070 exc_type = exc_type,
1071 exc_value = exc_value,
1074 return Nodes.ReraiseStatNode(pos)
1076 def p_import_statement(s):
1077 # s.sy in ('import', 'cimport')
1081 items = [p_dotted_name(s, as_allowed = 1)]
1084 items.append(p_dotted_name(s, as_allowed = 1))
1086 for pos, target_name, dotted_name, as_name in items:
1087 dotted_name = EncodedString(dotted_name)
1088 if kind == 'cimport':
1089 stat = Nodes.CImportStatNode(pos,
1090 module_name = dotted_name,
1093 if as_name and "." in dotted_name:
1094 name_list = ExprNodes.ListNode(pos, args = [
1095 ExprNodes.IdentifierStringNode(pos, value = EncodedString("*"))])
1098 stat = Nodes.SingleAssignmentNode(pos,
1099 lhs = ExprNodes.NameNode(pos,
1100 name = as_name or target_name),
1101 rhs = ExprNodes.ImportNode(pos,
1102 module_name = ExprNodes.IdentifierStringNode(
1103 pos, value = dotted_name),
1104 name_list = name_list))
1106 return Nodes.StatListNode(pos, stats = stats)
1108 def p_from_import_statement(s, first_statement = 0):
1112 (dotted_name_pos, _, dotted_name, _) = \
1113 p_dotted_name(s, as_allowed = 0)
1114 if s.sy in ('import', 'cimport'):
1118 s.error("Expected 'import' or 'cimport'")
1119 is_cimport = kind == 'cimport'
1120 is_parenthesized = False
1122 imported_names = [(s.position(), "*", None, None)]
1126 is_parenthesized = True
1128 imported_names = [p_imported_name(s, is_cimport)]
1131 if is_parenthesized and s.sy == ')':
1133 imported_names.append(p_imported_name(s, is_cimport))
1134 if is_parenthesized:
1136 dotted_name = EncodedString(dotted_name)
1137 if dotted_name == '__future__':
1138 if not first_statement:
1139 s.error("from __future__ imports must occur at the beginning of the file")
1141 for (name_pos, name, as_name, kind) in imported_names:
1142 if name == "braces":
1143 s.error("not a chance", name_pos)
1146 directive = getattr(Future, name)
1147 except AttributeError:
1148 s.error("future feature %s is not defined" % name, name_pos)
1150 s.context.future_directives.add(directive)
1151 return Nodes.PassStatNode(pos)
1152 elif kind == 'cimport':
1153 return Nodes.FromCImportStatNode(pos,
1154 module_name = dotted_name,
1155 imported_names = imported_names)
1157 imported_name_strings = []
1159 for (name_pos, name, as_name, kind) in imported_names:
1160 encoded_name = EncodedString(name)
1161 imported_name_strings.append(
1162 ExprNodes.IdentifierStringNode(name_pos, value = encoded_name))
1165 ExprNodes.NameNode(name_pos,
1166 name = as_name or name)))
1167 import_list = ExprNodes.ListNode(
1168 imported_names[0][0], args = imported_name_strings)
1169 dotted_name = EncodedString(dotted_name)
1170 return Nodes.FromImportStatNode(pos,
1171 module = ExprNodes.ImportNode(dotted_name_pos,
1172 module_name = ExprNodes.IdentifierStringNode(pos, value = dotted_name),
1173 name_list = import_list),
1176 imported_name_kinds = ('class', 'struct', 'union')
1178 def p_imported_name(s, is_cimport):
1181 if is_cimport and s.systring in imported_name_kinds:
1185 as_name = p_as_name(s)
1186 return (pos, name, as_name, kind)
1188 def p_dotted_name(s, as_allowed):
1190 target_name = p_ident(s)
1192 names = [target_name]
1195 names.append(p_ident(s))
1197 as_name = p_as_name(s)
1198 return (pos, target_name, u'.'.join(names), as_name)
1201 if s.sy == 'IDENT' and s.systring == 'as':
1207 def p_assert_statement(s):
1211 cond = p_simple_expr(s)
1214 value = p_simple_expr(s)
1217 return Nodes.AssertStatNode(pos, cond = cond, value = value)
1219 statement_terminators = (';', 'NEWLINE', 'EOF')
1221 def p_if_statement(s):
1225 if_clauses = [p_if_clause(s)]
1226 while s.sy == 'elif':
1228 if_clauses.append(p_if_clause(s))
1229 else_clause = p_else_clause(s)
1230 return Nodes.IfStatNode(pos,
1231 if_clauses = if_clauses, else_clause = else_clause)
1235 test = p_simple_expr(s)
1237 return Nodes.IfClauseNode(pos,
1238 condition = test, body = body)
1240 def p_else_clause(s):
1247 def p_while_statement(s):
1251 test = p_simple_expr(s)
1253 else_clause = p_else_clause(s)
1254 return Nodes.WhileStatNode(pos,
1255 condition = test, body = body,
1256 else_clause = else_clause)
1258 def p_for_statement(s):
1262 kw = p_for_bounds(s)
1263 kw['body'] = p_suite(s)
1264 kw['else_clause'] = p_else_clause(s)
1265 return Nodes.ForStatNode(pos, **kw)
1267 def p_for_bounds(s):
1268 target = p_for_target(s)
1271 iterator = p_for_iterator(s)
1272 return { 'target': target, 'iterator': iterator }
1276 bound1 = p_bit_expr(s)
1278 # Support shorter "for a <= x < b" syntax
1279 bound1, target = target, None
1280 rel1 = p_for_from_relation(s)
1281 name2_pos = s.position()
1283 rel2_pos = s.position()
1284 rel2 = p_for_from_relation(s)
1285 bound2 = p_bit_expr(s)
1286 step = p_for_from_step(s)
1288 target = ExprNodes.NameNode(name2_pos, name = name2)
1290 if not target.is_name:
1292 "Target of for-from statement must be a variable name")
1293 elif name2 != target.name:
1295 "Variable name in for-from range does not match target")
1296 if rel1[0] != rel2[0]:
1298 "Relation directions in for-from do not match")
1299 return {'target': target,
1306 def p_for_from_relation(s):
1307 if s.sy in inequality_relations:
1312 s.error("Expected one of '<', '<=', '>' '>='")
1314 def p_for_from_step(s):
1317 step = p_bit_expr(s)
1322 inequality_relations = ('<', '<=', '>', '>=')
1324 def p_target(s, terminator):
1326 expr = p_starred_expr(s)
1330 while s.sy != terminator:
1331 exprs.append(p_starred_expr(s))
1335 return ExprNodes.TupleNode(pos, args = exprs)
1339 def p_for_target(s):
1340 return p_target(s, 'in')
1342 def p_for_iterator(s):
1344 expr = p_testlist(s)
1345 return ExprNodes.IteratorNode(pos, sequence = expr)
1347 def p_try_statement(s):
1354 if s.sy in ('except', 'else'):
1355 while s.sy == 'except':
1356 except_clauses.append(p_except_clause(s))
1359 else_clause = p_suite(s)
1360 body = Nodes.TryExceptStatNode(pos,
1361 body = body, except_clauses = except_clauses,
1362 else_clause = else_clause)
1363 if s.sy != 'finally':
1365 # try-except-finally is equivalent to nested try-except/try-finally
1366 if s.sy == 'finally':
1368 finally_clause = p_suite(s)
1369 return Nodes.TryFinallyStatNode(pos,
1370 body = body, finally_clause = finally_clause)
1372 s.error("Expected 'except' or 'finally'")
1374 def p_except_clause(s):
1381 exc_type = p_simple_expr(s)
1382 if s.sy == ',' or (s.sy == 'IDENT' and s.systring == 'as'):
1384 exc_value = p_simple_expr(s)
1385 elif s.sy == 'IDENT' and s.systring == 'as':
1386 # Py3 syntax requires a name here
1390 exc_value = ExprNodes.NameNode(pos2, name = name)
1392 return Nodes.ExceptClauseNode(pos,
1393 pattern = exc_type, target = exc_value, body = body)
1395 def p_include_statement(s, ctx):
1397 s.next() # 'include'
1398 _, include_file_name = p_string_literal(s)
1399 s.expect_newline("Syntax error in include statement")
1400 if s.compile_time_eval:
1401 include_file_name = include_file_name.decode(s.source_encoding)
1402 include_file_path = s.context.find_include_file(include_file_name, pos)
1403 if include_file_path:
1404 s.included_files.append(include_file_name)
1405 f = Utils.open_source_file(include_file_path, mode="rU")
1406 source_desc = FileSourceDescriptor(include_file_path)
1407 s2 = PyrexScanner(f, source_desc, s, source_encoding=f.encoding, parse_comments=s.parse_comments)
1409 tree = p_statement_list(s2, ctx)
1416 return Nodes.PassStatNode(pos)
1418 def p_with_statement(s):
1421 # if s.sy == 'IDENT' and s.systring in ('gil', 'nogil'):
1422 if s.sy == 'IDENT' and s.systring == 'nogil':
1426 return Nodes.GILStatNode(pos, state = state, body = body)
1427 elif s.systring == 'template':
1432 templates.append(s.systring)
1434 while s.systring == ',':
1436 templates.append(s.systring)
1441 s.expect_newline("Syntax error in template function declaration")
1444 body_ctx.templates = templates
1445 func_or_var = p_c_func_or_var_declaration(s, pos, body_ctx)
1449 error(pos, "Syntax error in template function declaration")
1453 if s.sy == 'IDENT' and s.systring == 'as':
1455 allow_multi = (s.sy == '(')
1456 target = p_target(s, ':')
1457 if not allow_multi and isinstance(target, ExprNodes.TupleNode):
1458 s.error("Multiple with statement target values not allowed without paranthesis")
1460 return Nodes.WithStatNode(pos, manager = manager,
1461 target = target, body = body)
1463 def p_simple_statement(s, first_statement = 0):
1464 #print "p_simple_statement:", s.sy, s.systring ###
1465 if s.sy == 'global':
1466 node = p_global_statement(s)
1467 elif s.sy == 'print':
1468 node = p_print_statement(s)
1469 elif s.sy == 'exec':
1470 node = p_exec_statement(s)
1472 node = p_del_statement(s)
1473 elif s.sy == 'break':
1474 node = p_break_statement(s)
1475 elif s.sy == 'continue':
1476 node = p_continue_statement(s)
1477 elif s.sy == 'return':
1478 node = p_return_statement(s)
1479 elif s.sy == 'raise':
1480 node = p_raise_statement(s)
1481 elif s.sy in ('import', 'cimport'):
1482 node = p_import_statement(s)
1483 elif s.sy == 'from':
1484 node = p_from_import_statement(s, first_statement = first_statement)
1485 elif s.sy == 'yield':
1486 node = p_yield_statement(s)
1487 elif s.sy == 'assert':
1488 node = p_assert_statement(s)
1489 elif s.sy == 'pass':
1490 node = p_pass_statement(s)
1492 node = p_expression_or_assignment(s)
1495 def p_simple_statement_list(s, ctx, first_statement = 0):
1496 # Parse a series of simple statements on one line
1497 # separated by semicolons.
1498 stat = p_simple_statement(s, first_statement = first_statement)
1502 #print "p_simple_statement_list: maybe more to follow" ###
1504 if s.sy in ('NEWLINE', 'EOF'):
1506 stats.append(p_simple_statement(s))
1507 stat = Nodes.StatListNode(stats[0].pos, stats = stats)
1508 s.expect_newline("Syntax error in simple statement list")
1511 def p_compile_time_expr(s):
1512 old = s.compile_time_expr
1513 s.compile_time_expr = 1
1515 s.compile_time_expr = old
1518 def p_DEF_statement(s):
1520 denv = s.compile_time_env
1524 expr = p_compile_time_expr(s)
1525 value = expr.compile_time_value(denv)
1526 #print "p_DEF_statement: %s = %r" % (name, value) ###
1527 denv.declare(name, value)
1529 return Nodes.PassStatNode(pos)
1531 def p_IF_statement(s, ctx):
1533 saved_eval = s.compile_time_eval
1534 current_eval = saved_eval
1535 denv = s.compile_time_env
1538 s.next() # 'IF' or 'ELIF'
1539 expr = p_compile_time_expr(s)
1540 s.compile_time_eval = current_eval and bool(expr.compile_time_value(denv))
1541 body = p_suite(s, ctx)
1542 if s.compile_time_eval:
1549 s.compile_time_eval = current_eval
1550 body = p_suite(s, ctx)
1554 result = Nodes.PassStatNode(pos)
1555 s.compile_time_eval = saved_eval
1558 def p_statement(s, ctx, first_statement = 0):
1559 cdef_flag = ctx.cdef_flag
1561 if s.sy == 'ctypedef':
1562 if ctx.level not in ('module', 'module_pxd'):
1563 s.error("ctypedef statement not allowed here")
1565 # error(s.position(), "'api' not allowed with 'ctypedef'")
1566 return p_ctypedef_statement(s, ctx)
1568 return p_DEF_statement(s)
1570 return p_IF_statement(s, ctx)
1571 elif s.sy == 'DECORATOR':
1572 if ctx.level not in ('module', 'class', 'c_class', 'function', 'property', 'module_pxd', 'c_class_pxd'):
1574 s.error('decorator not allowed here')
1576 decorators = p_decorators(s)
1577 if s.sy not in ('def', 'cdef', 'cpdef', 'class'):
1578 s.error("Decorators can only be followed by functions or classes")
1579 elif s.sy == 'pass' and cdef_flag:
1581 return p_pass_statement(s, with_newline = 1)
1587 elif s.sy == 'cpdef':
1592 if ctx.level not in ('module', 'module_pxd', 'function', 'c_class', 'c_class_pxd'):
1593 s.error('cdef statement not allowed here')
1595 node = p_cdef_statement(s, ctx(overridable = overridable))
1596 if decorators is not None:
1597 if not isinstance(node, (Nodes.CFuncDefNode, Nodes.CVarDefNode)):
1598 s.error("Decorators can only be followed by functions or Python classes")
1599 node.decorators = decorators
1603 error(s.pos, "'api' not allowed with this statement")
1605 # def statements aren't allowed in pxd files, except
1606 # as part of a cdef class
1607 if ('pxd' in ctx.level) and (ctx.level != 'c_class_pxd'):
1608 s.error('def statement not allowed here')
1610 return p_def_statement(s, decorators)
1611 elif s.sy == 'class':
1612 if ctx.level != 'module':
1613 s.error("class definition not allowed here")
1614 return p_class_statement(s, decorators)
1615 elif s.sy == 'include':
1616 if ctx.level not in ('module', 'module_pxd'):
1617 s.error("include statement not allowed here")
1618 return p_include_statement(s, ctx)
1619 elif ctx.level == 'c_class' and s.sy == 'IDENT' and s.systring == 'property':
1620 return p_property_decl(s)
1621 elif s.sy == 'pass' and ctx.level != 'property':
1622 return p_pass_statement(s, with_newline = 1)
1624 if ctx.level in ('c_class_pxd', 'property'):
1625 s.error("Executable statement not allowed here")
1627 return p_if_statement(s)
1628 elif s.sy == 'while':
1629 return p_while_statement(s)
1631 return p_for_statement(s)
1633 return p_try_statement(s)
1634 elif s.sy == 'with':
1635 return p_with_statement(s)
1637 return p_simple_statement_list(
1638 s, ctx, first_statement = first_statement)
1640 def p_statement_list(s, ctx, first_statement = 0):
1641 # Parse a series of statements separated by newlines.
1644 while s.sy not in ('DEDENT', 'EOF'):
1645 stats.append(p_statement(s, ctx, first_statement = first_statement))
1650 return Nodes.StatListNode(pos, stats = stats)
1652 def p_suite(s, ctx = Ctx(), with_doc = 0, with_pseudo_doc = 0):
1657 if s.sy == 'NEWLINE':
1660 if with_doc or with_pseudo_doc:
1661 doc = p_doc_string(s)
1662 body = p_statement_list(s, ctx)
1666 error(s.pos, "'api' not allowed with this statement")
1667 if ctx.level in ('module', 'class', 'function', 'other'):
1668 body = p_simple_statement_list(s, ctx)
1670 body = p_pass_statement(s)
1671 s.expect_newline("Syntax error in declarations")
1677 def p_positional_and_keyword_args(s, end_sy_set, templates = None):
1679 Parses positional and keyword arguments. end_sy_set
1680 should contain any s.sy that terminate the argument list.
1681 Argument expansion (* and **) are not allowed.
1683 Returns: (positional_args, keyword_args)
1685 positional_args = []
1689 while s.sy not in end_sy_set:
1690 if s.sy == '*' or s.sy == '**':
1691 s.error('Argument expansion not allowed here.')
1694 if s.sy == 'IDENT' and s.peek()[0] == '=':
1696 s.next() # s.sy is '='
1698 if looking_at_expr(s):
1699 arg = p_simple_expr(s)
1701 base_type = p_c_base_type(s, templates = templates)
1702 declarator = p_c_declarator(s, empty = 1)
1703 arg = Nodes.CComplexBaseTypeNode(base_type.pos,
1704 base_type = base_type, declarator = declarator)
1706 keyword_node = ExprNodes.IdentifierStringNode(
1707 arg.pos, value = EncodedString(ident))
1708 keyword_args.append((keyword_node, arg))
1712 if looking_at_expr(s):
1713 arg = p_simple_expr(s)
1715 base_type = p_c_base_type(s, templates = templates)
1716 declarator = p_c_declarator(s, empty = 1)
1717 arg = Nodes.CComplexBaseTypeNode(base_type.pos,
1718 base_type = base_type, declarator = declarator)
1720 positional_args.append(arg)
1722 if len(keyword_args) > 0:
1723 s.error("Non-keyword arg following keyword arg",
1727 if s.sy not in end_sy_set:
1729 s.error("Unmatched %s" % " or ".join(end_sy_set))
1732 return positional_args, keyword_args
1734 def p_c_base_type(s, self_flag = 0, nonempty = 0, templates = None):
1735 # If self_flag is true, this is the base type for the
1736 # self argument of a C method of an extension type.
1738 return p_c_complex_base_type(s)
1740 return p_c_simple_base_type(s, self_flag, nonempty = nonempty, templates = templates)
1742 def p_calling_convention(s):
1743 if s.sy == 'IDENT' and s.systring in calling_convention_words:
1750 calling_convention_words = ("__stdcall", "__cdecl", "__fastcall")
1752 def p_c_complex_base_type(s):
1756 base_type = p_c_base_type(s)
1757 declarator = p_c_declarator(s, empty = 1)
1759 return Nodes.CComplexBaseTypeNode(pos,
1760 base_type = base_type, declarator = declarator)
1762 def p_c_simple_base_type(s, self_flag, nonempty, templates = None):
1763 #print "p_c_simple_base_type: self_flag =", self_flag, nonempty
1770 if not s.sy == 'IDENT':
1771 error(pos, "Expected an identifier, found '%s'" % s.sy)
1772 if looking_at_base_type(s):
1773 #print "p_c_simple_base_type: looking_at_base_type at", s.position()
1775 if s.sy == 'IDENT' and s.systring in special_basic_c_types:
1776 signed, longness = special_basic_c_types[s.systring]
1780 signed, longness = p_sign_and_longness(s)
1781 if s.sy == 'IDENT' and s.systring in basic_c_type_names:
1786 if s.sy == 'IDENT' and s.systring == 'complex':
1789 elif looking_at_dotted_name(s):
1790 #print "p_c_simple_base_type: looking_at_type_name at", s.position()
1794 module_path.append(name)
1800 if nonempty and s.sy != 'IDENT':
1801 # Make sure this is not a declaration of a variable or function.
1804 if s.sy == '*' or s.sy == '**' or s.sy == '&':
1805 s.put_back('(', '(')
1807 s.put_back('(', '(')
1808 s.put_back('IDENT', name)
1810 elif s.sy not in ('*', '**', '[', '&'):
1811 s.put_back('IDENT', name)
1814 type_node = Nodes.CSimpleBaseTypeNode(pos,
1815 name = name, module_path = module_path,
1816 is_basic_c_type = is_basic, signed = signed,
1817 complex = complex, longness = longness,
1818 is_self_arg = self_flag, templates = templates)
1821 type_node = p_buffer_or_template(s, type_node, templates)
1826 type_node = Nodes.CNestedBaseTypeNode(pos, base_type = type_node, name = name)
1830 def p_buffer_or_template(s, base_type_node, templates):
1834 # Note that buffer_positional_options_count=1, so the only positional argument is dtype.
1835 # For templated types, all parameters are types.
1836 positional_args, keyword_args = (
1837 p_positional_and_keyword_args(s, (']',), templates)
1841 keyword_dict = ExprNodes.DictNode(pos,
1843 ExprNodes.DictItemNode(pos=key.pos, key=key, value=value)
1844 for key, value in keyword_args
1846 result = Nodes.TemplatedTypeNode(pos,
1847 positional_args = positional_args,
1848 keyword_args = keyword_dict,
1849 base_type_node = base_type_node)
1853 def looking_at_name(s):
1854 return s.sy == 'IDENT' and not s.systring in calling_convention_words
1856 def looking_at_expr(s):
1857 if s.systring in base_type_start_words:
1859 elif s.sy == 'IDENT':
1866 dotted_path.append(s.systring)
1868 saved = s.sy, s.systring
1871 elif s.sy == '*' or s.sy == '**':
1873 is_type = s.sy == ')'
1877 is_type = s.sy == '*'
1881 is_type = s.sy == ']'
1883 dotted_path.reverse()
1884 for p in dotted_path:
1885 s.put_back('IDENT', p)
1886 s.put_back('.', '.')
1887 s.put_back('IDENT', name)
1892 def looking_at_base_type(s):
1893 #print "looking_at_base_type?", s.sy, s.systring, s.position()
1894 return s.sy == 'IDENT' and s.systring in base_type_start_words
1896 def looking_at_dotted_name(s):
1900 result = s.sy == '.'
1901 s.put_back('IDENT', name)
1906 basic_c_type_names = ("void", "char", "int", "float", "double", "bint")
1908 special_basic_c_types = {
1909 # name : (signed, longness)
1910 "Py_ssize_t" : (2, 0),
1914 sign_and_longness_words = ("short", "long", "signed", "unsigned")
1916 base_type_start_words = \
1917 basic_c_type_names + sign_and_longness_words + tuple(special_basic_c_types)
1919 def p_sign_and_longness(s):
1922 while s.sy == 'IDENT' and s.systring in sign_and_longness_words:
1923 if s.systring == 'unsigned':
1925 elif s.systring == 'signed':
1927 elif s.systring == 'short':
1929 elif s.systring == 'long':
1932 return signed, longness
1935 literal = p_opt_string_literal(s)
1938 cname = EncodedString(cname)
1939 cname.encoding = s.source_encoding
1944 def p_c_declarator(s, ctx = Ctx(), empty = 0, is_type = 0, cmethod_flag = 0,
1945 assignable = 0, nonempty = 0,
1946 calling_convention_allowed = 0):
1947 # If empty is true, the declarator must be empty. If nonempty is true,
1948 # the declarator must be nonempty. Otherwise we don't care.
1949 # If cmethod_flag is true, then if this declarator declares
1950 # a function, it's a C method of an extension type.
1954 if s.sy == ')' or looking_at_name(s):
1955 base = Nodes.CNameDeclaratorNode(pos, name = EncodedString(u""), cname = None)
1956 result = p_c_func_declarator(s, pos, ctx, base, cmethod_flag)
1958 result = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
1959 cmethod_flag = cmethod_flag,
1960 nonempty = nonempty,
1961 calling_convention_allowed = 1)
1964 result = p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
1965 assignable, nonempty)
1966 if not calling_convention_allowed and result.calling_convention and s.sy != '(':
1967 error(s.position(), "%s on something that is not a function"
1968 % result.calling_convention)
1969 while s.sy in ('[', '('):
1972 result = p_c_array_declarator(s, result)
1975 result = p_c_func_declarator(s, pos, ctx, result, cmethod_flag)
1979 def p_c_array_declarator(s, base):
1987 return Nodes.CArrayDeclaratorNode(pos, base = base, dimension = dim)
1989 def p_c_func_declarator(s, pos, ctx, base, cmethod_flag):
1990 # Opening paren has already been skipped
1991 args = p_c_arg_list(s, ctx, cmethod_flag = cmethod_flag,
1992 nonempty_declarators = 0)
1993 ellipsis = p_optional_ellipsis(s)
1996 exc_val, exc_check = p_exception_value_clause(s)
1997 with_gil = p_with_gil(s)
1998 return Nodes.CFuncDeclaratorNode(pos,
1999 base = base, args = args, has_varargs = ellipsis,
2000 exception_value = exc_val, exception_check = exc_check,
2001 nogil = nogil or ctx.nogil or with_gil, with_gil = with_gil)
2003 supported_overloaded_operators = set([
2004 '+', '-', '*', '/', '%',
2005 '++', '--', '~', '|', '&', '^', '<<', '>>',
2006 '==', '!=', '>=', '>', '<=', '<',
2010 def p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
2011 assignable, nonempty):
2013 calling_convention = p_calling_convention(s)
2016 base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2017 cmethod_flag = cmethod_flag,
2018 assignable = assignable, nonempty = nonempty)
2019 result = Nodes.CPtrDeclaratorNode(pos,
2021 elif s.sy == '**': # scanner returns this as a single token
2023 base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2024 cmethod_flag = cmethod_flag,
2025 assignable = assignable, nonempty = nonempty)
2026 result = Nodes.CPtrDeclaratorNode(pos,
2027 base = Nodes.CPtrDeclaratorNode(pos,
2031 base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2032 cmethod_flag = cmethod_flag,
2033 assignable = assignable, nonempty = nonempty)
2034 result = Nodes.CReferenceDeclaratorNode(pos, base = base)
2038 name = EncodedString(s.systring)
2040 error(s.position(), "Declarator should be empty")
2042 cname = p_opt_cname(s)
2043 if name != "operator" and s.sy == '=' and assignable:
2045 rhs = p_simple_expr(s)
2048 error(s.position(), "Empty declarator")
2051 if cname is None and ctx.namespace is not None:
2052 cname = ctx.namespace + "::" + name
2053 if name == 'operator' and ctx.visibility == 'extern':
2056 # Handle diphthong operators.
2063 if op in ['-', '+', '|', '&'] and s.sy == op:
2069 if op not in supported_overloaded_operators:
2070 s.error("Overloading operator '%s' not yet supported." % op)
2072 result = Nodes.CNameDeclaratorNode(pos,
2073 name = name, cname = cname, default = rhs)
2074 result.calling_convention = calling_convention
2078 if s.sy == 'IDENT' and s.systring == 'nogil':
2087 s.expect_keyword('gil')
2092 def p_exception_value_clause(s):
2095 if s.sy == 'except':
2106 exc_val = p_name(s, name)
2111 exc_val = p_simple_expr(s)
2112 return exc_val, exc_check
2114 c_arg_list_terminators = ('*', '**', '.', ')')
2116 def p_c_arg_list(s, ctx = Ctx(), in_pyfunc = 0, cmethod_flag = 0,
2117 nonempty_declarators = 0, kw_only = 0, annotated = 1):
2118 # Comma-separated list of C argument declarations, possibly empty.
2119 # May have a trailing comma.
2121 is_self_arg = cmethod_flag
2122 while s.sy not in c_arg_list_terminators:
2123 args.append(p_c_arg_decl(s, ctx, in_pyfunc, is_self_arg,
2124 nonempty = nonempty_declarators, kw_only = kw_only,
2125 annotated = annotated))
2132 def p_optional_ellipsis(s):
2139 def p_c_arg_decl(s, ctx, in_pyfunc, cmethod_flag = 0, nonempty = 0,
2140 kw_only = 0, annotated = 1):
2145 if s.in_python_file:
2146 # empty type declaration
2147 base_type = Nodes.CSimpleBaseTypeNode(pos,
2148 name = None, module_path = [],
2149 is_basic_c_type = 0, signed = 0,
2150 complex = 0, longness = 0,
2151 is_self_arg = cmethod_flag, templates = None)
2153 base_type = p_c_base_type(s, cmethod_flag, nonempty = nonempty)
2154 declarator = p_c_declarator(s, ctx, nonempty = nonempty)
2155 if s.sy == 'not' and not s.in_python_file:
2157 if s.sy == 'IDENT' and s.systring == 'None':
2160 s.error("Expected 'None'")
2162 error(pos, "'not None' only allowed in Python functions")
2164 if annotated and s.sy == ':':
2166 annotation = p_simple_expr(s)
2169 if 'pxd' in s.level:
2170 if s.sy not in ['*', '?']:
2171 error(pos, "default values cannot be specified in pxd files, use ? or *")
2172 default = ExprNodes.BoolNode(1)
2175 default = p_simple_expr(s)
2176 return Nodes.CArgDeclNode(pos,
2177 base_type = base_type,
2178 declarator = declarator,
2179 not_none = not_none,
2181 annotation = annotation,
2185 if s.sy == 'IDENT' and s.systring == 'api':
2191 def p_cdef_statement(s, ctx):
2193 ctx.visibility = p_visibility(s, ctx.visibility)
2194 ctx.api = ctx.api or p_api(s)
2196 if ctx.visibility not in ('private', 'public'):
2197 error(pos, "Cannot combine 'api' with '%s'" % ctx.visibility)
2198 if (ctx.visibility == 'extern') and s.sy == 'from':
2199 return p_cdef_extern_block(s, pos, ctx)
2200 elif s.sy == 'import':
2202 return p_cdef_extern_block(s, pos, ctx)
2206 error(pos, "cdef blocks cannot be declared cpdef")
2207 return p_cdef_block(s, ctx)
2210 error(pos, "cdef blocks cannot be declared cpdef")
2211 return p_cdef_block(s, ctx)
2212 elif s.sy == 'class':
2213 if ctx.level not in ('module', 'module_pxd'):
2214 error(pos, "Extension type definition not allowed here")
2216 error(pos, "Extension types cannot be declared cpdef")
2217 return p_c_class_definition(s, pos, ctx)
2218 elif s.sy == 'IDENT' and s.systring == 'cppclass':
2219 if ctx.visibility != 'extern':
2220 error(pos, "C++ classes need to be declared extern")
2221 return p_cpp_class_definition(s, pos, ctx)
2222 elif s.sy == 'IDENT' and s.systring in ("struct", "union", "enum", "packed"):
2223 if ctx.level not in ('module', 'module_pxd'):
2224 error(pos, "C struct/union/enum definition not allowed here")
2226 error(pos, "C struct/union/enum cannot be declared cpdef")
2227 if s.systring == "enum":
2228 return p_c_enum_definition(s, pos, ctx)
2230 return p_c_struct_or_union_definition(s, pos, ctx)
2232 return p_c_func_or_var_declaration(s, pos, ctx)
2234 def p_cdef_block(s, ctx):
2235 return p_suite(s, ctx(cdef_flag = 1))
2237 def p_cdef_extern_block(s, pos, ctx):
2239 error(pos, "cdef extern blocks cannot be declared cpdef")
2245 _, include_file = p_string_literal(s)
2246 if s.systring == "namespace":
2248 ctx.namespace = p_string_literal(s)[1]
2249 ctx = ctx(cdef_flag = 1, visibility = 'extern')
2252 body = p_suite(s, ctx)
2253 return Nodes.CDefExternNode(pos,
2254 include_file = include_file,
2256 namespace = ctx.namespace)
2258 def p_c_enum_definition(s, pos, ctx):
2259 # s.sy == ident 'enum'
2264 cname = p_opt_cname(s)
2265 if cname is None and ctx.namespace is not None:
2266 cname = ctx.namespace + "::" + name
2273 if s.sy != 'NEWLINE':
2274 p_c_enum_line(s, items)
2276 s.next() # 'NEWLINE'
2278 while s.sy not in ('DEDENT', 'EOF'):
2279 p_c_enum_line(s, items)
2281 return Nodes.CEnumDefNode(
2282 pos, name = name, cname = cname, items = items,
2283 typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2284 in_pxd = ctx.level == 'module_pxd')
2286 def p_c_enum_line(s, items):
2288 p_c_enum_item(s, items)
2291 if s.sy in ('NEWLINE', 'EOF'):
2293 p_c_enum_item(s, items)
2296 s.expect_newline("Syntax error in enum item list")
2298 def p_c_enum_item(s, items):
2301 cname = p_opt_cname(s)
2305 value = p_simple_expr(s)
2306 items.append(Nodes.CEnumDefItemNode(pos,
2307 name = name, cname = cname, value = value))
2309 def p_c_struct_or_union_definition(s, pos, ctx):
2311 if s.systring == 'packed':
2314 if s.sy != 'IDENT' or s.systring != 'struct':
2315 s.expected('struct')
2316 # s.sy == ident 'struct' or 'union'
2320 cname = p_opt_cname(s)
2321 if cname is None and ctx.namespace is not None:
2322 cname = ctx.namespace + "::" + name
2330 while s.sy != 'DEDENT':
2333 p_c_func_or_var_declaration(s, s.position(), body_ctx))
2336 s.expect_newline("Expected a newline")
2339 s.expect_newline("Syntax error in struct or union definition")
2340 return Nodes.CStructOrUnionDefNode(pos,
2341 name = name, cname = cname, kind = kind, attributes = attributes,
2342 typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2343 in_pxd = ctx.level == 'module_pxd', packed = packed)
2345 def p_visibility(s, prev_visibility):
2347 visibility = prev_visibility
2348 if s.sy == 'IDENT' and s.systring in ('extern', 'public', 'readonly'):
2349 visibility = s.systring
2350 if prev_visibility != 'private' and visibility != prev_visibility:
2351 s.error("Conflicting visibility options '%s' and '%s'"
2352 % (prev_visibility, visibility))
2356 def p_c_modifiers(s):
2357 if s.sy == 'IDENT' and s.systring in ('inline',):
2358 modifier = s.systring
2360 return [modifier] + p_c_modifiers(s)
2363 def p_c_func_or_var_declaration(s, pos, ctx):
2364 cmethod_flag = ctx.level in ('c_class', 'c_class_pxd')
2365 modifiers = p_c_modifiers(s)
2366 base_type = p_c_base_type(s, nonempty = 1, templates = ctx.templates)
2367 declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
2368 assignable = 1, nonempty = 1)
2369 declarator.overridable = ctx.overridable
2371 if ctx.level not in ('module', 'c_class', 'module_pxd', 'c_class_pxd') and not ctx.templates:
2372 s.error("C function definition not allowed here")
2373 doc, suite = p_suite(s, Ctx(level = 'function'), with_doc = 1)
2374 result = Nodes.CFuncDefNode(pos,
2375 visibility = ctx.visibility,
2376 base_type = base_type,
2377 declarator = declarator,
2380 modifiers = modifiers,
2382 overridable = ctx.overridable)
2385 # error(s.pos, "'api' not allowed with variable declaration")
2386 declarators = [declarator]
2389 if s.sy == 'NEWLINE':
2391 declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
2392 assignable = 1, nonempty = 1)
2393 declarators.append(declarator)
2394 s.expect_newline("Syntax error in C variable declaration")
2395 result = Nodes.CVarDefNode(pos,
2396 visibility = ctx.visibility,
2397 base_type = base_type,
2398 declarators = declarators,
2399 in_pxd = ctx.level == 'module_pxd',
2401 overridable = ctx.overridable)
2404 def p_ctypedef_statement(s, ctx):
2405 # s.sy == 'ctypedef'
2408 visibility = p_visibility(s, ctx.visibility)
2410 ctx = ctx(typedef_flag = 1, visibility = visibility)
2414 return p_c_class_definition(s, pos, ctx)
2415 elif s.sy == 'IDENT' and s.systring in ('packed', 'struct', 'union', 'enum'):
2416 if s.systring == 'enum':
2417 return p_c_enum_definition(s, pos, ctx)
2419 return p_c_struct_or_union_definition(s, pos, ctx)
2421 base_type = p_c_base_type(s, nonempty = 1)
2422 if base_type.name is None:
2423 s.error("Syntax error in ctypedef statement")
2424 declarator = p_c_declarator(s, ctx, is_type = 1, nonempty = 1)
2425 s.expect_newline("Syntax error in ctypedef statement")
2426 return Nodes.CTypeDefNode(
2427 pos, base_type = base_type,
2428 declarator = declarator, visibility = visibility,
2429 in_pxd = ctx.level == 'module_pxd')
2431 def p_decorators(s):
2433 while s.sy == 'DECORATOR':
2436 decstring = p_dotted_name(s, as_allowed=0)[2]
2437 names = decstring.split('.')
2438 decorator = ExprNodes.NameNode(pos, name=EncodedString(names[0]))
2439 for name in names[1:]:
2440 decorator = ExprNodes.AttributeNode(pos,
2441 attribute=EncodedString(name),
2444 decorator = p_call(s, decorator)
2445 decorators.append(Nodes.DecoratorNode(pos, decorator=decorator))
2446 s.expect_newline("Expected a newline after decorator")
2449 def p_def_statement(s, decorators=None):
2453 name = EncodedString( p_ident(s) )
2455 args, star_arg, starstar_arg = p_varargslist(s, terminator=')')
2458 error(s.pos, "Python function cannot be declared nogil")
2459 return_type_annotation = None
2462 return_type_annotation = p_simple_expr(s)
2463 doc, body = p_suite(s, Ctx(level = 'function'), with_doc = 1)
2464 return Nodes.DefNode(pos, name = name, args = args,
2465 star_arg = star_arg, starstar_arg = starstar_arg,
2466 doc = doc, body = body, decorators = decorators,
2467 return_type_annotation = return_type_annotation)
2469 def p_varargslist(s, terminator=')', annotated=1):
2470 args = p_c_arg_list(s, in_pyfunc = 1, nonempty_declarators = 1,
2471 annotated = annotated)
2477 star_arg = p_py_arg_decl(s)
2480 args.extend(p_c_arg_list(s, in_pyfunc = 1,
2481 nonempty_declarators = 1, kw_only = 1))
2482 elif s.sy != terminator:
2483 s.error("Syntax error in Python function argument list")
2486 starstar_arg = p_py_arg_decl(s)
2487 return (args, star_arg, starstar_arg)
2489 def p_py_arg_decl(s):
2495 annotation = p_simple_expr(s)
2496 return Nodes.PyArgDeclNode(pos, name = name, annotation = annotation)
2498 def p_class_statement(s, decorators):
2502 class_name = EncodedString( p_ident(s) )
2503 class_name.encoding = s.source_encoding
2506 base_list = p_simple_expr_list(s)
2510 doc, body = p_suite(s, Ctx(level = 'class'), with_doc = 1)
2511 return Nodes.PyClassDefNode(pos,
2513 bases = ExprNodes.TupleNode(pos, args = base_list),
2514 doc = doc, body = body, decorators = decorators)
2516 def p_c_class_definition(s, pos, ctx):
2520 class_name = p_ident(s)
2523 module_path.append(class_name)
2524 class_name = p_ident(s)
2525 if module_path and ctx.visibility != 'extern':
2526 error(pos, "Qualified class name only allowed for 'extern' C class")
2527 if module_path and s.sy == 'IDENT' and s.systring == 'as':
2529 as_name = p_ident(s)
2531 as_name = class_name
2532 objstruct_name = None
2534 base_class_module = None
2535 base_class_name = None
2538 base_class_path = [p_ident(s)]
2541 base_class_path.append(p_ident(s))
2543 s.error("C class may only have one base class")
2545 base_class_module = ".".join(base_class_path[:-1])
2546 base_class_name = base_class_path[-1]
2548 if ctx.visibility not in ('public', 'extern'):
2549 error(s.position(), "Name options only allowed for 'public' or 'extern' C class")
2550 objstruct_name, typeobj_name = p_c_class_options(s)
2552 if ctx.level == 'module_pxd':
2553 body_level = 'c_class_pxd'
2555 body_level = 'c_class'
2556 doc, body = p_suite(s, Ctx(level = body_level), with_doc = 1)
2558 s.expect_newline("Syntax error in C class definition")
2561 if ctx.visibility == 'extern':
2563 error(pos, "Module name required for 'extern' C class")
2565 error(pos, "Type object name specification not allowed for 'extern' C class")
2566 elif ctx.visibility == 'public':
2567 if not objstruct_name:
2568 error(pos, "Object struct name specification required for 'public' C class")
2569 if not typeobj_name:
2570 error(pos, "Type object name specification required for 'public' C class")
2571 elif ctx.visibility == 'private':
2573 error(pos, "Only 'public' C class can be declared 'api'")
2575 error(pos, "Invalid class visibility '%s'" % ctx.visibility)
2576 return Nodes.CClassDefNode(pos,
2577 visibility = ctx.visibility,
2578 typedef_flag = ctx.typedef_flag,
2580 module_name = ".".join(module_path),
2581 class_name = class_name,
2583 base_class_module = base_class_module,
2584 base_class_name = base_class_name,
2585 objstruct_name = objstruct_name,
2586 typeobj_name = typeobj_name,
2587 in_pxd = ctx.level == 'module_pxd',
2591 def p_c_class_options(s):
2592 objstruct_name = None
2598 if s.systring == 'object':
2600 objstruct_name = p_ident(s)
2601 elif s.systring == 'type':
2603 typeobj_name = p_ident(s)
2607 s.expect(']', "Expected 'object' or 'type'")
2608 return objstruct_name, typeobj_name
2610 def p_property_decl(s):
2612 s.next() # 'property'
2614 doc, body = p_suite(s, Ctx(level = 'property'), with_doc = 1)
2615 return Nodes.PropertyNode(pos, name = name, doc = doc, body = body)
2617 def p_doc_string(s):
2618 if s.sy == 'BEGIN_STRING':
2620 kind, result = p_cat_string_literal(s)
2622 s.expect_newline("Syntax error in doc string")
2624 # warning(pos, "Python 3 requires docstrings to be unicode strings")
2626 result.encoding = None # force a unicode string
2631 def p_code(s, level=None):
2632 body = p_statement_list(s, Ctx(level = level), first_statement = 1)
2634 s.error("Syntax error in statement [%s,%s]" % (
2635 repr(s.sy), repr(s.systring)))
2638 COMPILER_DIRECTIVE_COMMENT_RE = re.compile(r"^#\s*cython:\s*((\w|[.])+\s*=.*)$")
2640 def p_compiler_directive_comments(s):
2642 while s.sy == 'commentline':
2643 m = COMPILER_DIRECTIVE_COMMENT_RE.match(s.systring)
2645 directives = m.group(1).strip()
2647 result.update( Options.parse_directive_list(
2648 directives, ignore_unknown=True) )
2649 except ValueError, e:
2650 s.error(e.args[0], fatal=False)
2654 def p_module(s, pxd, full_module_name):
2657 directive_comments = p_compiler_directive_comments(s)
2658 s.parse_comments = False
2660 doc = p_doc_string(s)
2662 level = 'module_pxd'
2666 body = p_statement_list(s, Ctx(level = level), first_statement = 1)
2668 s.error("Syntax error in statement [%s,%s]" % (
2669 repr(s.sy), repr(s.systring)))
2670 return ModuleNode(pos, doc = doc, body = body,
2671 full_module_name = full_module_name,
2672 directive_comments = directive_comments)
2674 def p_cpp_class_definition(s, pos, ctx):
2675 # s.sy == 'cppclass'
2678 class_name = p_ident(s)
2679 cname = p_opt_cname(s)
2680 if cname is None and ctx.namespace is not None:
2681 cname = ctx.namespace + "::" + class_name
2683 error(pos, "Qualified class name not allowed C++ class")
2686 templates = [p_ident(s)]
2689 templates.append(p_ident(s))
2695 base_classes = [p_dotted_name(s, False)[2]]
2698 base_classes.append(p_dotted_name(s, False)[2])
2703 error(s.position(), "Name options not allowed for C++ class")
2709 body_ctx = Ctx(visibility = ctx.visibility)
2710 body_ctx.templates = templates
2711 while s.sy != 'DEDENT':
2712 if s.systring == 'cppclass':
2714 p_cpp_class_definition(s, s.position(), body_ctx))
2715 elif s.sy != 'pass':
2717 p_c_func_or_var_declaration(s, s.position(), body_ctx))
2720 s.expect_newline("Expected a newline")
2723 s.expect_newline("Syntax error in C++ class definition")
2724 return Nodes.CppClassNode(pos,
2727 base_classes = base_classes,
2728 visibility = ctx.visibility,
2729 in_pxd = ctx.level == 'module_pxd',
2730 attributes = attributes,
2731 templates = templates)
2735 #----------------------------------------------
2739 #----------------------------------------------
2741 def print_parse_tree(f, node, level, key = None):
2742 from types import ListType, TupleType
2743 from Nodes import Node
2748 f.write("%s: " % key)
2751 f.write("(%s @ %s\n" % (node[0], node[1]))
2752 for i in xrange(2, len(node)):
2753 print_parse_tree(f, node[i], level+1)
2754 f.write("%s)\n" % ind)
2756 elif isinstance(node, Node):
2759 except AttributeError:
2760 tag = node.__class__.__name__
2761 f.write("%s @ %s\n" % (tag, node.pos))
2762 for name, value in node.__dict__.items():
2763 if name != 'tag' and name != 'pos':
2764 print_parse_tree(f, value, level+1, name)
2768 for i in xrange(len(node)):
2769 print_parse_tree(f, node[i], level+1)
2770 f.write("%s]\n" % ind)
2772 f.write("%s%s\n" % (ind, node))