Skip to content

Instantly share code, notes, and snippets.

@jevinskie
Created April 9, 2025 19:31
Show Gist options
  • Save jevinskie/30717932f0c6bdf6f4f7094fee7e92c2 to your computer and use it in GitHub Desktop.
Save jevinskie/30717932f0c6bdf6f4f7094fee7e92c2 to your computer and use it in GitHub Desktop.
Python StringList for @= line concatenation
from collections.abc import Sequence
from typing import cast, Self
import attrs
@attrs.define
class StringList:
_lines: list[str] = attrs.Factory(list)
@property
def lines(self) -> list[str]:
return self._lines
def __matmul__(self, other) -> Self:
if isinstance(other, str):
return type(self)(self._lines + [other])
elif isinstance(other, Sequence):
ol = cast(list[str], other)
return type(self)(self._lines + ol)
else:
raise TypeError(
f"Unsupported operand type for @: 'StringList' and '{type(other).__name__}'"
)
def __str__(self) -> str:
return "\n".join(self._lines)
def generate_espresso(einf: dict[str, tuple[int, int]]) -> str:
el = StringList()
el @= ".i 32"
el @= ".o 1"
el @= ".ilb " + " ".join([f"I{i}" for i in reversed(range(32))])
el @= ".olb V"
for i, kv in enumerate(einf.items()):
bmi, bpi = kv[1]
bits = ""
for j in reversed(range(32)):
sb = 1 << j
if bmi & sb:
if bpi & sb:
bits += "1"
else:
bits += "0"
else:
bits += "-"
bits += " 1"
el @= bits
el @= ".e"
el @= ""
return str(el)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment