6 from string import join, replace
7 from types import ListType, TupleType
8 from Scanning import PyrexScanner
11 from ModuleNode import ModuleNode
12 from Errors import error, InternalError
14 def p_ident(s, message = "Expected an identifier"):
24 while s.sy == 'IDENT':
25 names.append(s.systring)
32 #------------------------------------------
36 #------------------------------------------
38 def p_binop_expr(s, ops, p_sub_expr):
39 #print "p_binop_expr:", ops, p_sub_expr ###
41 #print "p_binop_expr(%s):" % p_sub_expr, s.sy ###
47 n1 = ExprNodes.binop_node(pos, op, n1, n2)
50 #expression: or_test [if or_test else test] | lambda_form
61 return ExprNodes.CondExprNode(pos, test=test, true_val=expr, false_val=other)
63 s.error("Expected 'else'")
67 #test: or_test | lambda_form
72 #or_test: and_test ('or' and_test)*
75 #return p_binop_expr(s, ('or',), p_and_test)
76 return p_rassoc_binop_expr(s, ('or',), p_and_test)
78 def p_rassoc_binop_expr(s, ops, p_subexpr):
84 n2 = p_rassoc_binop_expr(s, ops, p_subexpr)
85 n1 = ExprNodes.binop_node(pos, op, n1, n2)
88 #and_test: not_test ('and' not_test)*
91 #return p_binop_expr(s, ('and',), p_not_test)
92 return p_rassoc_binop_expr(s, ('and',), p_not_test)
94 #not_test: 'not' not_test | comparison
100 return ExprNodes.NotNode(pos, operand = p_not_test(s))
102 return p_comparison(s)
104 #comparison: expr (comp_op expr)*
105 #comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
109 if s.sy in comparison_ops:
113 n1 = ExprNodes.PrimaryCmpNode(pos,
114 operator = op, operand1 = n1, operand2 = n2)
115 if s.sy in comparison_ops:
116 n1.cascade = p_cascaded_cmp(s)
119 def p_cascaded_cmp(s):
123 result = ExprNodes.CascadedCmpNode(pos,
124 operator = op, operand2 = n2)
125 if s.sy in comparison_ops:
126 result.cascade = p_cascaded_cmp(s)
149 '<', '>', '==', '>=', '<=', '<>', '!=',
153 #expr: xor_expr ('|' xor_expr)*
156 return p_binop_expr(s, ('|',), p_xor_expr)
158 #xor_expr: and_expr ('^' and_expr)*
161 return p_binop_expr(s, ('^',), p_and_expr)
163 #and_expr: shift_expr ('&' shift_expr)*
166 return p_binop_expr(s, ('&',), p_shift_expr)
168 #shift_expr: arith_expr (('<<'|'>>') arith_expr)*
171 return p_binop_expr(s, ('<<', '>>'), p_arith_expr)
173 #arith_expr: term (('+'|'-') term)*
176 return p_binop_expr(s, ('+', '-'), p_term)
178 #term: factor (('*'|'/'|'%') factor)*
181 return p_binop_expr(s, ('*', '/', '%', '//'), p_factor)
183 #factor: ('+'|'-'|'~'|'&'|typecast|sizeof) factor | power
187 if sy in ('+', '-', '~'):
191 return ExprNodes.unop_node(pos, op, p_factor(s))
196 return ExprNodes.AmpersandNode(pos, operand = arg)
199 elif sy == 'IDENT' and s.systring == "sizeof":
208 base_type = p_c_base_type(s)
209 declarator = p_c_declarator(s, empty = 1)
216 operand = p_factor(s)
217 return ExprNodes.TypecastNode(pos,
218 base_type = base_type,
219 declarator = declarator,
221 typecheck = typecheck)
224 # s.sy == ident "sizeof"
228 if looking_at_type(s) or looking_at_dotted_name(s):
229 base_type = p_c_base_type(s)
230 declarator = p_c_declarator(s, empty = 1)
231 node = ExprNodes.SizeofTypeNode(pos,
232 base_type = base_type, declarator = declarator)
234 operand = p_simple_expr(s)
235 node = ExprNodes.SizeofVarNode(pos, operand = operand)
239 #power: atom trailer* ('**' factor)*
243 while s.sy in ('(', '[', '.'):
244 n1 = p_trailer(s, n1)
249 n1 = ExprNodes.binop_node(pos, '**', n1, n2)
252 #trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
254 def p_trailer(s, node1):
257 return p_call(s, node1)
259 return p_index(s, node1)
263 return ExprNodes.AttributeNode(pos,
264 obj = node1, attribute = name)
266 # arglist: argument (',' argument)* [',']
267 # argument: [test '='] test # Really [keyword '='] test
269 def p_call(s, function):
277 while s.sy not in ('*', '**', ')'):
278 arg = p_simple_expr(s)
282 s.error("Expected an identifier before '='",
284 keyword = ExprNodes.StringNode(arg.pos,
286 arg = p_simple_expr(s)
287 keyword_args.append((keyword, arg))
290 s.error("Non-keyword arg following keyword arg",
292 positional_args.append(arg)
298 star_arg = p_simple_expr(s)
303 starstar_arg = p_simple_expr(s)
307 if not (keyword_args or star_arg or starstar_arg):
308 return ExprNodes.SimpleCallNode(pos,
310 args = positional_args)
314 if positional_args or not star_arg:
315 arg_tuple = ExprNodes.TupleNode(pos,
316 args = positional_args)
318 star_arg_tuple = ExprNodes.AsTupleNode(pos, arg = star_arg)
320 arg_tuple = ExprNodes.binop_node(pos,
321 operator = '+', operand1 = arg_tuple,
322 operand2 = star_arg_tuple)
324 arg_tuple = star_arg_tuple
326 keyword_dict = ExprNodes.DictNode(pos,
327 key_value_pairs = keyword_args)
328 return ExprNodes.GeneralCallNode(pos,
330 positional_args = arg_tuple,
331 keyword_args = keyword_dict,
332 starstar_arg = starstar_arg)
334 #lambdef: 'lambda' [varargslist] ':' test
336 #subscriptlist: subscript (',' subscript)* [',']
338 def p_index(s, base):
342 subscripts = p_subscript_list(s)
343 if len(subscripts) == 1 and len(subscripts[0]) == 2:
344 start, stop = subscripts[0]
345 result = ExprNodes.SliceIndexNode(pos,
346 base = base, start = start, stop = stop)
348 indexes = make_slice_nodes(pos, subscripts)
349 if len(indexes) == 1:
352 index = ExprNodes.TupleNode(pos, args = indexes)
353 result = ExprNodes.IndexNode(pos,
354 base = base, index = index)
358 def p_subscript_list(s):
359 items = [p_subscript(s)]
364 items.append(p_subscript(s))
367 #subscript: '.' '.' '.' | test | [test] ':' [test] [':' [test]]
370 # Parse a subscript and return a list of
371 # 1, 2 or 3 ExprNodes, depending on how
372 # many slice elements were encountered.
376 return [ExprNodes.EllipsisNode(pos)]
378 start = p_slice_element(s, (':',))
382 stop = p_slice_element(s, (':', ',', ']'))
386 step = p_slice_element(s, (':', ',', ']'))
387 return [start, stop, step]
389 def p_slice_element(s, follow_set):
390 # Simple expression which may be missing iff
391 # it is followed by something in follow_set.
392 if s.sy not in follow_set:
393 return p_simple_expr(s)
397 def expect_ellipsis(s):
402 def make_slice_nodes(pos, subscripts):
403 # Convert a list of subscripts as returned
404 # by p_subscript_list into a list of ExprNodes,
405 # creating SliceNodes for elements with 2 or
408 for subscript in subscripts:
409 if len(subscript) == 1:
410 result.append(subscript[0])
412 result.append(make_slice_node(pos, *subscript))
415 def make_slice_node(pos, start, stop = None, step = None):
417 start = ExprNodes.NoneNode(pos)
419 stop = ExprNodes.NoneNode(pos)
421 step = ExprNodes.NoneNode(pos)
422 return ExprNodes.SliceNode(pos,
423 start = start, stop = stop, step = step)
425 #atom: '(' [testlist] ')' | '[' [listmaker] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+
433 result = ExprNodes.TupleNode(pos, args = [])
439 return p_list_maker(s)
441 return p_dict_maker(s)
443 return p_backquote_expr(s)
447 return ExprNodes.IntNode(pos, value = value)
451 return ExprNodes.LongNode(pos, value = value)
455 return ExprNodes.FloatNode(pos, value = value)
457 value = s.systring[:-1]
459 return ExprNodes.ImagNode(pos, value = value)
460 elif sy == 'STRING' or sy == 'BEGIN_STRING':
461 kind, value = p_cat_string_literal(s)
463 return ExprNodes.CharNode(pos, value = value)
465 return ExprNodes.StringNode(pos, value = value)
470 return ExprNodes.NoneNode(pos)
472 return ExprNodes.BoolNode(pos, value=1)
473 elif name == "False":
474 return ExprNodes.BoolNode(pos, value=0)
476 return p_name(s, name)
479 return ExprNodes.NullNode(pos)
481 s.error("Expected an identifier or literal")
485 if not s.compile_time_expr:
487 value = s.compile_time_env.lookup_here(name)
492 if isinstance(value, int):
493 return ExprNodes.IntNode(pos, value = rep)
494 elif isinstance(value, long):
495 return ExprNodes.LongNode(pos, value = rep)
496 elif isinstance(value, float):
497 return ExprNodes.FloatNode(pos, value = rep)
498 elif isinstance(value, str):
499 return ExprNodes.StringNode(pos, value = rep[1:-1])
501 error(pos, "Invalid type for compile-time constant: %s"
502 % value.__class__.__name__)
503 return ExprNodes.NameNode(pos, name = name)
505 def p_cat_string_literal(s):
506 # A sequence of one or more adjacent string literals.
507 # Returns (kind, value) where kind in ('', 'c', 'r')
508 kind, value = p_string_literal(s)
511 while s.sy == 'STRING' or s.sy == 'BEGIN_STRING':
512 next_kind, next_value = p_string_literal(s)
515 "Cannot concatenate char literal with another string or char literal")
516 strings.append(next_value)
517 value = ''.join(strings)
520 def p_opt_string_literal(s):
521 if s.sy == 'STRING' or s.sy == 'BEGIN_STRING':
522 return p_string_literal(s)
526 def p_string_literal(s):
527 # A single string or char literal.
528 # Returns (kind, value) where kind in ('', 'c', 'r', 'u')
530 value = unquote(s.systring)
533 # s.sy == 'BEGIN_STRING'
535 #is_raw = s.systring[:1].lower() == "r"
536 kind = s.systring[:1].lower()
537 if kind not in "cru":
543 #print "p_string_literal: sy =", sy, repr(s.systring) ###
546 if len(systr) == 1 and systr in "'\"\n":
548 if kind == 'u' and not isinstance(systr, unicode):
549 systr = systr.decode("UTF-8")
555 chars.append(r'\\\n')
557 chars.append(r'\\\"')
559 chars.append(r'\\\\')
561 chars.append('\\' + systr)
564 if c in "'\"\\abfnrtv01234567":
567 chars.append('\\x0' + systr[2:])
573 chars.append(r'\\' + systr[1:])
574 elif sy == 'NEWLINE':
576 elif sy == 'END_STRING':
579 s.error("Unclosed string literal", pos = pos)
582 "Unexpected token %r:%r in string literal" %
586 value = u''.join(chars)
588 value = ''.join(chars)
589 #print "p_string_literal: value =", repr(value) ###
594 if s[:1].lower() == "r":
598 if q == '"""' or q == "'''":
603 s = s.replace('\\', '\\\\')
604 s = s.replace('\n', '\\\n')
606 # Split into double quotes, newlines, escape sequences
607 # and spans of regular chars
608 l1 = re.split(r'((?:\\[0-7]{1,3})|(?:\\x[0-9A-Fa-f]{2})|(?:\\.)|(?:\\\n)|(?:\n)|")', s)
609 print "unquote: l1 =", l1 ###
612 if item == '"' or item == '\n':
613 l2.append('\\' + item)
616 elif item[:1] == '\\':
618 if item[1] in '"\\abfnrtv':
622 elif item[1:2] == 'x':
623 l2.append('\\x0' + item[2:])
632 # list_display ::= "[" [listmaker] "]"
633 # listmaker ::= expression ( list_for | ( "," expression )* [","] )
634 # list_iter ::= list_for | list_if
635 # list_for ::= "for" expression_list "in" testlist [list_iter]
636 # list_if ::= "if" test [list_iter]
644 return ExprNodes.ListNode(pos, args = [])
645 expr = p_simple_expr(s)
650 while not isinstance(inner_loop.body, Nodes.PassStatNode):
651 inner_loop = inner_loop.body
652 if isinstance(inner_loop, Nodes.IfStatNode):
653 inner_loop = inner_loop.if_clauses[0]
654 append = ExprNodes.ListComprehensionAppendNode( pos, expr = expr )
655 inner_loop.body = Nodes.ExprStatNode(pos, expr = append)
656 return ExprNodes.ListComprehensionNode(pos, loop = loop, append = append)
661 exprs += p_simple_expr_list(s)
663 return ExprNodes.ListNode(pos, args = exprs)
671 return Nodes.PassStatNode(s.position())
678 kw['else_clause'] = None
679 kw['body'] = p_list_iter(s)
680 return Nodes.ForStatNode(pos, **kw)
687 return Nodes.IfStatNode(pos,
688 if_clauses = [Nodes.IfClauseNode(pos, condition = test, body = p_list_iter(s))],
691 #dictmaker: test ':' test (',' test ':' test)* [',']
699 key = p_simple_expr(s)
701 value = p_simple_expr(s)
702 items.append((key, value))
707 return ExprNodes.DictNode(pos, key_value_pairs = items)
709 def p_backquote_expr(s):
715 return ExprNodes.BackquoteNode(pos, arg = arg)
717 def p_simple_expr_list(s):
719 while s.sy not in expr_terminators:
720 exprs.append(p_simple_expr(s))
728 expr = p_simple_expr(s)
731 exprs = [expr] + p_simple_expr_list(s)
732 return ExprNodes.TupleNode(pos, args = exprs)
737 #testlist: test (',' test)* [',']
738 # differs from p_expr only in the fact that it cannot contain conditional expressions
747 exprs.append(p_test(s))
748 return ExprNodes.TupleNode(pos, args = exprs)
752 expr_terminators = (')', ']', '}', ':', '=', 'NEWLINE')
754 #-------------------------------------------------------
758 #-------------------------------------------------------
760 def p_global_statement(s):
761 # assume s.sy == 'global'
764 names = p_ident_list(s)
765 return Nodes.GlobalNode(pos, names = names)
767 def p_expression_or_assignment(s):
768 expr_list = [p_expr(s)]
771 expr_list.append(p_expr(s))
772 if len(expr_list) == 1:
773 if re.match("[+*/\%^\&|-]=", s.sy):
775 if not isinstance(lhs, (ExprNodes.AttributeNode, ExprNodes.IndexNode, ExprNodes.NameNode) ):
776 error(lhs.pos, "Illegal operand for inplace operation.")
780 return Nodes.InPlaceAssignmentNode(lhs.pos, operator = operator, lhs = lhs, rhs = rhs)
782 if isinstance(expr, ExprNodes.StringNode):
783 return Nodes.PassStatNode(expr.pos)
785 return Nodes.ExprStatNode(expr.pos, expr = expr)
788 flatten_parallel_assignments(expr_list, expr_list_list)
790 for expr_list in expr_list_list:
791 lhs_list = expr_list[:-1]
793 if len(lhs_list) == 1:
794 node = Nodes.SingleAssignmentNode(rhs.pos,
795 lhs = lhs_list[0], rhs = rhs)
797 node = Nodes.CascadedAssignmentNode(rhs.pos,
798 lhs_list = lhs_list, rhs = rhs)
803 return Nodes.ParallelAssignmentNode(nodes[0].pos, stats = nodes)
805 def flatten_parallel_assignments(input, output):
806 # The input is a list of expression nodes, representing
807 # the LHSs and RHS of one (possibly cascaded) assignment
808 # statement. If they are all sequence constructors with
809 # the same number of arguments, rearranges them into a
810 # list of equivalent assignments between the individual
811 # elements. This transformation is applied recursively.
812 size = find_parallel_assignment_size(input)
814 for i in range(size):
815 new_exprs = [expr.args[i] for expr in input]
816 flatten_parallel_assignments(new_exprs, output)
820 def find_parallel_assignment_size(input):
821 # The input is a list of expression nodes. If
822 # they are all sequence constructors with the same number
823 # of arguments, return that number, else return -1.
824 # Produces an error message if they are all sequence
825 # constructors but not all the same size.
827 if not expr.is_sequence_constructor:
830 rhs_size = len(rhs.args)
831 for lhs in input[:-1]:
832 lhs_size = len(lhs.args)
833 if lhs_size <> rhs_size:
834 error(lhs.pos, "Unpacking sequence of wrong size (expected %d, got %d)"
835 % (lhs_size, rhs_size))
839 def p_print_statement(s):
844 s.error("'print >>' not yet implemented")
847 if s.sy not in ('NEWLINE', 'EOF'):
848 args.append(p_simple_expr(s))
851 if s.sy in ('NEWLINE', 'EOF'):
854 args.append(p_simple_expr(s))
855 return Nodes.PrintStatNode(pos,
856 args = args, ends_with_comma = ewc)
858 def p_del_statement(s):
862 args = p_simple_expr_list(s)
863 return Nodes.DelStatNode(pos, args = args)
865 def p_pass_statement(s, with_newline = 0):
869 s.expect_newline("Expected a newline")
870 return Nodes.PassStatNode(pos)
872 def p_break_statement(s):
876 return Nodes.BreakStatNode(pos)
878 def p_continue_statement(s):
882 return Nodes.ContinueStatNode(pos)
884 def p_return_statement(s):
888 if s.sy not in statement_terminators:
892 return Nodes.ReturnStatNode(pos, value = value)
894 def p_raise_statement(s):
901 if s.sy not in statement_terminators:
902 exc_type = p_simple_expr(s)
905 exc_value = p_simple_expr(s)
908 exc_tb = p_simple_expr(s)
909 if exc_type or exc_value or exc_tb:
910 return Nodes.RaiseStatNode(pos,
912 exc_value = exc_value,
915 return Nodes.ReraiseStatNode(pos)
917 def p_import_statement(s):
918 # s.sy in ('import', 'cimport')
922 items = [p_dotted_name(s, as_allowed = 1)]
925 items.append(p_dotted_name(s, as_allowed = 1))
927 for pos, target_name, dotted_name, as_name in items:
928 if kind == 'cimport':
929 stat = Nodes.CImportStatNode(pos,
930 module_name = dotted_name,
933 if as_name and "." in dotted_name:
934 name_list = ExprNodes.ListNode(pos, args = [
935 ExprNodes.StringNode(pos, value = "*")])
938 stat = Nodes.SingleAssignmentNode(pos,
939 lhs = ExprNodes.NameNode(pos,
940 name = as_name or target_name),
941 rhs = ExprNodes.ImportNode(pos,
942 module_name = ExprNodes.StringNode(pos,
943 value = dotted_name),
944 name_list = name_list))
946 return Nodes.StatListNode(pos, stats = stats)
948 def p_from_import_statement(s):
952 (dotted_name_pos, _, dotted_name, _) = \
953 p_dotted_name(s, as_allowed = 0)
954 if s.sy in ('import', 'cimport'):
958 s.error("Expected 'import' or 'cimport'")
960 s.error("'import *' not supported")
961 imported_names = [p_imported_name(s)]
964 imported_names.append(p_imported_name(s))
965 if kind == 'cimport':
966 for (name_pos, name, as_name) in imported_names:
967 local_name = as_name or name
968 s.add_type_name(local_name)
969 return Nodes.FromCImportStatNode(pos,
970 module_name = dotted_name,
971 imported_names = imported_names)
973 imported_name_strings = []
975 for (name_pos, name, as_name) in imported_names:
976 imported_name_strings.append(
977 ExprNodes.StringNode(name_pos, value = name))
980 ExprNodes.NameNode(name_pos,
981 name = as_name or name)))
982 import_list = ExprNodes.ListNode(
983 imported_names[0][0], args = imported_name_strings)
984 return Nodes.FromImportStatNode(pos,
985 module = ExprNodes.ImportNode(dotted_name_pos,
986 module_name = ExprNodes.StringNode(dotted_name_pos,
987 value = dotted_name),
988 name_list = import_list),
991 def p_imported_name(s):
994 as_name = p_as_name(s)
995 return (pos, name, as_name)
997 def p_dotted_name(s, as_allowed):
999 target_name = p_ident(s)
1001 names = [target_name]
1004 names.append(p_ident(s))
1006 as_name = p_as_name(s)
1007 return (pos, target_name, join(names, "."), as_name)
1010 if s.sy == 'IDENT' and s.systring == 'as':
1016 def p_assert_statement(s):
1020 cond = p_simple_expr(s)
1023 value = p_simple_expr(s)
1026 return Nodes.AssertStatNode(pos, cond = cond, value = value)
1028 statement_terminators = (';', 'NEWLINE', 'EOF')
1030 def p_if_statement(s):
1034 if_clauses = [p_if_clause(s)]
1035 while s.sy == 'elif':
1037 if_clauses.append(p_if_clause(s))
1038 else_clause = p_else_clause(s)
1039 return Nodes.IfStatNode(pos,
1040 if_clauses = if_clauses, else_clause = else_clause)
1044 test = p_simple_expr(s)
1046 return Nodes.IfClauseNode(pos,
1047 condition = test, body = body)
1049 def p_else_clause(s):
1056 def p_while_statement(s):
1060 test = p_simple_expr(s)
1062 else_clause = p_else_clause(s)
1063 return Nodes.WhileStatNode(pos,
1064 condition = test, body = body,
1065 else_clause = else_clause)
1067 def p_for_statement(s):
1071 kw = p_for_bounds(s)
1072 kw['body'] = p_suite(s)
1073 kw['else_clause'] = p_else_clause(s)
1074 return Nodes.ForStatNode(pos, **kw)
1076 def p_for_bounds(s):
1077 target = p_for_target(s)
1080 iterator = p_for_iterator(s)
1081 return { 'target': target, 'iterator': iterator }
1082 elif s.sy == 'from':
1084 bound1 = p_bit_expr(s)
1085 rel1 = p_for_from_relation(s)
1086 name2_pos = s.position()
1088 rel2_pos = s.position()
1089 rel2 = p_for_from_relation(s)
1090 bound2 = p_bit_expr(s)
1091 step = p_for_from_step(s)
1092 if not target.is_name:
1094 "Target of for-from statement must be a variable name")
1095 elif name2 <> target.name:
1097 "Variable name in for-from range does not match target")
1098 if rel1[0] <> rel2[0]:
1100 "Relation directions in for-from do not match")
1101 return {'target': target,
1108 def p_for_from_relation(s):
1109 if s.sy in inequality_relations:
1114 s.error("Expected one of '<', '<=', '>' '>='")
1116 def p_for_from_step(s):
1119 step = p_bit_expr(s)
1124 inequality_relations = ('<', '<=', '>', '>=')
1126 def p_for_target(s):
1128 expr = p_bit_expr(s)
1133 exprs.append(p_bit_expr(s))
1137 return ExprNodes.TupleNode(pos, args = exprs)
1141 def p_for_iterator(s):
1143 expr = p_testlist(s)
1144 return ExprNodes.IteratorNode(pos, sequence = expr)
1146 def p_try_statement(s):
1153 if s.sy in ('except', 'else'):
1154 while s.sy == 'except':
1155 except_clauses.append(p_except_clause(s))
1158 else_clause = p_suite(s)
1159 return Nodes.TryExceptStatNode(pos,
1160 body = body, except_clauses = except_clauses,
1161 else_clause = else_clause)
1162 elif s.sy == 'finally':
1164 finally_clause = p_suite(s)
1165 return Nodes.TryFinallyStatNode(pos,
1166 body = body, finally_clause = finally_clause)
1168 s.error("Expected 'except' or 'finally'")
1170 def p_except_clause(s):
1177 exc_type = p_simple_expr(s)
1180 exc_value = p_simple_expr(s)
1182 return Nodes.ExceptClauseNode(pos,
1183 pattern = exc_type, target = exc_value, body = body)
1185 def p_include_statement(s, level):
1187 s.next() # 'include'
1188 _, include_file_name = p_string_literal(s)
1189 s.expect_newline("Syntax error in include statement")
1190 if s.compile_time_eval:
1191 include_file_path = s.context.find_include_file(include_file_name, pos)
1192 if include_file_path:
1193 f = open(include_file_path, "rU")
1194 s2 = PyrexScanner(f, include_file_path, s)
1196 tree = p_statement_list(s2, level)
1203 return Nodes.PassStatNode(pos)
1205 def p_with_statement(s):
1208 # if s.sy == 'IDENT' and s.systring in ('gil', 'nogil'):
1209 if s.sy == 'IDENT' and s.systring == 'nogil':
1213 return Nodes.GILStatNode(pos, state = state, body = body)
1215 s.error("Only 'with gil' and 'with nogil' implemented",
1218 def p_simple_statement(s):
1219 #print "p_simple_statement:", s.sy, s.systring ###
1220 if s.sy == 'global':
1221 node = p_global_statement(s)
1222 elif s.sy == 'print':
1223 node = p_print_statement(s)
1225 node = p_del_statement(s)
1226 elif s.sy == 'break':
1227 node = p_break_statement(s)
1228 elif s.sy == 'continue':
1229 node = p_continue_statement(s)
1230 elif s.sy == 'return':
1231 node = p_return_statement(s)
1232 elif s.sy == 'raise':
1233 node = p_raise_statement(s)
1234 elif s.sy in ('import', 'cimport'):
1235 node = p_import_statement(s)
1236 elif s.sy == 'from':
1237 node = p_from_import_statement(s)
1238 elif s.sy == 'assert':
1239 node = p_assert_statement(s)
1240 elif s.sy == 'pass':
1241 node = p_pass_statement(s)
1243 node = p_expression_or_assignment(s)
1246 def p_simple_statement_list(s):
1247 # Parse a series of simple statements on one line
1248 # separated by semicolons.
1249 stat = p_simple_statement(s)
1253 #print "p_simple_statement_list: maybe more to follow" ###
1255 if s.sy in ('NEWLINE', 'EOF'):
1257 stats.append(p_simple_statement(s))
1258 stat = Nodes.StatListNode(stats[0].pos, stats = stats)
1259 s.expect_newline("Syntax error in simple statement list")
1262 def p_compile_time_expr(s):
1263 old = s.compile_time_expr
1264 s.compile_time_expr = 1
1266 s.compile_time_expr = old
1269 def p_DEF_statement(s):
1271 denv = s.compile_time_env
1275 expr = p_compile_time_expr(s)
1276 value = expr.compile_time_value(denv)
1277 #print "p_DEF_statement: %s = %r" % (name, value) ###
1278 denv.declare(name, value)
1280 return Nodes.PassStatNode(pos)
1282 def p_IF_statement(s, level, cdef_flag, visibility, api):
1284 saved_eval = s.compile_time_eval
1285 current_eval = saved_eval
1286 denv = s.compile_time_env
1289 s.next() # 'IF' or 'ELIF'
1290 expr = p_compile_time_expr(s)
1291 s.compile_time_eval = current_eval and bool(expr.compile_time_value(denv))
1292 body = p_suite(s, level, cdef_flag, visibility, api = api)
1293 if s.compile_time_eval:
1300 s.compile_time_eval = current_eval
1301 body = p_suite(s, level, cdef_flag, visibility, api = api)
1305 result = Nodes.PassStatNode(pos)
1306 s.compile_time_eval = saved_eval
1309 def p_statement(s, level, cdef_flag = 0, visibility = 'private', api = 0):
1310 if s.sy == 'ctypedef':
1311 if level not in ('module', 'module_pxd'):
1312 s.error("ctypedef statement not allowed here")
1314 error(s.position(), "'api' not allowed with 'ctypedef'")
1315 return p_ctypedef_statement(s, level, visibility, api)
1317 return p_DEF_statement(s)
1319 return p_IF_statement(s, level, cdef_flag, visibility, api)
1330 if level not in ('module', 'module_pxd', 'function', 'c_class', 'c_class_pxd'):
1331 s.error('cdef statement not allowed here')
1333 return p_cdef_statement(s, level, visibility = visibility,
1334 api = api, overridable = overridable)
1335 # elif s.sy == 'cpdef':
1337 # return p_c_func_or_var_declaration(s, level, s.position(), visibility = visibility, api = api, overridable = True)
1340 error(s.pos, "'api' not allowed with this statement")
1342 if level not in ('module', 'class', 'c_class', 'property'):
1343 s.error('def statement not allowed here')
1345 return p_def_statement(s)
1346 elif s.sy == 'class':
1347 if level <> 'module':
1348 s.error("class definition not allowed here")
1349 return p_class_statement(s)
1350 elif s.sy == 'include':
1351 if level not in ('module', 'module_pxd'):
1352 s.error("include statement not allowed here")
1353 return p_include_statement(s, level)
1354 elif level == 'c_class' and s.sy == 'IDENT' and s.systring == 'property':
1355 return p_property_decl(s)
1356 elif s.sy == 'pass' and level <> 'property':
1357 return p_pass_statement(s, with_newline = 1)
1359 if level in ('c_class_pxd', 'property'):
1360 s.error("Executable statement not allowed here")
1362 return p_if_statement(s)
1363 elif s.sy == 'while':
1364 return p_while_statement(s)
1366 return p_for_statement(s)
1368 return p_try_statement(s)
1369 elif s.sy == 'with':
1370 return p_with_statement(s)
1372 return p_simple_statement_list(s)
1374 def p_statement_list(s, level,
1375 cdef_flag = 0, visibility = 'private', api = 0):
1376 # Parse a series of statements separated by newlines.
1379 while s.sy not in ('DEDENT', 'EOF'):
1380 stats.append(p_statement(s, level,
1381 cdef_flag = cdef_flag, visibility = visibility, api = api))
1385 return Nodes.StatListNode(pos, stats = stats)
1387 def p_suite(s, level = 'other', cdef_flag = 0,
1388 visibility = 'private', with_doc = 0, with_pseudo_doc = 0, api = 0):
1393 if s.sy == 'NEWLINE':
1396 if with_doc or with_pseudo_doc:
1397 doc = p_doc_string(s)
1398 body = p_statement_list(s,
1400 cdef_flag = cdef_flag,
1401 visibility = visibility,
1406 error(s.pos, "'api' not allowed with this statement")
1407 if level in ('module', 'class', 'function', 'other'):
1408 body = p_simple_statement_list(s)
1410 body = p_pass_statement(s)
1411 s.expect_newline("Syntax error in declarations")
1417 def p_c_base_type(s, self_flag = 0):
1418 # If self_flag is true, this is the base type for the
1419 # self argument of a C method of an extension type.
1421 return p_c_complex_base_type(s)
1423 return p_c_simple_base_type(s, self_flag)
1425 def p_calling_convention(s):
1426 if s.sy == 'IDENT' and s.systring in calling_convention_words:
1433 calling_convention_words = ("__stdcall", "__cdecl")
1435 def p_c_complex_base_type(s):
1439 base_type = p_c_base_type(s)
1440 declarator = p_c_declarator(s, empty = 1)
1442 return Nodes.CComplexBaseTypeNode(pos,
1443 base_type = base_type, declarator = declarator)
1445 def p_c_simple_base_type(s, self_flag):
1446 #print "p_c_simple_base_type: self_flag =", self_flag
1452 if looking_at_base_type(s):
1453 #print "p_c_simple_base_type: looking_at_base_type at", s.position()
1455 signed, longness = p_sign_and_longness(s)
1456 if s.sy == 'IDENT' and s.systring in basic_c_type_names:
1461 elif s.looking_at_type_name() or looking_at_dotted_name(s):
1462 #print "p_c_simple_base_type: looking_at_type_name at", s.position()
1466 module_path.append(name)
1470 #print "p_c_simple_base_type: not looking at type at", s.position()
1472 return Nodes.CSimpleBaseTypeNode(pos,
1473 name = name, module_path = module_path,
1474 is_basic_c_type = is_basic, signed = signed,
1475 longness = longness, is_self_arg = self_flag)
1477 def looking_at_type(s):
1478 return looking_at_base_type(s) or s.looking_at_type_name()
1480 def looking_at_base_type(s):
1481 #print "looking_at_base_type?", s.sy, s.systring, s.position()
1482 return s.sy == 'IDENT' and s.systring in base_type_start_words
1484 def looking_at_dotted_name(s):
1488 result = s.sy == '.'
1489 s.put_back('IDENT', name)
1494 basic_c_type_names = ("void", "char", "int", "float", "double", "Py_ssize_t", "bint")
1496 sign_and_longness_words = ("short", "long", "signed", "unsigned")
1498 base_type_start_words = \
1499 basic_c_type_names + sign_and_longness_words
1501 def p_sign_and_longness(s):
1504 while s.sy == 'IDENT' and s.systring in sign_and_longness_words:
1505 if s.systring == 'unsigned':
1507 elif s.systring == 'signed':
1509 elif s.systring == 'short':
1511 elif s.systring == 'long':
1514 return signed, longness
1517 literal = p_opt_string_literal(s)
1524 def p_c_declarator(s, empty = 0, is_type = 0, cmethod_flag = 0, assignable = 0,
1525 nonempty = 0, calling_convention_allowed = 0):
1526 # If empty is true, the declarator must be empty. If nonempty is true,
1527 # the declarator must be nonempty. Otherwise we don't care.
1528 # If cmethod_flag is true, then if this declarator declares
1529 # a function, it's a C method of an extension type.
1533 if s.sy == ')' or looking_at_type(s):
1534 base = Nodes.CNameDeclaratorNode(pos, name = "", cname = None)
1535 result = p_c_func_declarator(s, pos, base, cmethod_flag)
1537 result = p_c_declarator(s, empty, is_type, cmethod_flag, nonempty = nonempty,
1538 calling_convention_allowed = 1)
1541 result = p_c_simple_declarator(s, empty, is_type, cmethod_flag, assignable, nonempty)
1542 if not calling_convention_allowed and result.calling_convention and s.sy <> '(':
1543 error(s.position(), "%s on something that is not a function"
1544 % result.calling_convention)
1545 while s.sy in ('[', '('):
1548 result = p_c_array_declarator(s, result)
1551 result = p_c_func_declarator(s, pos, result, cmethod_flag)
1555 def p_c_array_declarator(s, base):
1563 return Nodes.CArrayDeclaratorNode(pos, base = base, dimension = dim)
1565 def p_c_func_declarator(s, pos, base, cmethod_flag):
1566 # Opening paren has already been skipped
1567 args = p_c_arg_list(s, in_pyfunc = 0, cmethod_flag = cmethod_flag,
1568 nonempty_declarators = 0)
1569 ellipsis = p_optional_ellipsis(s)
1572 exc_val, exc_check = p_exception_value_clause(s)
1573 with_gil = p_with_gil(s)
1574 return Nodes.CFuncDeclaratorNode(pos,
1575 base = base, args = args, has_varargs = ellipsis,
1576 exception_value = exc_val, exception_check = exc_check,
1577 nogil = nogil or with_gil, with_gil = with_gil)
1579 def p_c_simple_declarator(s, empty, is_type, cmethod_flag, assignable, nonempty):
1581 calling_convention = p_calling_convention(s)
1584 base = p_c_declarator(s, empty, is_type, cmethod_flag, assignable, nonempty)
1585 result = Nodes.CPtrDeclaratorNode(pos,
1587 elif s.sy == '**': # scanner returns this as a single token
1589 base = p_c_declarator(s, empty, is_type, cmethod_flag, assignable, nonempty)
1590 result = Nodes.CPtrDeclaratorNode(pos,
1591 base = Nodes.CPtrDeclaratorNode(pos,
1598 s.add_type_name(name)
1600 error(s.position(), "Declarator should be empty")
1602 cname = p_opt_cname(s)
1603 if s.sy == '=' and assignable:
1605 rhs = p_simple_expr(s)
1608 error(s.position(), "Empty declarator")
1611 result = Nodes.CNameDeclaratorNode(pos,
1612 name = name, cname = cname, rhs = rhs)
1613 result.calling_convention = calling_convention
1617 if s.sy == 'IDENT' and s.systring == 'nogil':
1626 s.expect_keyword('gil')
1631 def p_exception_value_clause(s):
1634 if s.sy == 'except':
1643 exc_val = p_simple_expr(s)
1644 return exc_val, exc_check
1646 c_arg_list_terminators = ('*', '**', '.', ')')
1648 #def p_c_arg_list(s, in_pyfunc, cmethod_flag = 0, nonempty_declarators = 0,
1651 # if s.sy not in c_arg_list_terminators:
1652 # args.append(p_c_arg_decl(s, in_pyfunc, cmethod_flag,
1653 # nonempty = nonempty_declarators, kw_only = kw_only))
1654 # while s.sy == ',':
1656 # if s.sy in c_arg_list_terminators:
1658 # args.append(p_c_arg_decl(s, in_pyfunc), nonempty = nonempty_declarators,
1659 # kw_only = kw_only)
1662 def p_c_arg_list(s, in_pyfunc, cmethod_flag = 0, nonempty_declarators = 0,
1664 # Comma-separated list of C argument declarations, possibly empty.
1665 # May have a trailing comma.
1667 is_self_arg = cmethod_flag
1668 while s.sy not in c_arg_list_terminators:
1669 args.append(p_c_arg_decl(s, in_pyfunc, is_self_arg,
1670 nonempty = nonempty_declarators, kw_only = kw_only))
1677 def p_optional_ellipsis(s):
1684 def p_c_arg_decl(s, in_pyfunc, cmethod_flag = 0, nonempty = 0, kw_only = 0):
1688 base_type = p_c_base_type(s, cmethod_flag)
1689 declarator = p_c_declarator(s, nonempty = nonempty)
1692 if s.sy == 'IDENT' and s.systring == 'None':
1695 s.error("Expected 'None'")
1697 error(pos, "'not None' only allowed in Python functions")
1701 if 'pxd' in s.level:
1702 if s.sy not in ['*', '?']:
1703 error(pos, "default values cannot be specified in pxd files, use ? or *")
1707 default = p_simple_expr(s)
1708 return Nodes.CArgDeclNode(pos,
1709 base_type = base_type,
1710 declarator = declarator,
1711 not_none = not_none,
1716 if s.sy == 'IDENT' and s.systring == 'api':
1722 def p_cdef_statement(s, level, visibility = 'private', api = 0,
1723 overridable = False):
1725 if overridable and level not in ('c_class', 'c_class_pxd'):
1726 error(pos, "Overridable cdef function not allowed here")
1727 visibility = p_visibility(s, visibility)
1728 api = api or p_api(s)
1730 if visibility not in ('private', 'public'):
1731 error(pos, "Cannot combine 'api' with '%s'" % visibility)
1732 if visibility == 'extern' and s.sy == 'from':
1733 return p_cdef_extern_block(s, level, pos)
1735 return p_cdef_block(s, level, visibility, api)
1736 elif s.sy == 'class':
1737 if level not in ('module', 'module_pxd'):
1738 error(pos, "Extension type definition not allowed here")
1740 # error(pos, "'api' not allowed with extension class")
1741 return p_c_class_definition(s, level, pos, visibility = visibility, api = api)
1742 elif s.sy == 'IDENT' and s.systring in struct_union_or_enum:
1743 if level not in ('module', 'module_pxd'):
1744 error(pos, "C struct/union/enum definition not allowed here")
1745 #if visibility == 'public':
1746 # error(pos, "Public struct/union/enum definition not implemented")
1748 # error(pos, "'api' not allowed with '%s'" % s.systring)
1749 if s.systring == "enum":
1750 return p_c_enum_definition(s, pos, level, visibility)
1752 return p_c_struct_or_union_definition(s, pos, level, visibility)
1753 elif s.sy == 'pass':
1754 node = p_pass_statement(s)
1755 s.expect_newline('Expected a newline')
1758 return p_c_func_or_var_declaration(s, level, pos, visibility, api,
1761 def p_cdef_block(s, level, visibility, api):
1762 return p_suite(s, level, cdef_flag = 1, visibility = visibility, api = api)
1764 def p_cdef_extern_block(s, level, pos):
1770 _, include_file = p_string_literal(s)
1771 body = p_suite(s, level, cdef_flag = 1, visibility = 'extern')
1772 return Nodes.CDefExternNode(pos,
1773 include_file = include_file,
1776 struct_union_or_enum = (
1777 "struct", "union", "enum"
1780 def p_c_enum_definition(s, pos, level, visibility, typedef_flag = 0):
1781 # s.sy == ident 'enum'
1786 s.add_type_name(name)
1787 cname = p_opt_cname(s)
1794 if s.sy <> 'NEWLINE':
1795 p_c_enum_line(s, items)
1797 s.next() # 'NEWLINE'
1799 while s.sy not in ('DEDENT', 'EOF'):
1800 p_c_enum_line(s, items)
1802 return Nodes.CEnumDefNode(pos, name = name, cname = cname,
1803 items = items, typedef_flag = typedef_flag, visibility = visibility,
1804 in_pxd = level == 'module_pxd')
1806 def p_c_enum_line(s, items):
1808 p_c_enum_item(s, items)
1811 if s.sy in ('NEWLINE', 'EOF'):
1813 p_c_enum_item(s, items)
1816 s.expect_newline("Syntax error in enum item list")
1818 def p_c_enum_item(s, items):
1821 cname = p_opt_cname(s)
1825 value = p_simple_expr(s)
1826 items.append(Nodes.CEnumDefItemNode(pos,
1827 name = name, cname = cname, value = value))
1829 def p_c_struct_or_union_definition(s, pos, level, visibility, typedef_flag = 0):
1830 # s.sy == ident 'struct' or 'union'
1834 cname = p_opt_cname(s)
1835 s.add_type_name(name)
1842 while s.sy <> 'DEDENT':
1845 p_c_func_or_var_declaration(s, level = 'other', pos = s.position()))
1848 s.expect_newline("Expected a newline")
1851 s.expect_newline("Syntax error in struct or union definition")
1852 return Nodes.CStructOrUnionDefNode(pos,
1853 name = name, cname = cname, kind = kind, attributes = attributes,
1854 typedef_flag = typedef_flag, visibility = visibility,
1855 in_pxd = level == 'module_pxd')
1857 def p_visibility(s, prev_visibility):
1859 visibility = prev_visibility
1860 if s.sy == 'IDENT' and s.systring in ('extern', 'public', 'readonly'):
1861 visibility = s.systring
1862 if prev_visibility <> 'private' and visibility <> prev_visibility:
1863 s.error("Conflicting visibility options '%s' and '%s'"
1864 % (prev_visibility, visibility))
1868 def p_c_modifiers(s):
1869 if s.sy == 'IDENT' and s.systring in ('inline',):
1870 modifier = s.systring
1872 return [modifier] + p_c_modifiers(s)
1875 def p_c_func_or_var_declaration(s, level, pos, visibility = 'private', api = 0,
1876 overridable = False):
1877 cmethod_flag = level in ('c_class', 'c_class_pxd')
1878 modifiers = p_c_modifiers(s)
1879 base_type = p_c_base_type(s)
1880 declarator = p_c_declarator(s, cmethod_flag = cmethod_flag, assignable = 1, nonempty = 1)
1881 declarator.overridable = overridable
1883 if level not in ('module', 'c_class'):
1884 s.error("C function definition not allowed here")
1885 doc, suite = p_suite(s, 'function', with_doc = 1)
1886 result = Nodes.CFuncDefNode(pos,
1887 visibility = visibility,
1888 base_type = base_type,
1889 declarator = declarator,
1892 modifiers = modifiers,
1894 overridable = overridable)
1897 # error(s.pos, "'api' not allowed with variable declaration")
1898 declarators = [declarator]
1901 if s.sy == 'NEWLINE':
1903 declarator = p_c_declarator(s, cmethod_flag = cmethod_flag, assignable = 1, nonempty = 1)
1904 declarators.append(declarator)
1905 s.expect_newline("Syntax error in C variable declaration")
1906 result = Nodes.CVarDefNode(pos,
1907 visibility = visibility,
1908 base_type = base_type,
1909 declarators = declarators,
1910 in_pxd = level == 'module_pxd',
1912 overridable = overridable)
1915 def p_ctypedef_statement(s, level, visibility = 'private', api = 0):
1916 # s.sy == 'ctypedef'
1919 visibility = p_visibility(s, visibility)
1921 return p_c_class_definition(s, level, pos,
1922 visibility = visibility, typedef_flag = 1, api = api)
1923 elif s.sy == 'IDENT' and s.systring in ('struct', 'union', 'enum'):
1924 if s.systring == 'enum':
1925 return p_c_enum_definition(s, pos, level, visibility, typedef_flag = 1)
1927 return p_c_struct_or_union_definition(s, pos, level, visibility,
1930 base_type = p_c_base_type(s)
1931 declarator = p_c_declarator(s, is_type = 1, nonempty = 1)
1932 s.expect_newline("Syntax error in ctypedef statement")
1933 return Nodes.CTypeDefNode(pos,
1934 base_type = base_type, declarator = declarator, visibility = visibility,
1935 in_pxd = level == 'module_pxd')
1937 def p_def_statement(s):
1944 args = p_c_arg_list(s, in_pyfunc = 1, nonempty_declarators = 1)
1950 star_arg = p_py_arg_decl(s)
1953 args.extend(p_c_arg_list(s, in_pyfunc = 1,
1954 nonempty_declarators = 1, kw_only = 1))
1956 s.error("Syntax error in Python function argument list")
1959 starstar_arg = p_py_arg_decl(s)
1962 error(s.pos, "Python function cannot be declared nogil")
1963 doc, body = p_suite(s, 'function', with_doc = 1)
1964 return Nodes.DefNode(pos, name = name, args = args,
1965 star_arg = star_arg, starstar_arg = starstar_arg,
1966 doc = doc, body = body)
1968 def p_py_arg_decl(s):
1971 return Nodes.PyArgDeclNode(pos, name = name)
1973 def p_class_statement(s):
1977 class_name = p_ident(s)
1980 base_list = p_simple_expr_list(s)
1984 doc, body = p_suite(s, 'class', with_doc = 1)
1985 return Nodes.PyClassDefNode(pos,
1987 bases = ExprNodes.TupleNode(pos, args = base_list),
1988 doc = doc, body = body)
1990 def p_c_class_definition(s, level, pos,
1991 visibility = 'private', typedef_flag = 0, api = 0):
1995 class_name = p_ident(s)
1998 module_path.append(class_name)
1999 class_name = p_ident(s)
2000 if module_path and visibility <> 'extern':
2001 error(pos, "Qualified class name only allowed for 'extern' C class")
2002 if module_path and s.sy == 'IDENT' and s.systring == 'as':
2004 as_name = p_ident(s)
2006 as_name = class_name
2007 s.add_type_name(as_name)
2008 objstruct_name = None
2010 base_class_module = None
2011 base_class_name = None
2014 base_class_path = [p_ident(s)]
2017 base_class_path.append(p_ident(s))
2019 s.error("C class may only have one base class")
2021 base_class_module = ".".join(base_class_path[:-1])
2022 base_class_name = base_class_path[-1]
2024 if visibility not in ('public', 'extern'):
2025 error(s.position(), "Name options only allowed for 'public' or 'extern' C class")
2026 objstruct_name, typeobj_name = p_c_class_options(s)
2028 if level == 'module_pxd':
2029 body_level = 'c_class_pxd'
2031 body_level = 'c_class'
2032 doc, body = p_suite(s, body_level, with_doc = 1)
2034 s.expect_newline("Syntax error in C class definition")
2037 if visibility == 'extern':
2039 error(pos, "Module name required for 'extern' C class")
2041 error(pos, "Type object name specification not allowed for 'extern' C class")
2042 elif visibility == 'public':
2043 if not objstruct_name:
2044 error(pos, "Object struct name specification required for 'public' C class")
2045 if not typeobj_name:
2046 error(pos, "Type object name specification required for 'public' C class")
2047 elif visibility == 'private':
2049 error(pos, "Only 'public' C class can be declared 'api'")
2051 error(pos, "Invalid class visibility '%s'" % visibility)
2052 return Nodes.CClassDefNode(pos,
2053 visibility = visibility,
2054 typedef_flag = typedef_flag,
2056 module_name = ".".join(module_path),
2057 class_name = class_name,
2059 base_class_module = base_class_module,
2060 base_class_name = base_class_name,
2061 objstruct_name = objstruct_name,
2062 typeobj_name = typeobj_name,
2063 in_pxd = level == 'module_pxd',
2067 def p_c_class_options(s):
2068 objstruct_name = None
2074 if s.systring == 'object':
2076 objstruct_name = p_ident(s)
2077 elif s.systring == 'type':
2079 typeobj_name = p_ident(s)
2083 s.expect(']', "Expected 'object' or 'type'")
2084 return objstruct_name, typeobj_name
2086 def p_property_decl(s):
2088 s.next() # 'property'
2090 doc, body = p_suite(s, 'property', with_doc = 1)
2091 return Nodes.PropertyNode(pos, name = name, doc = doc, body = body)
2093 def p_doc_string(s):
2094 if s.sy == 'STRING' or s.sy == 'BEGIN_STRING':
2095 _, result = p_cat_string_literal(s)
2097 s.expect_newline("Syntax error in doc string")
2102 def p_module(s, pxd, full_module_name):
2103 s.add_type_name("object")
2105 doc = p_doc_string(s)
2107 level = 'module_pxd'
2110 body = p_statement_list(s, level)
2112 s.error("Syntax error in statement [%s,%s]" % (
2113 repr(s.sy), repr(s.systring)))
2114 return ModuleNode(pos, doc = doc, body = body, full_module_name = full_module_name)
2116 #----------------------------------------------
2120 #----------------------------------------------
2122 def print_parse_tree(f, node, level, key = None):
2123 from Nodes import Node
2128 f.write("%s: " % key)
2131 f.write("(%s @ %s\n" % (node[0], node[1]))
2132 for i in xrange(2, len(node)):
2133 print_parse_tree(f, node[i], level+1)
2134 f.write("%s)\n" % ind)
2136 elif isinstance(node, Node):
2139 except AttributeError:
2140 tag = node.__class__.__name__
2141 f.write("%s @ %s\n" % (tag, node.pos))
2142 for name, value in node.__dict__.items():
2143 if name <> 'tag' and name <> 'pos':
2144 print_parse_tree(f, value, level+1, name)
2148 for i in xrange(len(node)):
2149 print_parse_tree(f, node[i], level+1)
2150 f.write("%s]\n" % ind)
2152 f.write("%s%s\n" % (ind, node))