Debian Codegraph @

gavo/base/structure.py

raw
1 """
2 Representation of structured data deserializable from XML.
3
4 We want all the managed attribute stuff since the main user input comes
5 from resource descriptors, and we want relatively strong input validation
6 here. Also, lots of fancy copying and crazy cross-referencing is
7 going on in our resource definitions, so we want a certain amount of
8 rigorous structure. Finally, a monolithic parser for that stuff
9 becomes *really* huge and tedious, so I want to keep the XML parsing
10 information in the constructed objects themselves.
11 """
12
13 #c Copyright 2008-2025, the GAVO project <[email protected]>
14 #c
15 #c This program is free software, covered by the GNU GPL. See the
16 #c COPYING file in the source distribution.
17
18
19 from gavo import utils
20 from gavo.base import attrdef
21 from gavo.base import common
22 from gavo.base import parsecontext
23
24 from gavo.utils.dachstypes import (cast, Any, Callable, Dict, Iterator,
25 List, Optional, Set, StructParseContext, StructParserValue,
26 Tuple, Type, Union)
27
28
29 def sortAttrs(attrSeq: List[attrdef.AttributeDef]
30 ) -> List[attrdef.AttributeDef]:
31 """evaluates the ``before`` attributes on the AttributeDefs in attrsSeq
32 and returns a sequence satisfying them.
33
34 It returns a reference to attrSeq for convenience.
35 """
36 beforeGraph, prependMeta = [], False
37 for att in attrSeq:
38 if att.before:
39 beforeGraph.append((att.name_, att.before))
40 if att.name_=="meta_":
41 prependMeta = True
42
43 if beforeGraph:
44 attDict = dict((a.name_, a) for a in attrSeq)
45 sortedNames = utils.topoSort(beforeGraph)
46
47 # Hack: metadata always comes first
48 if prependMeta:
49 sortedNames[:0] = ["meta_"]
50
51 sortedAtts = [attDict[n] for n in sortedNames]
52 attrSeq = sortedAtts+list(set(attrSeq)-set(sortedAtts))
53 return attrSeq
54
55
56 def buildstructure(cls: Type["StructureBase"]) -> Type["StructureBase"]:
57 """A class decorator for DaCHS structures.
58
59 This should eventually do what the StructType metaclass does
60 at this point, because with that, mypy annotations can be
61 fiddled in (which is mypy-impossible with metaclasses).
62
63 For now, it's a no-op that will go into code as we add type
64 annotations.
65 """
66 cls.STRUCT_SENTINEL = None # type: ignore # dynamic attribute creation
67 return cls
68
69
70 class StructType(type):
71 """A metaclass for the representation of structured data.
72
73 StructType classes with this will be called structures within
74 the DC software.
75
76 Structures do quite a bit of the managed attribute nonsense to
77 meaningfully catch crazy user input.
78
79 Basically, you give a Structure class attributes (preferably with
80 underscores in front) specifying the attributes the instances
81 should have and how they should be handled.
82
83 Structures must be constructed with a parent (for the root
84 element, this is None). All other arguments should be keyword
85 arguments. If given, they have to refer to existing attributes,
86 and their values will directly give the the values of the
87 attribute (i.e., parsed values).
88
89 Structures should always inherit from StructBase below and
90 arrange for its constructor to be called, since, e.g., default
91 processing happens there.
92
93 Structures have a managedAttrs dictionary containing names and
94 attrdef.AttributeDef objects for the defined attributes.
95
96 TODO: We should probably move all this into the buildstructure class
97 decorator once we are done with type annotations. None of
98 what is here couldn't be done just as well in a class decorator
99 (which didn't exist when this was originally written).
100 """
101 def __init__(cls, name: str, bases: Tuple[type, ...], dict: Dict
102 ) -> None:
103 type.__init__(cls, name, bases, dict)
104 cls._collectManagedAttrs()
105 cls._insertAttrMethods()
106
107 def _collectManagedAttrs(cls) -> None:
108 """collects a dictionary of managed attributes in managedAttrs.
109 """
110 managedAttrs: Dict[str, attrdef.AttributeDef] = {}
111 completedCallbacks: List[Callable[[], None]] = []
112 attrSeq: List[attrdef.AttributeDef] = []
113
114 for name in dir(cls):
115 if not hasattr(cls, name):
116 continue
117 val = getattr(cls, name)
118
119 if isinstance(val, attrdef.AttributeDef):
120 managedAttrs[val.name_] = val
121 attrSeq.append(val)
122 if val.aliases:
123 for alias in val.aliases:
124 managedAttrs[alias] = val
125 cls.attrSeq = sortAttrs(attrSeq)
126 cls.managedAttrs = managedAttrs
127 cls.completedCallbacks = completedCallbacks
128
129 def _insertAttrMethods(cls) -> None:
130 """adds methods defined by cls's managedAttrs for the parent to
131 cls.
132 """
133 for val in set(cls.managedAttrs.values()):
134 for name, meth in val.iterParentMethods():
135 setattr(cls, name, meth)
136
137
138 class DataContent(attrdef.UnicodeAttribute):
139 """A magic attribute that allows character content to be added to
140 a structure.
141
142 You can configure it with all the arguments available for UnicodeAttribute.
143
144 Since parsers may call characters with an empty string for
145 empty elements, the empty string will not be fed (i.e., the default
146 will be preserved). This makes setting an empty string as an element content
147 impossible (you could use DataContent with strip=True, though), but that's
148 probably not a problem.
149
150 On an instance, you will find the content as a string in the content_
151 attribute.
152 """
153 typeDesc_ = "string"
154
155 def __init__(self, default: Union[utils.NotGivenType, str] = "",
156 description: str = "Undocumented", **kwargs: Any) -> None:
157 attrdef.UnicodeAttribute.__init__(self, "content_", default=default,
158 description=description, **kwargs)
159
160 def feed(self,
161 ctx: StructParseContext,
162 instance: "Structure",
163 value: str) -> None:
164 if value=='':
165 return
166 attrdef.UnicodeAttribute.feed(self, ctx, instance, value)
167
168 def makeUserDoc(self) -> str:
169 return ("**Character content** of the element (defaulting to %s) -- %s"%(
170 repr(self.default_), self.description_))
171
172
173 @buildstructure
174 class StructureBase(common.StructCallbacks, metaclass=StructType):
175 """A base class for all structures (i.e., RD elements).
176
177 You must arrange for calling its constructor from classes inheriting
178 this.
179
180 The constructor receives a parent (another structure, or None)
181 and keyword arguments containing values for actual attributes
182 (which will be set without any intervening consultation of the
183 AttributeDef).
184
185 The attribute definitions talking about structures let you
186 set parent to None when constructing default values; they will
187 then insert the actual parent.
188 """
189
190 name_: Union[str, Type[utils.Undefined]] = attrdef.Undefined
191
192 _id = parsecontext.IdAttribute("id",
193 description="Node identity for referencing")
194
195 # the following is managed by setPosition/getSourcePosition
196 __fName: Optional[str] = None
197 __lineNumber: Optional[Union[int, str]] = None
198
199 def __init__(self,
200 parent: Optional["ParseableStructure"],
201 **kwargs: Any) -> None:
202
203 self.parent: Optional["ParseableStructure"] = None
204 if parent is not None:
205 self.setParent(parent)
206
207 # set defaults
208 for val in self.attrSeq:
209 try:
210 if not hasattr(self, val.name_): # don't clobber properties
211 # set up by attributes.
212 setattr(self, val.name_, val.default_)
213 except AttributeError: # default on property given
214 raise utils.logOldExc(common.StructureError(
215 f"{val.name_} attributes on {self.name_} have builtin defaults only"))
216
217 # set keyword arguments
218 for name, val in kwargs.items():
219 if name in self.managedAttrs:
220 if not hasattr(self.managedAttrs[name], "computed_"):
221 self.managedAttrs[name].feedObject(self, val)
222 else:
223 raise common.StructureError(
224 "{} objects have no attribute {}".format(
225 self.__class__.__name__, name))
226
227 def _nop(self, *args, **kwargs):
228 pass
229
230 def setParent(self, parent: "ParseableStructure") -> None:
231 """sets the parent of a Structure.
232
233 This is a method mainly to let individual elements override the
234 behaviour.
235 """
236 self.parent = parent
237 super().setParent(parent)
238
239 def setPosition(self,
240 fName: Optional[str],
241 lineNumber: Union[int, str]) -> None:
242 """should be called by parsers to what file at what line the
243 serialisation came from.
244 """
245 self.__fName, self.__lineNumber = fName, lineNumber
246
247 def getSourcePosition(self) -> str:
248 """returns a string representation of where the struct was parsed
249 from.
250 """
251 if self.__fName is None:
252 return "<internally built>"
253 else:
254 return "{}, line {}".format(self.__fName, self.__lineNumber)
255
256 def getAttributes(self, attDefsFrom: Optional[StructType] = None
257 ) -> Dict[str, Any]:
258 """returns a dict of the current attributes, suitable for making
259 a shallow copy of self.
260
261 Struct attributes will not be reparented, so there are limits to
262 what you can do with such shallow copies.
263 """
264 if attDefsFrom is None:
265 attrs = set(self.managedAttrs.values())
266 else:
267 attrs = set(attDefsFrom.managedAttrs.values())
268 try:
269 return dict([(att.name_, getattr(self, att.name_))
270 for att in attrs])
271 except AttributeError as msg:
272 raise utils.logOldExc(common.StructureError(
273 "Attempt to copy from invalid source: %s"%str(msg)))
274
275 def getCopyableAttributes(self,
276 ignoreKeys: Set[str] = set(),
277 ctx: Optional[StructParseContext] = None,
278 newParent: Optional["StructureBase"] = None) -> Dict[str, Any]:
279 """returns a dictionary mapping attribute names to copyable children.
280
281 ignoreKeys can be a set or dict of additional attribute names to ignore.
282 The children are orphan deep copies.
283 """
284 return dict((att.name_, att.getCopy(self, newParent, ctx))
285 for att in self.attrSeq
286 if att.copyable and att.name_ not in ignoreKeys)
287
288 def adopt(self, struct: "ParseableStructure") -> "ParseableStructure":
289 """reparents a structure to self.
290
291 This returns the structure for convenience.
292
293 This fails if there is a previous parent set, as structures
294 don't actually support unparenting (and I have found no reason for
295 them to do so).
296 """
297 if struct.parent:
298 # TODO: we probably should warn this, or clone the struct, or whatever.
299 # Simply reparenting the struct feels wrong. But it's worked so
300 # far, so let's ignore this for now.
301 pass
302
303 struct.setParent(cast("ParseableStructure", self))
304 return struct
305
306 def iterChildren(self) -> Iterator["Structure"]:
307 """iterates over structure children of self.
308
309 To make this work, attributes containing structs must define
310 iterChildren methods (and the others must not).
311 """
312 for att in self.attrSeq:
313 if hasattr(att, "iterChildren"):
314 for c in att.iterChildren(self):
315 yield c
316
317 @classmethod
318 def fromStructure(cls, newParent: "Structure", oldStructure: "Structure"
319 ) -> "StructureBase":
320 consArgs = dict([(att.name_, getattr(oldStructure, att.name_))
321 for att in oldStructure.attrSeq])
322 return cls(newParent, **consArgs)
323
324 def breakCircles(self) -> None:
325 """removes the parent attributes from all child structures recursively.
326
327 The struct will probably be broken after this, but this is sometimes
328 necessary to help the python garbage collector.
329
330 In case you're asking: parent cannot be a weak reference with the current
331 parse architecture, as it usually is the only reference to the embedding
332 object. Yes, we should probably change that.
333 """
334 for child in self.iterChildren():
335 # we don't want to touch structs that aren't our children
336 if hasattr(child, "parent") and child.parent is self:
337 if hasattr(child, "breakCircles"):
338 child.breakCircles()
339 delattr(child, "parent")
340
341
342 class ParseableStructure(StructureBase, common.Parser):
343 """A base class for Structures parseable from EventProcessors (and
344 thus XML).
345
346 This is still abstract in that you need at least a name_ attribute.
347 But it knows how to be fed from a parser, plus you have feed and feedObject
348 methods that look up the attribute names and call the methods on the
349 respective attribute definitions.
350 """
351 _pristine = True
352
353 def finishElement(self, ctx: StructParseContext):
354 return self
355
356 def getAttribute(self, name: str) -> Any:
357 """Returns an attribute instance from name.
358
359 This function will raise a StructureError if no matching attribute
360 definition is found.
361 """
362 if name in self.managedAttrs:
363 return self.managedAttrs[name]
364 if name=="content_":
365 raise common.StructureError(
366 f"{self.name_} elements must not have character data content.")
367 raise common.StructureError(
368 f"{self.name_} elements have no {name} attributes or children.")
369
370 def end_(self,
371 ctx: StructParseContext,
372 name: str,
373 value: StructParserValue) -> Optional[common.Parser]:
374 try:
375 self.finishElement(ctx)
376 except common.Replace as ex:
377 if ex.newName is not None:
378 name = ex.newName
379 if ex.newOb.id is not None:
380 ctx.registerId(ex.newOb.id, ex.newOb)
381 if self.parent is not None:
382 cast("ParseableStructure", self.parent).feedObject(name, ex.newOb)
383 except common.Ignore:
384 pass
385 else:
386 if self.parent:
387 cast("ParseableStructure", self.parent).feedObject(name, self)
388 # del self.feedEvent (at some point we might selectively reclaim parsers)
389 return self.parent
390
391 def value_(self,
392 ctx: StructParseContext,
393 name: str,
394 value: StructParserValue) -> common.Parser:
395 attDef = self.getAttribute(name)
396 try:
397 attDef.feed(ctx, self, value)
398 except common.Replace as ex:
399 return ex.newOb
400 self._pristine = False
401 return cast(common.Parser, self)
402
403 def start_(self,
404 ctx: StructParseContext,
405 name: str,
406 value: StructParserValue) -> Optional[Union[common.Parser, str]]:
407 attDef = self.getAttribute(name)
408 if hasattr(attDef, "create"):
409 return attDef.create(self, ctx, name)
410 else:
411 return name
412
413 def feed(self,
414 name: str,
415 literal: str,
416 ctx: Optional[StructParseContext] = None) -> None:
417 """feeds the literal to the attribute name.
418
419 If you do not have a proper parse context ctx, so there
420 may be restrictions on what literals can be fed.
421 """
422 self.managedAttrs[name].feed(ctx, self, literal)
423
424 def feedObject(self, name: str, ob: Any) -> None:
425 """feeds the object ob to the attribute name.
426 """
427 self.managedAttrs[name].feedObject(self, ob)
428
429 def iterEvents(self) -> Iterator[common.ParserEvent]:
430 """yields an event sequence that transfers the copyable information
431 from self to something receiving the events.
432
433 If something is not copyable, it is ignored (i.e., keeps its default
434 on the target object).
435 """
436 for att in self.attrSeq:
437 if not att.copyable:
438 continue
439 if hasattr(att, "iterEvents"):
440 yield from att.iterEvents(self)
441 else:
442 val = getattr(self, att.name_)
443 if att.name_=="value":
444 import pdb;pdb.Pdb(nosigint=True).set_trace()
445 if val!=att.default_:
446 yield common.ParserEvent("value", att.name_, att.unparse(val))
447
448 def change(self, **kwargs: Any) -> "StructureBase":
449 """returns a copy of self with all attributes in kwargs overridden with
450 the passed values.
451 """
452 parent = kwargs.pop("parent_", self.parent)
453 runExits, ctx = False, kwargs.pop("ctx", None)
454 if ctx is None:
455 runExits, ctx = True, parsecontext.ParseContext()
456
457 newInstance = self.__class__(parent)
458 for attName, attValue in self.getCopyableAttributes(
459 set(kwargs), ctx, newInstance).items():
460 newInstance.feedObject(attName, attValue)
461 for attName, attValue in kwargs.items():
462 newInstance.feedObject(attName, attValue)
463
464 newInstance.finishElement(ctx)
465
466 if runExits:
467 ctx.runExitFuncs(newInstance)
468 return newInstance
469
470 def copy(self,
471 parent: "StructureBase",
472 ctx: Optional[StructParseContext] = None) -> "StructureBase":
473 """returns a deep copy of self, reparented to parent.
474
475 This is a shallow wrapper around change, present for backward
476 compatibility.
477 """
478 return self.change(parent_=parent, ctx=ctx)
479
480 def feedFrom(self,
481 other: "Structure",
482 ctx: Optional[StructParseContext] = None,
483 suppress: Set = set()) -> None:
484 """feeds parsed objects from another structure.
485
486 This only works if the other structure is a of the same or a superclass
487 of self.
488 """
489 from gavo.base import xmlstruct
490 if ctx is None:
491 ctx = parsecontext.ParseContext()
492 evProc = xmlstruct.EventProcessor(self, ctx)
493 evProc.setParser(cast(Structure, self))
494 for ev in other.iterEvents():
495 evProc.feed(*ev)
496
497
498 # This is so we don't sling around Nones in finishElement.
499 # It should only be passed to instance's completeElement
500 # methods, and they shouldn't do crazy things in here.
501 # Still, we make sure that no ids are registered.
502 class _NullParseContextType(parsecontext.ParseContext):
503 """for base.structure-internal use only.
504 """
505 def registerId(self,
506 elId: str,
507 value: "Structure",
508 silentOverwrite: bool = False) -> None:
509 # we're fake, so don't store anything
510 pass
511 _NullParseContext = _NullParseContextType()
512
513
514 @buildstructure
515 class Structure(ParseableStructure):
516 """the base class for all RD elements.
517
518 It will do some basic validation and will call hooks to complete elements
519 and compute computed attributes, based on ParseableStructure's finishElement
520 hook.
521
522 Also, it supports onParentComplete callbacks; this works by checking
523 if any managedAttr has a onParentComplete method and calling it
524 with the current value of that attribute if necessary.
525 """
526 def callCompletedCallbacks(self) -> None:
527 for attName, attType in self.managedAttrs.items():
528 if hasattr(attType, "onParentComplete"):
529 attVal = getattr(self, attType.name_)
530 if attVal!=attType.default_:
531 attType.onParentComplete(attVal)
532
533 def finishElement(self, ctx: StructParseContext = _NullParseContext
534 ) -> "Structure":
535 self.completeElement(ctx)
536 self.validate()
537 self.onElementComplete()
538 self.callCompletedCallbacks()
539 return self
540
541 def validate(self) -> None:
542 for val in set(self.managedAttrs.values()):
543 if getattr(self, val.name_) is attrdef.Undefined:
544 raise common.StructureError(
545 f"You must set {val.name_} on {self.name_} elements")
546 if hasattr(val, "validate"):
547 val.validate(self)
548 super().validate()
549
550 def onElementComplete(self) -> None:
551 super().onElementComplete()
552
553 def completeElement(self, ctx: StructParseContext) -> None:
554 super().completeElement(ctx)
555
556
557 class RestrictionMixin(common.StructCallbacks):
558 """A mixin for structure classes not allowed in untrusted RDs.
559 """
560 def completeElement(self, ctx: StructParseContext) -> None:
561 if getattr(ctx, "restricted", False):
562 # self.name_ could be undefined below, but then that's our
563 # least problem.
564 raise common.RestrictedElement(self.name_) # type: ignore
565 super().completeElement(ctx)
566
567
568 def makeStruct(structClass: StructType, **kwargs: Any) -> Structure:
569 """creates a parentless instance of structClass with ``**kwargs``.
570
571 You can pass in a ``parent_`` kwarg to force a parent, and a ``ctx_``
572 if you need a parse context.
573
574 This is the preferred way to create struct instances in DaCHS, as it
575 will cause the sequence of completers and validators run. Use it like
576 this::
577
578 MS(rscdef.Column, name="ra", type="double precision)
579 """
580 ctx = kwargs.pop("ctx_", None)
581 parent = kwargs.pop("parent_", None)
582 return structClass(parent, **kwargs).finishElement(ctx)