Debian Codegraph @

brian2/parsing/functions.py

raw
1 import ast
2 import inspect
3
4 from brian2.utils.stringtools import deindent, get_identifiers, indent
5
6 from .rendering import NodeRenderer
7
8 __all__ = [
9 "AbstractCodeFunction",
10 "abstract_code_from_function",
11 "extract_abstract_code_functions",
12 "substitute_abstract_code_functions",
13 ]
14
15
16 class AbstractCodeFunction:
17 """
18 The information defining an abstract code function
19
20 Has attributes corresponding to initialisation parameters
21
22 Parameters
23 ----------
24
25 name : str
26 The function name.
27 args : list of str
28 The arguments to the function.
29 code : str
30 The abstract code string consisting of the body of the function less
31 the return statement.
32 return_expr : str or None
33 The expression returned, or None if there is nothing returned.
34 """
35
36 def __init__(self, name, args, code, return_expr):
37 self.name = name
38 self.args = args
39 self.code = code
40 self.return_expr = return_expr
41
42 def __str__(self):
43 s = (
44 f"def {self.name}({', '.join(self.args)}):\n{indent(self.code)}\n return"
45 f" {self.return_expr}\n"
46 )
47 return s
48
49 __repr__ = __str__
50
51
52 def abstract_code_from_function(func):
53 """
54 Converts the body of the function to abstract code
55
56 Parameters
57 ----------
58 func : function, str or ast.FunctionDef
59 The function object to convert. Note that the arguments to the
60 function are ignored.
61
62 Returns
63 -------
64 func : AbstractCodeFunction
65 The corresponding abstract code function
66
67 Raises
68 ------
69 SyntaxError
70 If unsupported features are used such as if statements or indexing.
71 """
72 if callable(func):
73 code = deindent(inspect.getsource(func))
74 funcnode = ast.parse(code, mode="exec").body[0]
75 elif isinstance(func, str):
76 funcnode = ast.parse(func, mode="exec").body[0]
77 elif func.__class__ is ast.FunctionDef:
78 funcnode = func
79 else:
80 raise TypeError("Unsupported function type")
81
82 if funcnode.args.vararg is not None:
83 raise SyntaxError("No support for variable number of arguments")
84 if funcnode.args.kwarg is not None:
85 raise SyntaxError("No support for arbitrary keyword arguments")
86 if len(funcnode.args.defaults):
87 raise SyntaxError("No support for default values in functions")
88
89 nodes = funcnode.body
90 nr = NodeRenderer()
91 lines = []
92 return_expr = None
93 for node in nodes:
94 if node.__class__ is ast.Return:
95 return_expr = nr.render_node(node.value)
96 break
97 else:
98 lines.append(nr.render_node(node))
99 abstract_code = "\n".join(lines)
100 args = [arg.arg for arg in funcnode.args.args]
101 name = funcnode.name
102 return AbstractCodeFunction(name, args, abstract_code, return_expr)
103
104
105 def extract_abstract_code_functions(code):
106 """
107 Returns a set of abstract code functions from function definitions.
108
109 Returns all functions defined at the top level and ignores any other
110 code in the string.
111
112 Parameters
113 ----------
114 code : str
115 The code string defining some functions.
116
117 Returns
118 -------
119 funcs : dict
120 A mapping ``(name, func)`` for ``func`` an `AbstractCodeFunction`.
121 """
122 code = deindent(code)
123 nodes = ast.parse(code, mode="exec").body
124 funcs = {}
125 for node in nodes:
126 if node.__class__ is ast.FunctionDef:
127 func = abstract_code_from_function(node)
128 funcs[func.name] = func
129 return funcs
130
131
132 class VarRewriter(ast.NodeTransformer):
133 """
134 Rewrites all variable names in names by prepending pre
135 """
136
137 def __init__(self, pre):
138 self.pre = pre
139
140 def visit_Name(self, node):
141 return ast.Name(id=self.pre + node.id, ctx=node.ctx)
142
143 def visit_Call(self, node):
144 args = [self.visit(arg) for arg in node.args]
145 return ast.Call(
146 func=ast.Name(id=node.func.id, ctx=ast.Load()),
147 args=args,
148 keywords=[],
149 )
150
151
152 class FunctionRewriter(ast.NodeTransformer):
153 """
154 Inlines a function call using temporary variables
155
156 numcalls is the number of times the function rewriter has been called so
157 far, this is used to make sure that when recursively inlining there is no
158 name aliasing. The substitute_abstract_code_functions ensures that this is
159 kept up to date between recursive runs.
160
161 The pre attribute is the set of lines to be inserted above the currently
162 being processed line, i.e. the inline code.
163
164 The visit method returns the current line processed so that the function
165 call is replaced with the output of the inlining.
166 """
167
168 def __init__(self, func, numcalls=0):
169 self.func = func
170 self.numcalls = numcalls
171 self.pre = []
172 self.suspend = False
173
174 def visit_Call(self, node):
175 # we suspend operations during an inlining operation, then resume
176 # afterwards, see below, so we only ever try to expand one inline
177 # function call at a time, i.e. no f(f(x)). This case is handled
178 # by the recursion.
179 if self.suspend:
180 return node
181 # We only work with the function we're provided
182 if node.func.id != self.func.name:
183 return node
184 # Suspend while processing arguments (no recursion)
185 self.suspend = True
186 args = [self.visit(arg) for arg in node.args]
187 self.suspend = False
188 # The basename is used for function-local variables
189 basename = f"_inline_{self.func.name}_{str(self.numcalls)}"
190 # Assign all the function-local variables
191 for argname, arg in zip(self.func.args, args, strict=True):
192 newpre = ast.Assign(
193 targets=[ast.Name(id=f"{basename}_{argname}", ctx=ast.Store())],
194 value=arg,
195 )
196 self.pre.append(newpre)
197 # Rewrite the lines of code of the function using the names defined
198 # above
199 vr = VarRewriter(f"{basename}_")
200 for funcline in ast.parse(self.func.code).body:
201 self.pre.append(vr.visit(funcline))
202 # And rewrite the return expression
203 return_expr = vr.visit(ast.parse(self.func.return_expr, mode="eval").body)
204 self.pre.append(
205 ast.Assign(
206 targets=[ast.Name(id=basename, ctx=ast.Store())], value=return_expr
207 )
208 )
209 # Finally we replace the function call with the output of the inlining
210 newnode = ast.Name(id=basename)
211 self.numcalls += 1
212 return newnode
213
214
215 def substitute_abstract_code_functions(code, funcs):
216 """
217 Performs inline substitution of all the functions in the code
218
219 Parameters
220 ----------
221 code : str
222 The abstract code to make inline substitutions into.
223 funcs : list, dict or set of AbstractCodeFunction
224 The function substitutions to use, note in the case of a dict, the
225 keys are ignored and the function name is used.
226
227 Returns
228 -------
229 code : str
230 The code with inline substitutions performed.
231 """
232 if isinstance(funcs, (list, set)):
233 newfuncs = dict()
234 for f in funcs:
235 newfuncs[f.name] = f
236 funcs = newfuncs
237
238 code = deindent(code)
239 lines = ast.parse(code, mode="exec").body
240
241 # This is a slightly nasty hack, but basically we just check by looking at
242 # the existing identifiers how many inline operations have already been
243 # performed by previous calls to this function
244 ids = get_identifiers(code)
245 funcstarts = {}
246 for func in funcs.values():
247 subids = {id for id in ids if id.startswith(f"_inline_{func.name}_")}
248 subids = {id.replace(f"_inline_{func.name}_", "") for id in subids}
249 alli = []
250 for subid in subids:
251 p = subid.find("_")
252 if p > 0:
253 subid = subid[:p]
254 i = int(subid)
255 alli.append(i)
256 if len(alli) == 0:
257 i = 0
258 else:
259 i = max(alli) + 1
260 funcstarts[func.name] = i
261
262 # Now we rewrite all the lines, replacing each line with a sequence of
263 # lines performing the inlining
264 newlines = []
265 for line in lines:
266 for func in funcs.values():
267 rw = FunctionRewriter(func, funcstarts[func.name])
268 line = rw.visit(line)
269 newlines.extend(rw.pre)
270 funcstarts[func.name] = rw.numcalls
271 newlines.append(line)
272
273 # Now we render to a code string
274 nr = NodeRenderer()
275 newcode = "\n".join(nr.render_node(line) for line in newlines)
276
277 # We recurse until no changes in the code to ensure that all functions
278 # are expanded if one function refers to another, etc.
279 if newcode == code:
280 return newcode
281 else:
282 return substitute_abstract_code_functions(newcode, funcs)