| 1 |
""" |
| 2 |
Code to parse structures from XML sources. |
| 3 |
|
| 4 |
The purpose of much of the mess here is to symmetrize XML attributes |
| 5 |
and values. Basically, we want start, value, end events whether |
| 6 |
or not a piece of data comes in an element with a certain tag name or |
| 7 |
via a named attribute. |
| 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 io |
| 17 |
import pathlib |
| 18 |
import re |
| 19 |
|
| 20 |
from gavo import utils |
| 21 |
from gavo.base import activetags |
| 22 |
from gavo.base import common |
| 23 |
from gavo.base import parsecontext |
| 24 |
|
| 25 |
from gavo.utils.dachstypes import (cast, TYPE_CHECKING, |
| 26 |
Dict, Iterator, Optional, Structure, |
| 27 |
StructParseContext, StructParserValue, TextIO, Type, Union) |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from gavo.base.structure import ParseableStructure |
| 31 |
_StructureArg = Union[ParseableStructure, Type[ParseableStructure]] |
| 32 |
|
| 33 |
|
| 34 |
ALL_WHITESPACE = re.compile(r"\s*$") |
| 35 |
|
| 36 |
|
| 37 |
class EventProcessor(common.Parser): |
| 38 |
"""A dispatcher for parse events to structures. |
| 39 |
|
| 40 |
It is constructed with the root structure of the result tree, either |
| 41 |
as a type or as an instance. |
| 42 |
|
| 43 |
After that, events can be fed to the feed method that makes sure |
| 44 |
they are routed to the proper object. |
| 45 |
""" |
| 46 |
|
| 47 |
# The event processor distinguishes between parsing atoms (just one |
| 48 |
# value) and structured data using the next attribute. If it is not |
| 49 |
# None, the next value coming in will be turned to a "value" event |
| 50 |
# on the current parser. If it is None, we hand through the event |
| 51 |
# to the current structure. |
| 52 |
|
| 53 |
debug = False |
| 54 |
|
| 55 |
def __init__(self, |
| 56 |
rootStruct: "_StructureArg", |
| 57 |
ctx: StructParseContext) -> None: |
| 58 |
self.curParser: common.Parser = self |
| 59 |
self.next: Union[common.Parser, str, None] = None |
| 60 |
self.ctx = ctx |
| 61 |
self.result = self._instantiate(rootStruct) |
| 62 |
|
| 63 |
@staticmethod |
| 64 |
def _instantiate(rootStruct: "_StructureArg") -> Structure: |
| 65 |
# in practice, all struct types in DaCHS are Structure-s and |
| 66 |
# none are just ParseableStructure-s. That's the only |
| 67 |
# reason the cast is safe; this asks for refactoring... |
| 68 |
if isinstance(rootStruct, type): |
| 69 |
return cast(Structure, rootStruct(None)) |
| 70 |
else: |
| 71 |
return cast(Structure, rootStruct) |
| 72 |
|
| 73 |
def _feedToAtom(self, |
| 74 |
type: common.ParserEventType, |
| 75 |
name: str, |
| 76 |
value: StructParserValue) -> None: |
| 77 |
if type=='start': |
| 78 |
raise common.StructureError("%s elements cannot have %s children"%( |
| 79 |
self.next, name)) |
| 80 |
|
| 81 |
elif type=='value' or type=="parsedvalue": |
| 82 |
# For atoms, you can only set content_ -- they have no attributes. |
| 83 |
if name!="content_": |
| 84 |
raise common.StructureError("%s is atomic and thus has" |
| 85 |
" no attribute %s."%(self.next, name)) |
| 86 |
# the cast in the next line is because I hope that logically, |
| 87 |
# this case will not be reached when self.next is None. |
| 88 |
self.curParser.feedEvent( |
| 89 |
self.ctx, common.ParserEventType.value, cast(str, self.next), value) |
| 90 |
|
| 91 |
elif type=='end': |
| 92 |
self.next = None |
| 93 |
|
| 94 |
def _feedToStructured(self, |
| 95 |
type: common.ParserEventType, |
| 96 |
name: str, |
| 97 |
value: StructParserValue) -> None: |
| 98 |
next = self.curParser.feedEvent(self.ctx, type, name, value) |
| 99 |
if isinstance(next, str): |
| 100 |
self.next = next |
| 101 |
else: |
| 102 |
self.curParser = cast(common.Parser, next) |
| 103 |
|
| 104 |
def feed(self, |
| 105 |
type: common.ParserEventType, |
| 106 |
name: str, |
| 107 |
value: StructParserValue = None) -> None: |
| 108 |
"""feeds an event. |
| 109 |
|
| 110 |
This is the main entry point for user calls. |
| 111 |
""" |
| 112 |
# Special handling for active tags: They may occur everywhere and |
| 113 |
# thus are not not parsed by the element parsers but by us. |
| 114 |
# Active tags may define ACTIVE_NOEXPAND to undo that behaviour |
| 115 |
# (i.e., see active tag events themselves). |
| 116 |
if (type=="start" |
| 117 |
and activetags.isActive(name) |
| 118 |
and not hasattr(self.curParser, "ACTIVE_NOEXPAND")): |
| 119 |
self.curParser = activetags.getActiveTag(name)(self.curParser) |
| 120 |
return |
| 121 |
|
| 122 |
if self.next is None: |
| 123 |
self._feedToStructured(type, name, value) |
| 124 |
else: |
| 125 |
self._feedToAtom(type, name, value) |
| 126 |
|
| 127 |
def feedEvent(self, |
| 128 |
ctx: StructParseContext, |
| 129 |
evType: common.ParserEventType, |
| 130 |
name: str, |
| 131 |
value: StructParserValue) -> Optional[Union[common.Parser, str]]: |
| 132 |
"""dispatches an event to the root structure. |
| 133 |
|
| 134 |
Do not call this yourself unless you know what you're doing. The |
| 135 |
method to feed "real" events to is feed. |
| 136 |
""" |
| 137 |
if name!=self.result.name_: |
| 138 |
raise common.StructureError("Expected root element %s, found %s"%( |
| 139 |
self.result.name_, name)) |
| 140 |
|
| 141 |
if evType=="start": |
| 142 |
self.result.idmap = ctx.idmap # type: ignore # dynamic attribute |
| 143 |
ctx.setPositionOn(self.result) |
| 144 |
return self.result |
| 145 |
|
| 146 |
else: |
| 147 |
raise common.StructureError("Bad document structure") |
| 148 |
|
| 149 |
def setParser(self, parser: Structure) -> None: |
| 150 |
"""sets a structure to receive parse events. |
| 151 |
|
| 152 |
In particular, this bypasses any checks that the event stream coming |
| 153 |
is is actually destined for root. Use this for replay-type things |
| 154 |
(feedFrom, active tags) exclusively. |
| 155 |
""" |
| 156 |
self.curParser = parser |
| 157 |
self.result.idmap = self.ctx.idmap # type: ignore # dynamic attribute |
| 158 |
|
| 159 |
|
| 160 |
def _synthesizeAttributeEvents( |
| 161 |
evProc: EventProcessor, |
| 162 |
context: StructParseContext, |
| 163 |
attrs: Dict[str, str]) -> None: |
| 164 |
"""generates value events for the attributes in attrs. |
| 165 |
""" |
| 166 |
# original attributes must be fed first since they will usually |
| 167 |
# yield a different target object |
| 168 |
original = attrs.pop("original", None) |
| 169 |
if original: |
| 170 |
evProc.feed(common.ParserEventType.value, "original", original) |
| 171 |
|
| 172 |
# mixins must be fed last as they might depend on stuff set |
| 173 |
# in other attributes |
| 174 |
mixin = attrs.pop("mixin", None) |
| 175 |
|
| 176 |
for key, val in attrs.items(): |
| 177 |
evProc.feed(common.ParserEventType.value, key, val) |
| 178 |
|
| 179 |
if mixin: |
| 180 |
evProc.feed(common.ParserEventType.value, "mixin", mixin) |
| 181 |
|
| 182 |
|
| 183 |
def feedTo( |
| 184 |
rootStruct: "_StructureArg", |
| 185 |
eventSource: Iterator, |
| 186 |
context: StructParseContext, |
| 187 |
feedInto: bool = False) -> Structure: |
| 188 |
"""feeds events from eventSource to rootStruct. |
| 189 |
|
| 190 |
A new event processor is used for feeding. No context |
| 191 |
exit functions are run. |
| 192 |
|
| 193 |
The processed root structure is returned. |
| 194 |
|
| 195 |
if feedInto is true, the event creating the root structure is not |
| 196 |
expected (TODO: this is crap; fix it so that this is always the |
| 197 |
case when rootStruct is an instance). |
| 198 |
""" |
| 199 |
evProc = EventProcessor(rootStruct, context) |
| 200 |
if feedInto: |
| 201 |
evProc.setParser(evProc.result) |
| 202 |
buf = [] |
| 203 |
|
| 204 |
try: |
| 205 |
for type, name, payload in eventSource: |
| 206 |
# buffer data |
| 207 |
if type=="data": |
| 208 |
buf.append(payload) |
| 209 |
continue |
| 210 |
else: |
| 211 |
if buf: |
| 212 |
res = "".join(buf) |
| 213 |
if not ALL_WHITESPACE.match(res): |
| 214 |
evProc.feed(common.ParserEventType.value, "content_", res) |
| 215 |
buf = [] |
| 216 |
|
| 217 |
# "normal" event feed |
| 218 |
evProc.feed(type, name, payload) |
| 219 |
|
| 220 |
# start event: Synthesize value events for attributes. |
| 221 |
if type=="start" and payload: |
| 222 |
_synthesizeAttributeEvents(evProc, context, payload) |
| 223 |
payload = None |
| 224 |
|
| 225 |
except Exception as ex: |
| 226 |
if (not getattr(ex, "posInMsg", False) |
| 227 |
and getattr(ex, "pos", None) is None): |
| 228 |
# only add pos when the message string does not already have it. |
| 229 |
ex.pos = eventSource.pos # type: ignore # dynamic attribute |
| 230 |
raise |
| 231 |
return evProc.result |
| 232 |
|
| 233 |
|
| 234 |
def parseFromStream( |
| 235 |
rootStruct: "_StructureArg", |
| 236 |
inputStream: TextIO, |
| 237 |
context: Optional[StructParseContext] = None) -> Structure: |
| 238 |
"""parses a tree rooted in rootStruct from some file-like object inputStream. |
| 239 |
|
| 240 |
It returns the root element of the resulting tree. If rootStruct is |
| 241 |
a type subclass, it will be instantiated to create a root |
| 242 |
element, if it is an instance, this instance will be the root. |
| 243 |
""" |
| 244 |
eventSource = utils.iterparse(inputStream) |
| 245 |
if context is None: |
| 246 |
context = parsecontext.ParseContext() |
| 247 |
context.setEventSource(eventSource) |
| 248 |
res = feedTo(rootStruct, eventSource, context) |
| 249 |
context.runExitFuncs(res) |
| 250 |
return res |
| 251 |
|
| 252 |
|
| 253 |
def parseFromString( |
| 254 |
rootStruct: "_StructureArg", |
| 255 |
inputString: str, |
| 256 |
context: Optional[StructParseContext] = None) -> Structure: |
| 257 |
"""parses a DaCHS RD tree rooted in ``rootStruct`` from a string. |
| 258 |
|
| 259 |
It returns the root element of the resulting tree. You would use this like |
| 260 |
this:: |
| 261 |
|
| 262 |
parseFromString(rscdef.Column, "<column name='foo'/>") |
| 263 |
""" |
| 264 |
return parseFromStream(rootStruct, io.StringIO(inputString), context) |
| 265 |
|
| 266 |
|
| 267 |
def structToETree(aStruct: Structure) -> utils.ElementTree.Element: |
| 268 |
"""returns an ElementTree for the copyable content of aStruct. |
| 269 |
|
| 270 |
Note that due to manipulations at parse time and non-copyable content, |
| 271 |
this will, in general, not reproduce the original XML trees. |
| 272 |
""" |
| 273 |
nodeStack = [utils.ElementTree.Element(cast(str, aStruct.name_))] |
| 274 |
for evType, elName, value in aStruct.iterEvents(): |
| 275 |
# data model horror. let me hack around it for now |
| 276 |
if elName=='_synthesizedRoles': |
| 277 |
continue |
| 278 |
try: |
| 279 |
if evType=="start": |
| 280 |
nodeStack.append(utils.ElementTree.SubElement(nodeStack[-1], elName)) |
| 281 |
elif evType=="end": |
| 282 |
nodeStack.pop() |
| 283 |
elif evType=="value": |
| 284 |
|
| 285 |
if value is None or value is common.NotGiven: |
| 286 |
# do not serialise empty or missing attributes at all |
| 287 |
pass |
| 288 |
|
| 289 |
elif elName=="content_": |
| 290 |
# This will become an actual "attribute" in an element. |
| 291 |
# Let's see how much we will regret blindly stringifying |
| 292 |
# these. |
| 293 |
nodeStack[-1].text = str(value) |
| 294 |
|
| 295 |
elif hasattr(value, "payload"): |
| 296 |
# it's an _AttBox, which ought to go soon anyway; skip |
| 297 |
# these, it's only hit stupid legacy STC annotation |
| 298 |
continue |
| 299 |
|
| 300 |
else: |
| 301 |
if isinstance(value, pathlib.Path): |
| 302 |
value = str(value) |
| 303 |
if hasattr(value, "id"): |
| 304 |
# I blindly assume that's a reference |
| 305 |
value = value.id |
| 306 |
|
| 307 |
# silently swallow everything that's not a string by now. |
| 308 |
# should we do better? |
| 309 |
if isinstance(value, str): |
| 310 |
nodeStack[-1].set(elName, value) |
| 311 |
else: |
| 312 |
raise utils.Error("Invalid struct event: %s"%evType) |
| 313 |
except Exception as exc: |
| 314 |
exc.dachsNote = ( # type: ignore # dynamic attribute |
| 315 |
"Badness occurred in element %s, event %s," |
| 316 |
" value %s\n"%(elName, evType, value)) |
| 317 |
raise |
| 318 |
return nodeStack[-1] |
| 319 |
|
| 320 |
|
| 321 |
def structToXML(aStruct: Structure) -> str: |
| 322 |
"""returns RD XML for a structure as a native string. |
| 323 |
""" |
| 324 |
dest = io.BytesIO() |
| 325 |
utils.ElementTree.ElementTree(structToETree(aStruct)).write(dest, encoding="utf-8") |
| 326 |
return dest.getvalue().decode("utf-8") |