feat(lua): add fields method to sexpr Lua API

Signed-off-by: Leonardo de Moura <leonardo@microsoft.com>
This commit is contained in:
Leonardo de Moura 2013-11-13 12:10:24 -08:00
parent e2efce6b62
commit a80adae1c3
2 changed files with 33 additions and 0 deletions

View file

@ -179,6 +179,23 @@ static int sexpr_get_kind(lua_State * L) {
return 1;
}
static int sexpr_fields(lua_State * L) {
sexpr const & e = to_sexpr(L, 1);
switch (e.kind()) {
case sexpr_kind::Nil: return 0;
case sexpr_kind::String: return sexpr_to_string(L);
case sexpr_kind::Bool: return sexpr_to_bool(L);
case sexpr_kind::Int: return sexpr_to_int(L);
case sexpr_kind::Double: return sexpr_to_double(L);
case sexpr_kind::Name: return sexpr_to_name(L);
case sexpr_kind::MPZ: return sexpr_to_mpz(L);
case sexpr_kind::MPQ: return sexpr_to_mpq(L);
case sexpr_kind::Cons: sexpr_head(L); sexpr_tail(L); return 2;
}
lean_unreachable(); // LCOV_EXCL_LINE
return 0; // LCOV_EXCL_LINE
}
static const struct luaL_Reg sexpr_m[] = {
{"__gc", sexpr_gc}, // never throws
{"__tostring", safe_function<sexpr_tostring>},
@ -206,6 +223,7 @@ static const struct luaL_Reg sexpr_m[] = {
{"to_name", safe_function<sexpr_to_name>},
{"to_mpz", safe_function<sexpr_to_mpz>},
{"to_mpq", safe_function<sexpr_to_mpq>},
{"fields", safe_function<sexpr_fields>},
{0, 0}
};

15
tests/lua/sexpr5.lua Normal file
View file

@ -0,0 +1,15 @@
function display_leaves(s)
if s:kind() == sexpr_kind.Cons then
local h, t = s:fields()
display_leaves(h)
display_leaves(t)
else
print(s)
assert(s:kind() == sexpr_kind.Nil or s:kind() == sexpr_kind.String or tostring(s:fields()) == tostring(s))
assert(s:kind() ~= sexpr_kind.String or '"' .. tostring(s:fields()) .. '"' == tostring(s))
end
end
local l = sexpr(sexpr(1), sexpr(name("a")), sexpr(mpz(10)), sexpr(mpq(3)/2), sexpr(1, 2, 3), sexpr(sexpr("a"), sexpr(10, 2)), sexpr(), sexpr("foo"))
print(l)
display_leaves(l)