| 1 |
""" |
| 2 |
Attributes with structure (i.e., containing structures or more than one |
| 3 |
atom). |
| 4 |
|
| 5 |
These come with parsers of their own, in some way or other. |
| 6 |
|
| 7 |
Structure attributes, which do not have string literals and have some sort |
| 8 |
of internal structure, add methods |
| 9 |
|
| 10 |
- create(instance, ctx, name) -> structure -- creates a new object suitable |
| 11 |
as attribute value and returns it (for structures, instance becomes the |
| 12 |
parent of the new structure as a side effect of this operation). This |
| 13 |
is what should later be fed to feedObject. It must work as a parser, |
| 14 |
i.e., have a feedEvent method. The name argument gives the name of |
| 15 |
the element that caused the create call, allowing for polymorphic attrs. |
| 16 |
- replace(instance, oldVal, newVal) -> None -- replaces oldVal with newVal; |
| 17 |
this works like feedObject, except that an old value is overwritten. |
| 18 |
- iterEvents(instance) -> events -- yields events to recreate its value |
| 19 |
on another instance. |
| 20 |
""" |
| 21 |
|
| 22 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 23 |
#c |
| 24 |
#c This program is free software, covered by the GNU GPL. See the |
| 25 |
#c COPYING file in the source distribution. |
| 26 |
|
| 27 |
|
| 28 |
from gavo import utils |
| 29 |
from gavo.base import attrdef |
| 30 |
from gavo.base import common |
| 31 |
from gavo.base import literals |
| 32 |
from gavo.utils import excs |
| 33 |
|
| 34 |
from gavo.utils.dachstypes import (cast, |
| 35 |
Any, Callable, Dict, Iterator, List, Optional, |
| 36 |
Set, StructParseContext, StructParserValue, Structure, |
| 37 |
Tuple, Union) |
| 38 |
|
| 39 |
|
| 40 |
__docformat__ = "restructuredtext en" |
| 41 |
|
| 42 |
|
| 43 |
class CollOfAtomsAttribute(attrdef.AtomicAttribute): |
| 44 |
"""A base class for simple collections of atomic attributes. |
| 45 |
""" |
| 46 |
def __init__(self, |
| 47 |
name: str, |
| 48 |
default: List = [], |
| 49 |
itemAttD: attrdef.AtomicAttribute = attrdef.UnicodeAttribute("listItem"), |
| 50 |
**kwargs: Any) -> None: |
| 51 |
self.elementName_ = itemAttD.name_ |
| 52 |
kwargs.setdefault("aliases", []).append(self.elementName_) |
| 53 |
attrdef.AttributeDef.__init__(self, |
| 54 |
name, |
| 55 |
default=attrdef.Computed, |
| 56 |
**kwargs) |
| 57 |
self.itemAttD = itemAttD |
| 58 |
self.realDefault = default |
| 59 |
|
| 60 |
def iterEvents(self, instance: Structure) -> Iterator[common.ParserEvent]: |
| 61 |
for item in getattr(instance, self.name_): |
| 62 |
yield common.ParserEvent("start", self.elementName_, None) |
| 63 |
yield common.ParserEvent("value", "content_", self.itemAttD.unparse(item)) |
| 64 |
yield common.ParserEvent("end", self.elementName_, None) |
| 65 |
|
| 66 |
|
| 67 |
class ListOfAtomsAttribute(CollOfAtomsAttribute): |
| 68 |
"""is an attribute definition for an item containing many elements |
| 69 |
of the same type. |
| 70 |
|
| 71 |
It is constructed with an AttributeDef for the items. Note that it's |
| 72 |
safe to pass in lists as defaults since they are copied before being |
| 73 |
added to the instances, so you won't (and can't) have aliasing here. |
| 74 |
""" |
| 75 |
|
| 76 |
@property |
| 77 |
def default_(self) -> List: |
| 78 |
return self.realDefault[:] |
| 79 |
|
| 80 |
@property |
| 81 |
def typeDesc_(self) -> str: |
| 82 |
return "Zero or more {}-typed *{}* elements".format( |
| 83 |
self.itemAttD.typeDesc_, |
| 84 |
self.itemAttD.name_) |
| 85 |
|
| 86 |
def feed(self, |
| 87 |
ctx: StructParseContext, |
| 88 |
instance: Structure, |
| 89 |
value: str) -> None: |
| 90 |
if "\\" in value and hasattr(instance, "expand"): |
| 91 |
value = instance.expand(value) |
| 92 |
getattr(instance, self.name_).append(self.itemAttD.parse(value)) |
| 93 |
|
| 94 |
def feedObject(self, |
| 95 |
instance: Structure, |
| 96 |
value: Any) -> None: |
| 97 |
if isinstance(value, list): |
| 98 |
for item in value: |
| 99 |
self.feedObject(instance, item) |
| 100 |
else: |
| 101 |
getattr(instance, self.name_).append(value) |
| 102 |
self.doCallbacks(instance, value) |
| 103 |
|
| 104 |
def getCopy(self, |
| 105 |
instance: Structure, |
| 106 |
newParent: Structure, |
| 107 |
ctx: Optional[StructParseContext]) -> List[str]: |
| 108 |
return getattr(instance, self.name_)[:] |
| 109 |
|
| 110 |
def unparse(self, value: Any) -> str: |
| 111 |
return str(value) |
| 112 |
|
| 113 |
|
| 114 |
class SetOfAtomsAttribute(CollOfAtomsAttribute): |
| 115 |
"""is an attribute definition for an item containing many elements |
| 116 |
of the same type, when order doesn't matter but lookup times do. |
| 117 |
|
| 118 |
It is constructed with an AttributeDef for the items. Note that it's |
| 119 |
safe to pass in lists as defaults since they are copied before being |
| 120 |
added to the instances, so you won't (and can't) have aliasing here. |
| 121 |
""" |
| 122 |
@property |
| 123 |
def default_(self) -> Set: |
| 124 |
return set(self.realDefault) |
| 125 |
|
| 126 |
@property |
| 127 |
def typeDesc_(self) -> str: |
| 128 |
return "Set of {}s".format(self.itemAttD.typeDesc_) |
| 129 |
|
| 130 |
def feed(self, |
| 131 |
ctx: StructParseContext, |
| 132 |
instance: Structure, |
| 133 |
value: str) -> None: |
| 134 |
getattr(instance, self.name_).add(self.itemAttD.parse(value)) |
| 135 |
|
| 136 |
def feedObject(self, |
| 137 |
instance: Structure, |
| 138 |
value: str) -> None: |
| 139 |
if isinstance(value, set): |
| 140 |
for item in value: |
| 141 |
self.feedObject(instance, value) |
| 142 |
else: |
| 143 |
getattr(instance, self.name_).add(value) |
| 144 |
self.doCallbacks(instance, value) |
| 145 |
|
| 146 |
def getCopy(self, |
| 147 |
instance: Structure, |
| 148 |
newParent: Structure, |
| 149 |
ctx: Optional[StructParseContext]): |
| 150 |
return set(getattr(instance, self.name_)) |
| 151 |
|
| 152 |
|
| 153 |
class _DictAttributeParser(common.Parser): |
| 154 |
"""a parser for DictAttributes. |
| 155 |
|
| 156 |
These need a custom parser since they accept some exotic features, as |
| 157 |
discussed in DictAttribute's docstring. |
| 158 |
|
| 159 |
The parser keeps state in the _key and _adding attributes and needs to |
| 160 |
be _reset after use. |
| 161 |
""" |
| 162 |
def __init__(self, |
| 163 |
dict: Dict[str, Any], |
| 164 |
nextParser: Structure, |
| 165 |
parseValue: Callable[[str], Any], |
| 166 |
keyName: str, |
| 167 |
inverted: bool = False, |
| 168 |
expander: Any = None) -> None: |
| 169 |
|
| 170 |
self._key: Union[str, utils.UndefinedType] = utils.Undefined |
| 171 |
self._adding: bool = False |
| 172 |
|
| 173 |
self.dict, self.nextParser, self.parseValue = ( |
| 174 |
dict, nextParser, parseValue) |
| 175 |
self.keyName, self.inverted, self.expander = ( |
| 176 |
keyName, inverted, expander) |
| 177 |
self._reset() |
| 178 |
|
| 179 |
def _reset(self) -> None: |
| 180 |
self._key, self._adding = utils.Undefined, False |
| 181 |
|
| 182 |
def addPair(self, key: str, value: Any) -> None: |
| 183 |
if self.inverted: |
| 184 |
key, value = value, key |
| 185 |
if self._adding: |
| 186 |
self.dict[key] = self.dict.get(key, "")+value |
| 187 |
else: |
| 188 |
self.dict[key] = value |
| 189 |
|
| 190 |
def value_(self, |
| 191 |
ctx: StructParseContext, |
| 192 |
name: str, |
| 193 |
value: StructParserValue) -> "_DictAttributeParser": |
| 194 |
if name=="key" or name==self.keyName: |
| 195 |
self._key = str(value) |
| 196 |
|
| 197 |
elif name=="cumulate": |
| 198 |
self._adding = literals.parseBooleanLiteral(value) |
| 199 |
|
| 200 |
elif name=="content_": |
| 201 |
if self._key is utils.Undefined: |
| 202 |
raise common.StructureError("Content '%s' has no %s attribute"%( |
| 203 |
value, self.keyName)) |
| 204 |
|
| 205 |
if isinstance(value, str): |
| 206 |
if (self.expander |
| 207 |
and "\\" in value): |
| 208 |
value = self.expander.expand(value) |
| 209 |
value = self.parseValue(cast(str, value)) |
| 210 |
else: |
| 211 |
# we believe we're getting a parsed thing (during replay) |
| 212 |
pass |
| 213 |
|
| 214 |
if isinstance(self._key, str): |
| 215 |
self.addPair(self._key, value) |
| 216 |
else: |
| 217 |
NotImplementedError("This can't happen") |
| 218 |
|
| 219 |
self._reset() |
| 220 |
|
| 221 |
else: |
| 222 |
raise common.StructureError('No "%s" attributes on mappings'%name) |
| 223 |
|
| 224 |
return self |
| 225 |
|
| 226 |
def start_(self, |
| 227 |
ctx: StructParseContext, |
| 228 |
name: str, |
| 229 |
value: StructParserValue): |
| 230 |
raise common.StructureError("No %s elements in mappings"%name) |
| 231 |
|
| 232 |
def end_(self, ctx: StructParseContext, name: str, value: StructParserValue |
| 233 |
) -> Structure: |
| 234 |
if self._key is not utils.Undefined: |
| 235 |
raise common.StructureError("Empty map values are not allowed") |
| 236 |
return self.nextParser |
| 237 |
|
| 238 |
|
| 239 |
class DictAttribute(attrdef.AttributeDef): |
| 240 |
"""an attribute containing a mapping. |
| 241 |
|
| 242 |
DictAttributes are fairly complex beasts supporting a number of input |
| 243 |
forms. |
| 244 |
|
| 245 |
The input to those looks like <d key="foo">abc</d>; they are constructed |
| 246 |
with an itemAttD (like StructAttributes), but the name on those |
| 247 |
is ignored; they are just used for parsing from the strings in the |
| 248 |
element bodies, which means that itemAttDs must be derived from |
| 249 |
AtomicAttribute. |
| 250 |
|
| 251 |
You can give a different keyNames; the key attribute is always |
| 252 |
accepted, though. |
| 253 |
|
| 254 |
For sufficiently exotic situations, you can construct DictAttributes |
| 255 |
with inverted=True; the resulting dictionary will then have the keys as |
| 256 |
values and vice versa (this is a doubtful feature; let us know when |
| 257 |
you use it). |
| 258 |
|
| 259 |
You can also add to existing values using the cumulate XML attribute; |
| 260 |
<d key="s">a</d><d key="s" cumulate="True">bc</a> will leave |
| 261 |
abc in s. |
| 262 |
""" |
| 263 |
def __init__(self, |
| 264 |
name: str, |
| 265 |
description: str = "Undocumented", |
| 266 |
itemAttD: attrdef.AtomicAttribute = attrdef.UnicodeAttribute("value"), |
| 267 |
keyName: str = "key", |
| 268 |
elementName: Optional[str] = None, |
| 269 |
inverted: bool = False, |
| 270 |
expandMacros: bool = False, |
| 271 |
**kwargs: Any) -> None: |
| 272 |
self.elementName = elementName |
| 273 |
if self.elementName: |
| 274 |
kwargs.setdefault("aliases", []).append(self.elementName) |
| 275 |
else: |
| 276 |
kwargs.setdefault("aliases", []).append(itemAttD.name_) |
| 277 |
|
| 278 |
attrdef.AttributeDef.__init__(self, |
| 279 |
name, |
| 280 |
attrdef.Computed, |
| 281 |
description, |
| 282 |
**kwargs) |
| 283 |
self.itemAttD = itemAttD |
| 284 |
self.keyName = keyName |
| 285 |
self.inverted = inverted |
| 286 |
self.expandMacros = expandMacros |
| 287 |
|
| 288 |
@property |
| 289 |
def typeDesc_(self): |
| 290 |
return "Dict mapping strings to %s"%self.itemAttD.typeDesc_ |
| 291 |
|
| 292 |
@property |
| 293 |
def default_(self) -> Dict: |
| 294 |
return {} |
| 295 |
|
| 296 |
def feedObject(self, instance: Structure, value: Dict[str, str]) -> None: |
| 297 |
setattr(instance, self.name_, value) |
| 298 |
self.doCallbacks(instance, value) |
| 299 |
|
| 300 |
def create(self, |
| 301 |
parent: Structure, |
| 302 |
ctx: StructParseContext, |
| 303 |
name: str) -> _DictAttributeParser: |
| 304 |
expander = None |
| 305 |
if self.expandMacros and hasattr(parent, "expand"): |
| 306 |
expander = parent |
| 307 |
|
| 308 |
return _DictAttributeParser(getattr(parent, self.name_), |
| 309 |
parent, self.itemAttD.parse, keyName=self.keyName, |
| 310 |
inverted=self.inverted, |
| 311 |
expander=expander) |
| 312 |
|
| 313 |
def iterEvents(self, instance: Structure) -> Iterator[common.ParserEvent]: |
| 314 |
childName = self.elementName or self.itemAttD.name_ |
| 315 |
for key, value in getattr(instance, self.name_).items(): |
| 316 |
yield common.ParserEvent("start", childName, None) |
| 317 |
yield common.ParserEvent("value", "key", key) |
| 318 |
yield common.ParserEvent( |
| 319 |
"value", "content_", self.itemAttD.unparse(value)) |
| 320 |
yield common.ParserEvent("end", childName, None) |
| 321 |
|
| 322 |
def getCopy(self, |
| 323 |
instance: Structure, |
| 324 |
newParent: Structure, |
| 325 |
ctx: Optional[StructParseContext]) -> Dict[str, str]: |
| 326 |
return getattr(instance, self.name_).copy() |
| 327 |
|
| 328 |
def makeUserDoc(self) -> Optional[str]: |
| 329 |
if self.inverted: |
| 330 |
expl = ("the key is the element content, the value is in the 'key'" |
| 331 |
" (or, equivalently, %s) attribute"%self.keyName) |
| 332 |
else: |
| 333 |
expl = ("the value is the element content, the key is in the 'key'" |
| 334 |
" (or, equivalently, %s) attribute"%self.keyName) |
| 335 |
|
| 336 |
return "**%s** (mapping; %s) -- %s"%( |
| 337 |
self.name_, expl, self.description_) |
| 338 |
|
| 339 |
|
| 340 |
class PropertyAttribute(DictAttribute): |
| 341 |
"""adds the property protocol to the parent instance. |
| 342 |
|
| 343 |
The property protocol consists of the methods |
| 344 |
- setProperty(name, value), |
| 345 |
- getProperty(name, default=Undefined) |
| 346 |
- clearProperty(name) |
| 347 |
- hasProperty(name) |
| 348 |
|
| 349 |
getProperty works like dict.get, except it will raise a KeyError |
| 350 |
without a default. |
| 351 |
|
| 352 |
This is provided for user information and, to some extent, some |
| 353 |
DC-internal purposes. |
| 354 |
""" |
| 355 |
def __init__(self, |
| 356 |
description: str = "Properties (i.e., user-defined" |
| 357 |
" key-value pairs) for the element.", |
| 358 |
**kwargs: Any) -> None: |
| 359 |
kwargs.setdefault("aliases", []).append("property") |
| 360 |
DictAttribute.__init__(self, |
| 361 |
"properties", |
| 362 |
description=description, |
| 363 |
keyName="name", |
| 364 |
elementName="property", |
| 365 |
expandMacros=True, |
| 366 |
**kwargs) |
| 367 |
|
| 368 |
def iterParentMethods(self |
| 369 |
) -> Iterator[Tuple[str, Union[Callable, property]]]: |
| 370 |
def setProperty(self, name, value): |
| 371 |
self.properties[name] = value |
| 372 |
yield "setProperty", setProperty |
| 373 |
|
| 374 |
def getProperty(self, name, default=utils.Undefined): |
| 375 |
if default is utils.Undefined: |
| 376 |
try: |
| 377 |
return self.properties[name] |
| 378 |
except KeyError: |
| 379 |
raise excs.NotFoundError(name, |
| 380 |
"property", |
| 381 |
repr(self)) |
| 382 |
else: |
| 383 |
return self.properties.get(name, default) |
| 384 |
yield "getProperty", getProperty |
| 385 |
|
| 386 |
def clearProperty(self, name): |
| 387 |
if name in self.properties: |
| 388 |
del self.properties[name] |
| 389 |
yield "clearProperty", clearProperty |
| 390 |
|
| 391 |
def hasProperty(self, name): |
| 392 |
return name in self.properties |
| 393 |
yield "hasProperty", hasProperty |
| 394 |
|
| 395 |
def makeUserDoc(self) -> Optional[str]: |
| 396 |
return ("**property** (mapping of user-defined keywords in the" |
| 397 |
" name attribute to string values) -- %s"%self.description_) |
| 398 |
|
| 399 |
|
| 400 |
class _StructMakingAttribute(attrdef.AttributeDef): |
| 401 |
"""An abstract base for attributes containing zero, one, or |
| 402 |
more Structures. |
| 403 |
|
| 404 |
Implementing classes need to define the create method as described in |
| 405 |
the module docstring. iterEvents and replace as defined here might |
| 406 |
just work in simple cases. |
| 407 |
""" |
| 408 |
def __init__(self, name, **kwargs): |
| 409 |
attrdef.AttributeDef.__init__(self, name, **kwargs) |
| 410 |
|
| 411 |
def feedObject(self, instance: Structure, value: Structure) -> None: |
| 412 |
if value and value.parent is None: # adopt if necessary |
| 413 |
value.parent = instance |
| 414 |
setattr(instance, self.name_, value) |
| 415 |
self.doCallbacks(instance, value) |
| 416 |
|
| 417 |
def getCopy(self, |
| 418 |
instance: Structure, |
| 419 |
newParent: Structure, |
| 420 |
ctx: Optional[StructParseContext]) -> Any: |
| 421 |
val = getattr(instance, self.name_) |
| 422 |
if val is not None: |
| 423 |
return val.copy(newParent, ctx=ctx) |
| 424 |
|
| 425 |
def replace(self, |
| 426 |
instance: Structure, |
| 427 |
oldStruct: Structure, |
| 428 |
newStruct: Structure): |
| 429 |
setattr(instance, self.name_, newStruct) |
| 430 |
|
| 431 |
def iterEvents(self, instance: Structure) -> Iterator[common.ParserEvent]: |
| 432 |
val = getattr(instance, self.name_) |
| 433 |
if val is common.NotGiven: |
| 434 |
return |
| 435 |
if val is None: |
| 436 |
return |
| 437 |
yield common.ParserEvent("start", val.name_, None) |
| 438 |
for ev in val.iterEvents(): |
| 439 |
yield ev |
| 440 |
yield common.ParserEvent("end", val.name_, None) |
| 441 |
|
| 442 |
def iterChildren(self, instance: Structure) -> Iterator[Structure]: |
| 443 |
if getattr(instance, self.name_) is not None: |
| 444 |
yield getattr(instance, self.name_) |
| 445 |
|
| 446 |
def remove(self, child: Structure): |
| 447 |
setattr(child.parent, self.name_, self.default_) |
| 448 |
|
| 449 |
|
| 450 |
class StructAttribute(_StructMakingAttribute): |
| 451 |
"""describes an attribute containing a Structure |
| 452 |
|
| 453 |
These are constructed with a childFactory that must have a feedEvent |
| 454 |
method. Otherwise, they are normal structs, i.e., the receive a |
| 455 |
parent as the first argument and keyword arguments for values. |
| 456 |
|
| 457 |
In addition, you can pass a onParentComplete callback that |
| 458 |
are collected in the completedCallback list by the struct decorator. |
| 459 |
ParseableStruct instances call these when they receive their end |
| 460 |
event during XML deserialization. |
| 461 |
""" |
| 462 |
def __init__(self, |
| 463 |
name: str, |
| 464 |
childFactory: Optional[type[Structure]], |
| 465 |
default: Union[Structure, type[attrdef.Computed], |
| 466 |
utils.UndefinedType, None] = utils.Undefined, |
| 467 |
description: str = "Undocumented", |
| 468 |
**kwargs: Any) -> None: |
| 469 |
|
| 470 |
self.childFactory = childFactory |
| 471 |
if self.childFactory is not None: |
| 472 |
kwargs.setdefault("aliases", []).append(self.childFactory.name_) |
| 473 |
|
| 474 |
_StructMakingAttribute.__init__(self, |
| 475 |
name=name, default=default, description=description, **kwargs) |
| 476 |
|
| 477 |
@property |
| 478 |
def typeDesc_(self) -> str: |
| 479 |
if self.childFactory is not None: |
| 480 |
return getattr( |
| 481 |
self.childFactory, "docName_", str(self.childFactory.name_)) |
| 482 |
else: |
| 483 |
return "<Undefined>" |
| 484 |
|
| 485 |
def create(self, |
| 486 |
instance: Structure, |
| 487 |
ctx: StructParseContext, |
| 488 |
name: str) -> Structure: |
| 489 |
if self.childFactory is attrdef.Recursive: |
| 490 |
res = instance.__class__(instance) |
| 491 |
elif self.childFactory is None: |
| 492 |
raise ValueError("Cannot create a child without a factory") |
| 493 |
else: |
| 494 |
res = self.childFactory(instance) |
| 495 |
ctx.setPositionOn(res) |
| 496 |
return res |
| 497 |
|
| 498 |
def feed(self, |
| 499 |
ctx: StructParseContext, |
| 500 |
instance: Structure, |
| 501 |
value: str) -> None: |
| 502 |
|
| 503 |
if self.childFactory is None: |
| 504 |
raise ValueError("Cannot feed to a StructAttribute without a" |
| 505 |
" child factory") |
| 506 |
|
| 507 |
# if the child factory actually admits content_ (and needs nothing |
| 508 |
# else), allow naked values to be fed in, too. |
| 509 |
if "content_" in self.childFactory.managedAttrs: |
| 510 |
child = self.childFactory(instance, content_=value).finishElement(ctx) |
| 511 |
return self.feedObject(instance, child) |
| 512 |
|
| 513 |
raise common.LiteralParseError(self.name_, |
| 514 |
value, hint="These attributes have no literals at all, i.e.," |
| 515 |
" they are for internal use only.") |
| 516 |
|
| 517 |
def makeUserDoc(self) -> Optional[str]: |
| 518 |
if self.childFactory is attrdef.Recursive: |
| 519 |
contains = "(contains an instance of the embedding element)" |
| 520 |
else: |
| 521 |
contains = "(contains `Element %s`_)"%self.typeDesc_ |
| 522 |
return "**%s** %s -- %s"%( |
| 523 |
self.name_, contains, self.description_) |
| 524 |
|
| 525 |
def onParentComplete(self, val: Structure) -> None: |
| 526 |
if hasattr(val, "onParentComplete"): |
| 527 |
val.onParentComplete() |
| 528 |
|
| 529 |
|
| 530 |
class MultiStructAttribute(_StructMakingAttribute): |
| 531 |
"""describes an attribute containing one of a class of Structures. |
| 532 |
|
| 533 |
This is to support things like grammars or cores -- these can |
| 534 |
be of many types. |
| 535 |
|
| 536 |
This works like StructAttribute, except that childFactory now is |
| 537 |
a *function* returning elements (i.e., it's a childFactoryFactory). |
| 538 |
""" |
| 539 |
def __init__(self, |
| 540 |
name: str, |
| 541 |
childFactory: Callable[[str], Structure], |
| 542 |
childNames: List[str], |
| 543 |
**kwargs: Any) -> None: |
| 544 |
if "aliases" in kwargs: |
| 545 |
raise TypeError("aliases are not supported with MultiStructAttribute") |
| 546 |
_StructMakingAttribute.__init__( |
| 547 |
self, name=name, aliases=childNames, **kwargs) |
| 548 |
self.childFactory = childFactory |
| 549 |
|
| 550 |
@property |
| 551 |
def typeDesc_(self) -> str: |
| 552 |
return ("one of %s"%", ".join(self.aliases)) |
| 553 |
|
| 554 |
def create(self, |
| 555 |
structure: Structure, |
| 556 |
ctx: StructParseContext, |
| 557 |
name: str) -> Structure: |
| 558 |
# in the following, mypy insisted that a Structure can't be called, |
| 559 |
# which is just wrong. |
| 560 |
if self.childFactory is attrdef.Recursive: |
| 561 |
res = structure.__class__(structure) |
| 562 |
else: |
| 563 |
res = self.childFactory(name)(structure) # type: ignore |
| 564 |
ctx.setPositionOn(res) |
| 565 |
return res |
| 566 |
|
| 567 |
def feed(self, |
| 568 |
ctx: StructParseContext, |
| 569 |
instance: Structure, |
| 570 |
value: str) -> None: |
| 571 |
raise NotImplementedError("Cannot feed to MultiStructAttributes") |
| 572 |
|
| 573 |
def makeUserDoc(self) -> Optional[str]: |
| 574 |
possibleChildren = [] |
| 575 |
for name in self.aliases: |
| 576 |
possibleChildren.append("{}, an `Element {}`_".format( |
| 577 |
name, self.childFactory(name).name_)) |
| 578 |
|
| 579 |
return "**{}** (contains one of {}) -- {}".format( |
| 580 |
self.name_, "; ".join(possibleChildren), self.description_) |
| 581 |
|
| 582 |
|
| 583 |
class StructListAttribute(_StructMakingAttribute): |
| 584 |
"""describes an attribute containing a homogeneous list of structures. |
| 585 |
""" |
| 586 |
def __init__(self, |
| 587 |
name: str, |
| 588 |
childFactory: type[Structure], |
| 589 |
description: str = "Undocumented", |
| 590 |
**kwargs: Any) -> None: |
| 591 |
|
| 592 |
if "default" in kwargs: |
| 593 |
raise TypeError("StructListAttributes always default to an empty list") |
| 594 |
|
| 595 |
self.childFactory = childFactory |
| 596 |
if self.childFactory is not None: |
| 597 |
kwargs.setdefault("aliases", []).append(self.childFactory.name_) |
| 598 |
|
| 599 |
_StructMakingAttribute.__init__(self, |
| 600 |
name=name, |
| 601 |
default=attrdef.Computed, |
| 602 |
description=description, **kwargs) |
| 603 |
|
| 604 |
@property |
| 605 |
def default_(self) -> List: |
| 606 |
return [] |
| 607 |
|
| 608 |
@property |
| 609 |
def typeDesc_(self) -> str: |
| 610 |
if self.childFactory is attrdef.Recursive: |
| 611 |
return "Recursive element list" |
| 612 |
elif self.childFactory is None: |
| 613 |
return "<Undefined>" |
| 614 |
else: |
| 615 |
return "List of %s"%self.childFactory.name_ |
| 616 |
|
| 617 |
def create(self, instance: Structure, ctx: StructParseContext, name: str): |
| 618 |
if self.childFactory is attrdef.Recursive: |
| 619 |
res = instance.__class__(instance) |
| 620 |
else: |
| 621 |
res = self.childFactory(instance) |
| 622 |
ctx.setPositionOn(res) |
| 623 |
return res |
| 624 |
|
| 625 |
def addStruct(self, |
| 626 |
instance: Structure, |
| 627 |
value: Structure, |
| 628 |
destIndex: Optional[int] = None) -> None: |
| 629 |
"""adds a structure to the attribute's value. |
| 630 |
|
| 631 |
Do *not* directly add to the list, always go through this |
| 632 |
method; derived classes override it for special behaviour. |
| 633 |
Also, this is where callbacks are called. |
| 634 |
|
| 635 |
Use destIndex to overwrite an (existing!) struct; default is appending. |
| 636 |
""" |
| 637 |
if value.parent is None: # adopt if necessary |
| 638 |
value.parent = instance |
| 639 |
if destIndex is None: |
| 640 |
getattr(instance, self.name_).append(value) |
| 641 |
else: |
| 642 |
getattr(instance, self.name_)[destIndex] = value |
| 643 |
self.doCallbacks(instance, value) |
| 644 |
|
| 645 |
def feedObject(self, |
| 646 |
instance: Structure, |
| 647 |
value: Structure) -> None: |
| 648 |
if isinstance(value, list): |
| 649 |
for item in value: |
| 650 |
self.feedObject(instance, item) |
| 651 |
else: |
| 652 |
self.addStruct(instance, value) |
| 653 |
|
| 654 |
def getCopy(self, |
| 655 |
instance: Structure, |
| 656 |
newParent: Structure, |
| 657 |
ctx: Optional[StructParseContext]) -> List: |
| 658 |
res = [c.copy(newParent, ctx=ctx) |
| 659 |
for c in getattr(instance, self.name_)] |
| 660 |
return res |
| 661 |
|
| 662 |
def replace(self, |
| 663 |
instance: Structure, |
| 664 |
oldStruct: Structure, |
| 665 |
newStruct: Structure) -> None: |
| 666 |
# This will only replace the first occurrence of oldStruct if |
| 667 |
# multiple identical items are in the list. Any other behaviour |
| 668 |
# would be about as useful, so let's leave it at this for now. |
| 669 |
ind = getattr(instance, self.name_).index(oldStruct) |
| 670 |
self.addStruct(instance, newStruct, ind) |
| 671 |
|
| 672 |
def iterEvents(self, instance: Structure |
| 673 |
) -> Iterator[common.ParserEvent]: |
| 674 |
for val in getattr(instance, self.name_): |
| 675 |
yield common.ParserEvent("start", val.name_, None) |
| 676 |
yield from val.iterEvents() |
| 677 |
yield common.ParserEvent("end", val.name_, None) |
| 678 |
|
| 679 |
def iterChildren(self, instance: Structure) -> Iterator[Structure]: |
| 680 |
return iter(getattr(instance, self.name_)) |
| 681 |
|
| 682 |
def remove(self, child: Structure): |
| 683 |
getattr(child.parent, self.name_).remove(child) |
| 684 |
|
| 685 |
def onParentComplete(self, val: List[Structure]) -> None: |
| 686 |
if val: |
| 687 |
for item in val: |
| 688 |
if hasattr(item, "onParentComplete"): |
| 689 |
item.onParentComplete() |
| 690 |
|
| 691 |
def makeUserDoc(self) -> Optional[str]: |
| 692 |
if self.childFactory is attrdef.Recursive: |
| 693 |
contains = "(contains an instance of the embedding element" |
| 694 |
else: |
| 695 |
contains = "(contains `Element %s`_"%self.childFactory.name_ |
| 696 |
return ("**%s** %s and may be repeated zero or more" |
| 697 |
" times) -- %s")%(self.name_, contains, self.description_) |
| 698 |
|
| 699 |
|
| 700 |
class UniquedStructListAttribute(StructListAttribute): |
| 701 |
"""A StructListAttribute that will only admit one child per value |
| 702 |
of uniqueAttribute, overwriting existing entries if existing. |
| 703 |
|
| 704 |
Actually, you can pass a policy="drop" argument to just keep |
| 705 |
an existing element and drop the new one. |
| 706 |
""" |
| 707 |
def __init__(self, |
| 708 |
name: str, |
| 709 |
childFactory: type[Structure], |
| 710 |
uniqueAttribute: str, |
| 711 |
policy: str = "overwrite", |
| 712 |
**kwargs: Any) -> None: |
| 713 |
self.uniqueAttribute = uniqueAttribute |
| 714 |
if policy not in ["overwrite", "drop"]: |
| 715 |
raise common.StructureError("UniquedStructListAttribute policy" |
| 716 |
" must be either overwrite or drop") |
| 717 |
self.policy = policy |
| 718 |
StructListAttribute.__init__(self, name, childFactory, **kwargs) |
| 719 |
|
| 720 |
@property |
| 721 |
def typeDesc_(self) -> str: |
| 722 |
return "List of %s, uniqued on %s's value"%( |
| 723 |
self.childFactory.name_, self.uniqueAttribute) |
| 724 |
|
| 725 |
def addStruct(self, |
| 726 |
instance: Structure, |
| 727 |
value: Structure, |
| 728 |
ignored: Optional[int] = None) -> None: |
| 729 |
# we expect lists will not get so long as to make a linear search |
| 730 |
# actually expensive. Linear searching, on the other hand, saves |
| 731 |
# us from having to maintain and index (in the presence of |
| 732 |
# possible deletions!) |
| 733 |
uniqueOn = getattr(value, self.uniqueAttribute) |
| 734 |
for index, item in enumerate(iter(getattr(instance, self.name_))): |
| 735 |
if getattr(item, self.uniqueAttribute)==uniqueOn: |
| 736 |
if self.policy=="overwrite": |
| 737 |
StructListAttribute.addStruct(self, instance, value, index) |
| 738 |
break |
| 739 |
else: |
| 740 |
StructListAttribute.addStruct(self, instance, value) |
| 741 |
|
| 742 |
|
| 743 |
# Ok, so the inheritance here is evil. Untangling the hierarchy |
| 744 |
# is too much effort right now, so just shut up the type checker |
| 745 |
# where necessary |
| 746 |
class MultiStructListAttribute(StructListAttribute, MultiStructAttribute): # type: ignore |
| 747 |
"""describes a list of polymorphous children. |
| 748 |
|
| 749 |
See rscdesc cores as to why one could want this; the arguments are |
| 750 |
as for MultiStructAttribute. |
| 751 |
""" |
| 752 |
def __init__(self, |
| 753 |
name: str, |
| 754 |
childFactory: Callable[..., Structure], |
| 755 |
childNames: List[str], **kwargs: Any) -> None: # type: ignore |
| 756 |
kwargs.setdefault("aliases", []).extend(childNames) |
| 757 |
StructListAttribute.__init__(self, name, childFactory=None, **kwargs) # type:ignore |
| 758 |
self.childFactory = childFactory # type:ignore |
| 759 |
|
| 760 |
@property |
| 761 |
def typeDesc_(self) -> str: |
| 762 |
return "List of any of %s"%(", ".join(self.aliases)) |
| 763 |
|
| 764 |
def create(self, structure: Structure, ctx: StructParseContext, name: str |
| 765 |
) -> Structure: |
| 766 |
res = MultiStructAttribute.create(self, structure, ctx, name) |
| 767 |
ctx.setPositionOn(res) |
| 768 |
return res |
| 769 |
|
| 770 |
def makeUserDoc(self) -> Optional[str]: |
| 771 |
if self.childFactory is attrdef.Recursive: |
| 772 |
contains = "(contains an instance of the embedding element" |
| 773 |
else: |
| 774 |
contains = "(contains any of %s"%",".join(self.aliases) |
| 775 |
return ("**%s** %s and may be repeated zero or more" |
| 776 |
" times) -- %s")%(self.name_, contains, self.description_) |
| 777 |
|
| 778 |
|
| 779 |
__all__ = ["ListOfAtomsAttribute", "DictAttribute", "StructAttribute", |
| 780 |
"MultiStructAttribute", "StructListAttribute", "MultiStructListAttribute", |
| 781 |
"UniquedStructListAttribute", "SetOfAtomsAttribute", "PropertyAttribute"] |