Debian Codegraph @

gavo/base/activetags.py

raw
1 """
2 Active tags are used in prepare and insert computed material into RD trees.
3
4 And, ok, we are dealing with elements here rather than tags, but I liked
5 the name "active tags" much better, and there's too much talk of elements
6 in this source as it is.
7
8 The main tricky part with active tags is when they're nested. In
9 short, active tags are expanded even when within active tags. So,
10 if you write::
11
12 <STREAM id="foo">
13 <LOOP>
14 </LOOP>
15 </STREAM>
16
17 foo contains not a loop element but whatever that spit out. In particular,
18 macros within the loop are expanded not within some FEED element but
19 within the RD.
20
21 There is a non-expanding version of STREAM, too, but that has to take
22 special precautions.
23 """
24
25 #c Copyright 2008-2025, the GAVO project <[email protected]>
26 #c
27 #c This program is free software, covered by the GNU GPL. See the
28 #c COPYING file in the source distribution.
29
30
31 import csv
32 import re
33 from io import StringIO
34
35 from gavo import base # (to pass into codeItems' namespaces only)
36 from gavo import utils
37 from gavo.base import attrdef
38 from gavo.base import common
39 from gavo.base import complexattrs
40 from gavo.base import macros
41 from gavo.base import parsecontext
42 from gavo.base import structure
43
44 from gavo.utils.dachstypes import (cast, TYPE_CHECKING,
45 Any, Callable, Dict, Iterator, List, Optional, Self,
46 Structure, StructParseContext, StructParserValue, Type, Union)
47
48
49 if TYPE_CHECKING:
50 from gavo.base import xmlstruct
51
52
53 # the following is a sentinel for values that have been expanded
54 # by an active tag already. When active tags are nested, only the
55 # innermost active tag must expand macros so one can be sure that
56 # double-escaped macros actually end up when the events are finally
57 # replayed at the top level. _EXPANDED_VALUE must compare true to
58 # value since it is used as such in event triples.
59
60 class _ExValueType(object):
61 def __str__(self) -> str:
62 return "value"
63
64 def __repr__(self) -> str:
65 return "'value/expanded'"
66
67 def __eq__(self, other: object) -> bool:
68 return other=="value"
69
70 def __ne__(self, other: object):
71 return not other=="value"
72
73 _EXPANDED_VALUE =_ExValueType()
74
75
76 class ActiveTag:
77 """A mixin for active tags.
78
79 This is usually mixed into structure.Structures or derivatives. It
80 is also used as a sentinel to find all active tags below.
81 """
82 name_: Union[str, Type[utils.Undefined]] = utils.Undefined
83
84
85 class GhostMixin(common.StructCallbacks):
86 """A mixin to make a Structure ghostly.
87
88 Most active tags are "ghostly", i.e., the do not (directly)
89 show up in their parents. Therefore, as a part of the wrap-up
90 of the new element, we raise an Ignore exception, which tells
91 the Structure's ``end_`` method to not feed us to the parent.
92 """
93 def onElementComplete(self) -> None:
94 super().onElementComplete()
95 raise common.Ignore(self)
96
97
98 class _PreparedEventSource:
99 """An event source for xmlstruct.
100
101 It is constructed with a list of events as recorded by classes
102 inheriting from RecordingBase.
103 """
104 def __init__(self, events: List) -> None:
105 self.events_ = events
106 self.curEvent = -1
107 self.pos = None
108
109 def __iter__(self) -> "_PreparedEventSource":
110 return _PreparedEventSource(self.events_)
111
112 def __next__(self) -> common.ParserEvent:
113 self.curEvent += 1
114 try:
115 nextItem = self.events_[self.curEvent]
116 except IndexError:
117 raise StopIteration()
118 res, self.pos = nextItem[:3], nextItem[-1]
119 return res
120
121
122 @structure.buildstructure
123 class Defaults(structure.Structure):
124 """Defaults for macros.
125
126 In STREAMs and NXSTREAMs, DEFAULTS let you specify values filled into
127 macros when a FEED doesn't given them. Macro names are attribute names
128 (or element names, if you insist), defaults are their values.
129 """
130 name_ = "DEFAULTS"
131
132 def __init__(self, *args: Any, **kwargs: Any) -> None:
133 self.defaults: Dict[str, StructParserValue] = {}
134 structure.Structure.__init__(self, *args, **kwargs)
135
136 def start_(self,
137 ctx: StructParseContext,
138 name: str,
139 value: StructParserValue) -> Self:
140 return self
141
142 def value_(self,
143 ctx: StructParseContext,
144 name: str,
145 value: StructParserValue) -> Self:
146 if name=="content_":
147 self.storedContent = value
148 else:
149 self.defaults[name] = value
150 return self
151
152 def end_(self,
153 ctx: StructParseContext,
154 name: str,
155 value: StructParserValue) -> Optional[common.Parser]:
156 if name=="DEFAULTS":
157 self.finishElement(ctx)
158 if self.parent is not None:
159 self.parent.feedObject("DEFAULTS", self)
160 return self.parent
161 else:
162 self.defaults[name] = self.storedContent
163 del self.storedContent
164 return self
165
166
167 @structure.buildstructure
168 class RecordingBase(structure.Structure):
169 """An "abstract base" for active tags doing event recording.
170
171 The recorded events are available in the events attribute.
172 """
173 name_ = "invalid-not-overridden"
174
175 _doc = attrdef.UnicodeAttribute("doc", description="A description of"
176 " this stream (should be restructured text).", strip=False)
177 _defaults = complexattrs.StructAttribute("DEFAULTS",
178 childFactory=Defaults, description="A mapping giving"
179 " defaults for macros expanded in this stream. Macros"
180 " not defaulted will fail when not given in a FEED's attributes.",
181 default=None)
182
183 def __init__(self, *args: Any, **kwargs: Any) -> None:
184 self.events_: List[common.ParserEvent] = []
185 self.tagStack_: List[str] = []
186 structure.Structure.__init__(self, *args, **kwargs)
187
188 def feedEvent(self,
189 ctx: StructParseContext,
190 type: common.ParserEventType,
191 name: str,
192 value: StructParserValue) -> Optional[Union[common.Parser, str]]:
193 # keep _EXPANDED_VALUE rather than feed the value to protect it from
194 # further expansion by subordinate structures (except if we, the
195 # active tag, are the final recipient, in which case we gobble the thing
196 # ourselves).
197 if (type is _EXPANDED_VALUE and name not in self.managedAttrs):
198 self.events_.append(common.ParserEvent(
199 _EXPANDED_VALUE, name, value, ctx.pos))
200 return self
201 else:
202 return structure.Structure.feedEvent(self, ctx, type, name, value)
203
204 def start_(self,
205 ctx: StructParseContext,
206 name: str,
207 value: StructParserValue) -> Optional[Union[common.Parser, str]]:
208 if name in self.managedAttrs and not self.tagStack_:
209 res = structure.Structure.start_(self, ctx, name, value)
210 else:
211 self.events_.append(common.ParserEvent("start", name, value, ctx.pos))
212 res = self
213 self.tagStack_.append(name)
214 return res
215
216 def end_(self,
217 ctx: StructParseContext,
218 name: str,
219 value: StructParserValue) -> Optional[common.Parser]:
220 if name in self.managedAttrs and not self.tagStack_:
221 structure.Structure.end_(self, ctx, name, value)
222 else:
223 self.events_.append(common.ParserEvent("end", name, value, ctx.pos))
224 self.tagStack_.pop()
225 return self
226
227 def value_(self,
228 ctx: StructParseContext,
229 name: str,
230 value: StructParserValue) -> structure.Structure:
231 if name in self.managedAttrs and not self.tagStack_:
232 # our attribute
233 structure.Structure.value_(self, ctx, name, value)
234 else:
235 self.events_.append(common.ParserEvent("value", name, value, ctx.pos))
236 return self
237
238 def getEventSource(self) -> _PreparedEventSource:
239 """returns an object suitable as event source in xmlstruct.
240 """
241 return _PreparedEventSource(self.events_)
242
243 def unexpandMacros(self) -> None:
244 """undoes the marking of expanded values as expanded.
245
246 This is when, as with mixins, duplicate expansion of macros during
247 replay is desired.
248 """
249 for ind, ev in enumerate(self.events_):
250 if ev[0]==_EXPANDED_VALUE:
251 self.events_[ind] = common.ParserEvent("value", *ev[1:])
252
253 def dump(self):
254 indent = ""
255 for type, name, val, pos in self.events_:
256 print(f"{indent}{type}\t{name}\t{val}")
257 if type=="start":
258 indent += " "
259 elif type=="end":
260 indent = indent[:-2]
261
262 # This lets us feedFrom these
263 iterEvents = getEventSource
264
265
266 @structure.buildstructure
267 class EventStream(RecordingBase, GhostMixin, ActiveTag):
268 """An active tag that records events as they come in.
269
270 Their only direct effect is to leave a trace in the parser's id map.
271 The resulting event stream can be played back later.
272 """
273 name_ = "STREAM"
274
275 def end_(self,
276 ctx: StructParseContext,
277 name: str,
278 value: StructParserValue) -> Optional[common.Parser]:
279 # keep self out of the parse tree
280 if not self.tagStack_: # end of STREAM element
281 res = self.parent
282 self.parent = None
283 return res
284 return RecordingBase.end_(self, ctx, name, value)
285
286
287 @structure.buildstructure
288 class RawEventStream(EventStream):
289 """An event stream that records events, not expanding active tags.
290
291 Normal event streams expand embedded active tags in place. This is
292 frequently what you want, but it means that you cannot, e.g., fill
293 in loop variables through stream macros.
294
295 With non-expanded streams, you can do that::
296
297 <NXSTREAM id="cols">
298 <LOOP listItems="\\stuff">
299 <events>
300 <column name="\\\\item"/>
301 </events>
302 </LOOP>
303 </NXSTREAM>
304 <table id="foo">
305 <FEED source="cols" stuff="x y"/>
306 </table>
307
308 Note that the normal innermost-only rule for macro expansions
309 within active tags does not apply for NXSTREAMS. Macros expanded
310 by a replayed NXSTREAM will be re-expanded by the next active
311 tag that sees them (this is allow embedded active tags to use
312 macros; you need to double-escape macros for them, of course).
313 """
314
315 name_ = "NXSTREAM"
316
317 # Hack to signal xmlstruct.EventProcessor not to expand active tags here
318 ACTIVE_NOEXPAND = None
319
320
321 @structure.buildstructure
322 class EmbeddedStream(RecordingBase):
323 """An event stream as a child of another element.
324 """
325 name_ = "events" # Lower case since it's really a "normal" element that's
326 # added into the parse tree.
327 _passivate = attrdef.ActionAttribute("passivate",
328 methodName="_makePassive", description="If set to True, do not expand"
329 " active elements immediately in the body of these events"
330 " (as in an NXSTREAM)")
331
332 def _makePassive(self, ctx: StructParseContext) -> None:
333 if self.passivate.lower()=="true":
334 self.ACTIVE_NOEXPAND = True
335
336 def end_(self,
337 ctx: StructParseContext,
338 name: str,
339 value: StructParserValue) -> Optional[common.Parser]:
340 if not self.tagStack_: # end of my element, do standard structure thing.
341 return structure.Structure.end_(self, ctx, name, value)
342 return RecordingBase.end_(self, ctx, name, value)
343
344
345 @structure.buildstructure
346 class Prune(ActiveTag, structure.Structure):
347 """An active tag that lets you selectively delete children of the
348 current object.
349
350 You give it regular expression-valued attributes; on the replay of
351 the stream, matching items and their children will not be replayed.
352
353 If you give more than one attribute, the result will be a conjunction
354 of the specified conditions.
355
356 This only works if the items to be matched are true XML attributes
357 (i.e., not written as children).
358
359 For instance, the following will filter out all elements with a name
360 of VERB from the stream::
361
362 <PRUNE name="VERB"/>
363 """
364 name_ = "PRUNE"
365
366 def __init__(self, parent: structure.Structure, **kwargs: Any) -> None:
367 self.conds: Dict[str, StructParserValue] = {}
368 structure.Structure.__init__(self, parent)
369
370 def value_(self,
371 ctx: StructParseContext,
372 name: str,
373 value: Union[Dict[str, str], str, None]) -> Self:
374 self.conds[name] = str(value)
375 return self
376
377 def end_(self,
378 ctx: StructParseContext,
379 name: str,
380 value: Union[Dict[str, str], str, None]) -> Optional[common.Parser]:
381 assert name==self.name_
382 self.matches = self._getMatcher()
383 if self.parent is not None:
384 self.parent.feedObject(self.name_, self)
385 return self.parent
386
387 def _getMatcher(self) -> Callable[[Dict[str, str]], bool]:
388 """returns a callabe that takes a dictionary and matches the
389 entries against the conditions given.
390 """
391 conditions = []
392 for attName, regEx in self.conds.items():
393 conditions.append((attName, re.compile(str(regEx))))
394
395 def match(aDict: Dict[str, str]) -> bool:
396 for attName, expr in conditions:
397 val = aDict.get(attName)
398 if val is None: # not given or null empty attrs never match
399 return False
400 if not expr.search(str(val)):
401 return False
402 return True
403
404 return match
405
406
407 @structure.buildstructure
408 class Edit(EmbeddedStream):
409 """an event stream targeted at editing other structures.
410
411 When replaying a stream in the presence of EDITs, the elements are
412 are continually checked against ref. If an element matches, the
413 children of edit will be played back into it.
414 """
415 name_ = "EDIT"
416
417 _ref = attrdef.UnicodeAttribute("ref", description="Destination of"
418 " the edits, in the form elementName[<name or id>]",
419 default=utils.Undefined)
420
421 refPat = re.compile(
422 r"([A-Za-z_][A-Za-z0-9_]*)\[([A-Za-z_][A-Za-z0-9_]*)\]")
423
424 def onElementComplete(self) -> None:
425 mat = self.refPat.match(self.ref)
426 if not mat:
427 raise common.LiteralParseError("ref", self.ref,
428 hint="edit references have the form <element name>[<value of"
429 " name or id attribute>]")
430 self.triggerEl, self.triggerId = mat.groups()
431
432
433 @structure.buildstructure
434 class ReplayBase(ActiveTag, structure.Structure, macros.StandardMacroMixin):
435 """An "abstract base" for active tags replaying streams.
436 """
437 name_: Union[str, Type[utils.Undefined]] = utils.Undefined
438 _expandMacros = True
439
440 _source = parsecontext.ReferenceAttribute("source",
441 description="id of a stream to replay", default=None)
442 _events = complexattrs.StructAttribute("events",
443 childFactory=EmbeddedStream, default=None,
444 description="Alternatively to source, an XML fragment to be replayed")
445 _edits = complexattrs.StructListAttribute("edits",
446 childFactory=Edit, description="Changes to be performed on the"
447 " events played back.")
448 _reexpand = attrdef.BooleanAttribute("reexpand", False,
449 description="Force re-expansion of macros; usually, when replaying,"
450 " each string is only expanded once, mainly to avoid overly long"
451 " backslash-fences. Set this to true to force further expansion.")
452 _prunes = complexattrs.StructListAttribute("prunes",
453 childFactory=Prune, description="Conditions for removing"
454 " items from the playback stream.")
455
456 def _ensureEditsDict(self) -> None:
457 if not hasattr(self, "editsDict"):
458 self.editsDict = {}
459 for edit in self.edits:
460 self.editsDict[edit.triggerEl, edit.triggerId] = edit
461
462 def _isPruneable(self, val: Dict[str, str]) -> bool:
463 for p in self.prunes:
464 if p.matches(val):
465 return True
466 return False
467
468 def _replayTo(self,
469 events: List[common.ParserEvent],
470 evTarget: "xmlstruct.EventProcessor",
471 ctx: StructParseContext) -> None:
472 """pushes stored events into an event processor.
473
474 The public interface is replay (that receives a structure rather
475 than an event processor).
476 """
477 idStack: List[Union[str,set]] = []
478 pruneStack: List[None] = []
479
480 # see RawEventStream's docstring for why we do not want to suppress
481 # further expansion with NXSTREAMs
482 typeOfExpandedValues: Union[_ExValueType, str] = _EXPANDED_VALUE
483 if isinstance(self.source, RawEventStream):
484 typeOfExpandedValues = "value"
485
486 with ctx.replaying():
487 for type, name, val, pos in events:
488 if (self._expandMacros
489 and type=="value"
490 and (self.reexpand or type is not _EXPANDED_VALUE)
491 and "\\" in val):
492 try:
493 val = self.expand(val)
494 except macros.MacroError as ex:
495 ex.hint = ("This probably means that you should have set a %s"
496 " attribute in the FEED tag. For details see the"
497 " documentation of the STREAM with id %s."%(
498 ex.macroName,
499 getattr(self.source, "id", "<embedded>")))
500 raise
501 type = typeOfExpandedValues
502
503 # the following mess implements the logic for EDIT.
504 if type=="start":
505 idStack.append(set())
506 elif type=="value":
507 if idStack and name=="id" or name=="name":
508 cast(set, idStack[-1]).add(val)
509 elif type=="end":
510 ids = idStack.pop()
511 for foundId in ids:
512 if (name, foundId) in self.editsDict:
513 self._replayTo(self.editsDict[name, foundId].events_,
514 evTarget,
515 ctx)
516
517 # The following mess implements the logic for PRUNE
518 if type=="start":
519 if pruneStack:
520 pruneStack.append(None)
521 else:
522 if self.prunes and self._isPruneable(val):
523 pruneStack.append(None)
524
525 try:
526 if not pruneStack:
527 evTarget.feed(type, name, val)
528 except Exception as msg:
529 msg.pos = "%s (replaying, real error position %s)"%( # type: ignore
530 ctx.pos, pos)
531 raise
532
533 if pruneStack and type=="end":
534 pruneStack.pop()
535
536 # ReferenceAttribute and similar may change the element fed into;
537 # make sure the right object is returned up-tree
538 # (the cast reflects that we always have a structure we're feeding
539 # into here).
540 self.parent = cast(Structure, evTarget.curParser)
541
542 def replay(self,
543 events: List[common.ParserEvent],
544 destination: structure.ParseableStructure,
545 ctx: StructParseContext) -> None:
546 """pushes the stored events into the destination structure.
547
548 While doing this, local macros are expanded unless we already
549 receive the events from an active tag (e.g., nested streams
550 and such).
551 """
552 # XXX TODO: Circular import here. Think again and resolve.
553 from gavo.base.xmlstruct import EventProcessor
554 evTarget = EventProcessor(destination, ctx)
555 evTarget.setParser(cast(Structure, destination))
556
557 self._ensureEditsDict()
558 try:
559 previousTarget = getattr(ctx, "replayTarget", None)
560 ctx.replayTarget = destination
561 self._replayTo(events, evTarget, ctx)
562 finally:
563 if previousTarget:
564 ctx.replayTarget = previousTarget
565 else:
566 delattr(ctx, "replayTarget")
567
568
569 @structure.buildstructure
570 class DelayedReplayBase(ReplayBase, GhostMixin):
571 """An base class for active tags wanting to replay streams from
572 where the context is invisible.
573
574 These define a _replayer attribute that, when called, replays
575 the stored events *within the context at its end* and to the
576 parent.
577
578 This is what you want for the FEED and LOOP since they always work
579 on the embedding element and, by virtue of being ghosts, cannot
580 be copied. If the element embedding an event stream can be
581 copied, this will almost certainly not do what you want.
582 """
583 def _setupReplay(self, ctx: StructParseContext) -> None:
584 sources = [s for s in [self.source, self.events] if s]
585 if len(sources)!=1:
586 raise common.StructureError("Need exactly one of source and events"
587 " on %s elements"%self.name_)
588 stream = sources[0].events_
589 def replayer() -> None:
590 if self.parent is not None:
591 self.replay(stream, self.parent, ctx)
592 self._replayer = replayer
593
594 def end_(self,
595 ctx: StructParseContext,
596 name: str,
597 value: StructParserValue) -> Optional[common.Parser]:
598 self._setupReplay(ctx)
599 return structure.Structure.end_(self, ctx, name, value)
600
601
602 @structure.buildstructure
603 class ReplayedEventsWithFreeAttributesBase(DelayedReplayBase):
604 """An active tag that takes arbitrary attributes as macro definitions.
605 """
606 def __init__(self, parent, *args: Any, **kwargs: Any) -> None:
607 DelayedReplayBase.__init__(self, parent, *args, **kwargs)
608 # managedAttrs in general is a class attribute. Here, we want
609 # to add values for the macros, and these are instance-local.
610 self.managedAttrs = self.managedAttrs.copy()
611
612 def completeElement(self,
613 ctx: StructParseContext) -> None:
614 # define any missing macros that still are in defaults.
615 if self.source and self.source.DEFAULTS is not None:
616 for key, value in self.source.DEFAULTS.defaults.items():
617 if not hasattr(self, "macro_"+key):
618 setattr(self, "macro_"+key, lambda v=value: v)
619 super().completeElement(ctx)
620
621 def getAttribute(self, name: str) -> Any:
622 try:
623 return DelayedReplayBase.getAttribute(self, name)
624 except common.StructureError: # no "real" attribute, it's a macro def
625
626 if len(name)==1:
627 raise common.StructureError("DaCHS does not support one-character"
628 f' macro names. Hence, you cannot use "{name}" as a {self.name_}'
629 " attribute.")
630
631 def m() -> str:
632 return getattr(self, name)
633 setattr(self, "macro_"+name.strip(), m)
634 self.managedAttrs[name] = attrdef.UnicodeAttribute(name)
635 return self.managedAttrs[name]
636
637
638 @structure.buildstructure
639 class ReplayedEvents(ReplayedEventsWithFreeAttributesBase):
640 """An active tag that takes an event stream and replays the events,
641 possibly filling variables.
642
643 This element supports arbitrary attributes with unicode values. These
644 values are available as macros for replayed values.
645 """
646 name_ = "FEED"
647
648 def completeElement(self,
649 ctx: StructParseContext) -> None:
650 super().completeElement(ctx)
651 self._replayer()
652
653
654 @structure.buildstructure
655 class NonExpandedReplayedEvents(ReplayedEvents):
656 """A ReplayedEventStream that does not expand active tag macros.
657
658 You only want this when embedding a stream into another stream
659 that could want to expand the embedded macros.
660 """
661 name_ = "LFEED"
662 _expandMacros = False
663
664
665 class GeneratorAttribute(attrdef.UnicodeAttribute):
666 """An attribute containing a generator working on the parse context.
667 """
668 def feed(self,
669 ctx: StructParseContext,
670 instance: structure.Structure,
671 literal: str) -> None:
672 if ctx.restricted:
673 raise common.RestrictedElement("codeItems")
674 attrdef.UnicodeAttribute.feed(self, ctx, instance, literal)
675 src = utils.fixIndentation(
676 getattr(instance, self.name_),
677 " ", governingLine=1)
678 src = "def makeRows(context):\n"+src+"\n"
679 instance.iterRowsFromCode = utils.compileFunction( # type: ignore
680 src, "makeRows", useGlobals={
681 "definitionContext": ctx,
682 "utils": utils,
683 "base": base},
684 uniqueName="<{} at {}>".format(
685 instance.name_, instance.getSourcePosition()))
686
687
688 @structure.buildstructure
689 class Loop(ReplayedEventsWithFreeAttributesBase):
690 """An active tag that replays a feed several times, each time with
691 different values.
692 """
693 name_ = "LOOP"
694
695 _csvItems = attrdef.UnicodeAttribute("csvItems", default=None,
696 description="The items to loop over, in CSV-with-labels format.",
697 strip=True)
698 _listItems = attrdef.UnicodeAttribute("listItems", default=None,
699 description="The items to loop over, as space-separated single"
700 " items. Each item will show up once, as 'item' macro.",
701 strip=True)
702 _codeItems = GeneratorAttribute("codeItems", default=None,
703 description="A python generator body that yields dictionaries"
704 " that are then used as loop items. You can access the parse context"
705 " as the context variable in these code snippets. context.replayTarget"
706 " is the struct the loop is feeding to. You also get the utils and base"
707 " namespaces, though using them it *a bit* dangerous (we don't guarantee"
708 " their stability).", strip=False)
709
710 def maybeExpand(self, val: str) -> str:
711 if "\\" in val:
712 el = self.parent
713 while el:
714 if hasattr(el, "expand"):
715 return el.expand(val)
716 el = el.parent
717 return val
718
719 def _makeRowIteratorFromListItems(self) -> Optional[Iterator]:
720 if self.listItems is None:
721 return None
722 def rowIterator() -> Iterator[Dict[str, str]]:
723 for item in self.maybeExpand(self.listItems).split():
724 yield {"item": item}
725 return rowIterator()
726
727 def _makeRowIteratorFromCSV(self) -> Optional[csv.DictReader]:
728 if self.csvItems is None:
729 return None
730 # I'd rather not do the encode below, but 2.7 csv can't handle
731 # unicode. We'll need to decode stuff again.
732 src = self.maybeExpand(self.csvItems).strip()
733
734 return csv.DictReader(StringIO(src), skipinitialspace=True)
735
736 def _makeRowIteratorFromCode(self,
737 ctx: StructParseContext) -> Optional[Iterator]:
738 if self.codeItems is None:
739 return None
740 return self.iterRowsFromCode(ctx) # type: ignore
741
742 def _getRowIterator(self, ctx: StructParseContext) -> Iterator:
743 rowIterators = [ri for ri in [
744 self._makeRowIteratorFromListItems(),
745 self._makeRowIteratorFromCSV(),
746 self._makeRowIteratorFromCode(ctx)] if ri]
747 if len(rowIterators)!=1:
748 raise common.StructureError("Must give exactly one data source in"
749 " LOOP", hint="That's one of (at least) listItems, codeItems,"
750 " or csvItems.")
751 return rowIterators[0] # type: ignore
752
753 def completeElement(self, ctx: StructParseContext) -> None:
754 super().completeElement(ctx)
755 for row in self._getRowIterator(ctx):
756 for name, value in row.items():
757 if value:
758 value = value.strip()
759 if name is None:
760 raise utils.StructureError(
761 "Too many CSV items (extra data: %s)"%value)
762 setattr(self, "macro_"+name.strip(), lambda v=value: v)
763 self._replayer()
764
765
766 class Debug(ActiveTag, GhostMixin):
767 """Enter a debugger when parsing to here.
768
769 This is probably only interesting for DaCHS developers.
770 """
771 name_ = "DEBUG"
772
773 managedAttrs: Dict[str, Any] = {}
774 attrSeq: List = []
775
776 def __init__(self, parent, *args, **kwargs):
777 self.parent = parent
778
779 def feedEvent(self,
780 ctx: StructParseContext,
781 type: common.ParserEventType,
782 name: str,
783 value: StructParserValue):
784 if type=="end":
785 print("DEBUG elemeent: the parent element is in self.parent")
786 print(" Also, use ctx.getById(...) to get elements by id")
787 import pdb;pdb.Pdb(nosigint=True).set_trace()
788 return self.parent
789
790
791 getActiveTag = utils.buildClassResolver(
792 ActiveTag,
793 list(globals().values()),
794 key=lambda obj: getattr(obj, "name_", None) or None)
795
796
797 def registerActiveTag(activeTag: structure.Structure) -> None:
798 """declares activeTag as an active tag.
799
800 This is intended for active tags that might be defined one day
801 outside of this module; at least as of DaCHS 2.0, there's no such
802 thing.
803 """
804 getActiveTag.registry[activeTag.name_] = activeTag # type: ignore
805
806
807 def isActive(name: str) -> bool:
808 return name in getActiveTag.registry #type: ignore