| 1 |
""" |
| 2 |
Common code for DaCHS's base package. |
| 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 |
import enum |
| 11 |
import warnings |
| 12 |
|
| 13 |
from gavo import utils |
| 14 |
from gavo.utils import NotGiven #noflake: backwards compatiblity import |
| 15 |
|
| 16 |
from gavo.utils.excs import ( #noflake: exceptions are historically in base |
| 17 |
Error, |
| 18 |
BadCode, DataError, DBTableError, EmptyData, ExecutiveAction, |
| 19 |
LiteralParseError, |
| 20 |
MultiplicityError, NotFoundError, ParseException, RDNotFound, |
| 21 |
ReportableError, RestrictedElement, SkipThis, StructureError, |
| 22 |
SourceParseError, ValidationError) |
| 23 |
|
| 24 |
from gavo.utils.dachstypes import ( |
| 25 |
Any, NoReturn, Optional, |
| 26 |
Self, Structure, StructParseContext, StructParserValue, Type, Union) |
| 27 |
|
| 28 |
|
| 29 |
class Ignore(ExecutiveAction): |
| 30 |
"""An executive action causing an element to be not adopted by its |
| 31 |
parent. |
| 32 |
|
| 33 |
Raise this in -- typically -- onElementComplete if the element just |
| 34 |
built goes somewhere else but into its parent structure (or is |
| 35 |
somehow benignly unusable). Classic use case: Active Tags. |
| 36 |
""" |
| 37 |
|
| 38 |
|
| 39 |
class Replace(ExecutiveAction): |
| 40 |
"""An executive action replacing the current child with the Exception's |
| 41 |
argument. |
| 42 |
|
| 43 |
Use this sparingly. I'd like to get rid of it. |
| 44 |
""" |
| 45 |
def __init__(self, |
| 46 |
newOb: "Structure", |
| 47 |
newName: Optional[str] = None) -> None: |
| 48 |
self.newOb, self.newName = newOb, newName |
| 49 |
|
| 50 |
|
| 51 |
# the tree event types for our struct parsing |
| 52 |
try: |
| 53 |
ParserEventType = enum.StrEnum("ParserEventType", ["start", "end", "value"]) |
| 54 |
except AttributeError: |
| 55 |
# python < 3.11 |
| 56 |
class ParserEventType: # type: ignore |
| 57 |
start = "start" |
| 58 |
end = "end" |
| 59 |
value = "value" |
| 60 |
|
| 61 |
|
| 62 |
class Parser: |
| 63 |
"""A mixin for a structure you can feed events to. |
| 64 |
|
| 65 |
The class mixing thing in must define methods ``start_``, ``end_``, |
| 66 |
and ``value_``, each accepting a parse context (a base.RDParseContext |
| 67 |
instance), the name of an element or attribute, and a value |
| 68 |
(which is an attribute of dicts in the case of start, and a |
| 69 |
string in the case of value. |
| 70 |
|
| 71 |
They all must return either None or the next parser; start_ may also |
| 72 |
return a string, which then names the attribute the next value is for. |
| 73 |
""" |
| 74 |
def __init__(self) -> NoReturn: |
| 75 |
raise StructureError("Parser is now a pure mixin") |
| 76 |
|
| 77 |
def feedEvent(self, |
| 78 |
ctx: StructParseContext, |
| 79 |
type: ParserEventType, |
| 80 |
name: str, |
| 81 |
value: StructParserValue) -> Optional[Union["Parser", str]]: |
| 82 |
if type=="start": |
| 83 |
return self.start_(ctx, name, value) |
| 84 |
elif type=="value": |
| 85 |
return self.value_(ctx, name, value) |
| 86 |
elif type=="end": |
| 87 |
return self.end_(ctx, name, value) |
| 88 |
else: |
| 89 |
raise StructureError( |
| 90 |
"Illegal event type while building: '%s'"%type) |
| 91 |
|
| 92 |
def start_(self, |
| 93 |
ctx: StructParseContext, |
| 94 |
name: str, |
| 95 |
value: StructParserValue) -> Optional[Union["Parser", str]]: |
| 96 |
pass |
| 97 |
|
| 98 |
def end_(self, |
| 99 |
ctx: StructParseContext, |
| 100 |
name: str, |
| 101 |
value: StructParserValue) -> Optional["Parser"]: |
| 102 |
pass |
| 103 |
|
| 104 |
def value_(self, |
| 105 |
ctx: StructParseContext, |
| 106 |
name: str, |
| 107 |
value: StructParserValue) -> Optional["Parser"]: |
| 108 |
pass |
| 109 |
|
| 110 |
|
| 111 |
class ParserEvent(tuple): |
| 112 |
"""a tuple consists of an event type (a ParserEventType) |
| 113 |
the name and value from common.Parser, and the position object. |
| 114 |
|
| 115 |
We probably should use a namedtuple here one day and actually |
| 116 |
check we get what we need, but for now, this is only to acquiesce |
| 117 |
the type checker. |
| 118 |
""" |
| 119 |
def __new__(cls, *args): |
| 120 |
return super().__new__(cls, args) |
| 121 |
|
| 122 |
|
| 123 |
class StructParseDebugMixin: |
| 124 |
"""put this before Parser in the parent class list of a struct, |
| 125 |
and you'll see the events coming in to your parser. |
| 126 |
""" |
| 127 |
def feedEvent(self, |
| 128 |
ctx: StructParseContext, |
| 129 |
type: ParserEventType, |
| 130 |
name: str, |
| 131 |
value: StructParserValue) -> Optional[Self]: |
| 132 |
print(type, name, value, self) |
| 133 |
return super().feedEvent( # type: ignore |
| 134 |
self, ctx, type, name, value) |
| 135 |
|
| 136 |
|
| 137 |
class StructCallbacks: |
| 138 |
"""A class terminating super() calls for the structure callbacks. |
| 139 |
|
| 140 |
Structs, when finished, call completeElement(ctx), validate(), |
| 141 |
and onElementComplete() in sequence. All these need to up-call. |
| 142 |
This mixin provides non-upcalling implementations of these methods, |
| 143 |
and it needs to be present in mixins for structure. |
| 144 |
|
| 145 |
This will only work properly if self actually is a struct, as we rely |
| 146 |
on the presence of name_ attributes in case of prematurely terminated |
| 147 |
method resolution. |
| 148 |
""" |
| 149 |
name_: Union[str, Type[utils.Undefined]] = "(StructCallbacks terminator)" |
| 150 |
|
| 151 |
def __warnTermination(self, methname: str) -> None: |
| 152 |
if hasattr(super(), methname): |
| 153 |
mro = " ".join(c.__name__ for c in self.__class__.__mro__) |
| 154 |
warnings.warn(f"Discarding {methname} method while calling up" |
| 155 |
f" from {self.name_}, mro {mro} ") |
| 156 |
|
| 157 |
def validate(self) -> None: |
| 158 |
self.__warnTermination("validate") |
| 159 |
|
| 160 |
def completeElement(self, ctx: StructParseContext) -> None: |
| 161 |
self.__warnTermination("completeElement") |
| 162 |
|
| 163 |
def onElementComplete(self) -> None: |
| 164 |
self.__warnTermination("onElementComplete") |
| 165 |
|
| 166 |
def setParent(self, parent: Any) -> None: |
| 167 |
self.__warnTermination("setParent") |