Debian Codegraph @

gavo/rscdef/procdef.py

raw
1 """
2 Basic handling for embedded procedures.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import functools
12
13 from gavo import base
14 from gavo import utils
15 from gavo.rscdef import common
16 from gavo.rscdef import rmkfuncs
17
18
19
20 # Move this one to utils?
21 def unionByKey(*sequences):
22 """returns all items in sequences uniqued by the items' key attributes.
23
24 The order of the sequence items is not maintained, but items in
25 later sequences override those in earlier ones.
26 """
27 allItems = {}
28 for seq in sequences:
29 for item in seq:
30 allItems[item.key] = item
31 return list(allItems.values())
32
33
34 class RDParameter(base.Structure):
35 """A base class for parameters.
36 """
37 _name = base.UnicodeAttribute("key", default=base.Undefined,
38 description="The name of the parameter", copyable=True, strip=True,
39 aliases=["name"])
40 _descr = base.NWUnicodeAttribute("description", default=None,
41 description="Some human-readable description of what the"
42 " parameter is about", copyable=True, strip=True)
43 _expr = base.DataContent(description="The default for the parameter."
44 " The special value __NULL__ indicates a NULL (python None) as usual."
45 " An empty content means a non-preset parameter, which must be filled"
46 " in applications. Use the magic value __EMPTY__ to presetting an"
47 " empty string.",
48 copyable=True, strip=True, default=base.NotGiven)
49
50 def isDefaulted(self):
51 return self.content_ is not base.NotGiven
52
53 def validate(self):
54 super().validate()
55 if not utils.identifierPattern.match(self.key):
56 raise base.LiteralParseError("name", self.key, hint=
57 "The name you supplied was not defined by any procedure definition.")
58
59 def completeElement(self, ctx):
60 if self.content_=="__EMPTY__":
61 self.content_ = ""
62
63 super().completeElement(ctx)
64
65
66 class AliasableRDParameter(RDParameter):
67 """A base class for RD parameter definitions that support aliases.
68 """
69 _alias = base.UnicodeAttribute("alias", default=None,
70 description="A deprecated name for the parameter",
71 copyable=True, strip=True)
72
73
74 class ProcPar(AliasableRDParameter):
75 """A parameter of a procedure definition.
76
77 Bodies of ProcPars are interpreted as python expressions, in
78 which macros are expanded in the context of the procedure application's
79 parent. If a body is empty, the parameter has no default and has
80 to be filled by the procedure application.
81 """
82 name_ = "par"
83
84 _late = base.BooleanAttribute("late", default=False,
85 description="Bind the name not at setup time but at applying"
86 " time. In rowmaker procedures, for example, this allows you to"
87 " refer to variables like vars or rowIter in the bindings.")
88
89 def validate(self):
90 super().validate()
91
92 # Allow non-python syntax when things look like macro calls,
93 # but assume @ expressions will be expanded (which is not
94 # always true, admittedly)
95 if (self.content_
96 and not "\\" in self.content_):
97 utils.ensureExpression(
98 common.replaceProcDefAt(self.content_),
99 self.key)
100
101
102 class Binding(ProcPar):
103 """A binding of a procedure definition parameter to a concrete value.
104
105 The value to set is contained in the binding body in the form of
106 a python expression. The body must not be empty.
107 """
108 name_ = "bind"
109
110 def validate(self):
111 super().validate()
112 if not self.content_ or not self.content_.strip():
113 raise base.StructureError("Binding bodies must not be empty.")
114
115
116 class ProcSetup(base.Structure):
117 """Prescriptions for setting up a namespace for a procedure application.
118
119 You can add names to this namespace you using par(ameter)s.
120 If a parameter has no default and an procedure application does
121 not provide them, an error is raised.
122
123 You can also add names by providing a code attribute containing
124 a python function body in code. Within, the parameters are
125 available. The procedure application's parent can be accessed
126 as parent. All names you define in the code are available as
127 globals to the procedure body.
128
129 Caution: Macros are expanded within the code; this means you
130 need double backslashes if you want a single backslash in python
131 code.
132 """
133 name_ = "setup"
134
135 _code = base.ListOfAtomsAttribute("codeFrags",
136 description="Python function bodies setting globals for the function"
137 " application. Macros are expanded in the context"
138 " of the procedure's parent.",
139 itemAttD=base.UnicodeAttribute("code", description="Python function"
140 " bodies setting globals for the function application. Macros"
141 " are expanded in the context of the procedure's parent.",
142 copyable=True),
143 copyable=True)
144 _pars = base.StructListAttribute("pars", ProcPar,
145 description="Names to add to the procedure's global namespace.",
146 copyable=True)
147 _imports = base.UnicodeAttribute("imports",
148 description="A list of comma-separated imports to put into the"
149 " code's namespace. Dottesd specs like a.b.c are converted to"
150 " ``from a.b import c``",
151 default=base.NotGiven,
152 copyable=True)
153 _original = base.OriginalAttribute()
154
155 def _getParSettingCode(self, useLate, indent, bindings):
156 """returns code that sets our parameters.
157
158 If useLate is true, generate for late bindings. Indent the
159 code by indent. Bindings is a dictionary overriding
160 the defaults or setting parameter values.
161 """
162 parCode = []
163 for p in self.pars:
164 if p.late==useLate:
165 val = bindings.get(p.key, base.NotGiven)
166 if val is base.NotGiven:
167 val = p.content_
168 if val is base.NotGiven:
169 # val must be bound somewhere else (since _ensureParsBound
170 # succeeded); don't emit any code for this par in this setup
171 # and hope for the best.
172 continue
173
174 if not useLate and val.strip().startswith("@"):
175 # Heuristic: We forbid @-expressions in val. This is doene
176 # explicitly here because this error is hard to spot and
177 # we probably won't have much in the way of false positives.
178 raise base.StructureError("You cannot use @-references in"
179 f" non-late parameter bindings. But '{val}' (bound to {p.key})"
180 " looks like an @-reference, so I give up.",
181 pos=self.getSourcePosition())
182 parCode.append("%s%s = %s"%(indent, p.key, val))
183
184 return "\n".join(parCode)
185
186 def getParCode(self, bindings):
187 """returns code doing setup bindings un-indented.
188 """
189 return self._getParSettingCode(False, "", bindings)
190
191 def getLateCode(self, bindings):
192 """returns code doing late (in-function) bindings indented with two
193 spaces.
194 """
195 return self._getParSettingCode(True, " ", bindings)
196
197 def getImportsCode(self):
198 if not self.imports:
199 return
200 for spec in self.imports.strip().split(","):
201 parts = spec.strip().split(".")
202 if len(parts)>1:
203 yield "from %s import %s"%(".".join(parts[:-1]), parts[-1])
204 else:
205 yield "import "+parts[0]
206
207 def getBodyCode(self):
208 """returns the body code un-indented.
209 """
210 collectedCode = list(self.getImportsCode())
211 for frag in self.codeFrags:
212 try:
213 collectedCode.append(
214 utils.fixIndentation(frag, "", governingLine=1))
215 except base.LiteralParseError as ex:
216 ex.pos = self.getSourcePosition()
217 raise
218
219 return "\n".join(collectedCode)
220
221
222 class ProcDef(base.Structure, base.RestrictionMixin):
223 """An embedded procedure.
224
225 Embedded procedures are python code fragments with some interface defined
226 by their type. They can occur at various places (which is called procedure
227 application generically), e.g., as row generators in grammars, as apply-s in
228 rowmakers, or as SQL phrase makers in condDescs.
229
230 They consist of the actual actual code and, optionally, definitions like
231 the namespace setup, configuration parameters, or a documentation.
232
233 The procedure applications compile into python functions with special
234 global namespaces. The signatures of the functions are determined by
235 the type attribute.
236
237 ProcDefs are referred to by procedure applications using their id.
238 """
239 name_ = "procDef"
240
241 _code = base.UnicodeAttribute("code", default=base.NotGiven,
242 copyable=True, description="A python function body.")
243 _setup = base.StructListAttribute("setups", ProcSetup,
244 description="Setup of the namespace the function will run in",
245 copyable=True)
246 _doc = base.UnicodeAttribute("doc", default="", description=
247 "Human-readable docs for this proc (may be interpreted as restructured"
248 " text).", copyable=True)
249 _type = base.EnumeratedUnicodeAttribute("type", default=None, description=
250 "The type of the procedure definition. The procedure applications"
251 " will in general require certain types of definitions.",
252 validValues=["t_t", "apply", "rowfilter", "sourceFields", "mixinProc",
253 "phraseMaker", "descriptorGenerator", "dataFunction", "dataFormatter",
254 "metaMaker", "regTest", "iterator", "pargetter"],
255 copyable=True,
256 strip=True)
257 _deprecated = base.UnicodeAttribute("deprecated", default=None,
258 copyable=True, description="A deprecation message. This will"
259 " be shown if this procDef is being compiled.")
260 _original = base.OriginalAttribute()
261
262 def getCode(self):
263 """returns the body code indented with two spaces.
264 """
265 if self.code is base.NotGiven:
266 return ""
267 else:
268 try:
269 return utils.fixIndentation(self.code, " ", governingLine=1)
270 except base.LiteralParseError as ex:
271 ex.pos = self.getSourcePosition()
272 raise
273
274 @functools.lru_cache(1)
275 def getSetupPars(self):
276 """returns all parameters used by setup items, where lexically
277 later items override earlier items of the same name.
278 """
279 return unionByKey(*[s.pars for s in self.setups])
280
281 def getLateSetupCode(self, boundNames):
282 return "\n".join(s.getLateCode(boundNames) for s in self.setups)
283
284 def getParSetupCode(self, boundNames):
285 return "\n".join(s.getParCode(boundNames) for s in self.setups)
286
287 def getBodySetupCode(self, boundNames):
288 return "\n".join(s.getBodyCode() for s in self.setups)
289
290
291 class ProcApp(ProcDef):
292 """An abstract base for procedure applications.
293
294 Deriving classes need to provide:
295
296 - a requiredType attribute specifying what ProcDefs can be applied.
297 - a formalArgs attribute containing a (python) formal argument list
298 - of course, a name_ for XML purposes.
299
300 They can, in addition, give a class attribute additionalNamesForProcs,
301 which is a dictionary that is joined into the global namespace during
302 procedure compilation.
303 """
304 _procDef = base.ReferenceAttribute("procDef", forceType=ProcDef,
305 default=base.NotGiven, description="Reference to the procedure"
306 " definition to apply", copyable=True)
307 _bindings = base.StructListAttribute("bindings", description=
308 "Values for parameters of the procedure definition",
309 childFactory=Binding, copyable=True)
310 _name = base.UnicodeAttribute("name", default=base.NotGiven,
311 description="A name of the proc. ProcApps compute their (python)"
312 " names to be somewhat random strings. Set a name manually to"
313 " receive more easily decipherable error messages. If you do that,"
314 " you have to care about name clashes yourself, though.", strip=True)
315
316 requiredType = None
317
318 additionalNamesForProcs = {}
319
320 def validate(self):
321 if self.procDef and self.procDef.type and self.requiredType:
322 if self.procDef.type!=self.requiredType:
323 raise base.StructureError("The procDef %s has type %s, but"
324 " here %s procDefs are required."%(self.procDef.id,
325 self.procDef.type, self.requiredType))
326
327 if self.procDef:
328 if self.procDef.deprecated:
329 if self.getSourcePosition()!="<internally built>":
330 # for now, don't warn about these; they typically
331 # originate when copying/adapting cores and will just
332 # confuse operators
333 procId = "unnamed procApp"
334 if self.name:
335 procId = "procApp %s"%self.name
336
337 base.ui.notifyWarning("%s, %s: %s"%(
338 self.getSourcePosition(),
339 procId,
340 utils.fixIndentation(self.procDef.deprecated, "")))
341
342 super().validate()
343 self._ensureParsBound()
344
345 def completeElement(self, ctx):
346 super().completeElement(ctx)
347 if self.name is base.NotGiven: # make up a name from self's id
348 self.name = ("proc%x"%id(self)).replace("-", "")
349
350 @functools.lru_cache(1)
351 def getSetupPars(self):
352 """returns the setup parameters for the proc app, where procDef
353 parameters may be overridden by self's parameters.
354 """
355 allSetups = []
356 if self.procDef is not base.NotGiven:
357 allSetups.extend(self.procDef.setups)
358 allSetups.extend(self.setups)
359 return unionByKey(*[s.pars for s in allSetups])
360
361 def _ensureParsBound(self):
362 """raises an error if non-defaulted pars of procDef are not filled
363 by the bindings.
364 """
365 bindNames = dict((b.key, b) for b in self.bindings)
366 for p in self.getSetupPars():
367
368 if p.alias and p.alias in bindNames:
369 binding = bindNames.pop(p.alias)
370 binding.key = p.key
371 if p.key in bindNames:
372 raise base.StructureError("Both canonical name and alias bound:"
373 " %s, %s"%(p.key, p.alias))
374 else:
375 bindNames[p.key] = binding
376
377 if not p.isDefaulted():
378 if not p.key in bindNames:
379 raise base.StructureError("Parameter %s is not defaulted in"
380 " %s and thus must be bound."%(p.key, self.name))
381 if p.key in bindNames:
382 bindNames.pop(p.key)
383
384 if bindNames:
385 raise base.StructureError("May not bind non-existing parameter(s)"
386 " %s."%(", ".join(bindNames)))
387
388 def onElementComplete(self):
389 super().onElementComplete()
390 self._boundNames = dict((b.key, b.content_) for b in self.bindings)
391
392 def _combineWithProcDef(self, methodName, boundNames):
393 # A slightly tricky helper method for the implementation of get*SetupCode:
394 # this combines the results of calling methodName on a procDef
395 # (where applicable) with calling it on ProcDef for self.
396 parts = []
397 if self.procDef is not base.NotGiven:
398 parts.append(getattr(self.procDef, methodName)(boundNames))
399
400 parts.append(getattr(ProcDef, methodName)(self, boundNames))
401 return "\n".join(parts)
402
403 def getLateSetupCode(self, boundNames):
404 return self._combineWithProcDef("getLateSetupCode", boundNames)
405
406 def getParSetupCode(self, boundNames):
407 return self._combineWithProcDef("getParSetupCode", boundNames)
408
409 def getBodySetupCode(self, boundNames):
410 return self._combineWithProcDef("getBodySetupCode", boundNames)
411
412 def getSetupCode(self):
413 code = "\n".join((
414 self.getParSetupCode(self._boundNames),
415 self.getBodySetupCode(self._boundNames)))
416 if "\\" in code:
417 code = self.parent.expand(code)
418 return code
419
420 def _getFunctionDefinition(self, mainSource):
421 """returns mainSource in a function definition with proper
422 signature including setup of late code.
423 """
424 parts = [self.getLateSetupCode(self._boundNames)]
425 parts.append(mainSource)
426 body = "\n".join(parts)
427 if not body.strip():
428 body = " pass"
429 return "def %s(%s):\n%s"%(self.name, self.formalArgs,
430 body)
431
432 def getFuncCode(self):
433 """returns a function definition for this proc application.
434
435 This includes bindings of late parameters.
436
437 Locally defined code overrides code defined in a procDef.
438 """
439 mainCode = ""
440 if self.code is base.NotGiven:
441 if self.procDef is not base.NotGiven:
442 mainCode = self.procDef.getCode()
443 else:
444 mainCode = self.getCode()
445 code = self._getFunctionDefinition(mainCode)
446 if "\\" in code:
447 code = self.parent.expand(code)
448 return code
449
450 def _compileForParent(self, parent):
451 """helps compile.
452 """
453 # go get the RD for parent; it's always handy in this kind
454 # of code
455 curEl = parent
456 while not hasattr(curEl, "rd"):
457 if curEl.parent:
458 curEl = curEl.parent
459 else:
460 break
461 try:
462 rd = curEl.rd
463 except AttributeError:
464 # maybe an unrooted element
465 rd = None
466
467 return rmkfuncs.makeProc(
468 self.name, self.getFuncCode(),
469 self.getSetupCode(), parent,
470 self.getSourcePosition(),
471 rd=rd,
472 procDef=self,
473 **self.additionalNamesForProcs)
474
475 def breakCircles(self):
476 # overridden to undo additional memoization
477 ProcDef.breakCircles(self)
478 utils.forgetMemoized(self)
479
480 def compile(self, parent=None):
481 """returns a callable for this procedure application.
482
483 You can pass a different parent; it will then be used to
484 expand macros. If you do not give it, the embedding structure will
485 be used.
486 """
487 if parent is None:
488 parent = self.parent
489 return utils.memoizeOn(parent, self, self._compileForParent, parent)