Helper for formatting strings. These format sequences are supported in fmt: %s: arbitrary object converted to string using str() %r: name of IR value/register %d: int %f: float %l: BasicBlock (formatted as label 'Ln') %t: RType
(self, fmt: str, *args: Any)
| 316 | # Helpers |
| 317 | |
| 318 | def format(self, fmt: str, *args: Any) -> str: |
| 319 | """Helper for formatting strings. |
| 320 | |
| 321 | These format sequences are supported in fmt: |
| 322 | |
| 323 | %s: arbitrary object converted to string using str() |
| 324 | %r: name of IR value/register |
| 325 | %d: int |
| 326 | %f: float |
| 327 | %l: BasicBlock (formatted as label 'Ln') |
| 328 | %t: RType |
| 329 | """ |
| 330 | result = [] |
| 331 | i = 0 |
| 332 | arglist = list(args) |
| 333 | while i < len(fmt): |
| 334 | n = fmt.find("%", i) |
| 335 | if n < 0: |
| 336 | n = len(fmt) |
| 337 | result.append(fmt[i:n]) |
| 338 | if n < len(fmt): |
| 339 | typespec = fmt[n + 1] |
| 340 | arg = arglist.pop(0) |
| 341 | if typespec == "r": |
| 342 | # Register/value |
| 343 | assert isinstance(arg, Value) |
| 344 | if isinstance(arg, Integer): |
| 345 | result.append(str(arg.value)) |
| 346 | elif isinstance(arg, Float): |
| 347 | result.append(repr(arg.value)) |
| 348 | elif isinstance(arg, CString): |
| 349 | result.append(f"CString({arg.value!r})") |
| 350 | elif isinstance(arg, Undef): |
| 351 | result.append(f"undef {arg.type.name}") |
| 352 | else: |
| 353 | result.append(self.names[arg]) |
| 354 | elif typespec == "d": |
| 355 | # Integer |
| 356 | result.append("%d" % arg) |
| 357 | elif typespec == "f": |
| 358 | # Float |
| 359 | result.append("%f" % arg) |
| 360 | elif typespec == "l": |
| 361 | # Basic block (label) |
| 362 | assert isinstance(arg, BasicBlock) |
| 363 | result.append("L%s" % arg.label) |
| 364 | elif typespec == "t": |
| 365 | # RType |
| 366 | assert isinstance(arg, RType) |
| 367 | result.append(arg.name) |
| 368 | elif typespec == "s": |
| 369 | # String |
| 370 | result.append(str(arg)) |
| 371 | else: |
| 372 | raise ValueError(f"Invalid format sequence %{typespec}") |
| 373 | i = n + 2 |
| 374 | else: |
| 375 | i = n |
no test coverage detected