1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
|
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
from fractions import Fraction
from io import StringIO
from typing import Any
import numpy as np
class NotFound:
pass
class Env:
__slots__ = ("data", "outer")
def __init__(self, data: dict[str, Any], outer: Env | None = None) -> None:
self.data = data
self.outer = outer
def __getitem__(self, key: str) -> Any:
if key in self.data:
return self.data[key]
if self.outer is not None:
return self.outer[key]
def __setitem__(self, key: str, val: Any) -> None:
self.data[key] = val
def __delitem__(self, key: str) -> None:
if key in self.data:
del self.data[key]
elif self.outer is not None:
del self.outer[key]
def __contains__(self, key: str) -> bool:
if key in self.data:
return True
if self.outer is not None:
return key in self.outer
return False
def update(self, my_dict: dict[str, Any]) -> None:
self.data.update(my_dict)
def get(self, key: str) -> Any:
if key in self.data:
return self.data[key]
if self.outer is not None:
return self.outer.get(key)
return NotFound()
class Sym:
__slots__ = ("val", "hash", "lineno", "column")
def __init__(self, val: str, lineno: int = -1, column: int = -1):
assert isinstance(val, str)
self.val = val
self.hash = hash(val)
self.lineno = lineno
self.column = column
def __str__(self) -> str:
return self.val
__repr__ = __str__
def __hash__(self) -> int:
return self.hash
def __eq__(self, obj: object) -> bool:
return type(obj) is Sym and self.hash == obj.hash
class Keyword:
__slots__ = "val"
def __init__(self, val: str):
self.val = val
def __str__(self) -> str:
return f"#:{self.val}"
__repr__ = __str__
def __eq__(self, obj: object) -> bool:
return type(obj) is Keyword and self.val == obj.val
class QuotedKeyword:
__slots__ = "val"
def __init__(self, val: Keyword | str):
self.val = val if isinstance(val, Keyword) else Keyword(val)
def __str__(self) -> str:
return f"{self.val}"
__repr__ = __str__
def __eq__(self, obj: object) -> bool:
return type(obj) is QuotedKeyword and self.val == obj.val
class Quoted:
__slots__ = "val"
def __init__(self, val: tuple):
self.val = val
def __len__(self) -> int:
return len(self.val)
def __getitem__(self, key: int | slice) -> Any:
if isinstance(key, slice) or type(self.val[key]) is tuple:
return Quoted(self.val[key])
return self.val[key]
def __iter__(self) -> Iterator:
return self.val.__iter__()
def __contains__(self, item: object) -> bool:
return item in self.val
def __eq__(self, obj: object) -> bool:
return type(obj) is Quoted and self.val == obj.val
class Char:
__slots__ = "val"
def __init__(self, val: str | int):
if type(val) is int:
self.val: str = chr(val)
else:
assert type(val) is str and len(val) == 1
self.val = val
def __str__(self) -> str:
return self.val
def __repr__(self) -> str:
names = {" ": "space", "\n": "newline", "\t": "tab"}
return f"#\\{self.val}" if self.val not in names else f"#\\{names[self.val]}"
def __eq__(self, obj: object) -> bool:
return type(obj) is Char and self.val == obj.val
def __radd__(self, obj2: str) -> str:
return obj2 + self.val
def display_dtype(dtype: np.dtype) -> str:
if dtype.kind == "b":
return "bool"
if dtype.kind == "i":
return f"int{dtype.itemsize * 8}"
if dtype.kind == "u":
return f"uint{dtype.itemsize * 8}"
return f"float{dtype.itemsize * 8}"
def display_str(val: object) -> str:
if val is None:
return "#<void>"
if val is True:
return "#t"
if val is False:
return "#f"
if type(val) is Sym:
return val.val
if type(val) is str:
return val
if type(val) is Char:
return f"{val}"
if type(val) is range:
return "#<range>"
if type(val) is complex:
join = "" if val.imag < 0 else "+"
return f"{val.real}{join}{val.imag}i"
if type(val) is np.bool_:
return "1" if val else "0"
if type(val) is np.float64 or type(val) is np.float32:
return f"{float(val)}"
if type(val) is Fraction:
return f"{val.numerator}/{val.denominator}"
if type(val) is Quoted or type(val) is tuple:
if not val:
return "()"
result = StringIO()
result.write(f"({display_str(val[0])}")
for item in val[1:]:
result.write(f" {display_str(item)}")
result.write(")")
return result.getvalue()
if type(val) is list:
if not val:
return "#()"
result = StringIO()
result.write(f"#({print_str(val[0])}")
for item in val[1:]:
result.write(f" {print_str(item)}")
result.write(")")
return result.getvalue()
if isinstance(val, dict):
result = StringIO()
result.write("#hash(")
is_first = True
for k, v in val.items():
if is_first:
result.write(f"[{print_str(k)} {print_str(v)}]")
is_first = False
else:
result.write(f" [{print_str(k)} {print_str(v)}]")
result.write(")")
return result.getvalue()
if isinstance(val, np.ndarray):
result = StringIO()
result.write(f"(array '{display_dtype(val.dtype)}")
if val.dtype.kind == "b":
for item in val:
result.write(" 1" if item else " 0")
else:
for item in val:
result.write(f" {item}")
result.write(")")
return result.getvalue()
return f"{val!r}"
str_escape = {
"\\": "\\\\",
'"': '\\"',
"\r": "\\r",
"\f": "\\f",
"\v": "\\v",
"\n": "\\n",
"\t": "\\t",
"\b": "\\b",
"\a": "\\a",
}
def print_str(val: object) -> str:
if type(val) is str:
for k, v in str_escape.items():
val = val.replace(k, v)
return f'"{val}"'
if type(val) is Char:
return f"{val!r}"
if type(val) is Keyword:
return f"'{val}"
if type(val) in (Sym, Quoted, QuotedKeyword):
return f"'{display_str(val)}"
return display_str(val)
@dataclass(slots=True)
class PaletClass:
name: str
attrs: tuple
values: list
def __str__(self) -> str:
result = StringIO()
result.write(f"({self.name}")
for i, val in enumerate(self.values):
result.write(f" #:{self.attrs[i * 2]} {print_str(val)}")
result.write(")")
return result.getvalue()
__repr__ = __str__
|