compiler: Make maps and lists able to look up their params
As a neat syntactic sugar, it's very neat if maps and lists are able to work as if they were functions, and look up their arguments. This implements just that, by translating (map key) to (index map key) internally, and (list idx) to (index list idx). Signed-off-by: Gergely Nagy <algernon@madhouse-project.org>
This commit is contained in:
parent
56dedfa6ed
commit
a7cd70c84a
@ -163,6 +163,10 @@ class AST27Converter(object):
|
|||||||
"for": self._ast_for,
|
"for": self._ast_for,
|
||||||
"kwapply": self._ast_kwapply,
|
"kwapply": self._ast_kwapply,
|
||||||
}
|
}
|
||||||
|
self.special_types = {
|
||||||
|
HYMap: self._ast_fn_index,
|
||||||
|
HYList: self._ast_fn_index,
|
||||||
|
}
|
||||||
self.in_fn = False
|
self.in_fn = False
|
||||||
|
|
||||||
def _ast_index(self, node):
|
def _ast_index(self, node):
|
||||||
@ -176,6 +180,13 @@ class AST27Converter(object):
|
|||||||
ast.Index(value=self.render(tar), ctx=ast.Load()),
|
ast.Index(value=self.render(tar), ctx=ast.Load()),
|
||||||
ast.Load())
|
ast.Load())
|
||||||
|
|
||||||
|
def _ast_fn_index(self, node):
|
||||||
|
i = node.get_invocation()
|
||||||
|
cmd = ["index"]
|
||||||
|
cmd.append(i['function'])
|
||||||
|
cmd.extend(i['args'])
|
||||||
|
return self.render_expression(HYExpression(cmd))
|
||||||
|
|
||||||
def _ast_dot(self, node):
|
def _ast_dot(self, node):
|
||||||
inv = node.get_invocation()
|
inv = node.get_invocation()
|
||||||
args = inv['args']
|
args = inv['args']
|
||||||
@ -370,6 +381,9 @@ class AST27Converter(object):
|
|||||||
|
|
||||||
inv = node.get_invocation()
|
inv = node.get_invocation()
|
||||||
|
|
||||||
|
if type(inv['function']) in self.special_types:
|
||||||
|
return self.special_types[type(inv['function'])](node)
|
||||||
|
|
||||||
if inv['function'] in self.native_cases:
|
if inv['function'] in self.native_cases:
|
||||||
return self.native_cases[inv['function']](node)
|
return self.native_cases[inv['function']](node)
|
||||||
|
|
||||||
|
5
tests/lang/colls.hy
Normal file
5
tests/lang/colls.hy
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
(defn test-map-index []
|
||||||
|
({"foo" "bar"} "foo"))
|
||||||
|
|
||||||
|
(defn test-list-index []
|
||||||
|
(["first" "second"] 1))
|
7
tests/lang/test_types_as_fn.py
Normal file
7
tests/lang/test_types_as_fn.py
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
import tests.lang.colls
|
||||||
|
|
||||||
|
def test_map_index():
|
||||||
|
assert tests.lang.colls.test_map_index() == "bar"
|
||||||
|
|
||||||
|
def test_list_index():
|
||||||
|
assert tests.lang.colls.test_list_index() == "second"
|
Loading…
x
Reference in New Issue
Block a user