| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
""" |
| 6 |
EI protocol parser |
| 7 |
|
| 8 |
This parser is intended to be generically useful for language bindings |
| 9 |
other than libei/libeis. If it isn't, please file a bug. |
| 10 |
|
| 11 |
When used as ei-scanner, it converts a Jinja2 template with the |
| 12 |
scanned protocol. Otherwise, use the `parse()` function to |
| 13 |
parse the protocol and return its structure as a set of Python |
| 14 |
classes. |
| 15 |
|
| 16 |
Opcodes for events and request are assigned in order as they |
| 17 |
appear in the XML file. |
| 18 |
""" |
| 19 |
|
| 20 |
from typing import Any, Dict, List, Optional, Tuple, Union |
| 21 |
from pathlib import Path |
| 22 |
from textwrap import dedent |
| 23 |
from dataclasses import dataclass, field |
| 24 |
|
| 25 |
import argparse |
| 26 |
import jinja2 |
| 27 |
import jinja2.environment |
| 28 |
import os |
| 29 |
import sys |
| 30 |
import xml.sax |
| 31 |
import xml.sax.handler |
| 32 |
|
| 33 |
""" |
| 34 |
Mapping of allowed protocol types to the single-character signature strings |
| 35 |
used in the various code pieces. |
| 36 |
""" |
| 37 |
PROTOCOL_TYPES = { |
| 38 |
"uint32": "u", |
| 39 |
"int32": "i", |
| 40 |
"uint64": "t", |
| 41 |
"int64": "x", |
| 42 |
"float": "f", |
| 43 |
"fd": "h", |
| 44 |
"new_id": "n", |
| 45 |
"object": "o", |
| 46 |
"string": "s", |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
def snake2camel(s: str) -> str: |
| 51 |
""" |
| 52 |
Convert snake_case to CamelCase (well, strictly speaking |
| 53 |
PascalCase |
| 54 |
""" |
| 55 |
return s.replace("_", " ").title().replace(" ", "") |
| 56 |
|
| 57 |
|
| 58 |
@dataclass |
| 59 |
class Description: |
| 60 |
summary: str = "" |
| 61 |
text: str = "" |
| 62 |
|
| 63 |
|
| 64 |
@dataclass |
| 65 |
class Argument: |
| 66 |
""" |
| 67 |
Argument to a request or a reply |
| 68 |
""" |
| 69 |
|
| 70 |
name: str |
| 71 |
protocol_type: str |
| 72 |
summary: str |
| 73 |
enum: Optional["Enum"] |
| 74 |
interface: Optional["Interface"] |
| 75 |
interface_arg: Optional["Argument"] = None |
| 76 |
""" |
| 77 |
For an argument with "interface_arg", this field points to the argument that |
| 78 |
contains the interface name. |
| 79 |
""" |
| 80 |
interface_arg_for: Optional["Argument"] = None |
| 81 |
""" |
| 82 |
For an argument referenced by another argument through "interface_name", this field |
| 83 |
points to the other argument that references this argument. |
| 84 |
""" |
| 85 |
version_arg: Optional["Argument"] = None |
| 86 |
""" |
| 87 |
For an argument with type "new_id", this field points to the argument that |
| 88 |
contains the version for this new object. |
| 89 |
""" |
| 90 |
version_arg_for: Optional["Argument"] = None |
| 91 |
""" |
| 92 |
For an argument referenced by another argument of type "new_id", this field |
| 93 |
points to the other argument that references this argument. |
| 94 |
""" |
| 95 |
allow_null: bool = False |
| 96 |
""" |
| 97 |
For an argument of type string, specify if the argument may be NULL. |
| 98 |
""" |
| 99 |
|
| 100 |
def __post_init(self): |
| 101 |
if self.protocol_type is None or self.protocol_type not in PROTOCOL_TYPES: |
| 102 |
raise ValueError(f"Failed to parse protocol_type {self.protocol_type}") |
| 103 |
if self.interface is not None and self.signature not in ["n", "o"]: |
| 104 |
raise ValueError("Interface may only be set for object types") |
| 105 |
|
| 106 |
@property |
| 107 |
def signature(self) -> str: |
| 108 |
""" |
| 109 |
The single-character signature for this argument |
| 110 |
""" |
| 111 |
return PROTOCOL_TYPES[self.protocol_type] |
| 112 |
|
| 113 |
@property |
| 114 |
def as_c_arg(self) -> str: |
| 115 |
return f"{self.c_type} {self.name}" |
| 116 |
|
| 117 |
@property |
| 118 |
def c_type(self) -> str: |
| 119 |
return { |
| 120 |
"uint32": "uint32_t", |
| 121 |
"int32": "int32_t", |
| 122 |
"uint64": "uint64_t", |
| 123 |
"int64": "int64_t", |
| 124 |
"string": "const char *", |
| 125 |
"fd": "int", |
| 126 |
"float": "float", |
| 127 |
"object": "object_id_t", |
| 128 |
"new_id": "new_id_t", |
| 129 |
}[self.protocol_type] |
| 130 |
|
| 131 |
@classmethod |
| 132 |
def create( |
| 133 |
cls, |
| 134 |
name: str, |
| 135 |
protocol_type: str, |
| 136 |
summary: str = "", |
| 137 |
enum: Optional["Enum"] = None, |
| 138 |
interface: Optional["Interface"] = None, |
| 139 |
allow_null: bool = False, |
| 140 |
) -> "Argument": |
| 141 |
return cls( |
| 142 |
name=name, |
| 143 |
protocol_type=protocol_type, |
| 144 |
summary=summary, |
| 145 |
enum=enum, |
| 146 |
interface=interface, |
| 147 |
allow_null=allow_null, |
| 148 |
) |
| 149 |
|
| 150 |
|
| 151 |
@dataclass |
| 152 |
class Message: |
| 153 |
""" |
| 154 |
Parent class for a wire message (Request or Event). |
| 155 |
""" |
| 156 |
|
| 157 |
name: str |
| 158 |
since: int |
| 159 |
opcode: int |
| 160 |
interface: "Interface" |
| 161 |
description: Optional[Description] = None |
| 162 |
is_destructor: bool = False |
| 163 |
context_type: Optional[str] = None |
| 164 |
|
| 165 |
arguments: List[Argument] = field(init=False, default_factory=list) |
| 166 |
|
| 167 |
def __post_init(self): |
| 168 |
if self.context_type not in [None, "sender", "receiver"]: |
| 169 |
raise ValueError(f"Invalid context type {self.context_type}") |
| 170 |
|
| 171 |
def add_argument(self, arg: Argument) -> None: |
| 172 |
if arg.name in [a.name for a in self.arguments]: |
| 173 |
raise ValueError(f"Duplicate argument name '{arg.name}'") |
| 174 |
self.arguments.append(arg) |
| 175 |
|
| 176 |
@property |
| 177 |
def num_arguments(self) -> int: |
| 178 |
return len(self.arguments) |
| 179 |
|
| 180 |
@property |
| 181 |
def signature(self) -> str: |
| 182 |
return "".join([a.signature for a in self.arguments]) |
| 183 |
|
| 184 |
@property |
| 185 |
def camel_name(self) -> str: |
| 186 |
return snake2camel(self.name) |
| 187 |
|
| 188 |
def find_argument(self, name: str) -> Optional[Argument]: |
| 189 |
for a in self.arguments: |
| 190 |
if a.name == name: |
| 191 |
return a |
| 192 |
return None |
| 193 |
|
| 194 |
|
| 195 |
@dataclass |
| 196 |
class Request(Message): |
| 197 |
@classmethod |
| 198 |
def create( |
| 199 |
cls, |
| 200 |
name: str, |
| 201 |
opcode: int, |
| 202 |
interface: "Interface", |
| 203 |
since: int = 1, |
| 204 |
is_destructor: bool = False, |
| 205 |
) -> "Request": |
| 206 |
return cls( |
| 207 |
name=name, |
| 208 |
opcode=opcode, |
| 209 |
since=since, |
| 210 |
interface=interface, |
| 211 |
is_destructor=is_destructor, |
| 212 |
) |
| 213 |
|
| 214 |
@property |
| 215 |
def fqdn(self) -> str: |
| 216 |
""" |
| 217 |
The full name of this Request as <interface name>_request_<request name> |
| 218 |
""" |
| 219 |
return f"{self.interface.name}_request_{self.name}" |
| 220 |
|
| 221 |
|
| 222 |
@dataclass |
| 223 |
class Event(Message): |
| 224 |
@classmethod |
| 225 |
def create( |
| 226 |
cls, |
| 227 |
name: str, |
| 228 |
opcode: int, |
| 229 |
interface: "Interface", |
| 230 |
since: int = 1, |
| 231 |
is_destructor: bool = False, |
| 232 |
) -> "Event": |
| 233 |
return cls( |
| 234 |
name=name, |
| 235 |
opcode=opcode, |
| 236 |
since=since, |
| 237 |
interface=interface, |
| 238 |
is_destructor=is_destructor, |
| 239 |
) |
| 240 |
|
| 241 |
@property |
| 242 |
def fqdn(self) -> str: |
| 243 |
""" |
| 244 |
The full name of this Event as <interface name>_event_<request name> |
| 245 |
""" |
| 246 |
return f"{self.interface.name}_event_{self.name}" |
| 247 |
|
| 248 |
|
| 249 |
@dataclass |
| 250 |
class Entry: |
| 251 |
""" |
| 252 |
An enum entry |
| 253 |
""" |
| 254 |
|
| 255 |
name: str |
| 256 |
value: int |
| 257 |
enum: "Enum" |
| 258 |
summary: str |
| 259 |
since: int |
| 260 |
|
| 261 |
@classmethod |
| 262 |
def create( |
| 263 |
cls, name: str, value: int, enum: "Enum", summary: str = "", since: int = 1 |
| 264 |
) -> "Entry": |
| 265 |
return cls(name=name, value=value, enum=enum, summary=summary, since=since) |
| 266 |
|
| 267 |
@property |
| 268 |
def fqdn(self) -> str: |
| 269 |
""" |
| 270 |
The full name of this Entry as <interface name>_<enum name>_<entry name> |
| 271 |
""" |
| 272 |
return f"{self.enum.fqdn}_{self.name}" |
| 273 |
|
| 274 |
|
| 275 |
@dataclass |
| 276 |
class Enum: |
| 277 |
name: str |
| 278 |
since: int |
| 279 |
interface: "Interface" |
| 280 |
is_bitfield: bool = False |
| 281 |
description: Optional[Description] = None |
| 282 |
|
| 283 |
entries: List[Entry] = field(init=False, default_factory=list) |
| 284 |
|
| 285 |
@classmethod |
| 286 |
def create( |
| 287 |
cls, |
| 288 |
name: str, |
| 289 |
interface: "Interface", |
| 290 |
since: int = 1, |
| 291 |
is_bitfield: bool = False, |
| 292 |
) -> "Enum": |
| 293 |
return cls(name=name, since=since, interface=interface, is_bitfield=is_bitfield) |
| 294 |
|
| 295 |
def add_entry(self, entry: Entry) -> None: |
| 296 |
for e in self.entries: |
| 297 |
if e.name == entry.name: |
| 298 |
raise ValueError(f"Duplicate enum name '{entry.name}'") |
| 299 |
|
| 300 |
if e.value == entry.value: |
| 301 |
raise ValueError(f"Duplicate enum value '{entry.value}'") |
| 302 |
|
| 303 |
if self.is_bitfield: |
| 304 |
if e.value < 0: |
| 305 |
raise ValueError("Bitmasks must not be less than zero") |
| 306 |
try: |
| 307 |
if e.value.bit_count() > 1: |
| 308 |
raise ValueError("Bitmasks must have exactly one bit set") |
| 309 |
except AttributeError: |
| 310 |
pass |
| 311 |
|
| 312 |
self.entries.append(entry) |
| 313 |
|
| 314 |
@property |
| 315 |
def fqdn(self): |
| 316 |
""" |
| 317 |
The full name of this Enum as <interface name>_<enum name> |
| 318 |
""" |
| 319 |
return f"{self.interface.name}_{self.name}" |
| 320 |
|
| 321 |
@property |
| 322 |
def camel_name(self) -> str: |
| 323 |
return snake2camel(self.name) |
| 324 |
|
| 325 |
|
| 326 |
@dataclass |
| 327 |
class Interface: |
| 328 |
protocol_name: str |
| 329 |
version: int |
| 330 |
requests: List[Request] = field(init=False, default_factory=list) |
| 331 |
events: List[Event] = field(init=False, default_factory=list) |
| 332 |
enums: List[Enum] = field(init=False, default_factory=list) |
| 333 |
|
| 334 |
mode: str |
| 335 |
description: Optional[Description] = None |
| 336 |
|
| 337 |
def __post_init(self): |
| 338 |
if self.mode not in ["ei", "eis", "brei"]: |
| 339 |
raise ValueError(f"Invalid mode {self.mode}") |
| 340 |
|
| 341 |
@property |
| 342 |
def name(self) -> str: |
| 343 |
""" |
| 344 |
Returns the mode-adjusted name of the interface, i.e. this may return |
| 345 |
"ei_pointer", "eis_pointer", "brei_pointer", etc. depending on the |
| 346 |
mode. |
| 347 |
""" |
| 348 |
return Interface.mangle_name(self.protocol_name, self.mode) |
| 349 |
|
| 350 |
@property |
| 351 |
def plainname(self) -> str: |
| 352 |
""" |
| 353 |
Returns the plain name of the interface, i.e. this returns |
| 354 |
"pointer", "handshake", etc. without the "ei_" or "eis_" prefix. |
| 355 |
""" |
| 356 |
if self.protocol_name.startswith("ei_"): |
| 357 |
return f"{self.protocol_name[3:]}" |
| 358 |
return self.protocol_name |
| 359 |
|
| 360 |
@staticmethod |
| 361 |
def mangle_name(name: str, component: str) -> str: |
| 362 |
""" |
| 363 |
Returns the mangled interface name with the component as prefix (e.g. eis_device). |
| 364 |
The XML only uses `ei_` as prefix, so let's replace that accordingly. |
| 365 |
""" |
| 366 |
if name.startswith("ei"): |
| 367 |
return f"{component}{name[2:]}" |
| 368 |
return name |
| 369 |
|
| 370 |
def add_request(self, request: Request) -> None: |
| 371 |
if request.name in [r.name for r in self.requests]: |
| 372 |
raise ValueError(f"Duplicate request name '{request.name}'") |
| 373 |
self.requests.append(request) |
| 374 |
|
| 375 |
def add_event(self, event: Event) -> None: |
| 376 |
if event.name in [r.name for r in self.events]: |
| 377 |
raise ValueError(f"Duplicate event name '{event.name}'") |
| 378 |
self.events.append(event) |
| 379 |
|
| 380 |
def add_enum(self, enum: Enum) -> None: |
| 381 |
if enum.name in [r.name for r in self.enums]: |
| 382 |
raise ValueError(f"Duplicate enum name '{enum.name}'") |
| 383 |
self.enums.append(enum) |
| 384 |
|
| 385 |
def find_enum(self, name: str) -> Optional[Enum]: |
| 386 |
for e in self.enums: |
| 387 |
if e.name == name: |
| 388 |
return e |
| 389 |
return None |
| 390 |
|
| 391 |
@property |
| 392 |
def outgoing(self) -> List[Message]: |
| 393 |
""" |
| 394 |
Returns the list of messages outgoing from this implementation. |
| 395 |
|
| 396 |
We use the same class for both ei and eis. To make the |
| 397 |
template simpler, the class maps requests/events to |
| 398 |
incoming/outgoing as correct relative to the implementation. |
| 399 |
""" |
| 400 |
if self.mode == "ei": |
| 401 |
return self.requests |
| 402 |
elif self.mode == "eis": |
| 403 |
return self.events |
| 404 |
else: |
| 405 |
raise NotImplementedError( |
| 406 |
f"Interface.outgoing is not supported for mode {self.mode}" |
| 407 |
) |
| 408 |
|
| 409 |
@property |
| 410 |
def incoming(self) -> List[Message]: |
| 411 |
""" |
| 412 |
Returns the list of messages incoming to this implementation. |
| 413 |
|
| 414 |
We use the same class for both ei and eis. To make the |
| 415 |
template simpler, the class maps requests/events to |
| 416 |
incoming/outgoing as correct relative to the implementation. |
| 417 |
""" |
| 418 |
if self.mode == "ei": |
| 419 |
return self.events |
| 420 |
elif self.mode == "eis": |
| 421 |
return self.requests |
| 422 |
else: |
| 423 |
raise NotImplementedError( |
| 424 |
f"Interface.incoming is not supported for mode {self.mode}" |
| 425 |
) |
| 426 |
|
| 427 |
@property |
| 428 |
def c_type(self) -> str: |
| 429 |
return f"struct {self.name} *" |
| 430 |
|
| 431 |
@property |
| 432 |
def as_c_arg(self) -> str: |
| 433 |
return f"{self.c_type} {self.name}" |
| 434 |
|
| 435 |
@property |
| 436 |
def camel_name(self) -> str: |
| 437 |
return snake2camel(self.name) |
| 438 |
|
| 439 |
@classmethod |
| 440 |
def create(cls, protocol_name: str, version: int, mode: str = "ei") -> "Interface": |
| 441 |
assert mode in ["ei", "eis", "brei"] |
| 442 |
return cls(protocol_name=protocol_name, version=version, mode=mode) |
| 443 |
|
| 444 |
|
| 445 |
@dataclass |
| 446 |
class XmlError(Exception): |
| 447 |
line: int |
| 448 |
column: int |
| 449 |
message: str |
| 450 |
|
| 451 |
def __str__(self) -> str: |
| 452 |
return f"line {self.line}:{self.column}: {self.message}" |
| 453 |
|
| 454 |
@classmethod |
| 455 |
def create(cls, message: str, location: Tuple[int, int] = (0, 0)) -> "XmlError": |
| 456 |
return cls(line=location[0], column=location[1], message=message) |
| 457 |
|
| 458 |
|
| 459 |
@dataclass |
| 460 |
class Copyright: |
| 461 |
text: str = "" |
| 462 |
is_complete: bool = field(init=False, default=False) |
| 463 |
|
| 464 |
|
| 465 |
@dataclass |
| 466 |
class Protocol: |
| 467 |
copyright: Optional[str] = None |
| 468 |
interfaces: List[Interface] = field(default_factory=list) |
| 469 |
|
| 470 |
|
| 471 |
@dataclass |
| 472 |
class ProtocolParser(xml.sax.handler.ContentHandler): |
| 473 |
component: str |
| 474 |
interfaces: List[Interface] = field(default_factory=list) |
| 475 |
copyright: Optional[Copyright] = field(init=False, default=None) |
| 476 |
|
| 477 |
current_interface: Optional[Interface] = field(init=False, default=None) |
| 478 |
current_message: Optional[Union[Message, Enum]] = field(init=False, default=None) |
| 479 |
current_description: Optional[Description] = field(init=False, default=None) |
| 480 |
|
| 481 |
current_interface_arg_names: Dict[str, str] = field( |
| 482 |
init=False, default_factory=dict |
| 483 |
) |
| 484 |
current_new_id_arg: Optional[Argument] = field(init=False, default=None) |
| 485 |
|
| 486 |
_run_counter: int = field(init=False, default=0, repr=False) |
| 487 |
|
| 488 |
@property |
| 489 |
def location(self) -> Tuple[int, int]: |
| 490 |
line = self._locator.getLineNumber() |
| 491 |
col = self._locator.getColumnNumber() |
| 492 |
return line, col |
| 493 |
|
| 494 |
def interface_by_name(self, protocol_name: str) -> Interface: |
| 495 |
""" |
| 496 |
Look up an interface by its protocol name (i.e. always "ei_foo", regardless of |
| 497 |
what we're generating). |
| 498 |
""" |
| 499 |
try: |
| 500 |
return [ |
| 501 |
iface |
| 502 |
for iface in self.interfaces |
| 503 |
if iface.protocol_name == protocol_name |
| 504 |
].pop() |
| 505 |
except IndexError: |
| 506 |
raise XmlError.create( |
| 507 |
f"Unable to find interface {protocol_name}", self.location |
| 508 |
) |
| 509 |
|
| 510 |
def startDocument(self): |
| 511 |
self._run_counter += 1 |
| 512 |
|
| 513 |
def startElement(self, element: str, attrs: dict): |
| 514 |
if element == "interface": |
| 515 |
if self.current_interface is not None: |
| 516 |
raise XmlError.create( |
| 517 |
f"Invalid element '{element}' inside interface '{self.current_interface.name}'", |
| 518 |
self.location, |
| 519 |
) |
| 520 |
|
| 521 |
try: |
| 522 |
name = attrs["name"] |
| 523 |
version = int(attrs["version"]) |
| 524 |
except KeyError as e: |
| 525 |
raise XmlError.create( |
| 526 |
f"Missing attribute {e} in element '{element}'", |
| 527 |
self.location, |
| 528 |
) |
| 529 |
|
| 530 |
protocol_name = name |
| 531 |
|
| 532 |
|
| 533 |
if self._run_counter > 1: |
| 534 |
intf = self.interface_by_name(protocol_name) |
| 535 |
else: |
| 536 |
intf = Interface.create( |
| 537 |
protocol_name=protocol_name, |
| 538 |
version=version, |
| 539 |
mode=self.component, |
| 540 |
) |
| 541 |
self.interfaces.append(intf) |
| 542 |
|
| 543 |
self.current_interface = intf |
| 544 |
|
| 545 |
|
| 546 |
if self._run_counter <= 1: |
| 547 |
return |
| 548 |
|
| 549 |
if element == "enum": |
| 550 |
if self.current_interface is None: |
| 551 |
raise XmlError.create( |
| 552 |
f"Invalid element '{element}' outside an <interface>", |
| 553 |
self.location, |
| 554 |
) |
| 555 |
if self.current_message is not None: |
| 556 |
raise XmlError.create( |
| 557 |
f"Invalid element '{element}' inside '{self.current_message.name}'", |
| 558 |
self.location, |
| 559 |
) |
| 560 |
try: |
| 561 |
name = attrs["name"] |
| 562 |
since = int(attrs["since"]) |
| 563 |
except KeyError as e: |
| 564 |
raise XmlError.create( |
| 565 |
f"Missing attribute {e} in element '{element}'", |
| 566 |
self.location, |
| 567 |
) |
| 568 |
if since > self.current_interface.version: |
| 569 |
raise XmlError.create( |
| 570 |
f"Invalid 'since' {since} for '{self.current_interface.name}.{name}'", |
| 571 |
self.location, |
| 572 |
) |
| 573 |
|
| 574 |
try: |
| 575 |
is_bitfield = { |
| 576 |
"true": True, |
| 577 |
"false": False, |
| 578 |
}[attrs.get("bitfield", "false")] |
| 579 |
except KeyError as e: |
| 580 |
raise XmlError.create( |
| 581 |
f"Invalid value {e} for boolean bitfield attribute in '{element}'", |
| 582 |
self.location, |
| 583 |
) |
| 584 |
|
| 585 |
|
| 586 |
|
| 587 |
if self._run_counter > 2: |
| 588 |
enum = self.current_interface.find_enum(name) |
| 589 |
if enum is None: |
| 590 |
raise XmlError.create( |
| 591 |
f"Invalid enum {name}. This is a parser bug", |
| 592 |
self.location, |
| 593 |
) |
| 594 |
else: |
| 595 |
enum = Enum.create( |
| 596 |
name=name, |
| 597 |
since=since, |
| 598 |
interface=self.current_interface, |
| 599 |
is_bitfield=is_bitfield, |
| 600 |
) |
| 601 |
try: |
| 602 |
self.current_interface.add_enum(enum) |
| 603 |
except ValueError as e: |
| 604 |
raise XmlError.create(str(e), self.location) |
| 605 |
self.current_message = enum |
| 606 |
|
| 607 |
|
| 608 |
if self._run_counter <= 2: |
| 609 |
return |
| 610 |
|
| 611 |
if element == "request": |
| 612 |
if self.current_interface is None: |
| 613 |
raise XmlError.create( |
| 614 |
f"Invalid element '{element}' outside an <interface>", |
| 615 |
self.location, |
| 616 |
) |
| 617 |
|
| 618 |
try: |
| 619 |
name = attrs["name"] |
| 620 |
since = int(attrs["since"]) |
| 621 |
except KeyError as e: |
| 622 |
raise XmlError.create( |
| 623 |
f"Missing attribute {e} in element '{element}'", |
| 624 |
self.location, |
| 625 |
) |
| 626 |
if since > self.current_interface.version: |
| 627 |
raise XmlError.create( |
| 628 |
f"Invalid 'since' {since} for '{self.current_interface.name}.{name}'", |
| 629 |
self.location, |
| 630 |
) |
| 631 |
|
| 632 |
is_destructor = attrs.get("type", "") == "destructor" |
| 633 |
opcode = len(self.current_interface.requests) |
| 634 |
request = Request.create( |
| 635 |
name=name, |
| 636 |
since=since, |
| 637 |
opcode=opcode, |
| 638 |
interface=self.current_interface, |
| 639 |
is_destructor=is_destructor, |
| 640 |
) |
| 641 |
request.context_type = attrs.get("context-type") |
| 642 |
try: |
| 643 |
self.current_interface.add_request(request) |
| 644 |
except ValueError as e: |
| 645 |
raise XmlError.create(str(e), self.location) |
| 646 |
self.current_message = request |
| 647 |
elif element == "event": |
| 648 |
if self.current_interface is None: |
| 649 |
raise XmlError.create( |
| 650 |
f"Invalid element '{element}' outside an <interface>", |
| 651 |
self.location, |
| 652 |
) |
| 653 |
if self.current_message is not None: |
| 654 |
raise XmlError.create( |
| 655 |
f"Invalid element '{element}' inside '{self.current_message.name}'", |
| 656 |
self.location, |
| 657 |
) |
| 658 |
try: |
| 659 |
name = attrs["name"] |
| 660 |
since = int(attrs["since"]) |
| 661 |
except KeyError as e: |
| 662 |
raise XmlError.create( |
| 663 |
f"Missing attribute {e} in element '{element}'", |
| 664 |
self.location, |
| 665 |
) |
| 666 |
if since > self.current_interface.version: |
| 667 |
raise XmlError.create( |
| 668 |
f"Invalid 'since' {since} for '{self.current_interface.name}.{name}'", |
| 669 |
self.location, |
| 670 |
) |
| 671 |
|
| 672 |
is_destructor = attrs.get("type", "") == "destructor" |
| 673 |
opcode = len(self.current_interface.events) |
| 674 |
event = Event.create( |
| 675 |
name=name, |
| 676 |
since=since, |
| 677 |
opcode=opcode, |
| 678 |
interface=self.current_interface, |
| 679 |
is_destructor=is_destructor, |
| 680 |
) |
| 681 |
event.context_type = attrs.get("context-type") |
| 682 |
try: |
| 683 |
self.current_interface.add_event(event) |
| 684 |
except ValueError as e: |
| 685 |
raise XmlError.create(str(e), self.location) |
| 686 |
self.current_message = event |
| 687 |
elif element == "arg": |
| 688 |
if self.current_interface is None: |
| 689 |
raise XmlError.create( |
| 690 |
f"Invalid element '{element}' outside an <interface>", |
| 691 |
self.location, |
| 692 |
) |
| 693 |
if not isinstance(self.current_message, Message): |
| 694 |
raise XmlError.create( |
| 695 |
f"Invalid element '{element}' must be inside <request> or <event>", |
| 696 |
self.location, |
| 697 |
) |
| 698 |
name = attrs["name"] |
| 699 |
proto_type = attrs["type"] |
| 700 |
if proto_type not in PROTOCOL_TYPES: |
| 701 |
raise XmlError.create( |
| 702 |
f"Invalid type '{proto_type}' for '{self.current_interface.name}.{self.current_message.name}::{name}'", |
| 703 |
self.location, |
| 704 |
) |
| 705 |
|
| 706 |
summary = attrs.get("summary", "") |
| 707 |
interface_name = attrs.get("interface", None) |
| 708 |
if interface_name is not None: |
| 709 |
interface = self.interface_by_name(interface_name) |
| 710 |
else: |
| 711 |
interface = None |
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
interface_arg_name = attrs.get("interface_arg", None) |
| 716 |
if interface_arg_name is not None: |
| 717 |
self.current_interface_arg_names[name] = interface_arg_name |
| 718 |
|
| 719 |
enum_name = attrs.get("enum", None) |
| 720 |
enum = None |
| 721 |
if enum_name is not None: |
| 722 |
if "." in enum_name: |
| 723 |
iname, enum_name = enum_name.split(".") |
| 724 |
intf = self.interface_by_name(iname) |
| 725 |
else: |
| 726 |
intf = self.current_interface |
| 727 |
|
| 728 |
enum = intf.find_enum(enum_name) |
| 729 |
if enum is None: |
| 730 |
raise XmlError.create( |
| 731 |
f"Failed to find enum '{intf.name}.{enum_name}'", |
| 732 |
self.location, |
| 733 |
) |
| 734 |
|
| 735 |
allow_null = attrs.get("allow-null", "false") == "true" |
| 736 |
arg = Argument.create( |
| 737 |
name=name, |
| 738 |
protocol_type=proto_type, |
| 739 |
summary=summary, |
| 740 |
enum=enum, |
| 741 |
interface=interface, |
| 742 |
allow_null=allow_null, |
| 743 |
) |
| 744 |
self.current_message.add_argument(arg) |
| 745 |
if proto_type == "new_id": |
| 746 |
if self.current_new_id_arg is not None: |
| 747 |
raise XmlError.create( |
| 748 |
f"Multiple args of type '{proto_type}' for '{self.current_interface.name}.{self.current_message.name}'", |
| 749 |
self.location, |
| 750 |
) |
| 751 |
self.current_new_id_arg = arg |
| 752 |
elif element == "entry": |
| 753 |
if self.current_interface is None: |
| 754 |
raise XmlError.create( |
| 755 |
f"Invalid element '{element}' outside an <interface>", |
| 756 |
self.location, |
| 757 |
) |
| 758 |
if not isinstance(self.current_message, Enum): |
| 759 |
raise XmlError.create( |
| 760 |
f"Invalid element '{element}' must be inside <enum>", |
| 761 |
self.location, |
| 762 |
) |
| 763 |
name = attrs["name"] |
| 764 |
value = int(attrs["value"]) |
| 765 |
summary = attrs.get("summary", "") |
| 766 |
since = int(attrs.get("since", 1)) |
| 767 |
entry = Entry.create( |
| 768 |
name=name, |
| 769 |
value=value, |
| 770 |
enum=self.current_message, |
| 771 |
summary=summary, |
| 772 |
since=since, |
| 773 |
) |
| 774 |
try: |
| 775 |
self.current_message.add_entry(entry) |
| 776 |
except ValueError as e: |
| 777 |
raise XmlError.create(str(e), self.location) |
| 778 |
elif element == "description": |
| 779 |
summary = attrs.get("summary", "") |
| 780 |
self.current_description = Description(summary=summary) |
| 781 |
elif element == "copyright": |
| 782 |
if self.copyright is not None: |
| 783 |
raise XmlError.create( |
| 784 |
"Multiple <copyright> tags in file", self.location |
| 785 |
) |
| 786 |
self.copyright = Copyright() |
| 787 |
|
| 788 |
def endElement(self, name): |
| 789 |
if name == "interface": |
| 790 |
assert self.current_interface is not None |
| 791 |
self.current_interface = None |
| 792 |
|
| 793 |
|
| 794 |
if self._run_counter <= 1: |
| 795 |
return |
| 796 |
|
| 797 |
if name == "enum": |
| 798 |
assert isinstance(self.current_message, Enum) |
| 799 |
self.current_message = None |
| 800 |
|
| 801 |
|
| 802 |
if self._run_counter <= 2: |
| 803 |
return |
| 804 |
|
| 805 |
|
| 806 |
if name in ["request", "event"]: |
| 807 |
assert isinstance(self.current_message, Message) |
| 808 |
assert isinstance(self.current_interface, Interface) |
| 809 |
|
| 810 |
|
| 811 |
for obj, iname in self.current_interface_arg_names.items(): |
| 812 |
obj_arg = self.current_message.find_argument(obj) |
| 813 |
iname_arg = self.current_message.find_argument(iname) |
| 814 |
|
| 815 |
assert obj_arg is not None |
| 816 |
assert iname_arg is not None |
| 817 |
|
| 818 |
obj_arg.interface_arg = iname_arg |
| 819 |
iname_arg.interface_arg_for = obj_arg |
| 820 |
self.current_interface_arg_names = {} |
| 821 |
|
| 822 |
if self.current_new_id_arg is not None: |
| 823 |
arg = self.current_new_id_arg |
| 824 |
version_arg = self.current_message.find_argument("version") |
| 825 |
if version_arg is None: |
| 826 |
|
| 827 |
if ( |
| 828 |
f"{self.current_interface.plainname}.{self.current_message.name}" |
| 829 |
!= "connection.sync" |
| 830 |
): |
| 831 |
raise XmlError.create( |
| 832 |
f"Unable to find a version argument for {self.current_interface.plainname}.{self.current_message.name}::{arg.name}", |
| 833 |
self.location, |
| 834 |
) |
| 835 |
else: |
| 836 |
arg.version_arg = version_arg |
| 837 |
version_arg.version_arg_for = arg |
| 838 |
self.current_new_id_arg = None |
| 839 |
if name == "request": |
| 840 |
assert isinstance(self.current_message, Request) |
| 841 |
self.current_message = None |
| 842 |
elif name == "event": |
| 843 |
assert isinstance(self.current_message, Event) |
| 844 |
self.current_message = None |
| 845 |
elif name == "description": |
| 846 |
assert self.current_description is not None |
| 847 |
self.current_description.text = dedent(self.current_description.text) |
| 848 |
if self.current_message is None: |
| 849 |
assert self.current_interface is not None |
| 850 |
self.current_interface.description = self.current_description |
| 851 |
else: |
| 852 |
self.current_message.description = self.current_description |
| 853 |
self.current_description = None |
| 854 |
elif name == "copyright": |
| 855 |
assert self.copyright is not None |
| 856 |
self.copyright.text = dedent(self.copyright.text) |
| 857 |
self.copyright.is_complete = True |
| 858 |
|
| 859 |
def characters(self, content): |
| 860 |
if self.current_description is not None: |
| 861 |
self.current_description.text += content |
| 862 |
elif self.copyright is not None and not self.copyright.is_complete: |
| 863 |
self.copyright.text += content |
| 864 |
|
| 865 |
@classmethod |
| 866 |
def create(cls, component: str) -> "ProtocolParser": |
| 867 |
h = cls(component=component) |
| 868 |
return h |
| 869 |
|
| 870 |
|
| 871 |
def parse(protofile: Path, component: str) -> Protocol: |
| 872 |
proto = ProtocolParser.create(component=component) |
| 873 |
xml.sax.parse(os.fspath(protofile), proto) |
| 874 |
|
| 875 |
xml.sax.parse(os.fspath(protofile), proto) |
| 876 |
xml.sax.parse(os.fspath(protofile), proto) |
| 877 |
copyright = proto.copyright.text if proto.copyright else None |
| 878 |
return Protocol( |
| 879 |
copyright=copyright, |
| 880 |
interfaces=proto.interfaces, |
| 881 |
) |
| 882 |
|
| 883 |
|
| 884 |
def generate_source( |
| 885 |
proto: Protocol, template: str, component: str, extra_data: Optional[dict] |
| 886 |
) -> jinja2.environment.TemplateStream: |
| 887 |
assert component in ["ei", "eis", "brei"] |
| 888 |
|
| 889 |
data: dict[str, Any] = {} |
| 890 |
data["component"] = component |
| 891 |
data["interfaces"] = proto.interfaces |
| 892 |
data["extra"] = extra_data |
| 893 |
|
| 894 |
loader: jinja2.BaseLoader |
| 895 |
if template == "-": |
| 896 |
loader = jinja2.FunctionLoader(lambda _: sys.stdin.read()) |
| 897 |
filename = "<stdin>" |
| 898 |
else: |
| 899 |
path = Path(template) |
| 900 |
assert path.exists(), f"Failed to find template {path}" |
| 901 |
filename = path.name |
| 902 |
loader = jinja2.FileSystemLoader(os.fspath(path.parent)) |
| 903 |
|
| 904 |
env = jinja2.Environment( |
| 905 |
loader=loader, |
| 906 |
trim_blocks=True, |
| 907 |
lstrip_blocks=True, |
| 908 |
) |
| 909 |
|
| 910 |
|
| 911 |
def filter_c_type(name): |
| 912 |
return f"struct {name} *" |
| 913 |
|
| 914 |
|
| 915 |
def filter_as_c_arg(name): |
| 916 |
return f"struct {name} *{name}" |
| 917 |
|
| 918 |
|
| 919 |
def filter_ei_escape_names(str, quotes="`"): |
| 920 |
if not str: |
| 921 |
return str |
| 922 |
|
| 923 |
import re |
| 924 |
|
| 925 |
return re.sub(rf"({component}[_-]\w*)((\.\w+)*)", rf"{quotes}\1\2{quotes}", str) |
| 926 |
|
| 927 |
env.filters["c_type"] = filter_c_type |
| 928 |
env.filters["as_c_arg"] = filter_as_c_arg |
| 929 |
env.filters["camel"] = snake2camel |
| 930 |
env.filters["ei_escape_names"] = filter_ei_escape_names |
| 931 |
jtemplate = env.get_template(filename) |
| 932 |
return jtemplate.stream(data) |
| 933 |
|
| 934 |
|
| 935 |
def scanner(argv: list[str]) -> None: |
| 936 |
parser = argparse.ArgumentParser( |
| 937 |
description=dedent( |
| 938 |
""" |
| 939 |
ei-scanner is a tool to parse the EI protocol description XML and |
| 940 |
pass the data to a Jinja2 template. That template can then be |
| 941 |
used to generate protocol bindings for the desired language. |
| 942 |
|
| 943 |
typical usages: |
| 944 |
ei-scanner --component=ei protocol.xml my-template.tpl |
| 945 |
ei-scanner --component=eis --output=bindings.rs protocol.xml bindings.rs.tpl |
| 946 |
|
| 947 |
Elements in the XML file are provided as variables with attributes |
| 948 |
generally matching the XML file. For example, each interface has requests, |
| 949 |
events and enums, and each of those has a name. |
| 950 |
|
| 951 |
ei-scanner additionally provides the following values to the Jinja2 templates: |
| 952 |
- interface.incoming and interface.outgoing: maps to the requests/events of |
| 953 |
the interface, depending on the component. |
| 954 |
- argument.signature: a single-character signature type mapping |
| 955 |
from the protocol XML type: |
| 956 |
uint32 -> "u" |
| 957 |
int32 -> "i" |
| 958 |
float -> "f" |
| 959 |
fd -> "h" |
| 960 |
new_id -> "n" |
| 961 |
object -> "o" |
| 962 |
string -> "s" |
| 963 |
|
| 964 |
ei-scanner adds the following Jinja2 filters for convenience: |
| 965 |
{{foo|c_type}} ... resolves to "struct foo *" |
| 966 |
{{foo|as_c_arg}} ... resolves to "struct foo *foo" |
| 967 |
{{foo_bar|camel}} ... resolves to "FooBar" |
| 968 |
|
| 969 |
""" |
| 970 |
), |
| 971 |
formatter_class=argparse.RawDescriptionHelpFormatter, |
| 972 |
) |
| 973 |
|
| 974 |
parser.add_argument( |
| 975 |
"--component", type=str, choices=["ei", "eis", "brei"], default="ei" |
| 976 |
) |
| 977 |
parser.add_argument( |
| 978 |
"--output", type=str, default="-", help="Output file to write to" |
| 979 |
) |
| 980 |
parser.add_argument("protocol", type=Path, help="The protocol XML file") |
| 981 |
parser.add_argument( |
| 982 |
"--jinja-extra-data", |
| 983 |
type=str, |
| 984 |
help="Extra data (in JSON format) to pass through to the Jinja template as 'extra'", |
| 985 |
default=None, |
| 986 |
) |
| 987 |
parser.add_argument( |
| 988 |
"--jinja-extra-data-file", |
| 989 |
type=Path, |
| 990 |
help="Path to file with extra data to pass through to the Jinja template as 'extra'", |
| 991 |
default=None, |
| 992 |
) |
| 993 |
parser.add_argument( |
| 994 |
"template", type=str, help="The Jinja2 compatible template file" |
| 995 |
) |
| 996 |
|
| 997 |
ns = parser.parse_args(argv) |
| 998 |
assert ns.protocol.exists() |
| 999 |
|
| 1000 |
try: |
| 1001 |
proto = parse( |
| 1002 |
protofile=ns.protocol, |
| 1003 |
component=ns.component, |
| 1004 |
) |
| 1005 |
except xml.sax.SAXParseException as e: |
| 1006 |
print(f"Parser error: {e}", file=sys.stderr) |
| 1007 |
raise SystemExit(1) |
| 1008 |
except XmlError as e: |
| 1009 |
print(f"Protocol XML error: {e}", file=sys.stderr) |
| 1010 |
raise SystemExit(1) |
| 1011 |
|
| 1012 |
if ns.jinja_extra_data is not None: |
| 1013 |
import json |
| 1014 |
|
| 1015 |
extra_data = json.loads(ns.jinja_extra_data) |
| 1016 |
elif ns.jinja_extra_data_file is not None: |
| 1017 |
if ns.jinja_extra_data_file.name.endswith( |
| 1018 |
".yml" |
| 1019 |
) or ns.jinja_extra_data_file.name.endswith(".yaml"): |
| 1020 |
import yaml |
| 1021 |
|
| 1022 |
with open(ns.jinja_extra_data_file) as fd: |
| 1023 |
extra_data = yaml.safe_load(fd) |
| 1024 |
elif ns.jinja_extra_data_file.name.endswith(".json"): |
| 1025 |
import json |
| 1026 |
|
| 1027 |
with open(ns.jinja_extra_data_file) as fd: |
| 1028 |
extra_data = json.load(fd) |
| 1029 |
else: |
| 1030 |
print("Unknown file format for jinja data", file=sys.stderr) |
| 1031 |
raise SystemExit(1) |
| 1032 |
else: |
| 1033 |
extra_data = None |
| 1034 |
|
| 1035 |
stream = generate_source( |
| 1036 |
proto=proto, template=ns.template, component=ns.component, extra_data=extra_data |
| 1037 |
) |
| 1038 |
|
| 1039 |
file = sys.stdout if ns.output == "-" else open(ns.output, "w") |
| 1040 |
stream.dump(file) |
| 1041 |
|
| 1042 |
|
| 1043 |
if __name__ == "__main__": |
| 1044 |
scanner(sys.argv[1:]) |