|
| 1 | +import datetime |
| 2 | +import uuid |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from decimal import Decimal |
| 5 | +from fractions import Fraction |
| 6 | +from typing import Union, Any, Pattern, Iterable |
| 7 | + |
| 8 | +from functional import seq |
| 9 | +from pyrsistent import pmap |
| 10 | + |
| 11 | +PrintCountSetting = Union[bool, int, None] |
| 12 | + |
| 13 | +SURPASSED_PRINT_LENGTH = "..." |
| 14 | +SURPASSED_PRINT_LEVEL = "#" |
| 15 | + |
| 16 | +PRINT_DUP = False |
| 17 | +PRINT_LENGTH: PrintCountSetting = 50 |
| 18 | +PRINT_LEVEL: PrintCountSetting = None |
| 19 | +PRINT_META = False |
| 20 | +PRINT_READABLY = True |
| 21 | +PRINT_SEPARATOR = " " |
| 22 | + |
| 23 | + |
| 24 | +def _dec_print_level(lvl: PrintCountSetting): |
| 25 | + """Decrement the print level if it is numeric.""" |
| 26 | + if isinstance(lvl, int): |
| 27 | + return lvl - 1 |
| 28 | + return lvl |
| 29 | + |
| 30 | + |
| 31 | +class LispObject(ABC): |
| 32 | + __slots__ = () |
| 33 | + |
| 34 | + def __repr__(self): |
| 35 | + return self.lrepr() |
| 36 | + |
| 37 | + def __str__(self): |
| 38 | + return self.lrepr(human_readable=True) |
| 39 | + |
| 40 | + @abstractmethod |
| 41 | + def _lrepr(self, **kwargs) -> str: |
| 42 | + """Private Lisp representation method. Callers (including object |
| 43 | + internal callers) should not call this method directly, but instead |
| 44 | + should use the module function .lrepr().""" |
| 45 | + raise NotImplementedError() |
| 46 | + |
| 47 | + def lrepr(self, **kwargs) -> str: |
| 48 | + """Return a string representation of this Lisp object which can be |
| 49 | + read by the reader.""" |
| 50 | + return lrepr(self, **kwargs) |
| 51 | + |
| 52 | + @staticmethod |
| 53 | + def seq_lrepr( |
| 54 | + iterable: Iterable[Any], start: str, end: str, meta=None, **kwargs |
| 55 | + ) -> str: |
| 56 | + """Produce a Lisp representation of a sequential collection, bookended |
| 57 | + with the start and end string supplied. The keyword arguments will be |
| 58 | + passed along to lrepr for the sequence elements.""" |
| 59 | + print_level = kwargs["print_level"] |
| 60 | + if isinstance(print_level, int) and print_level < 1: |
| 61 | + return SURPASSED_PRINT_LEVEL |
| 62 | + |
| 63 | + kwargs = LispObject._process_kwargs(**kwargs) |
| 64 | + |
| 65 | + trailer = [] |
| 66 | + print_dup = kwargs["print_dup"] |
| 67 | + print_length = kwargs["print_length"] |
| 68 | + if not print_dup and isinstance(print_length, int): |
| 69 | + items = seq(iterable).take(print_length + 1).to_list() |
| 70 | + if len(items) > print_length: |
| 71 | + items.pop() |
| 72 | + trailer.append(SURPASSED_PRINT_LENGTH) |
| 73 | + else: |
| 74 | + items = iterable |
| 75 | + |
| 76 | + items = seq(items).map(lambda o: lrepr(o, **kwargs)).to_list() |
| 77 | + seq_lrepr = PRINT_SEPARATOR.join(items + trailer) |
| 78 | + |
| 79 | + print_meta = kwargs["print_meta"] |
| 80 | + if print_meta and meta: |
| 81 | + return f"^{lrepr(meta, **kwargs)} {start}{seq_lrepr}{end}" |
| 82 | + |
| 83 | + return f"{start}{seq_lrepr}{end}" |
| 84 | + |
| 85 | + @staticmethod |
| 86 | + def _process_kwargs(**kwargs): |
| 87 | + """Process keyword arguments, decreasing the print-level. Should be called |
| 88 | + after examining the print level for the current level.""" |
| 89 | + return pmap(initial=kwargs).transform(["print_level"], _dec_print_level) |
| 90 | + |
| 91 | + |
| 92 | +def lrepr( # pylint: disable=too-many-arguments |
| 93 | + o: Any, |
| 94 | + human_readable: bool = False, |
| 95 | + print_dup: bool = PRINT_DUP, |
| 96 | + print_length: PrintCountSetting = PRINT_LENGTH, |
| 97 | + print_level: PrintCountSetting = PRINT_LEVEL, |
| 98 | + print_meta: bool = PRINT_META, |
| 99 | + print_readably: bool = PRINT_READABLY, |
| 100 | +) -> str: |
| 101 | + """Return a string representation of a Lisp object. |
| 102 | +
|
| 103 | + Permissible keyword arguments are: |
| 104 | + - human_readable: if logical True, print strings without quotations or |
| 105 | + escape sequences (default: false) |
| 106 | + - print_dup: if logical true, print objects in a way that preserves their |
| 107 | + types (default: false) |
| 108 | + - print_length: the number of items in a collection which will be printed, |
| 109 | + or no limit if bound to a logical falsey value (default: 50) |
| 110 | + - print_level: the depth of the object graph to print, starting with 0, or |
| 111 | + no limit if bound to a logical falsey value (default: nil) |
| 112 | + - print_meta: if logical true, print objects meta in a way that can be |
| 113 | + read back by the reader (default: false) |
| 114 | + - print_readably: if logical false, print strings and characters with |
| 115 | + non-alphanumeric characters converted to escape sequences |
| 116 | + (default: true) |
| 117 | +
|
| 118 | + Note that this function is not capable of capturing the values bound at |
| 119 | + runtime to the basilisp.core dynamic variables which correspond to each |
| 120 | + of the keyword arguments to this function. To use a version of lrepr |
| 121 | + which does capture those values, call basilisp.lang.runtime.lrepr directly.""" |
| 122 | + kwargs = pmap( |
| 123 | + { |
| 124 | + "human_readable": human_readable, |
| 125 | + "print_dup": print_dup, |
| 126 | + "print_length": print_length, |
| 127 | + "print_level": print_level, |
| 128 | + "print_meta": print_meta, |
| 129 | + "print_readably": print_readably, |
| 130 | + } |
| 131 | + ) |
| 132 | + if isinstance(o, LispObject): |
| 133 | + return o._lrepr(**kwargs) |
| 134 | + elif o is True: |
| 135 | + return "true" |
| 136 | + elif o is False: |
| 137 | + return "false" |
| 138 | + elif o is None: |
| 139 | + return "nil" |
| 140 | + elif isinstance(o, str): |
| 141 | + if human_readable: |
| 142 | + return o |
| 143 | + if print_readably is None or print_readably is False: |
| 144 | + return f'"{o}"' |
| 145 | + return f'"{o.encode("unicode_escape").decode("utf-8")}"' |
| 146 | + elif isinstance(o, complex): |
| 147 | + return repr(o).upper() |
| 148 | + elif isinstance(o, datetime.datetime): |
| 149 | + inst_str = o.isoformat() |
| 150 | + return f'#inst "{inst_str}"' |
| 151 | + elif isinstance(o, Decimal): |
| 152 | + if print_dup: |
| 153 | + return f"{str(o)}M" |
| 154 | + return str(o) |
| 155 | + elif isinstance(o, Fraction): |
| 156 | + return f"{o.numerator}/{o.denominator}" |
| 157 | + elif isinstance(o, Pattern): |
| 158 | + return f'#"{o.pattern}"' |
| 159 | + elif isinstance(o, uuid.UUID): |
| 160 | + uuid_str = str(o) |
| 161 | + return f'#uuid "{uuid_str}"' |
| 162 | + else: |
| 163 | + return repr(o) |
0 commit comments