2018-01-01 16:38:33 +01:00
|
|
|
# Copyright 2018 the authors.
|
2017-04-27 23:16:57 +02:00
|
|
|
# This file is part of Hy, which is free software licensed under the Expat
|
|
|
|
# license. See the LICENSE.
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
from __future__ import unicode_literals
|
2017-08-27 00:15:33 +02:00
|
|
|
from contextlib import contextmanager
|
2017-05-14 17:12:28 +02:00
|
|
|
from math import isnan, isinf
|
2017-02-19 01:15:58 +01:00
|
|
|
from hy._compat import PY3, str_type, bytes_type, long_type, string_types
|
2017-06-27 23:09:31 +02:00
|
|
|
from fractions import Fraction
|
2017-08-27 00:15:33 +02:00
|
|
|
from clint.textui import colored
|
|
|
|
|
|
|
|
|
|
|
|
PRETTY = True
|
|
|
|
|
|
|
|
|
|
|
|
@contextmanager
|
|
|
|
def pretty(pretty=True):
|
|
|
|
"""
|
|
|
|
Context manager to temporarily enable
|
|
|
|
or disable pretty-printing of Hy model reprs.
|
|
|
|
"""
|
|
|
|
global PRETTY
|
|
|
|
old, PRETTY = PRETTY, pretty
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
PRETTY = old
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
|
|
|
|
class HyObject(object):
|
|
|
|
"""
|
|
|
|
Generic Hy Object model. This is helpful to inject things into all the
|
|
|
|
Hy lexing Objects at once.
|
|
|
|
"""
|
|
|
|
|
2018-05-21 20:37:46 +02:00
|
|
|
def replace(self, other, recursive=False):
|
2017-02-17 04:43:00 +01:00
|
|
|
if isinstance(other, HyObject):
|
|
|
|
for attr in ["start_line", "end_line",
|
|
|
|
"start_column", "end_column"]:
|
|
|
|
if not hasattr(self, attr) and hasattr(other, attr):
|
|
|
|
setattr(self, attr, getattr(other, attr))
|
|
|
|
else:
|
2018-03-29 04:45:49 +02:00
|
|
|
raise TypeError("Can't replace a non Hy object '{}' with a Hy object '{}'".format(repr(other), repr(self)))
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
return self
|
|
|
|
|
2017-08-03 23:26:07 +02:00
|
|
|
def __repr__(self):
|
|
|
|
return "%s(%s)" % (self.__class__.__name__, super(HyObject, self).__repr__())
|
|
|
|
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
_wrappers = {}
|
|
|
|
|
|
|
|
|
|
|
|
def wrap_value(x):
|
|
|
|
"""Wrap `x` into the corresponding Hy type.
|
|
|
|
|
|
|
|
This allows replace_hy_obj to convert a non Hy object to a Hy object.
|
|
|
|
|
|
|
|
This also allows a macro to return an unquoted expression transparently.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2018-05-21 20:37:46 +02:00
|
|
|
new = _wrappers.get(type(x), lambda y: y)(x)
|
|
|
|
if not isinstance(new, HyObject):
|
|
|
|
raise TypeError("Don't know how to wrap {!r}: {!r}".format(type(x), x))
|
|
|
|
if isinstance(x, HyObject):
|
|
|
|
new = new.replace(x, recursive=False)
|
|
|
|
if not hasattr(new, "start_column"):
|
|
|
|
new.start_column = 0
|
|
|
|
if not hasattr(new, "start_line"):
|
|
|
|
new.start_line = 0
|
|
|
|
return new
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
|
|
|
|
def replace_hy_obj(obj, other):
|
2018-05-21 20:37:46 +02:00
|
|
|
return wrap_value(obj).replace(other)
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
|
2017-08-03 23:26:07 +02:00
|
|
|
def repr_indent(obj):
|
2017-08-23 21:18:27 +02:00
|
|
|
return repr(obj).replace("\n", "\n ")
|
2017-08-03 23:26:07 +02:00
|
|
|
|
|
|
|
|
2017-02-17 04:43:00 +01:00
|
|
|
class HyString(HyObject, str_type):
|
|
|
|
"""
|
|
|
|
Generic Hy String object. Helpful to store string literals from Hy
|
|
|
|
scripts. It's either a ``str`` or a ``unicode``, depending on the
|
|
|
|
Python version.
|
|
|
|
"""
|
2017-09-08 20:23:58 +02:00
|
|
|
def __new__(cls, s=None, brackets=None):
|
|
|
|
value = super(HyString, cls).__new__(cls, s)
|
|
|
|
value.brackets = brackets
|
|
|
|
return value
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
_wrappers[str_type] = HyString
|
|
|
|
|
|
|
|
|
2017-02-19 01:15:58 +01:00
|
|
|
class HyBytes(HyObject, bytes_type):
|
|
|
|
"""
|
|
|
|
Generic Hy Bytes object. It's either a ``bytes`` or a ``str``, depending
|
|
|
|
on the Python version.
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
|
|
|
_wrappers[bytes_type] = HyBytes
|
|
|
|
|
|
|
|
|
2018-04-23 19:52:22 +02:00
|
|
|
class HySymbol(HyObject, str_type):
|
2017-02-17 04:43:00 +01:00
|
|
|
"""
|
2018-04-23 19:52:22 +02:00
|
|
|
Hy Symbol. Basically a string.
|
2017-02-17 04:43:00 +01:00
|
|
|
"""
|
|
|
|
|
2018-04-23 19:52:22 +02:00
|
|
|
def __new__(cls, s=None):
|
|
|
|
return super(HySymbol, cls).__new__(cls, s)
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
_wrappers[bool] = lambda x: HySymbol("True") if x else HySymbol("False")
|
|
|
|
_wrappers[type(None)] = lambda foo: HySymbol("None")
|
|
|
|
|
|
|
|
|
2018-02-10 04:56:33 +01:00
|
|
|
class HyKeyword(HyObject):
|
|
|
|
"""Generic Hy Keyword object."""
|
2017-02-17 03:06:45 +01:00
|
|
|
|
2018-04-04 05:36:10 +02:00
|
|
|
__slots__ = ['name']
|
2017-02-17 04:43:00 +01:00
|
|
|
|
2018-02-10 04:56:33 +01:00
|
|
|
def __init__(self, value):
|
2018-04-04 05:36:10 +02:00
|
|
|
self.name = value
|
2017-02-17 04:43:00 +01:00
|
|
|
|
2017-08-03 23:26:07 +02:00
|
|
|
def __repr__(self):
|
2018-04-04 05:36:10 +02:00
|
|
|
return "%s(%r)" % (self.__class__.__name__, self.name)
|
2018-02-10 04:56:33 +01:00
|
|
|
|
|
|
|
def __str__(self):
|
2018-04-04 05:36:10 +02:00
|
|
|
return ":%s" % self.name
|
2018-02-10 04:56:33 +01:00
|
|
|
|
|
|
|
def __hash__(self):
|
2018-04-04 05:36:10 +02:00
|
|
|
return hash(self.name)
|
2018-02-10 04:56:33 +01:00
|
|
|
|
|
|
|
def __eq__(self, other):
|
|
|
|
if not isinstance(other, HyKeyword):
|
|
|
|
return NotImplemented
|
2018-04-04 05:36:10 +02:00
|
|
|
return self.name == other.name
|
2018-02-10 04:56:33 +01:00
|
|
|
|
|
|
|
def __ne__(self, other):
|
|
|
|
if not isinstance(other, HyKeyword):
|
|
|
|
return NotImplemented
|
2018-04-04 05:36:10 +02:00
|
|
|
return self.name != other.name
|
2018-02-10 04:56:33 +01:00
|
|
|
|
|
|
|
def __bool__(self):
|
2018-04-04 05:36:10 +02:00
|
|
|
return bool(self.name)
|
2017-08-03 23:26:07 +02:00
|
|
|
|
2018-07-24 18:19:37 +02:00
|
|
|
_sentinel = object()
|
|
|
|
|
|
|
|
def __call__(self, data, default=_sentinel):
|
|
|
|
try:
|
|
|
|
return data[self]
|
|
|
|
except KeyError:
|
|
|
|
if default is HyKeyword._sentinel:
|
|
|
|
raise
|
|
|
|
return default
|
|
|
|
|
2017-02-17 04:43:00 +01:00
|
|
|
|
2017-02-17 03:09:23 +01:00
|
|
|
def strip_digit_separators(number):
|
2017-09-16 23:19:05 +02:00
|
|
|
# Don't strip a _ or , if it's the first character, as _42 and
|
|
|
|
# ,42 aren't valid numbers
|
|
|
|
return (number[0] + number[1:].replace("_", "").replace(",", "")
|
|
|
|
if isinstance(number, string_types) and len(number) > 1
|
2017-02-17 03:09:23 +01:00
|
|
|
else number)
|
|
|
|
|
|
|
|
|
2017-02-17 04:43:00 +01:00
|
|
|
class HyInteger(HyObject, long_type):
|
|
|
|
"""
|
|
|
|
Internal representation of a Hy Integer. May raise a ValueError as if
|
|
|
|
int(foo) was called, given HyInteger(foo). On python 2.x long will
|
|
|
|
be used instead
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __new__(cls, number, *args, **kwargs):
|
|
|
|
if isinstance(number, string_types):
|
2017-02-17 03:09:23 +01:00
|
|
|
number = strip_digit_separators(number)
|
2017-02-17 04:43:00 +01:00
|
|
|
bases = {"0x": 16, "0o": 8, "0b": 2}
|
|
|
|
for leader, base in bases.items():
|
|
|
|
if number.startswith(leader):
|
|
|
|
# We've got a string, known leader, set base.
|
|
|
|
number = long_type(number, base=base)
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
# We've got a string, no known leader; base 10.
|
|
|
|
number = long_type(number, base=10)
|
|
|
|
else:
|
|
|
|
# We've got a non-string; convert straight.
|
|
|
|
number = long_type(number)
|
|
|
|
return super(HyInteger, cls).__new__(cls, number)
|
|
|
|
|
|
|
|
|
|
|
|
_wrappers[int] = HyInteger
|
|
|
|
if not PY3: # do not add long on python3
|
|
|
|
_wrappers[long_type] = HyInteger
|
|
|
|
|
|
|
|
|
2017-05-14 17:12:28 +02:00
|
|
|
def check_inf_nan_cap(arg, value):
|
|
|
|
if isinstance(arg, string_types):
|
2017-11-12 00:14:28 +01:00
|
|
|
if isinf(value) and "i" in arg.lower() and "Inf" not in arg:
|
2017-05-14 17:12:28 +02:00
|
|
|
raise ValueError('Inf must be capitalized as "Inf"')
|
|
|
|
if isnan(value) and "NaN" not in arg:
|
|
|
|
raise ValueError('NaN must be capitalized as "NaN"')
|
|
|
|
|
|
|
|
|
2017-02-17 04:43:00 +01:00
|
|
|
class HyFloat(HyObject, float):
|
|
|
|
"""
|
|
|
|
Internal representation of a Hy Float. May raise a ValueError as if
|
|
|
|
float(foo) was called, given HyFloat(foo).
|
|
|
|
"""
|
|
|
|
|
2017-05-14 17:12:28 +02:00
|
|
|
def __new__(cls, num, *args, **kwargs):
|
|
|
|
value = super(HyFloat, cls).__new__(cls, strip_digit_separators(num))
|
|
|
|
check_inf_nan_cap(num, value)
|
|
|
|
return value
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
_wrappers[float] = HyFloat
|
|
|
|
|
|
|
|
|
|
|
|
class HyComplex(HyObject, complex):
|
|
|
|
"""
|
|
|
|
Internal representation of a Hy Complex. May raise a ValueError as if
|
|
|
|
complex(foo) was called, given HyComplex(foo).
|
|
|
|
"""
|
|
|
|
|
2017-08-09 10:00:21 +02:00
|
|
|
def __new__(cls, real, imag=0, *args, **kwargs):
|
|
|
|
if isinstance(real, string_types):
|
|
|
|
value = super(HyComplex, cls).__new__(
|
|
|
|
cls, strip_digit_separators(real)
|
|
|
|
)
|
|
|
|
p1, _, p2 = real.lstrip("+-").replace("-", "+").partition("+")
|
|
|
|
check_inf_nan_cap(p1, value.imag if "j" in p1 else value.real)
|
2017-05-14 17:12:28 +02:00
|
|
|
if p2:
|
|
|
|
check_inf_nan_cap(p2, value.imag)
|
2017-08-09 10:00:21 +02:00
|
|
|
return value
|
|
|
|
return super(HyComplex, cls).__new__(cls, real, imag)
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
_wrappers[complex] = HyComplex
|
|
|
|
|
|
|
|
|
2018-04-15 05:58:52 +02:00
|
|
|
class HySequence(HyObject, list):
|
2017-02-17 04:43:00 +01:00
|
|
|
"""
|
2018-04-15 05:58:52 +02:00
|
|
|
An abstract type for sequence-like models to inherit from.
|
2017-02-17 04:43:00 +01:00
|
|
|
"""
|
|
|
|
|
2018-04-18 20:59:01 +02:00
|
|
|
def replace(self, other, recursive=True):
|
|
|
|
if recursive:
|
|
|
|
for x in self:
|
|
|
|
replace_hy_obj(x, other)
|
2017-02-17 04:43:00 +01:00
|
|
|
HyObject.replace(self, other)
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __add__(self, other):
|
2018-04-15 05:58:52 +02:00
|
|
|
return self.__class__(super(HySequence, self).__add__(other))
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
def __getslice__(self, start, end):
|
2018-04-15 05:58:52 +02:00
|
|
|
return self.__class__(super(HySequence, self).__getslice__(start, end))
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
def __getitem__(self, item):
|
2018-04-15 05:58:52 +02:00
|
|
|
ret = super(HySequence, self).__getitem__(item)
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
if isinstance(item, slice):
|
|
|
|
return self.__class__(ret)
|
|
|
|
|
|
|
|
return ret
|
|
|
|
|
2018-04-15 05:58:52 +02:00
|
|
|
color = None
|
2017-08-27 00:15:33 +02:00
|
|
|
|
2017-02-17 04:43:00 +01:00
|
|
|
def __repr__(self):
|
2018-04-15 05:58:52 +02:00
|
|
|
return str(self) if PRETTY else super(HySequence, self).__repr__()
|
2017-08-27 00:15:33 +02:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
with pretty():
|
|
|
|
c = self.color
|
|
|
|
if self:
|
|
|
|
return ("{}{}\n {}{}").format(
|
|
|
|
c(self.__class__.__name__),
|
|
|
|
c("(["),
|
|
|
|
(c(",") + "\n ").join([repr_indent(e) for e in self]),
|
|
|
|
c("])"))
|
|
|
|
else:
|
|
|
|
return '' + c(self.__class__.__name__ + "()")
|
2017-02-17 04:43:00 +01:00
|
|
|
|
2018-04-15 05:58:52 +02:00
|
|
|
|
|
|
|
class HyList(HySequence):
|
|
|
|
color = staticmethod(colored.cyan)
|
|
|
|
|
2018-05-21 20:37:46 +02:00
|
|
|
def recwrap(f):
|
|
|
|
return lambda l: f(wrap_value(x) for x in l)
|
|
|
|
|
|
|
|
_wrappers[HyList] = recwrap(HyList)
|
|
|
|
_wrappers[list] = recwrap(HyList)
|
|
|
|
_wrappers[tuple] = recwrap(HyList)
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
|
2018-04-15 05:58:52 +02:00
|
|
|
class HyDict(HySequence):
|
2017-02-17 04:43:00 +01:00
|
|
|
"""
|
|
|
|
HyDict (just a representation of a dict)
|
|
|
|
"""
|
|
|
|
|
2017-08-27 00:15:33 +02:00
|
|
|
def __str__(self):
|
|
|
|
with pretty():
|
|
|
|
g = colored.green
|
|
|
|
if self:
|
|
|
|
pairs = []
|
|
|
|
for k, v in zip(self[::2],self[1::2]):
|
|
|
|
k, v = repr_indent(k), repr_indent(v)
|
|
|
|
pairs.append(
|
2017-09-18 08:58:14 +02:00
|
|
|
("{0}{c}\n {1}\n "
|
2017-08-27 00:15:33 +02:00
|
|
|
if '\n' in k+v
|
2017-09-18 08:58:14 +02:00
|
|
|
else "{0}{c} {1}").format(k, v, c=g(',')))
|
2017-08-27 00:15:33 +02:00
|
|
|
if len(self) % 2 == 1:
|
|
|
|
pairs.append("{} {}\n".format(
|
|
|
|
repr_indent(self[-1]), g("# odd")))
|
|
|
|
return "{}\n {}{}".format(
|
2017-09-18 08:58:14 +02:00
|
|
|
g("HyDict(["), ("{c}\n ".format(c=g(',')).join(pairs)), g("])"))
|
2017-08-27 00:15:33 +02:00
|
|
|
else:
|
|
|
|
return '' + g("HyDict()")
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
def keys(self):
|
|
|
|
return self[0::2]
|
|
|
|
|
|
|
|
def values(self):
|
|
|
|
return self[1::2]
|
|
|
|
|
|
|
|
def items(self):
|
|
|
|
return list(zip(self.keys(), self.values()))
|
|
|
|
|
2018-05-21 20:37:46 +02:00
|
|
|
_wrappers[HyDict] = recwrap(HyDict)
|
2017-02-17 04:43:00 +01:00
|
|
|
_wrappers[dict] = lambda d: HyDict(wrap_value(x) for x in sum(d.items(), ()))
|
|
|
|
|
|
|
|
|
2018-04-15 05:58:52 +02:00
|
|
|
class HyExpression(HySequence):
|
2017-02-17 04:43:00 +01:00
|
|
|
"""
|
|
|
|
Hy S-Expression. Basically just a list.
|
|
|
|
"""
|
2017-08-27 00:15:33 +02:00
|
|
|
color = staticmethod(colored.yellow)
|
2017-02-17 04:43:00 +01:00
|
|
|
|
2018-05-21 20:37:46 +02:00
|
|
|
_wrappers[HyExpression] = recwrap(HyExpression)
|
2017-06-27 23:09:31 +02:00
|
|
|
_wrappers[Fraction] = lambda e: HyExpression(
|
|
|
|
[HySymbol("fraction"), wrap_value(e.numerator), wrap_value(e.denominator)])
|
2017-02-17 04:43:00 +01:00
|
|
|
|
|
|
|
|
2018-04-15 05:58:52 +02:00
|
|
|
class HySet(HySequence):
|
2017-02-17 04:43:00 +01:00
|
|
|
"""
|
|
|
|
Hy set (just a representation of a set)
|
|
|
|
"""
|
2017-08-27 00:15:33 +02:00
|
|
|
color = staticmethod(colored.red)
|
2017-02-17 04:43:00 +01:00
|
|
|
|
2018-05-21 20:37:46 +02:00
|
|
|
_wrappers[HySet] = recwrap(HySet)
|
|
|
|
_wrappers[set] = recwrap(HySet)
|