Debian Codegraph @

gavo/rscdef/mixins.py

raw
1 """
2 Resource mixins.
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 threading
12
13 from gavo import base
14 from gavo.base import activetags
15 from gavo.rscdef import procdef
16
17
18 __docformat__ = "restructuredtext en"
19
20
21 class ProcessEarly(procdef.ProcApp):
22 """A code fragment run by the mixin machinery when the structure
23 being worked on is being finished.
24
25 Within processEarly, you can access:
26
27 - the structure the mixin is applied to as "substrate"
28 - the mixin parameters as "mixinPars"
29 - the parse context as "context"
30
31 (the context is particularly handy for context.resolveId)
32 """
33 name_ = "processEarly"
34 formalArgs = "context, substrate, mixinPars"
35
36
37 class ProcessLate(procdef.ProcApp):
38 """A code fragment run by the mixin machinery when the parser parsing
39 everything exits.
40
41 Within processLate, you can access:
42
43 - the structure mixed in as "substrate",
44 - the root structure of the whole parse tree as root,
45 - the parse context as "context",
46 - and the mixin parameters (a dictionary) as "mixinPars".
47 """
48 name_ = "processLate"
49 formalArgs = "substrate, root, context, mixinPars"
50
51
52 class MixinPar(procdef.AliasableRDParameter):
53 """A parameter definition for mixins.
54
55 The (optional) body provides a default for the parameter.
56 """
57 name_ = "mixinPar"
58
59 _expr = base.DataContent(description="The default for the parameter."
60 " A __NULL__ here does not directly mean None/NULL, but since the"
61 " content will frequently end up in attributes, it will usually work"
62 " as presetting None."
63 " An empty content means a non-preset parameter, which must be filled"
64 " in applications. The magic value __EMPTY__ allows presetting an"
65 " empty string.",
66 # mixinPars must not evaluate __NULL__; this stuff ends up in
67 # macro expansions, where an actual None is not desirable.
68 null=None,
69 copyable=True, strip=True, default=base.NotGiven)
70
71 def validate(self):
72 super().validate()
73 if len(self.key)<2:
74 raise base.LiteralParseError("name", self.key, hint="Names of"
75 " mixin parameters must have at least two characters (since"
76 " they are exposed as macros")
77
78
79 class LateEvents(activetags.EmbeddedStream):
80 """An event stream played back by a mixin when the substrate is being
81 finalised (but before the early processing).
82 """
83 name_ = "lateEvents"
84
85
86 class MixinDef(activetags.ReplayBase):
87 """A definition for a resource mixin.
88
89 Resource mixins are resource descriptor fragments typically rooted
90 in tables (though it's conceivable that other structures could
91 grow mixin attributes as well).
92
93 They are used to define and implement certain behaviours components of
94 the DC software want to see:
95
96 - products want to be added into their table, and certain fields are required
97 within tables describing products
98 - tables containing positions need some basic machinery to support scs.
99 - siap needs quite a bunch of fields
100
101 Mixins consist of events that are played back on the structure
102 mixing in before anything else happens (much like original) and
103 two procedure definitions, viz, processEarly and processLate.
104 These can access the structure that has the mixin as substrate.
105
106 processEarly is called at the lexical location of the mixin.
107 processLate is executed just before the parser exits. This
108 is the place to fix up anything that uses the table mixed in. Note,
109 however, that you should be as conservative as possible here -- you
110 should think of DC structures as immutable as long as possible.
111
112 Programmatically, you can check if a certain table mixes in
113 something by calling its mixesIn method.
114
115 Recursive application of mixins, even to separate objects, will deadlock.
116 """
117 name_ = "mixinDef"
118
119 _doc = base.UnicodeAttribute("doc", description="Documentation for"
120 " this mixin", strip=False)
121 _events = base.StructAttribute("events",
122 childFactory=activetags.EmbeddedStream,
123 description="Events to be played back into the structure mixing"
124 " this in at mixin time.", copyable=True,
125 default=base.NotGiven)
126 _lateEvents = base.StructAttribute("lateEvents",
127 childFactory=LateEvents,
128 description="Events to be played back into the structure mixing"
129 " this in at completion time.", copyable=True,
130 default=base.NotGiven)
131 _processEarly = base.StructAttribute("processEarly",
132 default=None,
133 childFactory=ProcessEarly,
134 description="Code executed at element fixup.",
135 copyable=True)
136 _processLate = base.StructAttribute("processLate",
137 default=None,
138 childFactory=ProcessLate,
139 description="Code executed resource fixup.",
140 copyable=True)
141 _pars = base.UniquedStructListAttribute("pars",
142 childFactory=MixinPar,
143 uniqueAttribute="key",
144 description="Parameters available for this mixin.",
145 copyable=True)
146 _original = base.OriginalAttribute()
147
148 def completeElement(self, ctx):
149 # we want to double-expand macros in mixins. Thus, reset all
150 # value/expanded events to plain values
151 if self.events:
152 self.events.unexpandMacros()
153 if self.lateEvents:
154 self.lateEvents.unexpandMacros()
155
156 # This lock protects against multiple uses of applyTo. This is
157 # necessary because during replay, we have macroExpansions and
158 # macroParent reflect a concrete application's context.
159 self.applicationLock = threading.Lock()
160 super().completeElement(ctx)
161
162 def _defineMacros(self, fillers, destination):
163 """creates attributes macroExpansions and parentMacroPackage used by
164 execMacros.
165
166 Within mixins, you can use macros filled by mixin parameters or
167 expanded by the substrate. This information is local to a concrete
168 mixin application. Hence, applyTo calls this method, and the
169 attributes created are invalid for any subsequent or parallel applyTo
170 calls. Therefore, applyTo acquires the applicationLock before
171 calling this.
172 """
173 self.parentMacroPackage = None
174 if hasattr(destination, "execMacro"):
175 self.parentMacroPackage = destination
176
177 self.macroExpansions = {}
178 for p in self.pars:
179 if p.key in fillers:
180 self.macroExpansions[p.key] = fillers.pop(p.key)
181 if p.alias in fillers:
182 raise base.StructureError("Both canonical name and alias bound:"
183 " %s, %s"%(p.key, p.alias))
184
185 elif p.alias in fillers:
186 self.macroExpansions[p.key] = fillers.pop(p.alias)
187
188 elif p.isDefaulted():
189 self.macroExpansions[p.key] = p.content_
190
191 else:
192 raise base.StructureError("Mixin parameter %s mandatory"%p.key)
193
194 if fillers:
195 raise base.StructureError("The attribute(s) %s is/are not allowed"
196 " on this mixin"%(",".join(fillers)))
197
198 def execMacro(self, macName, args):
199 if macName in self.macroExpansions:
200 return self.macroExpansions[macName]
201 if self.parentMacroPackage:
202 return self.parentMacroPackage.execMacro(macName, args)
203
204 def applyTo(self, destination, ctx, fillers={}):
205 """replays the stored events on destination and arranges for processEarly
206 and processLate to be run.
207 """
208 with self.applicationLock:
209 self._defineMacros(fillers.copy(), destination)
210 if self.events:
211 self.replay(self.events.events_, destination, ctx)
212
213 if self.processEarly is not None:
214 self.processEarly.compile(destination)(ctx, destination,
215 self.macroExpansions)
216
217 if self.processLate is not None:
218 def procLate(rootStruct, parseContext,
219 destination=destination, exp=self.macroExpansions.copy()):
220 self.processLate.compile(destination)(
221 destination, rootStruct,
222 parseContext, exp)
223 ctx.addExitFunc(procLate)
224
225 if self.lateEvents:
226 origComplete = destination.completeElement
227 def newComplete(ctx):
228 with self.applicationLock:
229 self._defineMacros(fillers.copy(), destination)
230 self.replay(self.lateEvents.events_, destination, ctx)
231 origComplete(ctx)
232 destination.completeElement = newComplete
233
234 def applyToFinished(self, destination):
235 """applies the mixin to an object already parsed.
236
237 Late callbacks will only be executed if destination has an rd
238 attribute; if that is the case, this rd's idmap will be amended
239 with anything the mixin comes up with.
240 """
241 rd = None
242 if hasattr(destination, "rd"):
243 rd = destination.rd
244
245 ctx = base.ParseContext()
246 if rd is not None:
247 ctx.idmap = destination.rd.idmap
248 self.applyTo(destination, ctx)
249
250 # we don't keep the application lock for this; applyToFinished
251 # is more of a debugging thing, so we don't worry too much.
252 if self.lateEvents:
253 self.replay(self.lateEvents.events_, destination, ctx)
254
255 if rd is not None:
256 ctx.runExitFuncs(rd)
257
258
259 class _MixinParser(base.Parser):
260 """A parser for structured mixin references.
261
262 These can contain attribute definitions for any parameter of the
263 mixin referenced.
264 """
265 def __init__(self, parent, parentAttr):
266 self.parent, self.parentAttr = parent, parentAttr
267 self.fillers = {}
268 self.curName = None # this is non-None while parsing a child element
269
270 def start_(self, ctx, name, value):
271 if self.curName is not None:
272 raise base.StructureError("%s elements cannot have %s children in"
273 " mixins."%(self.curName, name))
274 self.curName = name
275 return self
276
277 def value_(self, ctx, name, value):
278 if name=="content_":
279 if self.curName:
280 self.fillers[self.curName] = value
281 else:
282 self.fillers["mixin name"] = value.strip()
283 else:
284 self.fillers[name] = value
285 return self
286
287 def end_(self, ctx, name, value):
288 if self.curName: # end parsing parameter binding
289 self.curName = None
290 return self
291 else: # end of mixin application, run the mixin and hand control back to
292 # mixin parent
293 if "mixin name" not in self.fillers:
294 raise base.StructureError("Empty mixin children not allowed")
295 mixinRef = self.fillers.pop("mixin name")
296 self.parentAttr.feed(ctx, self.parent, mixinRef, fillers=self.fillers)
297 return self.parent
298
299
300 class MixinAttribute(base.SetOfAtomsAttribute):
301 """An attribute defining a mixin.
302
303 This currently is only offered on tables, though in principle we could
304 have it anywhere now, but we'd want some compatibility checking
305 then.
306
307 This is never copyable since this would meaning playing the same
308 stuff into an object twice.
309
310 This means trouble for magic scripts (in particular processLate); e.g.,
311 if you copy a table mixing in products, the data element for that table
312 will not receive the product table. Goes to show the whole product
313 mess is ugly and needs a good idea.
314 """
315 def __init__(self, **kwargs):
316 kwargs["itemAttD"] = base.UnicodeAttribute("mixin", strip=True)
317 kwargs["description"] = kwargs.get("description",
318 "Reference to a mixin this table should contain; you can"
319 " give mixin parameters as attributes or children.")
320 kwargs["copyable"] = False
321 base.SetOfAtomsAttribute.__init__(self, "mixin", **kwargs)
322
323 def feed(self, ctx, instance, mixinRef, fillers={}):
324 """feeds the immediate elements and schedules the rest of
325 actions to be taken in time.
326 """
327 mixin = ctx.resolveId(mixinRef, instance=instance, forceType=MixinDef)
328 base.SetOfAtomsAttribute.feed(self, ctx, instance, mixinRef)
329 mixin.applyTo(instance, ctx, fillers)
330
331 # no need to override feedObject: On copy and such, replay has already
332 # happened.
333
334 def iterParentMethods(self):
335 def mixesIn(instance, mixinRef):
336 return mixinRef in instance.mixin
337 yield "mixesIn", mixesIn
338
339 def makeUserDoc(self):
340 return ("A mixin reference, typically to support certain protocol."
341 " See Mixins_.")
342
343 def create(self, parent, ctx, name):
344 # since mixins may contain parameters, we need a custom parser
345 # when mixin is a child.
346 return _MixinParser(parent, self)