1 # cython: auto_cpdef=True, infer_types=True, language_level=3
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
272 # little indirection for C-ification purposes
277 if sy in ('+', '-', '~'):
281 return ExprNodes.unop_node(pos, op, p_factor(s))
286 return ExprNodes.AmpersandNode(pos, operand = arg)
289 elif sy == 'IDENT' and s.systring == "sizeof":
298 base_type = p_c_base_type(s)
299 if base_type.name is None:
300 s.error("Unknown type")
301 declarator = p_c_declarator(s, empty = 1)
308 operand = p_factor(s)
309 return ExprNodes.TypecastNode(pos,
310 base_type = base_type,
311 declarator = declarator,
313 typecheck = typecheck)
316 # s.sy == ident "sizeof"
320 # Here we decide if we are looking at an expression or type
321 # If it is actually a type, but parsable as an expression,
322 # we treat it as an expression here.
323 if looking_at_expr(s):
325 node = ExprNodes.SizeofVarNode(pos, operand = operand)
327 base_type = p_c_base_type(s)
328 declarator = p_c_declarator(s, empty = 1)
329 node = ExprNodes.SizeofTypeNode(pos,
330 base_type = base_type, declarator = declarator)
334 def p_yield_expression(s):
338 if s.sy != ')' and s.sy not in statement_terminators:
342 return ExprNodes.YieldExprNode(pos, arg=arg)
344 def p_yield_statement(s):
346 yield_expr = p_yield_expression(s)
347 return Nodes.ExprStatNode(yield_expr.pos, expr=yield_expr)
349 #power: atom trailer* ('**' factor)*
352 if s.systring == 'new' and s.peek()[0] == 'IDENT':
355 while s.sy in ('(', '[', '.'):
356 n1 = p_trailer(s, n1)
361 n1 = ExprNodes.binop_node(pos, '**', n1, n2)
365 # s.systring == 'new'.
368 cppclass = p_c_base_type(s)
369 return p_call(s, ExprNodes.NewExprNode(pos, cppclass = cppclass))
371 #trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
373 def p_trailer(s, node1):
376 return p_call(s, node1)
378 return p_index(s, node1)
381 name = EncodedString( p_ident(s) )
382 return ExprNodes.AttributeNode(pos,
383 obj = node1, attribute = name)
385 # arglist: argument (',' argument)* [',']
386 # argument: [test '='] test # Really [keyword '='] test
388 def p_call_parse_args(s, allow_genexp = True):
396 while s.sy not in ('**', ')'):
399 s.error("only one star-arg parameter allowed",
408 s.error("Expected an identifier before '='",
410 encoded_name = EncodedString(arg.name)
411 keyword = ExprNodes.IdentifierStringNode(arg.pos, value = encoded_name)
413 keyword_args.append((keyword, arg))
416 s.error("Non-keyword arg following keyword arg",
419 s.error("Non-keyword arg following star-arg",
421 positional_args.append(arg)
427 if len(positional_args) == 1 and not star_arg:
428 positional_args = [ p_genexp(s, positional_args[0]) ]
431 starstar_arg = p_test(s)
435 return positional_args, keyword_args, star_arg, starstar_arg
437 def p_call_build_packed_args(pos, positional_args, keyword_args, star_arg):
440 if positional_args or not star_arg:
441 arg_tuple = ExprNodes.TupleNode(pos,
442 args = positional_args)
444 star_arg_tuple = ExprNodes.AsTupleNode(pos, arg = star_arg)
446 arg_tuple = ExprNodes.binop_node(pos,
447 operator = '+', operand1 = arg_tuple,
448 operand2 = star_arg_tuple)
450 arg_tuple = star_arg_tuple
452 keyword_args = [ExprNodes.DictItemNode(pos=key.pos, key=key, value=value)
453 for key, value in keyword_args]
454 keyword_dict = ExprNodes.DictNode(pos,
455 key_value_pairs = keyword_args)
456 return arg_tuple, keyword_dict
458 def p_call(s, function):
462 positional_args, keyword_args, star_arg, starstar_arg = \
465 if not (keyword_args or star_arg or starstar_arg):
466 return ExprNodes.SimpleCallNode(pos,
468 args = positional_args)
470 arg_tuple, keyword_dict = p_call_build_packed_args(
471 pos, positional_args, keyword_args, star_arg)
472 return ExprNodes.GeneralCallNode(pos,
474 positional_args = arg_tuple,
475 keyword_args = keyword_dict,
476 starstar_arg = starstar_arg)
478 #lambdef: 'lambda' [varargslist] ':' test
480 #subscriptlist: subscript (',' subscript)* [',']
482 def p_index(s, base):
486 subscripts = p_subscript_list(s)
487 if len(subscripts) == 1 and len(subscripts[0]) == 2:
488 start, stop = subscripts[0]
489 result = ExprNodes.SliceIndexNode(pos,
490 base = base, start = start, stop = stop)
492 indexes = make_slice_nodes(pos, subscripts)
493 if len(indexes) == 1:
496 index = ExprNodes.TupleNode(pos, args = indexes)
497 result = ExprNodes.IndexNode(pos,
498 base = base, index = index)
502 def p_subscript_list(s):
503 items = [p_subscript(s)]
508 items.append(p_subscript(s))
511 #subscript: '.' '.' '.' | test | [test] ':' [test] [':' [test]]
514 # Parse a subscript and return a list of
515 # 1, 2 or 3 ExprNodes, depending on how
516 # many slice elements were encountered.
518 start = p_slice_element(s, (':',))
522 stop = p_slice_element(s, (':', ',', ']'))
526 step = p_slice_element(s, (':', ',', ']'))
527 return [start, stop, step]
529 def p_slice_element(s, follow_set):
530 # Simple expression which may be missing iff
531 # it is followed by something in follow_set.
532 if s.sy not in follow_set:
537 def expect_ellipsis(s):
542 def make_slice_nodes(pos, subscripts):
543 # Convert a list of subscripts as returned
544 # by p_subscript_list into a list of ExprNodes,
545 # creating SliceNodes for elements with 2 or
548 for subscript in subscripts:
549 if len(subscript) == 1:
550 result.append(subscript[0])
552 result.append(make_slice_node(pos, *subscript))
555 def make_slice_node(pos, start, stop = None, step = None):
557 start = ExprNodes.NoneNode(pos)
559 stop = ExprNodes.NoneNode(pos)
561 step = ExprNodes.NoneNode(pos)
562 return ExprNodes.SliceNode(pos,
563 start = start, stop = stop, step = step)
565 #atom: '(' [yield_expr|testlist_comp] ')' | '[' [listmaker] ']' | '{' [dict_or_set_maker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+
573 result = ExprNodes.TupleNode(pos, args = [])
574 elif s.sy == 'yield':
575 result = p_yield_expression(s)
577 result = p_testlist_comp(s)
581 return p_list_maker(s)
583 return p_dict_or_set_maker(s)
585 return p_backquote_expr(s)
588 return ExprNodes.EllipsisNode(pos)
590 return p_int_literal(s)
594 return ExprNodes.FloatNode(pos, value = value)
596 value = s.systring[:-1]
598 return ExprNodes.ImagNode(pos, value = value)
599 elif sy == 'BEGIN_STRING':
600 kind, bytes_value, unicode_value = p_cat_string_literal(s)
602 return ExprNodes.CharNode(pos, value = bytes_value)
604 return ExprNodes.UnicodeNode(pos, value = unicode_value, bytes_value = bytes_value)
606 return ExprNodes.BytesNode(pos, value = bytes_value)
608 return ExprNodes.StringNode(pos, value = bytes_value, unicode_value = unicode_value)
610 name = EncodedString( s.systring )
613 return ExprNodes.NoneNode(pos)
615 return ExprNodes.BoolNode(pos, value=True)
616 elif name == "False":
617 return ExprNodes.BoolNode(pos, value=False)
618 elif name == "NULL" and not s.in_python_file:
619 return ExprNodes.NullNode(pos)
621 return p_name(s, name)
623 s.error("Expected an identifier or literal")
625 def p_int_literal(s):
631 while value[-1] in u"UuLl":
632 if value[-1] in u"Ll":
637 # '3L' is ambiguous in Py2 but not in Py3. '3U' and '3LL' are
638 # illegal in Py2 Python files. All suffixes are illegal in Py3
644 if longness == 'LL' or s.context.language_level >= 3:
648 error(pos, "illegal integer literal syntax in Python source file")
650 return ExprNodes.IntNode(pos,
651 is_c_literal = is_c_literal,
658 if not s.compile_time_expr and name in s.compile_time_env:
659 value = s.compile_time_env.lookup_here(name)
661 if isinstance(value, bool):
662 return ExprNodes.BoolNode(pos, value = value)
663 elif isinstance(value, int):
664 return ExprNodes.IntNode(pos, value = rep)
665 elif isinstance(value, long):
666 return ExprNodes.IntNode(pos, value = rep, longness = "L")
667 elif isinstance(value, float):
668 return ExprNodes.FloatNode(pos, value = rep)
669 elif isinstance(value, _unicode):
670 return ExprNodes.UnicodeNode(pos, value = value)
671 elif isinstance(value, _bytes):
672 return ExprNodes.BytesNode(pos, value = value)
674 error(pos, "Invalid type for compile-time constant: %s"
675 % value.__class__.__name__)
676 return ExprNodes.NameNode(pos, name = name)
678 def p_cat_string_literal(s):
679 # A sequence of one or more adjacent string literals.
680 # Returns (kind, bytes_value, unicode_value)
681 # where kind in ('b', 'c', 'u', '')
682 kind, bytes_value, unicode_value = p_string_literal(s)
683 if kind == 'c' or s.sy != 'BEGIN_STRING':
684 return kind, bytes_value, unicode_value
685 bstrings, ustrings = [bytes_value], [unicode_value]
686 bytes_value = unicode_value = None
687 while s.sy == 'BEGIN_STRING':
689 next_kind, next_bytes_value, next_unicode_value = p_string_literal(s)
691 error(pos, "Cannot concatenate char literal with another string or char literal")
692 elif next_kind != kind:
693 error(pos, "Cannot mix string literals of different types, expected %s'', got %s''" %
696 bstrings.append(next_bytes_value)
697 ustrings.append(next_unicode_value)
698 # join and rewrap the partial literals
699 if kind in ('b', 'c', '') or kind == 'u' and None not in bstrings:
700 # Py3 enforced unicode literals are parsed as bytes/unicode combination
701 bytes_value = BytesLiteral( StringEncoding.join_bytes(bstrings) )
702 bytes_value.encoding = s.source_encoding
703 if kind in ('u', ''):
704 unicode_value = EncodedString( u''.join([ u for u in ustrings if u is not None ]) )
705 return kind, bytes_value, unicode_value
707 def p_opt_string_literal(s, required_type='u'):
708 if s.sy == 'BEGIN_STRING':
709 kind, bytes_value, unicode_value = p_string_literal(s, required_type)
710 if required_type == 'u':
712 elif required_type == 'b':
715 s.error("internal parser configuration error")
719 def check_for_non_ascii_characters(string):
725 def p_string_literal(s, kind_override=None):
726 # A single string or char literal. Returns (kind, bvalue, uvalue)
727 # where kind in ('b', 'c', 'u', ''). The 'bvalue' is the source
728 # code byte sequence of the string literal, 'uvalue' is the
729 # decoded Unicode string. Either of the two may be None depending
730 # on the 'kind' of string, only unprefixed strings have both
733 # s.sy == 'BEGIN_STRING'
736 is_python3_source = s.context.language_level >= 3
737 has_non_ASCII_literal_characters = False
738 kind = s.systring[:1].lower()
743 is_raw = s.systring[1:2].lower() == 'r'
746 if kind == '' and kind_override is None and Future.unicode_literals in s.context.future_directives:
747 chars = StringEncoding.StrLiteralBuilder(s.source_encoding)
750 if kind_override is not None and kind_override in 'ub':
753 chars = StringEncoding.UnicodeLiteralBuilder()
755 chars = StringEncoding.StrLiteralBuilder(s.source_encoding)
757 chars = StringEncoding.BytesLiteralBuilder(s.source_encoding)
762 #print "p_string_literal: sy =", sy, repr(s.systring) ###
765 if is_python3_source and not has_non_ASCII_literal_characters and check_for_non_ascii_characters(systr):
766 has_non_ASCII_literal_characters = True
770 if is_python3_source and not has_non_ASCII_literal_characters \
771 and check_for_non_ascii_characters(systr):
772 has_non_ASCII_literal_characters = True
776 chars.append_charval( int(systr[1:], 8) )
779 elif c in u"abfnrtv":
781 StringEncoding.char_from_escape_sequence(systr))
786 chars.append_charval( int(systr[2:], 16) )
788 s.error("Invalid hex escape '%s'" % systr)
790 if kind in ('u', ''):
791 if len(systr) in (6,10):
792 chrval = int(systr[2:], 16)
793 if chrval > 1114111: # sys.maxunicode:
794 s.error("Invalid unicode escape '%s'" % systr)
796 s.error("Invalid unicode escape '%s'" % systr)
798 # unicode escapes in byte strings are not unescaped
800 chars.append_uescape(chrval, systr)
802 chars.append(u'\\' + systr[1:])
803 if is_python3_source and not has_non_ASCII_literal_characters \
804 and check_for_non_ascii_characters(systr):
805 has_non_ASCII_literal_characters = True
806 elif sy == 'NEWLINE':
808 elif sy == 'END_STRING':
811 s.error("Unclosed string literal", pos = pos)
814 "Unexpected token %r:%r in string literal" %
818 bytes_value = chars.getchar()
819 if len(bytes_value) != 1:
820 error(pos, u"invalid character literal: %r" % bytes_value)
822 bytes_value, unicode_value = chars.getstrings()
823 if is_python3_source and has_non_ASCII_literal_characters:
824 # Python 3 forbids literal non-ASCII characters in byte strings
826 s.error("bytes can only contain ASCII literal characters.", pos = pos)
829 return (kind, bytes_value, unicode_value)
831 # list_display ::= "[" [listmaker] "]"
832 # listmaker ::= expression ( comp_for | ( "," expression )* [","] )
833 # comp_iter ::= comp_for | comp_if
834 # comp_for ::= "for" expression_list "in" testlist [comp_iter]
835 # comp_if ::= "if" test [comp_iter]
843 return ExprNodes.ListNode(pos, args = [])
846 target = ExprNodes.ListNode(pos, args = [])
847 append = ExprNodes.ComprehensionAppendNode(
848 pos, expr=expr, target=ExprNodes.CloneNode(target))
849 loop = p_comp_for(s, append)
851 return ExprNodes.ComprehensionNode(
852 pos, loop=loop, append=append, target=target,
853 # list comprehensions leak their loop variable in Py2
854 has_local_scope = s.context.language_level >= 3)
858 exprs = p_simple_expr_list(s, expr)
862 return ExprNodes.ListNode(pos, args = exprs)
864 def p_comp_iter(s, body):
866 return p_comp_for(s, body)
868 return p_comp_if(s, body)
870 # insert the 'append' operation into the loop
873 def p_comp_for(s, body):
877 kw = p_for_bounds(s, allow_testlist=False)
878 kw.update(dict(else_clause = None, body = p_comp_iter(s, body)))
879 return Nodes.ForStatNode(pos, **kw)
881 def p_comp_if(s, body):
885 test = p_test_nocond(s)
886 return Nodes.IfStatNode(pos,
887 if_clauses = [Nodes.IfClauseNode(pos, condition = test,
888 body = p_comp_iter(s, body))],
891 #dictmaker: test ':' test (',' test ':' test)* [',']
893 def p_dict_or_set_maker(s):
899 return ExprNodes.DictNode(pos, key_value_pairs = [])
901 if s.sy == ',' or s.sy == '}':
908 values.append( p_test(s) )
910 return ExprNodes.SetNode(pos, args=values)
913 target = ExprNodes.SetNode(pos, args=[])
914 append = ExprNodes.ComprehensionAppendNode(
915 item.pos, expr=item, target=ExprNodes.CloneNode(target))
916 loop = p_comp_for(s, append)
918 return ExprNodes.ComprehensionNode(
919 pos, loop=loop, append=append, target=target)
921 # dict literal or comprehension
927 target = ExprNodes.DictNode(pos, key_value_pairs = [])
928 append = ExprNodes.DictComprehensionAppendNode(
929 item.pos, key_expr=key, value_expr=value,
930 target=ExprNodes.CloneNode(target))
931 loop = p_comp_for(s, append)
933 return ExprNodes.ComprehensionNode(
934 pos, loop=loop, append=append, target=target)
937 items = [ExprNodes.DictItemNode(key.pos, key=key, value=value)]
946 ExprNodes.DictItemNode(key.pos, key=key, value=value))
948 return ExprNodes.DictNode(pos, key_value_pairs=items)
952 return ExprNodes.DictNode(pos, key_value_pairs = [])
954 # NOTE: no longer in Py3 :)
955 def p_backquote_expr(s):
962 args.append(p_test(s))
967 arg = ExprNodes.TupleNode(pos, args = args)
968 return ExprNodes.BackquoteNode(pos, arg = arg)
970 def p_simple_expr_list(s, expr=None):
971 exprs = expr is not None and [expr] or []
972 while s.sy not in expr_terminators:
973 exprs.append( p_test(s) )
979 def p_test_or_starred_expr_list(s, expr=None):
980 exprs = expr is not None and [expr] or []
981 while s.sy not in expr_terminators:
982 exprs.append( p_test_or_starred_expr(s) )
989 #testlist: test (',' test)* [',']
996 exprs = p_simple_expr_list(s, expr)
997 return ExprNodes.TupleNode(pos, args = exprs)
1001 # testlist_star_expr: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
1003 def p_testlist_star_expr(s):
1005 expr = p_test_or_starred_expr(s)
1008 exprs = p_test_or_starred_expr_list(s, expr)
1009 return ExprNodes.TupleNode(pos, args = exprs)
1013 # testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
1015 def p_testlist_comp(s):
1017 expr = p_test_or_starred_expr(s)
1020 exprs = p_test_or_starred_expr_list(s, expr)
1021 return ExprNodes.TupleNode(pos, args = exprs)
1023 return p_genexp(s, expr)
1027 def p_genexp(s, expr):
1029 loop = p_comp_for(s, Nodes.ExprStatNode(
1030 expr.pos, expr = ExprNodes.YieldExprNode(expr.pos, arg=expr)))
1031 return ExprNodes.GeneratorExpressionNode(expr.pos, loop=loop)
1033 expr_terminators = (')', ']', '}', ':', '=', 'NEWLINE')
1035 #-------------------------------------------------------
1039 #-------------------------------------------------------
1041 def p_global_statement(s):
1042 # assume s.sy == 'global'
1045 names = p_ident_list(s)
1046 return Nodes.GlobalNode(pos, names = names)
1048 def p_nonlocal_statement(s):
1051 names = p_ident_list(s)
1052 return Nodes.NonlocalNode(pos, names = names)
1054 def p_expression_or_assignment(s):
1055 expr_list = [p_testlist_star_expr(s)]
1059 expr = p_yield_expression(s)
1061 expr = p_testlist_star_expr(s)
1062 expr_list.append(expr)
1063 if len(expr_list) == 1:
1064 if re.match(r"([+*/\%^\&|-]|<<|>>|\*\*|//)=", s.sy):
1066 if not isinstance(lhs, (ExprNodes.AttributeNode, ExprNodes.IndexNode, ExprNodes.NameNode) ):
1067 error(lhs.pos, "Illegal operand for inplace operation.")
1068 operator = s.sy[:-1]
1071 rhs = p_yield_expression(s)
1074 return Nodes.InPlaceAssignmentNode(lhs.pos, operator = operator, lhs = lhs, rhs = rhs)
1076 if isinstance(expr, (ExprNodes.UnicodeNode, ExprNodes.StringNode, ExprNodes.BytesNode)):
1077 return Nodes.PassStatNode(expr.pos)
1079 return Nodes.ExprStatNode(expr.pos, expr = expr)
1082 if len(expr_list) == 2:
1083 return Nodes.SingleAssignmentNode(rhs.pos,
1084 lhs = expr_list[0], rhs = rhs)
1086 return Nodes.CascadedAssignmentNode(rhs.pos,
1087 lhs_list = expr_list[:-1], rhs = rhs)
1089 def p_print_statement(s):
1099 ends_with_comma = s.sy in ('NEWLINE', 'EOF')
1103 if s.sy not in ('NEWLINE', 'EOF'):
1104 args.append(p_test(s))
1107 if s.sy in ('NEWLINE', 'EOF'):
1110 args.append(p_test(s))
1111 arg_tuple = ExprNodes.TupleNode(pos, args = args)
1112 return Nodes.PrintStatNode(pos,
1113 arg_tuple = arg_tuple, stream = stream,
1114 append_newline = not ends_with_comma)
1116 def p_exec_statement(s):
1120 args = [ p_bit_expr(s) ]
1123 args.append(p_test(s))
1126 args.append(p_test(s))
1128 error(pos, "'exec' currently requires a target mapping (globals/locals)")
1129 return Nodes.ExecStatNode(pos, args = args)
1131 def p_del_statement(s):
1135 # FIXME: 'exprlist' in Python
1136 args = p_simple_expr_list(s)
1137 return Nodes.DelStatNode(pos, args = args)
1139 def p_pass_statement(s, with_newline = 0):
1143 s.expect_newline("Expected a newline")
1144 return Nodes.PassStatNode(pos)
1146 def p_break_statement(s):
1150 return Nodes.BreakStatNode(pos)
1152 def p_continue_statement(s):
1153 # s.sy == 'continue'
1156 return Nodes.ContinueStatNode(pos)
1158 def p_return_statement(s):
1162 if s.sy not in statement_terminators:
1163 value = p_testlist(s)
1166 return Nodes.ReturnStatNode(pos, value = value)
1168 def p_raise_statement(s):
1175 if s.sy not in statement_terminators:
1176 exc_type = p_test(s)
1179 exc_value = p_test(s)
1183 if exc_type or exc_value or exc_tb:
1184 return Nodes.RaiseStatNode(pos,
1185 exc_type = exc_type,
1186 exc_value = exc_value,
1189 return Nodes.ReraiseStatNode(pos)
1191 def p_import_statement(s):
1192 # will do absolute import in Py3 and try both relative and absolute in Py2.
1193 if s.context.language_level >= 3:
1197 # s.sy in ('import', 'cimport')
1201 items = [p_dotted_name(s, as_allowed = 1)]
1204 items.append(p_dotted_name(s, as_allowed = 1))
1206 for pos, target_name, dotted_name, as_name in items:
1207 dotted_name = EncodedString(dotted_name)
1208 if kind == 'cimport':
1209 stat = Nodes.CImportStatNode(pos,
1210 module_name = dotted_name,
1213 if as_name and "." in dotted_name:
1214 name_list = ExprNodes.ListNode(pos, args = [
1215 ExprNodes.IdentifierStringNode(pos, value = EncodedString("*"))])
1218 stat = Nodes.SingleAssignmentNode(pos,
1219 lhs = ExprNodes.NameNode(pos,
1220 name = as_name or target_name),
1221 rhs = ExprNodes.ImportNode(pos,
1222 module_name = ExprNodes.IdentifierStringNode(
1223 pos, value = dotted_name),
1225 name_list = name_list))
1227 return Nodes.StatListNode(pos, stats = stats)
1229 def p_from_import_statement(s, first_statement = 0):
1234 # count relative import level
1240 # will do absolute import in Py3 and try both relative and absolute in Py2.
1241 if s.context.language_level >= 3:
1246 if level > 0 and s.sy == 'cimport':
1247 s.error("Relative cimport is not supported yet")
1248 if level > 0 and s.sy == 'import':
1249 # we are dealing with "from .. import foo, bar"
1250 dotted_name_pos, dotted_name = s.position(), ''
1252 (dotted_name_pos, _, dotted_name, _) = \
1253 p_dotted_name(s, as_allowed = 0)
1254 if s.sy in ('import', 'cimport'):
1258 s.error("Expected 'import' or 'cimport'")
1260 is_cimport = kind == 'cimport'
1261 is_parenthesized = False
1263 imported_names = [(s.position(), "*", None, None)]
1267 is_parenthesized = True
1269 imported_names = [p_imported_name(s, is_cimport)]
1272 if is_parenthesized and s.sy == ')':
1274 imported_names.append(p_imported_name(s, is_cimport))
1275 if is_parenthesized:
1277 dotted_name = EncodedString(dotted_name)
1278 if dotted_name == '__future__':
1279 if not first_statement:
1280 s.error("from __future__ imports must occur at the beginning of the file")
1281 elif level is not None:
1282 s.error("invalid syntax")
1284 for (name_pos, name, as_name, kind) in imported_names:
1285 if name == "braces":
1286 s.error("not a chance", name_pos)
1289 directive = getattr(Future, name)
1290 except AttributeError:
1291 s.error("future feature %s is not defined" % name, name_pos)
1293 s.context.future_directives.add(directive)
1294 return Nodes.PassStatNode(pos)
1295 elif kind == 'cimport':
1296 return Nodes.FromCImportStatNode(pos,
1297 module_name = dotted_name,
1298 imported_names = imported_names)
1300 imported_name_strings = []
1302 for (name_pos, name, as_name, kind) in imported_names:
1303 encoded_name = EncodedString(name)
1304 imported_name_strings.append(
1305 ExprNodes.IdentifierStringNode(name_pos, value = encoded_name))
1308 ExprNodes.NameNode(name_pos,
1309 name = as_name or name)))
1310 import_list = ExprNodes.ListNode(
1311 imported_names[0][0], args = imported_name_strings)
1312 dotted_name = EncodedString(dotted_name)
1313 return Nodes.FromImportStatNode(pos,
1314 module = ExprNodes.ImportNode(dotted_name_pos,
1315 module_name = ExprNodes.IdentifierStringNode(pos, value = dotted_name),
1317 name_list = import_list),
1320 imported_name_kinds = ('class', 'struct', 'union')
1322 def p_imported_name(s, is_cimport):
1325 if is_cimport and s.systring in imported_name_kinds:
1329 as_name = p_as_name(s)
1330 return (pos, name, as_name, kind)
1332 def p_dotted_name(s, as_allowed):
1334 target_name = p_ident(s)
1336 names = [target_name]
1339 names.append(p_ident(s))
1341 as_name = p_as_name(s)
1342 return (pos, target_name, u'.'.join(names), as_name)
1345 if s.sy == 'IDENT' and s.systring == 'as':
1351 def p_assert_statement(s):
1361 return Nodes.AssertStatNode(pos, cond = cond, value = value)
1363 statement_terminators = (';', 'NEWLINE', 'EOF')
1365 def p_if_statement(s):
1369 if_clauses = [p_if_clause(s)]
1370 while s.sy == 'elif':
1372 if_clauses.append(p_if_clause(s))
1373 else_clause = p_else_clause(s)
1374 return Nodes.IfStatNode(pos,
1375 if_clauses = if_clauses, else_clause = else_clause)
1381 return Nodes.IfClauseNode(pos,
1382 condition = test, body = body)
1384 def p_else_clause(s):
1391 def p_while_statement(s):
1397 else_clause = p_else_clause(s)
1398 return Nodes.WhileStatNode(pos,
1399 condition = test, body = body,
1400 else_clause = else_clause)
1402 def p_for_statement(s):
1406 kw = p_for_bounds(s, allow_testlist=True)
1408 else_clause = p_else_clause(s)
1409 kw.update(dict(body = body, else_clause = else_clause))
1410 return Nodes.ForStatNode(pos, **kw)
1412 def p_for_bounds(s, allow_testlist=True):
1413 target = p_for_target(s)
1416 iterator = p_for_iterator(s, allow_testlist)
1417 return dict( target = target, iterator = iterator )
1418 elif not s.in_python_file:
1421 bound1 = p_bit_expr(s)
1423 # Support shorter "for a <= x < b" syntax
1424 bound1, target = target, None
1425 rel1 = p_for_from_relation(s)
1426 name2_pos = s.position()
1428 rel2_pos = s.position()
1429 rel2 = p_for_from_relation(s)
1430 bound2 = p_bit_expr(s)
1431 step = p_for_from_step(s)
1433 target = ExprNodes.NameNode(name2_pos, name = name2)
1435 if not target.is_name:
1437 "Target of for-from statement must be a variable name")
1438 elif name2 != target.name:
1440 "Variable name in for-from range does not match target")
1441 if rel1[0] != rel2[0]:
1443 "Relation directions in for-from do not match")
1444 return dict(target = target,
1455 def p_for_from_relation(s):
1456 if s.sy in inequality_relations:
1461 s.error("Expected one of '<', '<=', '>' '>='")
1463 def p_for_from_step(s):
1464 if s.sy == 'IDENT' and s.systring == 'by':
1466 step = p_bit_expr(s)
1471 inequality_relations = ('<', '<=', '>', '>=')
1473 def p_target(s, terminator):
1475 expr = p_starred_expr(s)
1479 while s.sy != terminator:
1480 exprs.append(p_starred_expr(s))
1484 return ExprNodes.TupleNode(pos, args = exprs)
1488 def p_for_target(s):
1489 return p_target(s, 'in')
1491 def p_for_iterator(s, allow_testlist=True):
1494 expr = p_testlist(s)
1497 return ExprNodes.IteratorNode(pos, sequence = expr)
1499 def p_try_statement(s):
1506 if s.sy in ('except', 'else'):
1507 while s.sy == 'except':
1508 except_clauses.append(p_except_clause(s))
1511 else_clause = p_suite(s)
1512 body = Nodes.TryExceptStatNode(pos,
1513 body = body, except_clauses = except_clauses,
1514 else_clause = else_clause)
1515 if s.sy != 'finally':
1517 # try-except-finally is equivalent to nested try-except/try-finally
1518 if s.sy == 'finally':
1520 finally_clause = p_suite(s)
1521 return Nodes.TryFinallyStatNode(pos,
1522 body = body, finally_clause = finally_clause)
1524 s.error("Expected 'except' or 'finally'")
1526 def p_except_clause(s):
1533 exc_type = p_test(s)
1534 # normalise into list of single exception tests
1535 if isinstance(exc_type, ExprNodes.TupleNode):
1536 exc_type = exc_type.args
1538 exc_type = [exc_type]
1539 if s.sy == ',' or (s.sy == 'IDENT' and s.systring == 'as'):
1541 exc_value = p_test(s)
1542 elif s.sy == 'IDENT' and s.systring == 'as':
1543 # Py3 syntax requires a name here
1547 exc_value = ExprNodes.NameNode(pos2, name = name)
1549 return Nodes.ExceptClauseNode(pos,
1550 pattern = exc_type, target = exc_value, body = body)
1552 def p_include_statement(s, ctx):
1554 s.next() # 'include'
1555 unicode_include_file_name = p_string_literal(s, 'u')[2]
1556 s.expect_newline("Syntax error in include statement")
1557 if s.compile_time_eval:
1558 include_file_name = unicode_include_file_name
1559 include_file_path = s.context.find_include_file(include_file_name, pos)
1560 if include_file_path:
1561 s.included_files.append(include_file_name)
1562 f = Utils.open_source_file(include_file_path, mode="rU")
1563 source_desc = FileSourceDescriptor(include_file_path)
1564 s2 = PyrexScanner(f, source_desc, s, source_encoding=f.encoding, parse_comments=s.parse_comments)
1566 tree = p_statement_list(s2, ctx)
1573 return Nodes.PassStatNode(pos)
1575 def p_with_statement(s):
1577 if s.systring == 'template' and not s.in_python_file:
1578 node = p_with_template(s)
1580 node = p_with_items(s)
1583 def p_with_items(s):
1585 if not s.in_python_file and s.sy == 'IDENT' and s.systring == 'nogil':
1590 body = p_with_items(s)
1593 return Nodes.GILStatNode(pos, state = state, body = body)
1597 if s.sy == 'IDENT' and s.systring == 'as':
1599 target = p_starred_expr(s)
1602 body = p_with_items(s)
1605 return Nodes.WithStatNode(pos, manager = manager,
1606 target = target, body = body)
1608 def p_with_template(s):
1613 templates.append(s.systring)
1615 while s.systring == ',':
1617 templates.append(s.systring)
1622 s.expect_newline("Syntax error in template function declaration")
1625 body_ctx.templates = templates
1626 func_or_var = p_c_func_or_var_declaration(s, pos, body_ctx)
1630 error(pos, "Syntax error in template function declaration")
1632 def p_simple_statement(s, first_statement = 0):
1633 #print "p_simple_statement:", s.sy, s.systring ###
1634 if s.sy == 'global':
1635 node = p_global_statement(s)
1636 elif s.sy == 'nonlocal':
1637 node = p_nonlocal_statement(s)
1638 elif s.sy == 'print':
1639 node = p_print_statement(s)
1640 elif s.sy == 'exec':
1641 node = p_exec_statement(s)
1643 node = p_del_statement(s)
1644 elif s.sy == 'break':
1645 node = p_break_statement(s)
1646 elif s.sy == 'continue':
1647 node = p_continue_statement(s)
1648 elif s.sy == 'return':
1649 node = p_return_statement(s)
1650 elif s.sy == 'raise':
1651 node = p_raise_statement(s)
1652 elif s.sy in ('import', 'cimport'):
1653 node = p_import_statement(s)
1654 elif s.sy == 'from':
1655 node = p_from_import_statement(s, first_statement = first_statement)
1656 elif s.sy == 'yield':
1657 node = p_yield_statement(s)
1658 elif s.sy == 'assert':
1659 node = p_assert_statement(s)
1660 elif s.sy == 'pass':
1661 node = p_pass_statement(s)
1663 node = p_expression_or_assignment(s)
1666 def p_simple_statement_list(s, ctx, first_statement = 0):
1667 # Parse a series of simple statements on one line
1668 # separated by semicolons.
1669 stat = p_simple_statement(s, first_statement = first_statement)
1673 #print "p_simple_statement_list: maybe more to follow" ###
1675 if s.sy in ('NEWLINE', 'EOF'):
1677 stats.append(p_simple_statement(s))
1678 stat = Nodes.StatListNode(stats[0].pos, stats = stats)
1679 s.expect_newline("Syntax error in simple statement list")
1682 def p_compile_time_expr(s):
1683 old = s.compile_time_expr
1684 s.compile_time_expr = 1
1685 expr = p_testlist(s)
1686 s.compile_time_expr = old
1689 def p_DEF_statement(s):
1691 denv = s.compile_time_env
1695 expr = p_compile_time_expr(s)
1696 value = expr.compile_time_value(denv)
1697 #print "p_DEF_statement: %s = %r" % (name, value) ###
1698 denv.declare(name, value)
1700 return Nodes.PassStatNode(pos)
1702 def p_IF_statement(s, ctx):
1704 saved_eval = s.compile_time_eval
1705 current_eval = saved_eval
1706 denv = s.compile_time_env
1709 s.next() # 'IF' or 'ELIF'
1710 expr = p_compile_time_expr(s)
1711 s.compile_time_eval = current_eval and bool(expr.compile_time_value(denv))
1712 body = p_suite(s, ctx)
1713 if s.compile_time_eval:
1720 s.compile_time_eval = current_eval
1721 body = p_suite(s, ctx)
1725 result = Nodes.PassStatNode(pos)
1726 s.compile_time_eval = saved_eval
1729 def p_statement(s, ctx, first_statement = 0):
1730 cdef_flag = ctx.cdef_flag
1732 if s.sy == 'ctypedef':
1733 if ctx.level not in ('module', 'module_pxd'):
1734 s.error("ctypedef statement not allowed here")
1736 # error(s.position(), "'api' not allowed with 'ctypedef'")
1737 return p_ctypedef_statement(s, ctx)
1739 return p_DEF_statement(s)
1741 return p_IF_statement(s, ctx)
1742 elif s.sy == 'DECORATOR':
1743 if ctx.level not in ('module', 'class', 'c_class', 'function', 'property', 'module_pxd', 'c_class_pxd'):
1744 s.error('decorator not allowed here')
1746 decorators = p_decorators(s)
1747 if s.sy not in ('def', 'cdef', 'cpdef', 'class'):
1748 s.error("Decorators can only be followed by functions or classes")
1749 elif s.sy == 'pass' and cdef_flag:
1751 return p_pass_statement(s, with_newline = 1)
1757 elif s.sy == 'cpdef':
1762 if ctx.level not in ('module', 'module_pxd', 'function', 'c_class', 'c_class_pxd'):
1763 s.error('cdef statement not allowed here')
1765 node = p_cdef_statement(s, ctx(overridable = overridable))
1766 if decorators is not None:
1767 if not isinstance(node, (Nodes.CFuncDefNode, Nodes.CVarDefNode, Nodes.CClassDefNode)):
1768 s.error("Decorators can only be followed by functions or classes")
1769 node.decorators = decorators
1773 s.error("'api' not allowed with this statement")
1775 # def statements aren't allowed in pxd files, except
1776 # as part of a cdef class
1777 if ('pxd' in ctx.level) and (ctx.level != 'c_class_pxd'):
1778 s.error('def statement not allowed here')
1780 return p_def_statement(s, decorators)
1781 elif s.sy == 'class':
1782 if ctx.level not in ('module', 'function', 'class', 'other'):
1783 s.error("class definition not allowed here")
1784 return p_class_statement(s, decorators)
1785 elif s.sy == 'include':
1786 if ctx.level not in ('module', 'module_pxd'):
1787 s.error("include statement not allowed here")
1788 return p_include_statement(s, ctx)
1789 elif ctx.level == 'c_class' and s.sy == 'IDENT' and s.systring == 'property':
1790 return p_property_decl(s)
1791 elif s.sy == 'pass' and ctx.level != 'property':
1792 return p_pass_statement(s, with_newline = 1)
1794 if ctx.level in ('c_class_pxd', 'property'):
1795 s.error("Executable statement not allowed here")
1797 return p_if_statement(s)
1798 elif s.sy == 'while':
1799 return p_while_statement(s)
1801 return p_for_statement(s)
1803 return p_try_statement(s)
1804 elif s.sy == 'with':
1805 return p_with_statement(s)
1807 return p_simple_statement_list(
1808 s, ctx, first_statement = first_statement)
1810 def p_statement_list(s, ctx, first_statement = 0):
1811 # Parse a series of statements separated by newlines.
1814 while s.sy not in ('DEDENT', 'EOF'):
1815 stats.append(p_statement(s, ctx, first_statement = first_statement))
1820 return Nodes.StatListNode(pos, stats = stats)
1822 def p_suite(s, ctx = Ctx(), with_doc = 0, with_pseudo_doc = 0):
1827 if s.sy == 'NEWLINE':
1830 if with_doc or with_pseudo_doc:
1831 doc = p_doc_string(s)
1832 body = p_statement_list(s, ctx)
1836 s.error("'api' not allowed with this statement")
1837 if ctx.level in ('module', 'class', 'function', 'other'):
1838 body = p_simple_statement_list(s, ctx)
1840 body = p_pass_statement(s)
1841 s.expect_newline("Syntax error in declarations")
1847 def p_positional_and_keyword_args(s, end_sy_set, templates = None):
1849 Parses positional and keyword arguments. end_sy_set
1850 should contain any s.sy that terminate the argument list.
1851 Argument expansion (* and **) are not allowed.
1853 Returns: (positional_args, keyword_args)
1855 positional_args = []
1859 while s.sy not in end_sy_set:
1860 if s.sy == '*' or s.sy == '**':
1861 s.error('Argument expansion not allowed here.')
1864 if s.sy == 'IDENT' and s.peek()[0] == '=':
1866 s.next() # s.sy is '='
1868 if looking_at_expr(s):
1871 base_type = p_c_base_type(s, templates = templates)
1872 declarator = p_c_declarator(s, empty = 1)
1873 arg = Nodes.CComplexBaseTypeNode(base_type.pos,
1874 base_type = base_type, declarator = declarator)
1876 keyword_node = ExprNodes.IdentifierStringNode(
1877 arg.pos, value = EncodedString(ident))
1878 keyword_args.append((keyword_node, arg))
1882 if looking_at_expr(s):
1885 base_type = p_c_base_type(s, templates = templates)
1886 declarator = p_c_declarator(s, empty = 1)
1887 arg = Nodes.CComplexBaseTypeNode(base_type.pos,
1888 base_type = base_type, declarator = declarator)
1890 positional_args.append(arg)
1892 if len(keyword_args) > 0:
1893 s.error("Non-keyword arg following keyword arg",
1897 if s.sy not in end_sy_set:
1899 s.error("Unmatched %s" % " or ".join(end_sy_set))
1902 return positional_args, keyword_args
1904 def p_c_base_type(s, self_flag = 0, nonempty = 0, templates = None):
1905 # If self_flag is true, this is the base type for the
1906 # self argument of a C method of an extension type.
1908 return p_c_complex_base_type(s)
1910 return p_c_simple_base_type(s, self_flag, nonempty = nonempty, templates = templates)
1912 def p_calling_convention(s):
1913 if s.sy == 'IDENT' and s.systring in calling_convention_words:
1920 calling_convention_words = ("__stdcall", "__cdecl", "__fastcall")
1922 def p_c_complex_base_type(s):
1926 base_type = p_c_base_type(s)
1927 declarator = p_c_declarator(s, empty = 1)
1929 return Nodes.CComplexBaseTypeNode(pos,
1930 base_type = base_type, declarator = declarator)
1932 def p_c_simple_base_type(s, self_flag, nonempty, templates = None):
1933 #print "p_c_simple_base_type: self_flag =", self_flag, nonempty
1940 if not s.sy == 'IDENT':
1941 error(pos, "Expected an identifier, found '%s'" % s.sy)
1942 if looking_at_base_type(s):
1943 #print "p_c_simple_base_type: looking_at_base_type at", s.position()
1945 if s.sy == 'IDENT' and s.systring in special_basic_c_types:
1946 signed, longness = special_basic_c_types[s.systring]
1950 signed, longness = p_sign_and_longness(s)
1951 if s.sy == 'IDENT' and s.systring in basic_c_type_names:
1955 name = 'int' # long [int], short [int], long [int] complex, etc.
1956 if s.sy == 'IDENT' and s.systring == 'complex':
1959 elif looking_at_dotted_name(s):
1960 #print "p_c_simple_base_type: looking_at_type_name at", s.position()
1964 module_path.append(name)
1970 if nonempty and s.sy != 'IDENT':
1971 # Make sure this is not a declaration of a variable or function.
1974 if s.sy == '*' or s.sy == '**' or s.sy == '&':
1975 s.put_back('(', '(')
1977 s.put_back('(', '(')
1978 s.put_back('IDENT', name)
1980 elif s.sy not in ('*', '**', '[', '&'):
1981 s.put_back('IDENT', name)
1984 type_node = Nodes.CSimpleBaseTypeNode(pos,
1985 name = name, module_path = module_path,
1986 is_basic_c_type = is_basic, signed = signed,
1987 complex = complex, longness = longness,
1988 is_self_arg = self_flag, templates = templates)
1991 type_node = p_buffer_or_template(s, type_node, templates)
1996 type_node = Nodes.CNestedBaseTypeNode(pos, base_type = type_node, name = name)
2000 def p_buffer_or_template(s, base_type_node, templates):
2004 # Note that buffer_positional_options_count=1, so the only positional argument is dtype.
2005 # For templated types, all parameters are types.
2006 positional_args, keyword_args = (
2007 p_positional_and_keyword_args(s, (']',), templates)
2011 keyword_dict = ExprNodes.DictNode(pos,
2013 ExprNodes.DictItemNode(pos=key.pos, key=key, value=value)
2014 for key, value in keyword_args
2016 result = Nodes.TemplatedTypeNode(pos,
2017 positional_args = positional_args,
2018 keyword_args = keyword_dict,
2019 base_type_node = base_type_node)
2023 def looking_at_name(s):
2024 return s.sy == 'IDENT' and not s.systring in calling_convention_words
2026 def looking_at_expr(s):
2027 if s.systring in base_type_start_words:
2029 elif s.sy == 'IDENT':
2036 dotted_path.append(s.systring)
2038 saved = s.sy, s.systring
2041 elif s.sy == '*' or s.sy == '**':
2043 is_type = s.sy in (')', ']')
2047 is_type = s.sy == '*'
2051 is_type = s.sy == ']'
2053 dotted_path.reverse()
2054 for p in dotted_path:
2055 s.put_back('IDENT', p)
2056 s.put_back('.', '.')
2057 s.put_back('IDENT', name)
2062 def looking_at_base_type(s):
2063 #print "looking_at_base_type?", s.sy, s.systring, s.position()
2064 return s.sy == 'IDENT' and s.systring in base_type_start_words
2066 def looking_at_dotted_name(s):
2070 result = s.sy == '.'
2071 s.put_back('IDENT', name)
2076 basic_c_type_names = ("void", "char", "int", "float", "double", "bint")
2078 special_basic_c_types = {
2079 # name : (signed, longness)
2080 "Py_UNICODE" : (0, 0),
2082 "Py_ssize_t" : (2, 0),
2087 sign_and_longness_words = ("short", "long", "signed", "unsigned")
2089 base_type_start_words = \
2090 basic_c_type_names + sign_and_longness_words + tuple(special_basic_c_types)
2092 def p_sign_and_longness(s):
2095 while s.sy == 'IDENT' and s.systring in sign_and_longness_words:
2096 if s.systring == 'unsigned':
2098 elif s.systring == 'signed':
2100 elif s.systring == 'short':
2102 elif s.systring == 'long':
2105 return signed, longness
2108 literal = p_opt_string_literal(s, 'u')
2109 if literal is not None:
2110 cname = EncodedString(literal)
2111 cname.encoding = s.source_encoding
2116 def p_c_declarator(s, ctx = Ctx(), empty = 0, is_type = 0, cmethod_flag = 0,
2117 assignable = 0, nonempty = 0,
2118 calling_convention_allowed = 0):
2119 # If empty is true, the declarator must be empty. If nonempty is true,
2120 # the declarator must be nonempty. Otherwise we don't care.
2121 # If cmethod_flag is true, then if this declarator declares
2122 # a function, it's a C method of an extension type.
2126 if s.sy == ')' or looking_at_name(s):
2127 base = Nodes.CNameDeclaratorNode(pos, name = EncodedString(u""), cname = None)
2128 result = p_c_func_declarator(s, pos, ctx, base, cmethod_flag)
2130 result = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2131 cmethod_flag = cmethod_flag,
2132 nonempty = nonempty,
2133 calling_convention_allowed = 1)
2136 result = p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
2137 assignable, nonempty)
2138 if not calling_convention_allowed and result.calling_convention and s.sy != '(':
2139 error(s.position(), "%s on something that is not a function"
2140 % result.calling_convention)
2141 while s.sy in ('[', '('):
2144 result = p_c_array_declarator(s, result)
2147 result = p_c_func_declarator(s, pos, ctx, result, cmethod_flag)
2151 def p_c_array_declarator(s, base):
2159 return Nodes.CArrayDeclaratorNode(pos, base = base, dimension = dim)
2161 def p_c_func_declarator(s, pos, ctx, base, cmethod_flag):
2162 # Opening paren has already been skipped
2163 args = p_c_arg_list(s, ctx, cmethod_flag = cmethod_flag,
2164 nonempty_declarators = 0)
2165 ellipsis = p_optional_ellipsis(s)
2168 exc_val, exc_check = p_exception_value_clause(s)
2169 with_gil = p_with_gil(s)
2170 return Nodes.CFuncDeclaratorNode(pos,
2171 base = base, args = args, has_varargs = ellipsis,
2172 exception_value = exc_val, exception_check = exc_check,
2173 nogil = nogil or ctx.nogil or with_gil, with_gil = with_gil)
2175 supported_overloaded_operators = cython.set([
2176 '+', '-', '*', '/', '%',
2177 '++', '--', '~', '|', '&', '^', '<<', '>>', ',',
2178 '==', '!=', '>=', '>', '<=', '<',
2182 def p_c_simple_declarator(s, ctx, empty, is_type, cmethod_flag,
2183 assignable, nonempty):
2185 calling_convention = p_calling_convention(s)
2188 base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2189 cmethod_flag = cmethod_flag,
2190 assignable = assignable, nonempty = nonempty)
2191 result = Nodes.CPtrDeclaratorNode(pos,
2193 elif s.sy == '**': # scanner returns this as a single token
2195 base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2196 cmethod_flag = cmethod_flag,
2197 assignable = assignable, nonempty = nonempty)
2198 result = Nodes.CPtrDeclaratorNode(pos,
2199 base = Nodes.CPtrDeclaratorNode(pos,
2203 base = p_c_declarator(s, ctx, empty = empty, is_type = is_type,
2204 cmethod_flag = cmethod_flag,
2205 assignable = assignable, nonempty = nonempty)
2206 result = Nodes.CReferenceDeclaratorNode(pos, base = base)
2210 name = EncodedString(s.systring)
2212 error(s.position(), "Declarator should be empty")
2214 cname = p_opt_cname(s)
2215 if name != 'operator' and s.sy == '=' and assignable:
2220 error(s.position(), "Empty declarator")
2223 if cname is None and ctx.namespace is not None and nonempty:
2224 cname = ctx.namespace + "::" + name
2225 if name == 'operator' and ctx.visibility == 'extern' and nonempty:
2227 if [1 for c in op if c in '+-*/<=>!%&|([^~,']:
2229 # Handle diphthong operators.
2236 if op in ['-', '+', '|', '&'] and s.sy == op:
2242 if op not in supported_overloaded_operators:
2243 s.error("Overloading operator '%s' not yet supported." % op)
2245 result = Nodes.CNameDeclaratorNode(pos,
2246 name = name, cname = cname, default = rhs)
2247 result.calling_convention = calling_convention
2251 if s.sy == 'IDENT' and s.systring == 'nogil':
2260 s.expect_keyword('gil')
2265 def p_exception_value_clause(s):
2268 if s.sy == 'except':
2279 exc_val = p_name(s, name)
2285 return exc_val, exc_check
2287 c_arg_list_terminators = ('*', '**', '.', ')')
2289 def p_c_arg_list(s, ctx = Ctx(), in_pyfunc = 0, cmethod_flag = 0,
2290 nonempty_declarators = 0, kw_only = 0, annotated = 1):
2291 # Comma-separated list of C argument declarations, possibly empty.
2292 # May have a trailing comma.
2294 is_self_arg = cmethod_flag
2295 while s.sy not in c_arg_list_terminators:
2296 args.append(p_c_arg_decl(s, ctx, in_pyfunc, is_self_arg,
2297 nonempty = nonempty_declarators, kw_only = kw_only,
2298 annotated = annotated))
2305 def p_optional_ellipsis(s):
2312 def p_c_arg_decl(s, ctx, in_pyfunc, cmethod_flag = 0, nonempty = 0,
2313 kw_only = 0, annotated = 1):
2315 not_none = or_none = 0
2318 if s.in_python_file:
2319 # empty type declaration
2320 base_type = Nodes.CSimpleBaseTypeNode(pos,
2321 name = None, module_path = [],
2322 is_basic_c_type = 0, signed = 0,
2323 complex = 0, longness = 0,
2324 is_self_arg = cmethod_flag, templates = None)
2326 base_type = p_c_base_type(s, cmethod_flag, nonempty = nonempty)
2327 declarator = p_c_declarator(s, ctx, nonempty = nonempty)
2328 if s.sy in ('not', 'or') and not s.in_python_file:
2331 if s.sy == 'IDENT' and s.systring == 'None':
2334 s.error("Expected 'None'")
2336 error(pos, "'%s None' only allowed in Python functions" % kind)
2337 or_none = kind == 'or'
2338 not_none = kind == 'not'
2339 if annotated and s.sy == ':':
2341 annotation = p_test(s)
2344 if 'pxd' in s.level:
2345 if s.sy not in ['*', '?']:
2346 error(pos, "default values cannot be specified in pxd files, use ? or *")
2347 default = ExprNodes.BoolNode(1)
2351 return Nodes.CArgDeclNode(pos,
2352 base_type = base_type,
2353 declarator = declarator,
2354 not_none = not_none,
2357 annotation = annotation,
2361 if s.sy == 'IDENT' and s.systring == 'api':
2367 def p_cdef_statement(s, ctx):
2369 ctx.visibility = p_visibility(s, ctx.visibility)
2370 ctx.api = ctx.api or p_api(s)
2372 if ctx.visibility not in ('private', 'public'):
2373 error(pos, "Cannot combine 'api' with '%s'" % ctx.visibility)
2374 if (ctx.visibility == 'extern') and s.sy == 'from':
2375 return p_cdef_extern_block(s, pos, ctx)
2376 elif s.sy == 'import':
2378 return p_cdef_extern_block(s, pos, ctx)
2382 error(pos, "cdef blocks cannot be declared cpdef")
2383 return p_cdef_block(s, ctx)
2386 error(pos, "cdef blocks cannot be declared cpdef")
2387 return p_cdef_block(s, ctx)
2388 elif s.sy == 'class':
2389 if ctx.level not in ('module', 'module_pxd'):
2390 error(pos, "Extension type definition not allowed here")
2392 error(pos, "Extension types cannot be declared cpdef")
2393 return p_c_class_definition(s, pos, ctx)
2394 elif s.sy == 'IDENT' and s.systring == 'cppclass':
2395 if ctx.visibility != 'extern':
2396 error(pos, "C++ classes need to be declared extern")
2397 return p_cpp_class_definition(s, pos, ctx)
2398 elif s.sy == 'IDENT' and s.systring in ("struct", "union", "enum", "packed"):
2399 if ctx.level not in ('module', 'module_pxd'):
2400 error(pos, "C struct/union/enum definition not allowed here")
2402 error(pos, "C struct/union/enum cannot be declared cpdef")
2403 if s.systring == "enum":
2404 return p_c_enum_definition(s, pos, ctx)
2406 return p_c_struct_or_union_definition(s, pos, ctx)
2408 return p_c_func_or_var_declaration(s, pos, ctx)
2410 def p_cdef_block(s, ctx):
2411 return p_suite(s, ctx(cdef_flag = 1))
2413 def p_cdef_extern_block(s, pos, ctx):
2415 error(pos, "cdef extern blocks cannot be declared cpdef")
2421 include_file = p_string_literal(s, 'u')[2]
2422 ctx = ctx(cdef_flag = 1, visibility = 'extern')
2423 if s.systring == "namespace":
2425 ctx.namespace = p_string_literal(s, 'u')[2]
2428 body = p_suite(s, ctx)
2429 return Nodes.CDefExternNode(pos,
2430 include_file = include_file,
2432 namespace = ctx.namespace)
2434 def p_c_enum_definition(s, pos, ctx):
2435 # s.sy == ident 'enum'
2440 cname = p_opt_cname(s)
2441 if cname is None and ctx.namespace is not None:
2442 cname = ctx.namespace + "::" + name
2449 if s.sy != 'NEWLINE':
2450 p_c_enum_line(s, ctx, items)
2452 s.next() # 'NEWLINE'
2454 while s.sy not in ('DEDENT', 'EOF'):
2455 p_c_enum_line(s, ctx, items)
2457 return Nodes.CEnumDefNode(
2458 pos, name = name, cname = cname, items = items,
2459 typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2460 api = ctx.api, in_pxd = ctx.level == 'module_pxd')
2462 def p_c_enum_line(s, ctx, items):
2464 p_c_enum_item(s, ctx, items)
2467 if s.sy in ('NEWLINE', 'EOF'):
2469 p_c_enum_item(s, ctx, items)
2472 s.expect_newline("Syntax error in enum item list")
2474 def p_c_enum_item(s, ctx, items):
2477 cname = p_opt_cname(s)
2478 if cname is None and ctx.namespace is not None:
2479 cname = ctx.namespace + "::" + name
2484 items.append(Nodes.CEnumDefItemNode(pos,
2485 name = name, cname = cname, value = value))
2487 def p_c_struct_or_union_definition(s, pos, ctx):
2489 if s.systring == 'packed':
2492 if s.sy != 'IDENT' or s.systring != 'struct':
2493 s.expected('struct')
2494 # s.sy == ident 'struct' or 'union'
2498 cname = p_opt_cname(s)
2499 if cname is None and ctx.namespace is not None:
2500 cname = ctx.namespace + "::" + name
2508 while s.sy != 'DEDENT':
2511 p_c_func_or_var_declaration(s, s.position(), body_ctx))
2514 s.expect_newline("Expected a newline")
2517 s.expect_newline("Syntax error in struct or union definition")
2518 return Nodes.CStructOrUnionDefNode(pos,
2519 name = name, cname = cname, kind = kind, attributes = attributes,
2520 typedef_flag = ctx.typedef_flag, visibility = ctx.visibility,
2521 api = ctx.api, in_pxd = ctx.level == 'module_pxd', packed = packed)
2523 def p_visibility(s, prev_visibility):
2525 visibility = prev_visibility
2526 if s.sy == 'IDENT' and s.systring in ('extern', 'public', 'readonly'):
2527 visibility = s.systring
2528 if prev_visibility != 'private' and visibility != prev_visibility:
2529 s.error("Conflicting visibility options '%s' and '%s'"
2530 % (prev_visibility, visibility))
2534 def p_c_modifiers(s):
2535 if s.sy == 'IDENT' and s.systring in ('inline',):
2536 modifier = s.systring
2538 return [modifier] + p_c_modifiers(s)
2541 def p_c_func_or_var_declaration(s, pos, ctx):
2542 cmethod_flag = ctx.level in ('c_class', 'c_class_pxd')
2543 modifiers = p_c_modifiers(s)
2544 base_type = p_c_base_type(s, nonempty = 1, templates = ctx.templates)
2545 declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
2546 assignable = 1, nonempty = 1)
2547 declarator.overridable = ctx.overridable
2549 if ctx.level not in ('module', 'c_class', 'module_pxd', 'c_class_pxd') and not ctx.templates:
2550 s.error("C function definition not allowed here")
2551 doc, suite = p_suite(s, Ctx(level = 'function'), with_doc = 1)
2552 result = Nodes.CFuncDefNode(pos,
2553 visibility = ctx.visibility,
2554 base_type = base_type,
2555 declarator = declarator,
2558 modifiers = modifiers,
2560 overridable = ctx.overridable)
2563 # s.error("'api' not allowed with variable declaration")
2564 declarators = [declarator]
2567 if s.sy == 'NEWLINE':
2569 declarator = p_c_declarator(s, ctx, cmethod_flag = cmethod_flag,
2570 assignable = 1, nonempty = 1)
2571 declarators.append(declarator)
2572 s.expect_newline("Syntax error in C variable declaration")
2573 result = Nodes.CVarDefNode(pos,
2574 visibility = ctx.visibility,
2575 base_type = base_type,
2576 declarators = declarators,
2577 in_pxd = ctx.level == 'module_pxd',
2579 overridable = ctx.overridable)
2582 def p_ctypedef_statement(s, ctx):
2583 # s.sy == 'ctypedef'
2586 visibility = p_visibility(s, ctx.visibility)
2588 ctx = ctx(typedef_flag = 1, visibility = visibility)
2592 return p_c_class_definition(s, pos, ctx)
2593 elif s.sy == 'IDENT' and s.systring in ('packed', 'struct', 'union', 'enum'):
2594 if s.systring == 'enum':
2595 return p_c_enum_definition(s, pos, ctx)
2597 return p_c_struct_or_union_definition(s, pos, ctx)
2599 base_type = p_c_base_type(s, nonempty = 1)
2600 if base_type.name is None:
2601 s.error("Syntax error in ctypedef statement")
2602 declarator = p_c_declarator(s, ctx, is_type = 1, nonempty = 1)
2603 s.expect_newline("Syntax error in ctypedef statement")
2604 return Nodes.CTypeDefNode(
2605 pos, base_type = base_type,
2606 declarator = declarator,
2607 visibility = visibility, api = api,
2608 in_pxd = ctx.level == 'module_pxd')
2610 def p_decorators(s):
2612 while s.sy == 'DECORATOR':
2615 decstring = p_dotted_name(s, as_allowed=0)[2]
2616 names = decstring.split('.')
2617 decorator = ExprNodes.NameNode(pos, name=EncodedString(names[0]))
2618 for name in names[1:]:
2619 decorator = ExprNodes.AttributeNode(pos,
2620 attribute=EncodedString(name),
2623 decorator = p_call(s, decorator)
2624 decorators.append(Nodes.DecoratorNode(pos, decorator=decorator))
2625 s.expect_newline("Expected a newline after decorator")
2628 def p_def_statement(s, decorators=None):
2632 name = EncodedString( p_ident(s) )
2634 args, star_arg, starstar_arg = p_varargslist(s, terminator=')')
2637 error(pos, "Python function cannot be declared nogil")
2638 return_type_annotation = None
2641 return_type_annotation = p_test(s)
2642 doc, body = p_suite(s, Ctx(level = 'function'), with_doc = 1)
2643 return Nodes.DefNode(pos, name = name, args = args,
2644 star_arg = star_arg, starstar_arg = starstar_arg,
2645 doc = doc, body = body, decorators = decorators,
2646 return_type_annotation = return_type_annotation)
2648 def p_varargslist(s, terminator=')', annotated=1):
2649 args = p_c_arg_list(s, in_pyfunc = 1, nonempty_declarators = 1,
2650 annotated = annotated)
2656 star_arg = p_py_arg_decl(s, annotated=annotated)
2659 args.extend(p_c_arg_list(s, in_pyfunc = 1,
2660 nonempty_declarators = 1, kw_only = 1, annotated = annotated))
2661 elif s.sy != terminator:
2662 s.error("Syntax error in Python function argument list")
2665 starstar_arg = p_py_arg_decl(s, annotated=annotated)
2666 return (args, star_arg, starstar_arg)
2668 def p_py_arg_decl(s, annotated = 1):
2672 if annotated and s.sy == ':':
2674 annotation = p_test(s)
2675 return Nodes.PyArgDeclNode(pos, name = name, annotation = annotation)
2677 def p_class_statement(s, decorators):
2681 class_name = EncodedString( p_ident(s) )
2682 class_name.encoding = s.source_encoding
2687 positional_args, keyword_args, star_arg, starstar_arg = \
2688 p_call_parse_args(s, allow_genexp = False)
2689 arg_tuple, keyword_dict = p_call_build_packed_args(
2690 pos, positional_args, keyword_args, star_arg)
2691 if arg_tuple is None:
2692 # XXX: empty arg_tuple
2693 arg_tuple = ExprNodes.TupleNode(pos, args = [])
2694 doc, body = p_suite(s, Ctx(level = 'class'), with_doc = 1)
2695 return Nodes.PyClassDefNode(pos,
2698 keyword_args = keyword_dict,
2699 starstar_arg = starstar_arg,
2700 doc = doc, body = body, decorators = decorators)
2702 def p_c_class_definition(s, pos, ctx):
2706 class_name = p_ident(s)
2709 module_path.append(class_name)
2710 class_name = p_ident(s)
2711 if module_path and ctx.visibility != 'extern':
2712 error(pos, "Qualified class name only allowed for 'extern' C class")
2713 if module_path and s.sy == 'IDENT' and s.systring == 'as':
2715 as_name = p_ident(s)
2717 as_name = class_name
2718 objstruct_name = None
2720 base_class_module = None
2721 base_class_name = None
2724 base_class_path = [p_ident(s)]
2727 base_class_path.append(p_ident(s))
2729 s.error("C class may only have one base class")
2731 base_class_module = ".".join(base_class_path[:-1])
2732 base_class_name = base_class_path[-1]
2734 if ctx.visibility not in ('public', 'extern') and not ctx.api:
2735 error(s.position(), "Name options only allowed for 'public', 'api', or 'extern' C class")
2736 objstruct_name, typeobj_name = p_c_class_options(s)
2738 if ctx.level == 'module_pxd':
2739 body_level = 'c_class_pxd'
2741 body_level = 'c_class'
2742 doc, body = p_suite(s, Ctx(level = body_level), with_doc = 1)
2744 s.expect_newline("Syntax error in C class definition")
2747 if ctx.visibility == 'extern':
2749 error(pos, "Module name required for 'extern' C class")
2751 error(pos, "Type object name specification not allowed for 'extern' C class")
2752 elif ctx.visibility == 'public':
2753 if not objstruct_name:
2754 error(pos, "Object struct name specification required for 'public' C class")
2755 if not typeobj_name:
2756 error(pos, "Type object name specification required for 'public' C class")
2757 elif ctx.visibility == 'private':
2759 if not objstruct_name:
2760 error(pos, "Object struct name specification required for 'api' C class")
2761 if not typeobj_name:
2762 error(pos, "Type object name specification required for 'api' C class")
2764 error(pos, "Invalid class visibility '%s'" % ctx.visibility)
2765 return Nodes.CClassDefNode(pos,
2766 visibility = ctx.visibility,
2767 typedef_flag = ctx.typedef_flag,
2769 module_name = ".".join(module_path),
2770 class_name = class_name,
2772 base_class_module = base_class_module,
2773 base_class_name = base_class_name,
2774 objstruct_name = objstruct_name,
2775 typeobj_name = typeobj_name,
2776 in_pxd = ctx.level == 'module_pxd',
2780 def p_c_class_options(s):
2781 objstruct_name = None
2787 if s.systring == 'object':
2789 objstruct_name = p_ident(s)
2790 elif s.systring == 'type':
2792 typeobj_name = p_ident(s)
2796 s.expect(']', "Expected 'object' or 'type'")
2797 return objstruct_name, typeobj_name
2799 def p_property_decl(s):
2801 s.next() # 'property'
2803 doc, body = p_suite(s, Ctx(level = 'property'), with_doc = 1)
2804 return Nodes.PropertyNode(pos, name = name, doc = doc, body = body)
2806 def p_doc_string(s):
2807 if s.sy == 'BEGIN_STRING':
2809 kind, bytes_result, unicode_result = p_cat_string_literal(s)
2811 s.expect_newline("Syntax error in doc string")
2812 if kind in ('u', ''):
2813 return unicode_result
2814 warning(pos, "Python 3 requires docstrings to be unicode strings")
2819 def p_code(s, level=None):
2820 body = p_statement_list(s, Ctx(level = level), first_statement = 1)
2822 s.error("Syntax error in statement [%s,%s]" % (
2823 repr(s.sy), repr(s.systring)))
2826 COMPILER_DIRECTIVE_COMMENT_RE = re.compile(r"^#\s*cython\s*:\s*((\w|[.])+\s*=.*)$")
2828 def p_compiler_directive_comments(s):
2830 while s.sy == 'commentline':
2831 m = COMPILER_DIRECTIVE_COMMENT_RE.match(s.systring)
2833 directives = m.group(1).strip()
2835 result.update( Options.parse_directive_list(
2836 directives, ignore_unknown=True) )
2837 except ValueError, e:
2838 s.error(e.args[0], fatal=False)
2842 def p_module(s, pxd, full_module_name):
2845 directive_comments = p_compiler_directive_comments(s)
2846 s.parse_comments = False
2848 if 'language_level' in directive_comments:
2849 s.context.set_language_level(directive_comments['language_level'])
2851 doc = p_doc_string(s)
2853 level = 'module_pxd'
2857 body = p_statement_list(s, Ctx(level = level), first_statement = 1)
2859 s.error("Syntax error in statement [%s,%s]" % (
2860 repr(s.sy), repr(s.systring)))
2861 return ModuleNode(pos, doc = doc, body = body,
2862 full_module_name = full_module_name,
2863 directive_comments = directive_comments)
2865 def p_cpp_class_definition(s, pos, ctx):
2866 # s.sy == 'cppclass'
2869 class_name = p_ident(s)
2870 cname = p_opt_cname(s)
2871 if cname is None and ctx.namespace is not None:
2872 cname = ctx.namespace + "::" + class_name
2874 error(pos, "Qualified class name not allowed C++ class")
2877 templates = [p_ident(s)]
2880 templates.append(p_ident(s))
2886 base_classes = [p_dotted_name(s, False)[2]]
2889 base_classes.append(p_dotted_name(s, False)[2])
2894 error(s.position(), "Name options not allowed for C++ class")
2900 body_ctx = Ctx(visibility = ctx.visibility)
2901 body_ctx.templates = templates
2902 while s.sy != 'DEDENT':
2903 if s.systring == 'cppclass':
2905 p_cpp_class_definition(s, s.position(), body_ctx))
2906 elif s.sy != 'pass':
2908 p_c_func_or_var_declaration(s, s.position(), body_ctx))
2911 s.expect_newline("Expected a newline")
2915 s.expect_newline("Syntax error in C++ class definition")
2916 return Nodes.CppClassNode(pos,
2919 base_classes = base_classes,
2920 visibility = ctx.visibility,
2921 in_pxd = ctx.level == 'module_pxd',
2922 attributes = attributes,
2923 templates = templates)
2927 #----------------------------------------------
2931 #----------------------------------------------
2933 def print_parse_tree(f, node, level, key = None):
2934 from types import ListType, TupleType
2935 from Nodes import Node
2940 f.write("%s: " % key)
2943 f.write("(%s @ %s\n" % (node[0], node[1]))
2944 for i in xrange(2, len(node)):
2945 print_parse_tree(f, node[i], level+1)
2946 f.write("%s)\n" % ind)
2948 elif isinstance(node, Node):
2951 except AttributeError:
2952 tag = node.__class__.__name__
2953 f.write("%s @ %s\n" % (tag, node.pos))
2954 for name, value in node.__dict__.items():
2955 if name != 'tag' and name != 'pos':
2956 print_parse_tree(f, value, level+1, name)
2960 for i in xrange(len(node)):
2961 print_parse_tree(f, node[i], level+1)
2962 f.write("%s]\n" % ind)
2964 f.write("%s%s\n" % (ind, node))