|
| 1 | +from typing import Optional, TypeVar, Union |
| 2 | + |
| 3 | +from typing_extensions import Unpack |
| 4 | + |
| 5 | +from basilisp.lang.interfaces import ILispObject, ILookup |
| 6 | +from basilisp.lang.keyword import keyword |
| 7 | +from basilisp.lang.obj import PrintSettings, lrepr |
| 8 | +from basilisp.lang.symbol import Symbol |
| 9 | + |
| 10 | +K = TypeVar("K") |
| 11 | +V = TypeVar("V") |
| 12 | +T = Union[None, V, Symbol] |
| 13 | + |
| 14 | +_TAG_KW = keyword("tag") |
| 15 | +_FORM_KW = keyword("form") |
| 16 | + |
| 17 | + |
| 18 | +class TaggedLiteral( |
| 19 | + ILispObject, |
| 20 | + ILookup[K, T], |
| 21 | +): |
| 22 | + """Basilisp TaggedLiteral. https://clojure.org/reference/reader#tagged_literals""" |
| 23 | + |
| 24 | + __slots__ = ("_tag", "_form", "_hash") |
| 25 | + |
| 26 | + def __init__(self, tag: Symbol, form) -> None: |
| 27 | + self._tag = tag |
| 28 | + self._form = form |
| 29 | + self._hash: Optional[int] = None |
| 30 | + |
| 31 | + @property |
| 32 | + def tag(self) -> Symbol: |
| 33 | + return self._tag |
| 34 | + |
| 35 | + @property |
| 36 | + def form(self): |
| 37 | + return self._form |
| 38 | + |
| 39 | + def __bool__(self): |
| 40 | + return True |
| 41 | + |
| 42 | + def __eq__(self, other): |
| 43 | + if self is other: |
| 44 | + return True |
| 45 | + if not isinstance(other, TaggedLiteral): |
| 46 | + return NotImplemented |
| 47 | + return self._tag == other._tag and self._form == other._form |
| 48 | + |
| 49 | + def __hash__(self): |
| 50 | + if self._hash is None: |
| 51 | + self._hash = hash((self._tag, self._form)) |
| 52 | + return self._hash |
| 53 | + |
| 54 | + def __getitem__(self, item): |
| 55 | + return self.val_at(item) |
| 56 | + |
| 57 | + def val_at(self, k: K, default: Optional[V] = None) -> T: |
| 58 | + if k == _TAG_KW: |
| 59 | + return self._tag |
| 60 | + elif k == _FORM_KW: |
| 61 | + return self._form |
| 62 | + else: |
| 63 | + return default |
| 64 | + |
| 65 | + def _lrepr(self, **kwargs: Unpack[PrintSettings]) -> str: |
| 66 | + return f"#{self._tag} {lrepr(self._form, **kwargs)}" |
| 67 | + |
| 68 | + |
| 69 | +def tagged_literal(tag: Symbol, form): |
| 70 | + """Construct a data representation of a tagged literal from a |
| 71 | + tag symbol and a form.""" |
| 72 | + if not isinstance(tag, Symbol): |
| 73 | + raise TypeError(f"tag must be a Symbol, not '{type(tag)}'") |
| 74 | + return TaggedLiteral(tag, form) |
0 commit comments