emacs-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: continuation passing in Emacs vs. JUST-THIS-ONE


From: Tomas Hlavaty
Subject: Re: continuation passing in Emacs vs. JUST-THIS-ONE
Date: Mon, 27 Mar 2023 01:50:51 +0200

On Sat 11 Mar 2023 at 14:53, Thomas Koch <thomas@koch.ro> wrote:
> While I don't know elisp, I unfortunately had to do JavaScript. Like
> Emacs, JS is single-threaded. While I share the sentiment about JS,
> there are still things to learn from it, e.g. event driven
> programming.

I guess you mean async & await as opposed to callback hell.

I think that the essence of async & await is to teleport a value from
one place to another.  It has nothing to do with asynchronicity.  It
just happens that this is useful with asynchronous code where it is
convenient to teleport a value from under one stack (or thread) of
execution to under the current stack (or thread) of execution.

(await               <- 2) to the current place
 (async
   ...
   (yield 42)))      <- 1) teleport 42
=> 42

async is just a syntactic sugar to lexically provide the
necessary facilities to make this teleportation work.  Thanks to
lexical binding and lisp macros, this is easy work for the lisp
compiler:

(defun await (future)
  (let (z)
    (while (eq 'EAGAIN (setq z (funcall future)))
      (sit-for 0.2))
    z))
    
(defmacro async (&rest body)
  (declare (indent 0))
  (let ((z (gensym))
        (e (gensym)))
    `(let (,e (,z 'EAGAIN))
       (cl-flet ((yield (x) (setq ,z x))
                 (fail (string &rest args) (setq ,e (cons string args))))
         ,@body)
       (lambda () (if ,e (apply #'error ,e) ,z)))))

Doing it this way brings great flexibility in what the three dots in the
sketch above can be: synchronous code in the current thread of
execution, asynchronous process with its filter or sentinel callback,
another thread or maybe a timer loop like in javascript.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]