Permit macros to return constants

This commit is contained in:
Konrad Hinsen 2013-06-05 12:19:06 +02:00
parent 2c582fbd52
commit e47bac1f96
2 changed files with 41 additions and 1 deletions

View File

@ -21,6 +21,11 @@
from hy.models.expression import HyExpression
from hy.models.string import HyString
from hy.models.list import HyList
from hy.models.integer import HyInteger
from hy.models.float import HyFloat
from hy.models.complex import HyComplex
from hy.models.dict import HyDict
from hy.util import str_type
from collections import defaultdict
@ -44,6 +49,20 @@ def require(source_module_name, target_module_name):
refs[name] = macro
def _wrap_value(x):
wrapper = _wrappers.get(type(x))
if wrapper is None:
return x
else:
return wrapper(x)
_wrappers = {int: HyInteger,
float: HyFloat,
complex: HyComplex,
str_type: HyString,
dict: lambda d: HyDict(_wrap_value(x) for x in sum(d.items(), ())),
list: lambda l: HyList(_wrap_value(x) for x in l)}
def process(tree, module_name):
if isinstance(tree, HyExpression):
fn = tree[0]
@ -57,7 +76,7 @@ def process(tree, module_name):
if m is None:
m = _hy_macros[None].get(fn)
if m is not None:
obj = m(*ntree[1:])
obj = _wrap_value(m(*ntree[1:]))
obj.replace(tree)
return obj

View File

@ -8,3 +8,24 @@
(setv x [])
(rev (.append x 1) (.append x 2) (.append x 3))
(assert (= x [3 2 1])))
; Macros returning constants
(defmacro an-int [] 42)
(assert (= (an-int) 42))
(defmacro a-float [] 42.)
(assert (= (a-float) 42.))
(defmacro a-complex [] 42j)
(assert (= (a-complex) 42j))
(defmacro a-string [] "foo")
(assert (= (a-string) "foo"))
(defmacro a-list [] [1 2])
(assert (= (a-list) [1 2]))
(defmacro a-dict [] {1 2})
(assert (= (a-dict) {1 2}))