Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/mako/pyparser.py: 82%
125 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:02 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:02 +0000
1# mako/pyparser.py
2# Copyright 2006-2023 the Mako authors and contributors <see AUTHORS file>
3#
4# This module is part of Mako and is released under
5# the MIT License: http://www.opensource.org/licenses/mit-license.php
7"""Handles parsing of Python code.
9Parsing to AST is done via _ast on Python > 2.5, otherwise the compiler
10module is used.
11"""
13import operator
15import _ast
17from mako import _ast_util
18from mako import compat
19from mako import exceptions
20from mako import util
22# words that cannot be assigned to (notably
23# smaller than the total keys in __builtins__)
24reserved = {"True", "False", "None", "print"}
26# the "id" attribute on a function node
27arg_id = operator.attrgetter("arg")
29util.restore__ast(_ast)
32def parse(code, mode="exec", **exception_kwargs):
33 """Parse an expression into AST"""
35 try:
36 return _ast_util.parse(code, "<unknown>", mode)
37 except Exception as e:
38 raise exceptions.SyntaxException(
39 "(%s) %s (%r)"
40 % (
41 compat.exception_as().__class__.__name__,
42 compat.exception_as(),
43 code[0:50],
44 ),
45 **exception_kwargs,
46 ) from e
49class FindIdentifiers(_ast_util.NodeVisitor):
50 def __init__(self, listener, **exception_kwargs):
51 self.in_function = False
52 self.in_assign_targets = False
53 self.local_ident_stack = set()
54 self.listener = listener
55 self.exception_kwargs = exception_kwargs
57 def _add_declared(self, name):
58 if not self.in_function:
59 self.listener.declared_identifiers.add(name)
60 else:
61 self.local_ident_stack.add(name)
63 def visit_ClassDef(self, node):
64 self._add_declared(node.name)
66 def visit_Assign(self, node):
68 # flip around the visiting of Assign so the expression gets
69 # evaluated first, in the case of a clause like "x=x+5" (x
70 # is undeclared)
72 self.visit(node.value)
73 in_a = self.in_assign_targets
74 self.in_assign_targets = True
75 for n in node.targets:
76 self.visit(n)
77 self.in_assign_targets = in_a
79 def visit_ExceptHandler(self, node):
80 if node.name is not None:
81 self._add_declared(node.name)
82 if node.type is not None:
83 self.visit(node.type)
84 for statement in node.body:
85 self.visit(statement)
87 def visit_Lambda(self, node, *args):
88 self._visit_function(node, True)
90 def visit_FunctionDef(self, node):
91 self._add_declared(node.name)
92 self._visit_function(node, False)
94 def _expand_tuples(self, args):
95 for arg in args:
96 if isinstance(arg, _ast.Tuple):
97 yield from arg.elts
98 else:
99 yield arg
101 def _visit_function(self, node, islambda):
103 # push function state onto stack. dont log any more
104 # identifiers as "declared" until outside of the function,
105 # but keep logging identifiers as "undeclared". track
106 # argument names in each function header so they arent
107 # counted as "undeclared"
109 inf = self.in_function
110 self.in_function = True
112 local_ident_stack = self.local_ident_stack
113 self.local_ident_stack = local_ident_stack.union(
114 [arg_id(arg) for arg in self._expand_tuples(node.args.args)]
115 )
116 if islambda:
117 self.visit(node.body)
118 else:
119 for n in node.body:
120 self.visit(n)
121 self.in_function = inf
122 self.local_ident_stack = local_ident_stack
124 def visit_For(self, node):
126 # flip around visit
128 self.visit(node.iter)
129 self.visit(node.target)
130 for statement in node.body:
131 self.visit(statement)
132 for statement in node.orelse:
133 self.visit(statement)
135 def visit_Name(self, node):
136 if isinstance(node.ctx, _ast.Store):
137 # this is eqiuvalent to visit_AssName in
138 # compiler
139 self._add_declared(node.id)
140 elif (
141 node.id not in reserved
142 and node.id not in self.listener.declared_identifiers
143 and node.id not in self.local_ident_stack
144 ):
145 self.listener.undeclared_identifiers.add(node.id)
147 def visit_Import(self, node):
148 for name in node.names:
149 if name.asname is not None:
150 self._add_declared(name.asname)
151 else:
152 self._add_declared(name.name.split(".")[0])
154 def visit_ImportFrom(self, node):
155 for name in node.names:
156 if name.asname is not None:
157 self._add_declared(name.asname)
158 elif name.name == "*":
159 raise exceptions.CompileException(
160 "'import *' is not supported, since all identifier "
161 "names must be explicitly declared. Please use the "
162 "form 'from <modulename> import <name1>, <name2>, "
163 "...' instead.",
164 **self.exception_kwargs,
165 )
166 else:
167 self._add_declared(name.name)
170class FindTuple(_ast_util.NodeVisitor):
171 def __init__(self, listener, code_factory, **exception_kwargs):
172 self.listener = listener
173 self.exception_kwargs = exception_kwargs
174 self.code_factory = code_factory
176 def visit_Tuple(self, node):
177 for n in node.elts:
178 p = self.code_factory(n, **self.exception_kwargs)
179 self.listener.codeargs.append(p)
180 self.listener.args.append(ExpressionGenerator(n).value())
181 ldi = self.listener.declared_identifiers
182 self.listener.declared_identifiers = ldi.union(
183 p.declared_identifiers
184 )
185 lui = self.listener.undeclared_identifiers
186 self.listener.undeclared_identifiers = lui.union(
187 p.undeclared_identifiers
188 )
191class ParseFunc(_ast_util.NodeVisitor):
192 def __init__(self, listener, **exception_kwargs):
193 self.listener = listener
194 self.exception_kwargs = exception_kwargs
196 def visit_FunctionDef(self, node):
197 self.listener.funcname = node.name
199 argnames = [arg_id(arg) for arg in node.args.args]
200 if node.args.vararg:
201 argnames.append(node.args.vararg.arg)
203 kwargnames = [arg_id(arg) for arg in node.args.kwonlyargs]
204 if node.args.kwarg:
205 kwargnames.append(node.args.kwarg.arg)
206 self.listener.argnames = argnames
207 self.listener.defaults = node.args.defaults # ast
208 self.listener.kwargnames = kwargnames
209 self.listener.kwdefaults = node.args.kw_defaults
210 self.listener.varargs = node.args.vararg
211 self.listener.kwargs = node.args.kwarg
214class ExpressionGenerator:
215 def __init__(self, astnode):
216 self.generator = _ast_util.SourceGenerator(" " * 4)
217 self.generator.visit(astnode)
219 def value(self):
220 return "".join(self.generator.result)