Skip to content

Commit

Permalink
Convert list from elisp to python
Browse files Browse the repository at this point in the history
I'm really surprised that works.
  • Loading branch information
813gan committed Aug 17, 2024
1 parent 31d7375 commit bc1ea28
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
24 changes: 24 additions & 0 deletions emacspy.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,28 @@ cdef class EmacsValue:
cdef emacs_env* env = get_env()
return EmacsValue.wrap(env.type_of(env, self.v)).sym_str()

# i hate this joggling with pointers mixed with python syntax.
# TODO: rewrite that in C with serious data validation?
def as_list(self):
cdef emacs_env* env = get_env()
fcar = unwrap(sym("car"))
fcdr = unwrap(sym("cdr"))
is_false = unwrap(sym("null"))
is_list = unwrap(sym("listp"))
ret = list()
cdef emacs_value cdr = self.v

if not EmacsValue.wrap(env.funcall(env, is_list, 1, &cdr)).to_python_type():
raise ValueError("Attepted list translation on non list")

while True:
car = env.funcall(env, fcar, 1, &cdr)
cdr = env.funcall(env, fcdr, 1, &cdr)
ret.append(EmacsValue.wrap(car).to_python_type())
if EmacsValue.wrap(env.funcall(env, is_false, 1, &cdr)).to_python_type():
break
return ret

def to_python_type(self):
my_type = self.type()
if my_type == "string":
Expand All @@ -173,6 +195,8 @@ cdef class EmacsValue:
return False
elif as_str == "t":
return True
elif my_type == "cons": # list
return self.as_list()
raise ValueError("Unable to export emacs value")

def __str__(self):
Expand Down
24 changes: 23 additions & 1 deletion tests/test.el
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,26 @@
(should (eq 3 (length nested-lst)))
(should (eq 3 (nth 2 nested-lst))) )
(should (string= "test" (nth 1 lst)))
(should (eq nil (nth 2 lst))) ) )
(should (eq nil (nth 2 lst))) )

(let ((lst (py-get-global-variable
"test"
(py-set-global "test" '(t nil 3 "test") "test_list"))))
(should (eq 't (nth 0 lst)))
(should (eq nil (nth 1 lst)))
(should (eq 3 (nth 2 lst)))
(should (string= "test" (nth 3 lst)))
(should (eq 4 (length lst))) )

(let ((lst (py-get-global-variable
"test"
(py-set-global "test" '(("test") (1 2 3)) "test_list"))))
(should (eq 2 (length lst)))
(let ((nested-lst (nth 0 lst)))
(should (listp nested-lst))
(should (eq 1 (length nested-lst)))
(should (string= "test" (car nested-lst))) )
(let ((nested-lst (nth 1 lst)))
(should (listp nested-lst))
(should (eq 3 (length nested-lst)))
(should (eq 3 (nth 2 nested-lst))) ) ))

0 comments on commit bc1ea28

Please sign in to comment.