Debian Codegraph @

brian2/codegen/templates.py

raw
1 """
2 Handles loading templates from a directory.
3 """
4
5 import re
6 from collections.abc import Mapping
7
8 from jinja2 import (
9 ChoiceLoader,
10 Environment,
11 PackageLoader,
12 StrictUndefined,
13 TemplateNotFound,
14 )
15
16 from brian2.utils.stringtools import get_identifiers, indent, strip_empty_lines
17
18 __all__ = ["Templater"]
19
20 AUTOINDENT_START = "%%START_AUTOINDENT%%"
21 AUTOINDENT_END = "%%END_AUTOINDENT%%"
22
23
24 def autoindent(code):
25 if isinstance(code, list):
26 code = "\n".join(code)
27 if not code.startswith("\n"):
28 code = f"\n{code}"
29 if not code.endswith("\n"):
30 code = f"{code}\n"
31 return AUTOINDENT_START + code + AUTOINDENT_END
32
33
34 def autoindent_postfilter(code):
35 lines = code.split("\n")
36 outlines = []
37 addspaces = 0
38 for line in lines:
39 if AUTOINDENT_START in line:
40 if addspaces > 0:
41 raise SyntaxError("Cannot nest autoindents")
42 addspaces = line.find(AUTOINDENT_START)
43 line = line.replace(AUTOINDENT_START, "")
44 if AUTOINDENT_END in line:
45 line = line.replace(AUTOINDENT_END, "")
46 addspaces = 0
47 outlines.append(" " * addspaces + line)
48 return "\n".join(outlines)
49
50
51 def variables_to_array_names(variables, access_data=True):
52 from brian2.devices.device import get_device
53
54 device = get_device()
55 names = [device.get_array_name(var, access_data=access_data) for var in variables]
56 return names
57
58
59 class LazyTemplateLoader:
60 """
61 Helper object to load templates only when they are needed.
62 """
63
64 def __init__(self, environment, extension):
65 self.env = environment
66 self.extension = extension
67 self._templates = {}
68
69 def get_template(self, name):
70 if name not in self._templates:
71 try:
72 template = CodeObjectTemplate(
73 self.env.get_template(name + self.extension),
74 self.env.loader.get_source(self.env, name + self.extension)[0],
75 )
76 except TemplateNotFound:
77 try:
78 # Try without extension as well (e.g. for makefiles)
79 template = CodeObjectTemplate(
80 self.env.get_template(name),
81 self.env.loader.get_source(self.env, name)[0],
82 )
83 except TemplateNotFound:
84 raise KeyError(f'No template with name "{name}" found.') from None
85 self._templates[name] = template
86 return self._templates[name]
87
88
89 class Templater:
90 """
91 Class to load and return all the templates a `CodeObject` defines.
92
93 Parameters
94 ----------
95
96 package_name : str, tuple of str
97 The package where the templates are saved. If this is a tuple then each template will be searched in order
98 starting from the first package in the tuple until the template is found. This allows for derived templates
99 to be used. See also `~Templater.derive`.
100 extension : str
101 The file extension (e.g. ``.pyx``) used for the templates.
102 env_globals : dict (optional)
103 A dictionary of global values accessible by the templates. Can be used for providing utility functions.
104 In all cases, the filter 'autoindent' is available (see existing templates for example usage).
105 templates_dir : str, tuple of str, optional
106 The name of the directory containing the templates. Defaults to ``'templates'``.
107
108 Notes
109 -----
110 Templates are accessed using ``templater.template_base_name`` (the base name is without the file extension).
111 This returns a `CodeObjectTemplate`.
112 """
113
114 def __init__(
115 self, package_name, extension, env_globals=None, templates_dir="templates"
116 ):
117 if isinstance(package_name, str):
118 package_name = (package_name,)
119 if isinstance(templates_dir, str):
120 templates_dir = (templates_dir,)
121 loader = ChoiceLoader(
122 [
123 PackageLoader(name, t_dir)
124 for name, t_dir in zip(package_name, templates_dir, strict=True)
125 ]
126 )
127 self.env = Environment(
128 loader=loader,
129 trim_blocks=True,
130 lstrip_blocks=True,
131 undefined=StrictUndefined,
132 )
133 self.env.globals["autoindent"] = autoindent
134 self.env.filters["autoindent"] = autoindent
135 self.env.filters["variables_to_array_names"] = variables_to_array_names
136 if env_globals is not None:
137 self.env.globals.update(env_globals)
138 else:
139 env_globals = {}
140 self.env_globals = env_globals
141 self.package_names = package_name
142 self.templates_dir = templates_dir
143 self.extension = extension
144 self.templates = LazyTemplateLoader(self.env, extension)
145
146 def __getattr__(self, item):
147 try:
148 return self.templates.get_template(item)
149 except KeyError as ex:
150 raise AttributeError from ex # raise the correct error type for __getattr__
151
152 def derive(
153 self, package_name, extension=None, env_globals=None, templates_dir="templates"
154 ):
155 """
156 Return a new Templater derived from this one, where the new package name and globals overwrite the old.
157 """
158 if extension is None:
159 extension = self.extension
160 if isinstance(package_name, str):
161 package_name = (package_name,)
162 if env_globals is None:
163 env_globals = {}
164 if isinstance(templates_dir, str):
165 templates_dir = (templates_dir,)
166 package_name = package_name + self.package_names
167 templates_dir = templates_dir + self.templates_dir
168 new_env_globals = self.env_globals.copy()
169 new_env_globals.update(**env_globals)
170 return Templater(
171 package_name,
172 extension=extension,
173 env_globals=new_env_globals,
174 templates_dir=templates_dir,
175 )
176
177
178 class CodeObjectTemplate:
179 """
180 Single template object returned by `Templater` and used for final code generation
181
182 Should not be instantiated by the user, but only directly by `Templater`.
183
184 Notes
185 -----
186
187 The final code is obtained from this by calling the template (see `~CodeObjectTemplater.__call__`).
188 """
189
190 def __init__(self, template, template_source):
191 self.template = template
192 self.template_source = template_source
193 #: The set of variables in this template
194 self.variables = set()
195 #: The indices over which the template iterates completely
196 self.iterate_all = set()
197 #: Read-only variables that are changed by this template
198 self.writes_read_only = set()
199 # This is the bit inside {} for USES_VARIABLES { list of words }
200 specifier_blocks = re.findall(
201 r"\bUSES_VARIABLES\b\s*\{(.*?)\}", template_source, re.M | re.S
202 )
203 # Same for ITERATE_ALL
204 iterate_all_blocks = re.findall(
205 r"\bITERATE_ALL\b\s*\{(.*?)\}", template_source, re.M | re.S
206 )
207 # And for WRITES_TO_READ_ONLY_VARIABLES
208 writes_read_only_blocks = re.findall(
209 r"\bWRITES_TO_READ_ONLY_VARIABLES\b\s*\{(.*?)\}",
210 template_source,
211 re.M | re.S,
212 )
213 #: Does this template allow writing to scalar variables?
214 self.allows_scalar_write = "ALLOWS_SCALAR_WRITE" in template_source
215
216 for block in specifier_blocks:
217 self.variables.update(get_identifiers(block))
218 for block in iterate_all_blocks:
219 self.iterate_all.update(get_identifiers(block))
220 for block in writes_read_only_blocks:
221 self.writes_read_only.update(get_identifiers(block))
222
223 def __call__(self, scalar_code, vector_code, **kwds):
224 """
225 Return a usable code block or blocks from this template.
226
227 Parameters
228 ----------
229 scalar_code : dict
230 Dictionary of scalar code blocks.
231 vector_code : dict
232 Dictionary of vector code blocks
233 **kwds
234 Additional parameters to pass to the template
235
236 Notes
237 -----
238
239 Returns either a string (if macros were not used in the template), or a `MultiTemplate` (if macros were used).
240 """
241 if (
242 scalar_code is not None
243 and len(scalar_code) == 1
244 and list(scalar_code)[0] is None
245 ):
246 scalar_code = scalar_code[None]
247 if (
248 vector_code is not None
249 and len(vector_code) == 1
250 and list(vector_code)[0] is None
251 ):
252 vector_code = vector_code[None]
253 kwds["scalar_code"] = scalar_code
254 kwds["vector_code"] = vector_code
255 module = self.template.make_module(kwds)
256 if len([k for k in module.__dict__ if not k.startswith("_")]):
257 return MultiTemplate(module)
258 else:
259 return autoindent_postfilter(str(module))
260
261
262 class MultiTemplate(Mapping):
263 """
264 Code generated by a `CodeObjectTemplate` with multiple blocks
265
266 Each block is a string stored as an attribute with the block name. The
267 object can also be accessed as a dictionary.
268 """
269
270 def __init__(self, module):
271 self._templates = {}
272 for k, f in module.__dict__.items():
273 if not k.startswith("_"):
274 s = autoindent_postfilter(str(f()))
275 setattr(self, k, s)
276 self._templates[k] = s
277
278 def __getitem__(self, item):
279 return self._templates[item]
280
281 def __iter__(self):
282 return iter(self._templates)
283
284 def __len__(self):
285 return len(self._templates)
286
287 def __str__(self):
288 s = ""
289 for k, v in list(self._templates.items()):
290 s += f"{k}:\n"
291 s += f"{strip_empty_lines(indent(v))}\n"
292 return s
293
294 __repr__ = __str__