Debian Codegraph @

gavo/base/parsecontext.py

raw
1 """
2 ParseContexts for parsing into structures.
3
4 A Context is a scratchpad for struct parsing. It always provides an idmap, but
5 you're free to insert additional attributes.
6
7 Based on this, we provide some attribute definitions.
8 """
9
10 #c Copyright 2008-2025, the GAVO project <[email protected]>
11 #c
12 #c This program is free software, covered by the GNU GPL. See the
13 #c COPYING file in the source distribution.
14
15
16 import contextlib
17
18 from gavo import utils
19 from gavo.base import attrdef
20 from gavo.base import caches
21 from gavo.base import common
22
23 from gavo.utils.dachstypes import (cast, Any, Callable, DaCHSConnection, Dict,
24 Iterable, Iterator, List, Optional, StructParseContext, StructParserValue,
25 Structure, TYPE_CHECKING, Union)
26
27
28 if TYPE_CHECKING:
29 from gavo.utils.plainxml import ErrorPosition
30 from gavo.rscdef import TableDef
31 from gavo.base.structure import StructType, ParseableStructure
32
33
34 def assertType(id: str, ob: Structure, forceType: Optional["StructType"]
35 ) -> Structure:
36 """raises a StructureError if forceType is not None and ob is not of
37 type forceType, returns ob otherwise.
38 """
39 if forceType:
40 if not isinstance(ob, forceType):
41 raise common.StructureError("Reference to '%s' yielded object of type"
42 " %s, but expected a(n) %s instance."%(id, ob.__class__.__name__,
43 forceType.__name__))
44 return ob
45
46
47 def resolveCrossId(
48 id: str, forceType: Optional["StructType"] = None, **kwargs: Any) -> Structure:
49 """resolves ``id``, where id is of the form ``rdId#id``.
50
51 ``forceType``, if non-None must be a DaCHS struct type (e.g.,
52 rscdef.Table); a ``StructureError`` will be raised if the reference
53 resolves to something else than an instance of that type.
54
55 ``id`` can also be a simple rd id.
56
57 ``kwargs`` lets you pass additional keyword arguments to the ``getRD``
58 calls that may be triggered by this.
59 """
60 try:
61 rdId, rest = id.split("#")
62 except ValueError:
63 if "#" in id:
64 raise common.LiteralParseError("id", id, hint="There must be at most"
65 " one hash sign ('#') in cross ids, separating the rd identifier"
66 " from the rd-internal id")
67 rdId, rest = id, None
68
69 try:
70 srcRD = caches.getRD(rdId, **kwargs) # type: ignore # caches-fix
71 except common.RDNotFound as ex:
72 ex.hint = (
73 "I was trying to resolve the reference %s; note that DaCHS only"
74 " uses RDs residing below inputsDir and ignores all others."
75 " If there's an RD that DaCHS insists isn't there, that's"
76 " probably the reason."%id)
77 raise
78
79 if rest is None:
80 return assertType(id, srcRD, forceType)
81 else:
82 return resolveId(srcRD, rest, forceType=forceType)
83
84
85 def resolveNameBased(
86 container: Structure,
87 id: str,
88 forceType: Optional["StructType"] = None) -> Structure:
89 """Tries to find a thing with name id within container.
90
91 If container defines a method getElementForName, it will be called; it
92 must either return some element with this name or raise a NotFoundError.
93
94 If no such method exists, the function iterates over container until
95 it finds an element with el.name==id. If no such element exists,
96 it again raises a NotFoundError.
97
98 The function raises a NotFoundError when no such thing exists.
99 """
100 if hasattr(container, "getElementForName"):
101 return container.getElementForName(id)
102
103 ob = None
104 try:
105 # non-iterables are handled in the exception handler
106 for ob in cast(Iterable, container):
107 if hasattr(ob, "name") and ob.name==id:
108 return assertType(id, ob, forceType)
109 except TypeError:
110 if ob is None:
111 raise utils.logOldExc(common.NotFoundError(id, "Element with name",
112 "container %s"%repr(container),
113 hint="The container, %s, is not iterable"%repr(container)))
114 else:
115 raise utils.logOldExc(common.NotFoundError(id, "Element with name",
116 "container %s"%repr(container),
117 hint="Element %s is of type %s and thus unsuitable"
118 " for name path"%(ob.name, type(ob))))
119 raise common.NotFoundError(id, "Element with name",
120 f"container {container.id}")
121
122
123 def resolveComplexId(
124 ctx: StructParseContext,
125 id: str,
126 forceType: Optional["StructType"] = None) -> Structure:
127 """resolves a dotted id.
128
129 See resolveId.
130 """
131 try:
132 pId, name = id.split(".")
133 except ValueError:
134 raise utils.logOldExc(common.LiteralParseError("id", id,
135 hint="A complex reference (parent.name) is expected here"))
136 container = ctx.getById(pId)
137 return resolveNameBased(container, name, forceType)
138
139
140 def _resolveOnNamepath(ctx: StructParseContext, id: str, instance: Structure
141 ) -> Structure:
142 if hasattr(instance, "resolveName"):
143 return instance.resolveName(ctx, id)
144 if (instance and instance.parent and
145 hasattr(instance.parent, "resolveName")):
146 return instance.parent.resolveName(ctx, id)
147 raise common.NotFoundError(id, "Element with id or name", "name path")
148
149
150 def resolveId(
151 ctx: StructParseContext,
152 id: str,
153 instance: Optional[Structure] = None,
154 forceType: Optional["StructType"] = None) -> Structure:
155 """tries to resolve id in context.
156
157 ctx is some object having a getById method; this could be an RD
158 or a parse context.
159
160 The rules for id are as follows:
161
162 (#) if id has a # in it, split it and take the first part to be
163 an RD id, the second and id built according to the rest of this spec.
164
165 (#) if id has a dot in it, split at the first dot to get a pair of
166 id and name. Iterate over the element with id, and look for something
167 with a "name" attribute valued name. If this fails, raise a
168 NotFoundError.
169
170 (#) if instance is not None and has a resolveName method or has a parent, and
171 that parent has a resolveName method, pass id to it. If it does not raise a
172 NotFoundError, return the result. This is for parents with a
173 rscdef.NamePathAttribute.
174
175 (#) ask the ParseContext ctx's getById method to resolve id, not
176 catching the NotFoundError this will raise if the id is not known.
177 """
178 if "#" in id:
179 return resolveCrossId(id, forceType)
180 if ctx is None:
181 raise common.StructureError(
182 "Cannot intra-reference (%s) when parsing without a context"%id)
183 if "." in id:
184 return resolveComplexId(ctx, id, forceType)
185
186 srcOb = None
187 if instance:
188 try:
189 srcOb = _resolveOnNamepath(ctx, id, instance)
190 except common.NotFoundError:
191 # no such named element, try element with id
192 pass
193 if srcOb is None and ctx is not None:
194 srcOb = ctx.getById(id, forceType)
195 return assertType(id, srcOb, forceType)
196
197
198 class IdAttribute(attrdef.UnicodeAttribute):
199 """is an attribute that registers its parent in the context's id map
200 in addition to setting its id attribute.
201 """
202 typingType_ = "str"
203
204 def feed(self,
205 ctx: StructParseContext,
206 parent: Structure,
207 literal: str) -> None:
208 attrdef.UnicodeAttribute.feed(self, ctx, parent, literal)
209 if ctx is not None:
210 ctx.registerId(parent.id, parent, ctx.replayLevel>0)
211 parent.qualifiedId = ctx.getQualifiedId(literal) # type: ignore
212
213 def getCopy(self,
214 parent: Structure,
215 newParent: Structure,
216 ctx: Optional[StructParseContext]) -> None:
217 return None # ids may not be copied
218
219 def makeUserDoc(self) -> Optional[str]:
220 return "" # don't mention it in docs -- all structures have it
221
222
223 class OriginalAttribute(attrdef.AtomicAttribute):
224 """is an attribute that resolves an item copies over the managed
225 attributes from the referenced item.
226
227 The references may be anything resolveId can cope with.
228
229 You can pass a forceType argument to make sure only references to
230 specific types are allowable. In general, this will be the class
231 itself of a base class. If you don't do this, you'll probably get
232 weird AttributeErrors for certain inputs.
233
234 To work reliably, these attributes have to be known to the XML
235 parser so it makes sure they are processed first. This currently
236 works by name, and "original" is reserved for this purpose. Other
237 names will raise an AssertionError right now.
238
239 As a safety mechanism, OriginalAttribute checks if it is replacing
240 a "pristine" object, i.e. one that has not had events fed to it.
241 """
242 computed_ = True
243 typeDesc_ = "id reference"
244
245 def __init__(self,
246 name: str = "original",
247 description: str = "An id of an element"
248 " to base the current one on. This provides a simple inheritance"
249 " method. The general rules for advanced referencing in RDs apply.",
250 forceType: Optional[Any] = None, **kwargs: Any) -> None:
251 assert name=='original'
252 attrdef.AtomicAttribute.__init__(self, name, None, description,
253 **kwargs)
254 self.forceType = forceType
255
256 def feedObject(self,
257 instance: Structure,
258 original: Structure,
259 ctx: Optional[StructParseContext] = None) -> None:
260 if not instance._pristine:
261 raise common.StructureError("Original must be applied before modifying"
262 " the destination structure.", hint="You should normally use"
263 " original only as attribute. If you insist on having it as"
264 " an element, it must be the first one and all other structure"
265 " members must be set through elements, too")
266 instance._originalObject = original # type: ignore
267 instance.feedFrom(original, ctx)
268
269 def feed(self,
270 ctx: StructParseContext,
271 instance: Structure,
272 literal: str) -> None:
273 self.feedObject(instance,
274 resolveId(ctx, literal, instance, self.forceType), ctx)
275
276
277 class _ReferenceParser(common.Parser):
278 """A helper class for the ReferenceAttribute.
279 """
280 def __init__(self,
281 refAttr: attrdef.AttributeDef,
282 parent: Structure,
283 baseName: str) -> None:
284 self.refAttr, self.parent = refAttr, parent
285 # the following is a sentinel that will be fixed by _ensureChild
286 self.child: Structure = cast(Structure, common.NotGiven)
287 self.baseName = baseName
288
289 def _ensureChild(self, ctx: StructParseContext) -> None:
290 """creates an instance of the new, immediate child to be filled and
291 leaves it in self.child.
292 """
293 if self.child is common.NotGiven:
294 self.child = cast("ReferenceAttribute", self.refAttr
295 )._makeChild(self.baseName, self.parent)
296 ctx.setPositionOn(cast(Structure, self.child))
297
298 def start_(self,
299 ctx: StructParseContext,
300 name: str,
301 value: StructParserValue
302 ) -> Optional[Union[common.Parser, str]]:
303 # start event: we have an immediate child. Create it and feed this
304 # event to the newly created child.
305 self._ensureChild(ctx)
306 return self.child.feedEvent(ctx, common.ParserEventType.start, name, value)
307
308 def end_(self,
309 ctx: StructParseContext,
310 name: str,
311 value: StructParserValue) -> Structure:
312 if self.child is common.NotGiven: # empty element; make a child
313 self._ensureChild(ctx)
314 if self.child is not None: # immediate child was given:
315 self.child.finishElement(ctx)
316 self.parent.feedObject(name, self.child)
317 return self.parent
318
319 def value_(self,
320 ctx: StructParseContext,
321 name: str,
322 value: StructParserValue) -> Any:
323 # value event: If it's a content_, it's a reference, else it's an
324 # attribute on a child of ours.
325 if name=="content_":
326 if self.child:
327 raise common.StructureError("Content received on ReferenceParser"
328 " although a child is already there.", hint="You should"
329 " not see this. Complain fiercely.")
330 self.refAttr.feed(ctx, self.parent, value)
331 # tell end_ to keep its hands off. Again, it's a sentinel.
332 self.child = cast(Structure, None)
333 return self
334 else:
335 self._ensureChild(ctx)
336 return self.child.feedEvent(
337 ctx, common.ParserEventType.value, name, value)
338
339
340 class ReferenceAttribute(attrdef.AtomicAttribute):
341 """An attribute keeping a reference to some other structure
342
343 This is a bit messy since the value referred to keeps its original
344 parent, so self.attr.parent!=self for these attributes. This is
345 ok for many applications, but it will certainly not work for, e.g.
346 tables (roughly, it's always trouble when an attribute value's
347 implementation refers to self.parent; this is particularly true
348 for structures having an RDAttribute).
349
350 So, before adding a reference attribute, think first whether
351 it wouldn't be wiser to have the real thing and rather use active tags.
352 """
353 typeDesc_ = "id reference"
354
355 def __init__(self,
356 name: str = "ref",
357 default: Any = utils.Undefined,
358 description: str = "Uncodumented",
359 forceType: Optional["StructType"] = None,
360 **kwargs: Any) -> None:
361 attrdef.AtomicAttribute.__init__(self, name, default,
362 description, **kwargs)
363 self.forceType = forceType
364
365 def _getForceType(self, instance: Structure) -> Optional["StructType"]:
366 """returns self.forceType unless it is Recursive, in which case instance's
367 type is returned.
368 """
369 if self.forceType is attrdef.Recursive:
370 return instance.__class__
371 else:
372 return self.forceType
373
374 def unparse(self, value: Union[Structure, List[Structure]]) -> str:
375 if value is None: # ref attribute was empty
376 return None
377 if hasattr(value, "qualifiedId"):
378 return value.qualifiedId # type: ignore
379 elif isinstance(value, str):
380 return value
381 else: # See HACK notice in feed
382 setattr(value, "unparse-approved-anonymous", True)
383 return value # type: ignore
384
385 # Since ReferenceAttributes can now contain immediate elements,
386 # just returning an id (as happens by default) may not be enough
387 # for serialization -- the immediate object is nowhere else.
388 # We could fix that using something like this, at the expense
389 # of unrolling all the elements. We don't do much DaCHS structure
390 # serialization, and thus I believe it's just not worth it.
391 # def iterEvents(self, instance):
392 # # This needs a special iterEvents to actually return embedded
393 # # structures if necessary
394 # val = getattr(instance, self.name_)
395 # if val==self.default_:
396 # return
397 #
398 # if hasattr(val, "_RefAttrImmediate"):
399 # yield ("start", self.name_, None)
400 # for ev in val.iterEvents():
401 # yield ev
402 # yield ("end", self.name_, None)
403 # else:
404 # yield ("value", self.name_, self.unparse(val))
405
406 def feed(self,
407 ctx: StructParseContext,
408 instance: Structure,
409 literal: str) -> None:
410 if literal is None: # ref attribute empty during a copy
411 return # do nothing, since nothing was ref'd in original
412
413 # HACK: when copying around structures, it's possible that anonymous
414 # structures can be fed in here. We *really* don't want to make
415 # up ids for them. Thus, we allow them out in unparse and in here
416 # again.
417 if hasattr(literal, "unparse-approved-anonymous"):
418 self.feedObject(instance, literal)
419 else:
420 self.feedObject(instance,
421 resolveId(ctx, literal, instance, self._getForceType(instance)))
422
423 def _makeChild(self,
424 name: str,
425 parent: Structure) -> Structure:
426 """returns a new element of the appropriate type.
427
428 This method raises a StructureError if that type is not known.
429 Within ReferenceAttribute, the type is given by forceType.
430 """
431 if self.forceType is None:
432 raise common.StructureError(f"Only references allowed for {self.name_},"
433 ", but an immediate object was found",
434 hint="This means that"
435 " you tried to replace a reference to an element with"
436 " the element itself. This is only allowed if the reference"
437 " forces a type, which is not the case here.")
438
439 # after the test above we know we're not getting None here
440 child = cast("StructType", self._getForceType(parent))(parent)
441 # leave a sentinel in the child that will later let us
442 # iterEvents not the id but the struct itself.
443 child._RefAttrImmediate = True
444 return child
445
446 def create(self,
447 structure: Structure,
448 ctx: StructParseContext,
449 name: str) -> common.Parser:
450 # we don't know at this point whether or not the next event will be
451 # an open (-> create a new instance of self.forceType) or a
452 # value (-> resolve). Thus, create an intermediate parser that
453 # does the right thing.
454 return _ReferenceParser(self, structure, name)
455
456
457 class ReferenceListAttribute(ReferenceAttribute):
458 """A list of references.
459
460 These can come as distinct elements -- <ref>a</ref><ref>b</ref> -- or
461 as a comma-joined string with ignored whitespace --
462 ref="a, //services#b, x.y", or in a mixture between the two.
463 """
464 typeDesc_ = "list of id references (comma separated or in distinct elements)"
465
466 def __init__(self, name: str, **kwargs: Any) -> None:
467 if kwargs.get("default") is not None:
468 raise common.StructureError("ReferenceListAttributes cannot have"
469 " defaults")
470 kwargs["default"] = attrdef.Computed
471 ReferenceAttribute.__init__(self, name, **kwargs)
472
473 @property
474 def default_(self) -> List:
475 return []
476
477 def feedObject(self,
478 instance: Structure,
479 value: Union[Structure, List[Structure]]) -> None:
480 if isinstance(value, list):
481 for item in value:
482 self.feedObject(instance, item)
483 else:
484 getattr(instance, self.name_).append(value)
485 self.doCallbacks(instance, value)
486
487 def feed(self,
488 ctx: StructParseContext,
489 instance: Structure,
490 literal: str) -> None:
491 # split literal up if there's commas
492 if literal is None: # see ReferenceAttribute.feed
493 return
494 if "," in literal:
495 for s in literal.split(","):
496 ReferenceAttribute.feed(self, ctx, instance, s.strip())
497 else:
498 ReferenceAttribute.feed(self, ctx, instance, literal)
499
500 def unparse(self, value: Union[Structure, List[Structure]]):
501 # Hack to avoid to have to figure out globally ok ids; see
502 # comments in ReferenceAttribute
503 class BlessedList(list):
504 pass
505 if not isinstance(value, list):
506 value = [value]
507 setattr(BlessedList, "unparse-approved-anonymous", True)
508 return BlessedList(cast(List, value))
509
510
511 class ParseContext:
512 """A scratchpad for any kind of data parsers want to pass to feed
513 methods.
514
515 These objects are available to the feed methods as their
516 first objects.
517
518 If restricted is True, embedded code must raise an error.
519
520 You should set an eventSource using the setter provided. This is
521 the iterparse instance the events are coming from (or something else
522 that has a pos attribute returning the current position).
523
524 You can register exit functions to do some "global" cleanup. Parsers
525 should call runExitFuncs right before they return the results; this arranges
526 for these functions to be called. The signature of an exit function is
527 exitfunc(rootStruct, parseContext) -> whatever.
528
529 Then there's injected info. This is used to read "dynamic" metadata
530 for RDs from the database up front and then fill the respective data
531 where appropriate. Use inject to fill this (for RDs, do things
532 like that in the rscdef.rdinj module) and getInjected to get data out
533 again.
534 """
535 def __init__(self,
536 restricted: bool = False,
537 forRD: Optional[str] = None) -> None:
538 self.idmap: Dict[str, Structure] = {}
539 self.restricted = restricted
540 self.forRD = forRD
541 self.eventSource: Optional[utils.iterparse] = None
542 self.injectedData: Dict[str, Any] = {}
543 self.exitFuncs: List[Callable[[Structure, StructParseContext], None]] = []
544 # if non-0, we're replaying events
545 self.replayLevel = 0
546 self.replayTarget: Optional[ParseableStructure] = None
547
548 def setEventSource(self, evSource: utils.iterparse) -> None:
549 self.eventSource = evSource
550
551 def addExitFunc(self,
552 callable: Callable[[Structure, StructParseContext], None]) -> None:
553 self.exitFuncs.append(callable)
554
555 def inject(self,
556 key: str,
557 data: Any) -> None:
558 """sets injected data for key.
559
560 This will silently overwrite any pre-existing data.
561 """
562 self.injectedData[key] = data
563
564 def getInjected(self, key: str, default: Any = common.NotGiven) -> Any:
565 """get injected data for key.
566
567 This will raise a KeyError if no data for key has been injected
568 (or default, if given).
569
570 For keys available here while parsing RDs, see rscdef.rdinj, look
571 for ctx.inject.
572 """
573 try:
574 return self.injectedData[key]
575 except KeyError:
576 if default is not common.NotGiven:
577 return default
578 raise
579
580 @contextlib.contextmanager
581 def replaying(self) -> Iterator:
582 """is called by active tags to indicate they're replaying
583 events.
584
585 The main effect right now is to suppress diagnostics for overwritten
586 ids. But let's see what else we might want to use it for.
587
588 The API to see if we're replaying: replayLevel>0.
589 """
590 self.replayLevel += 1
591 try:
592 yield
593 finally:
594 self.replayLevel -= 1
595
596 @property
597 def pos(self) -> Union["ErrorPosition", str]:
598 """returns a token stringifying into a position guess.
599 """
600 if self.eventSource is None:
601 return "(while parsing sourceless)"
602 else:
603 return self.eventSource.pos
604
605 def setPositionOn(self, struct: Structure) -> None:
606 """calls a struct's setPosition method to tell it where it came from.
607 """
608 if isinstance(self.pos, str):
609 struct.setPosition(self.pos, -1)
610 else:
611 struct.setPosition(self.pos.fName, self.pos.line)
612
613 def getQualifiedId(self, id: str) -> str:
614 """returns an id including the current RD's id, if known, otherwise id
615 itself.
616 """
617 if self.forRD:
618 return "%s#%s"%(self.forRD, id)
619 return id
620
621 def registerId(self,
622 elId: str,
623 value: Structure,
624 silentOverwrite: bool = False) -> None:
625 """enters a value in the id map.
626
627 We allow overriding in id. That should not happen while parsing
628 an XML document because of their uniqueness requirement, but
629 might come in handy for programmatic manipulations.
630
631 We'll still emit an Info in that case (and may need to find a way to
632 suppress it).
633 """
634 if elId in self.idmap:
635 if not silentOverwrite:
636 utils.sendUIEvent("Info", "Element with id %s overwritten."%elId)
637 self.idmap[elId] = value
638
639 def getById(self,
640 id: str, forceType: Optional["StructType"] = None) -> Structure:
641 """returns the object last registered for id.
642
643 You probably want to use resolveId; getById does no namePath or
644 resource descriptor resolution.
645 """
646 if id not in self.idmap:
647 raise common.NotFoundError(id, "Element with id", "parse context",
648 hint="Elements referenced must occur lexically (i.e., within the"
649 " input file) before the reference. If this actually gives"
650 " you trouble, contact the authors. Usually, though, this"
651 " error just means you mistyped a name.")
652 res = self.idmap[id]
653 return assertType(id, res, forceType)
654
655 def resolveId(self,
656 id: str,
657 instance: Optional[Structure] = None,
658 forceType: Optional["StructType"] = None) -> Structure:
659 """returns the object referred to by the complex id.
660
661 See the resolveId function.
662 """
663 return resolveId(self, id, instance, forceType)
664
665 def runExitFuncs(self, root: Structure) -> None:
666 for func in self.exitFuncs:
667 func(root, self)
668
669
670 def getTableDefForTable(connection: DaCHSConnection, tableName: str
671 ) -> "TableDef":
672 """returns a TableDef object for a SQL table name.
673
674 connection needs to be TableConnection or something with higher privileges.
675
676 This really has little to do with resolving identifiers, but
677 this module already has getRDs and similar, so it seemed the least
678 unnatural place.
679 """
680 if not "." in tableName:
681 tableName = "public."+tableName
682
683 res = list(connection.queryToDicts(
684 "select sourcerd, tablename from dc.tablemeta where"
685 " lower(tableName)=%(tableName)s",
686 {"tableName": tableName.lower()}))
687 if len(res)>1:
688 raise common.ReportableError("More than one entry for table %s in"
689 " dc.tablemeta!"%tableName,
690 hint="This is a severe internal error and really should not happen."
691 " Please report this bug.")
692 elif not res:
693 raise common.NotFoundError(tableName, "table", "published tables")
694
695 row = res[0]
696 return caches.getRD(row["sourcerd"] # type: ignore # caches-fix
697 ).getById(row["tablename"].split(".")[-1])