Document reserved keys
[emacs.git] / lisp / emacs-lisp / generator.el
blob506df59d8e2c3428989d90f32d465ed82a55401b
1 ;;; generator.el --- generators -*- lexical-binding: t -*-
3 ;;; Copyright (C) 2015-2018 Free Software Foundation, Inc.
5 ;; Author: Daniel Colascione <dancol@dancol.org>
6 ;; Keywords: extensions, elisp
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; This package implements generators for Emacs Lisp through a
27 ;; continuation-passing transformation. It provides essentially the
28 ;; same generator API and iterator facilities that Python and
29 ;; JavaScript ES6 provide.
31 ;; `iter-lambda' and `iter-defun' work like `lambda' and `defun',
32 ;; except that they evaluate to or define, respectively, generator
33 ;; functions. These functions, when called, return an iterator.
34 ;; An iterator is an opaque object that generates a sequence of
35 ;; values. Callers use `iter-next' to retrieve the next value from
36 ;; the sequence; when the sequence is exhausted, `iter-next' will
37 ;; raise the `iter-end-of-sequence' condition.
39 ;; Generator functions are written like normal functions, except that
40 ;; they can invoke `iter-yield' to suspend themselves and return a
41 ;; value to callers; this value becomes the return value of
42 ;; `iter-next'. On the next call to `iter-next', execution of the
43 ;; generator function resumes where it left off. When a generator
44 ;; function returns normally, the `iter-next' raises
45 ;; `iter-end-of-sequence' with the value the function returned.
47 ;; `iter-yield-from' yields all the values from another iterator; it
48 ;; then evaluates to the value the sub-iterator returned normally.
49 ;; This facility is useful for functional composition of generators
50 ;; and for implementing coroutines.
52 ;; `iter-yield' is illegal inside the UNWINDFORMS of an
53 ;; `unwind-protect' for various sordid internal reasons documented in
54 ;; the code.
56 ;; N.B. Each call to a generator function generates a *new* iterator,
57 ;; and each iterator maintains its own internal state.
59 ;; This raw form of iteration is general, but a bit awkward to use, so
60 ;; this library also provides some convenience functions:
62 ;; `iter-do' is like `cl-do', except that instead of walking a list,
63 ;; it walks an iterator. `cl-loop' is also extended with a new
64 ;; keyword, `iter-by', that iterates over an iterator.
67 ;;; Implementation:
70 ;; The internal cps transformation code uses the cps- namespace.
71 ;; Iteration functions use the `iter-' namespace. Generator functions
72 ;; are somewhat less efficient than conventional elisp routines,
73 ;; although we try to avoid CPS transformation on forms that do not
74 ;; invoke `iter-yield'.
77 ;;; Code:
79 (require 'cl-lib)
81 (defvar cps--bindings nil)
82 (defvar cps--states nil)
83 (defvar cps--value-symbol nil)
84 (defvar cps--state-symbol nil)
85 (defvar cps--cleanup-table-symbol nil)
86 (defvar cps--cleanup-function nil)
88 (defmacro cps--gensym (fmt &rest args)
89 `(gensym (format ,fmt ,@args)))
91 (defvar cps--dynamic-wrappers '(identity)
92 "List of transformer functions to apply to atomic forms we
93 evaluate in CPS context.")
95 (defconst cps-standard-special-forms
96 '(setq setq-default throw interactive)
97 "List of special forms that we treat just like ordinary
98 function applications." )
100 (defun cps--trace-funcall (func &rest args)
101 (message "%S: args=%S" func args)
102 (let ((result (apply func args)))
103 (message "%S: result=%S" func result)
104 result))
106 (defun cps--trace (fmt &rest args)
107 (princ (apply #'format (concat fmt "\n") args)))
109 (defun cps--special-form-p (definition)
110 "Non-nil if and only if DEFINITION is a special form."
111 ;; Copied from ad-special-form-p
112 (if (and (symbolp definition) (fboundp definition))
113 (setf definition (indirect-function definition)))
114 (and (subrp definition) (eq (cdr (subr-arity definition)) 'unevalled)))
116 (defmacro cps--define-unsupported (function)
117 `(defun ,(intern (format "cps--transform-%s" function))
118 (error "%s not supported in generators" ,function)))
120 (defmacro cps--with-value-wrapper (wrapper &rest body)
121 "Continue generating CPS code with an atomic-form wrapper
122 to the current stack of such wrappers. WRAPPER is a function that
123 takes a form and returns a wrapped form.
125 Whenever we generate an atomic form (i.e., a form that can't
126 iter-yield), we first (before actually inserting that form in our
127 generated code) pass that form through all the transformer
128 functions. We use this facility to wrap forms that can transfer
129 control flow non-locally in goo that diverts this control flow to
130 the CPS state machinery.
132 (declare (indent 1))
133 `(let ((cps--dynamic-wrappers
134 (cons
135 ,wrapper
136 cps--dynamic-wrappers)))
137 ,@body))
139 (defun cps--make-dynamic-binding-wrapper (dynamic-var static-var)
140 (cl-assert lexical-binding)
141 (lambda (form)
142 `(let ((,dynamic-var ,static-var))
143 (unwind-protect ; Update the static shadow after evaluation is done
144 ,form
145 (setf ,static-var ,dynamic-var)))))
147 (defmacro cps--with-dynamic-binding (dynamic-var static-var &rest body)
148 "Evaluate BODY such that generated atomic evaluations run with
149 DYNAMIC-VAR bound to STATIC-VAR."
150 (declare (indent 2))
151 `(cps--with-value-wrapper
152 (cps--make-dynamic-binding-wrapper ,dynamic-var ,static-var)
153 ,@body))
155 (defun cps--add-state (kind body)
156 "Create a new CPS state with body BODY and return the state's name."
157 (declare (indent 1))
158 (let* ((state (cps--gensym "cps-state-%s-" kind)))
159 (push (list state body cps--cleanup-function) cps--states)
160 (push state cps--bindings)
161 state))
163 (defun cps--add-binding (original-name)
164 (car (push (cps--gensym (format "cps-binding-%s-" original-name))
165 cps--bindings)))
167 (defun cps--find-special-form-handler (form)
168 (let* ((handler-name (format "cps--transform-%s" (car-safe form)))
169 (handler (intern-soft handler-name)))
170 (and (fboundp handler) handler)))
172 (defvar cps-inhibit-atomic-optimization nil
173 "When t, always rewrite forms into cps even when they
174 don't yield.")
176 (defvar cps--yield-seen)
178 (defun cps--atomic-p (form)
179 "Return whether the given form never yields."
181 (and (not cps-inhibit-atomic-optimization)
182 (let* ((cps--yield-seen))
183 (ignore (macroexpand-all
184 `(cl-macrolet ((cps-internal-yield
185 (_val)
186 (setf cps--yield-seen t)))
187 ,form)
188 macroexpand-all-environment))
189 (not cps--yield-seen))))
191 (defun cps--make-atomic-state (form next-state)
192 (let ((tform `(prog1 ,form (setf ,cps--state-symbol ,next-state))))
193 (cl-loop for wrapper in cps--dynamic-wrappers
194 do (setf tform (funcall wrapper tform)))
195 ;; Bind cps--cleanup-function to nil here because the wrapper
196 ;; function mechanism is responsible for cleanup here, not the
197 ;; generic cleanup mechanism. If we didn't make this binding,
198 ;; we'd run cleanup handlers twice on anything that made it out
199 ;; to toplevel.
200 (let ((cps--cleanup-function nil))
201 (cps--add-state "atom"
202 `(setf ,cps--value-symbol ,tform)))))
204 (defun cps--transform-1 (form next-state)
205 (pcase form
207 ;; If we're looking at an "atomic" form (i.e., one that does not
208 ;; iter-yield), just evaluate the form as a whole instead of rewriting
209 ;; it into CPS.
211 ((guard (cps--atomic-p form))
212 (cps--make-atomic-state form next-state))
214 ;; Process `and'.
216 (`(and) ; (and) -> t
217 (cps--transform-1 t next-state))
218 (`(and ,condition) ; (and CONDITION) -> CONDITION
219 (cps--transform-1 condition next-state))
220 (`(and ,condition . ,rest)
221 ;; Evaluate CONDITION; if it's true, go on to evaluate the rest
222 ;; of the `and'.
223 (cps--transform-1
224 condition
225 (cps--add-state "and"
226 `(setf ,cps--state-symbol
227 (if ,cps--value-symbol
228 ,(cps--transform-1 `(and ,@rest)
229 next-state)
230 ,next-state)))))
232 ;; Process `catch'.
234 (`(catch ,tag . ,body)
235 (let ((tag-binding (cps--add-binding "catch-tag")))
236 (cps--transform-1 tag
237 (cps--add-state "cps-update-tag"
238 `(setf ,tag-binding ,cps--value-symbol
239 ,cps--state-symbol
240 ,(cps--with-value-wrapper
241 (cps--make-catch-wrapper
242 tag-binding next-state)
243 (cps--transform-1 `(progn ,@body)
244 next-state)))))))
246 ;; Process `cond': transform into `if' or `or' depending on the
247 ;; precise kind of the condition we're looking at.
249 (`(cond) ; (cond) -> nil
250 (cps--transform-1 nil next-state))
251 (`(cond (,condition) . ,rest)
252 (cps--transform-1 `(or ,condition (cond ,@rest))
253 next-state))
254 (`(cond (,condition . ,body) . ,rest)
255 (cps--transform-1 `(if ,condition
256 (progn ,@body)
257 (cond ,@rest))
258 next-state))
260 ;; Process `condition-case': do the heavy lifting in a helper
261 ;; function.
263 (`(condition-case ,var ,bodyform . ,handlers)
264 (cps--with-value-wrapper
265 (cps--make-condition-wrapper var next-state handlers)
266 (cps--transform-1 bodyform
267 next-state)))
269 ;; Process `if'.
271 (`(if ,cond ,then . ,else)
272 (cps--transform-1 cond
273 (cps--add-state "if"
274 `(setf ,cps--state-symbol
275 (if ,cps--value-symbol
276 ,(cps--transform-1 then
277 next-state)
278 ,(cps--transform-1 `(progn ,@else)
279 next-state))))))
281 ;; Process `progn' and `inline': they are identical except for the
282 ;; name, which has some significance to the byte compiler.
284 (`(inline) (cps--transform-1 nil next-state))
285 (`(inline ,form) (cps--transform-1 form next-state))
286 (`(inline ,form . ,rest)
287 (cps--transform-1 form
288 (cps--transform-1 `(inline ,@rest)
289 next-state)))
291 (`(progn) (cps--transform-1 nil next-state))
292 (`(progn ,form) (cps--transform-1 form next-state))
293 (`(progn ,form . ,rest)
294 (cps--transform-1 form
295 (cps--transform-1 `(progn ,@rest)
296 next-state)))
298 ;; Process `let' in a helper function that transforms it into a
299 ;; let* with temporaries.
301 (`(let ,bindings . ,body)
302 (let* ((bindings (cl-loop for binding in bindings
303 collect (if (symbolp binding)
304 (list binding nil)
305 binding)))
306 (temps (cl-loop for (var _value-form) in bindings
307 collect (cps--add-binding var))))
308 (cps--transform-1
309 `(let* ,(append
310 (cl-loop for (_var value-form) in bindings
311 for temp in temps
312 collect (list temp value-form))
313 (cl-loop for (var _binding) in bindings
314 for temp in temps
315 collect (list var temp)))
316 ,@body)
317 next-state)))
319 ;; Process `let*' binding: process one binding at a time. Flatten
320 ;; lexical bindings.
322 (`(let* () . ,body)
323 (cps--transform-1 `(progn ,@body) next-state))
325 (`(let* (,binding . ,more-bindings) . ,body)
326 (let* ((var (if (symbolp binding) binding (car binding)))
327 (value-form (car (cdr-safe binding)))
328 (new-var (cps--add-binding var)))
330 (cps--transform-1
331 value-form
332 (cps--add-state "let*"
333 `(setf ,new-var ,cps--value-symbol
334 ,cps--state-symbol
335 ,(if (or (not lexical-binding) (special-variable-p var))
336 (cps--with-dynamic-binding var new-var
337 (cps--transform-1
338 `(let* ,more-bindings ,@body)
339 next-state))
340 (cps--transform-1
341 (cps--replace-variable-references
342 var new-var
343 `(let* ,more-bindings ,@body))
344 next-state)))))))
346 ;; Process `or'.
348 (`(or) (cps--transform-1 nil next-state))
349 (`(or ,condition) (cps--transform-1 condition next-state))
350 (`(or ,condition . ,rest)
351 (cps--transform-1
352 condition
353 (cps--add-state "or"
354 `(setf ,cps--state-symbol
355 (if ,cps--value-symbol
356 ,next-state
357 ,(cps--transform-1
358 `(or ,@rest) next-state))))))
360 ;; Process `prog1'.
362 (`(prog1 ,first) (cps--transform-1 first next-state))
363 (`(prog1 ,first . ,body)
364 (cps--transform-1
365 first
366 (let ((temp-var-symbol (cps--add-binding "prog1-temp")))
367 (cps--add-state "prog1"
368 `(setf ,temp-var-symbol
369 ,cps--value-symbol
370 ,cps--state-symbol
371 ,(cps--transform-1
372 `(progn ,@body)
373 (cps--add-state "prog1inner"
374 `(setf ,cps--value-symbol ,temp-var-symbol
375 ,cps--state-symbol ,next-state))))))))
377 ;; Process `prog2'.
379 (`(prog2 ,form1 ,form2 . ,body)
380 (cps--transform-1
381 `(progn ,form1 (prog1 ,form2 ,@body))
382 next-state))
384 ;; Process `unwind-protect': If we're inside an unwind-protect, we
385 ;; have a block of code UNWINDFORMS which we would like to run
386 ;; whenever control flows away from the main piece of code,
387 ;; BODYFORM. We deal with the local control flow case by
388 ;; generating BODYFORM such that it yields to a continuation that
389 ;; executes UNWINDFORMS, which then yields to NEXT-STATE.
391 ;; Non-local control flow is trickier: we need to ensure that we
392 ;; execute UNWINDFORMS even when control bypasses our normal
393 ;; continuation. To make this guarantee, we wrap every external
394 ;; application (i.e., every piece of elisp that can transfer
395 ;; control non-locally) in an unwind-protect that runs UNWINDFORMS
396 ;; before allowing the non-local control transfer to proceed.
398 ;; Unfortunately, because elisp lacks a mechanism for generically
399 ;; capturing the reason for an arbitrary non-local control
400 ;; transfer and restarting the transfer at a later point, we
401 ;; cannot reify non-local transfers and cannot allow
402 ;; continuation-passing code inside UNWINDFORMS.
404 (`(unwind-protect ,bodyform . ,unwindforms)
405 ;; Signal the evaluator-generator that it needs to generate code
406 ;; to handle cleanup forms.
407 (unless cps--cleanup-table-symbol
408 (setf cps--cleanup-table-symbol (cps--gensym "cps-cleanup-table-")))
409 (let* ((unwind-state
410 (cps--add-state
411 "unwind"
412 ;; N.B. It's safe to just substitute unwindforms by
413 ;; sexp-splicing: we've already replaced all variable
414 ;; references inside it with lifted equivalents.
415 `(progn
416 ,@unwindforms
417 (setf ,cps--state-symbol ,next-state))))
418 (old-cleanup cps--cleanup-function)
419 (cps--cleanup-function
420 (let ((cps--cleanup-function nil))
421 (cps--add-state "cleanup"
422 `(progn
423 ,(when old-cleanup `(funcall ,old-cleanup))
424 ,@unwindforms)))))
425 (cps--with-value-wrapper
426 (cps--make-unwind-wrapper unwindforms)
427 (cps--transform-1 bodyform unwind-state))))
429 ;; Process `while'.
431 (`(while ,test . ,body)
432 ;; Open-code state addition instead of using cps--add-state: we
433 ;; need our states to be self-referential. (That's what makes the
434 ;; state a loop.)
435 (let* ((loop-state
436 (cps--gensym "cps-state-while-"))
437 (eval-loop-condition-state
438 (cps--transform-1 test loop-state))
439 (loop-state-body
440 `(progn
441 (setf ,cps--state-symbol
442 (if ,cps--value-symbol
443 ,(cps--transform-1
444 `(progn ,@body)
445 eval-loop-condition-state)
446 ,next-state)))))
447 (push (list loop-state loop-state-body cps--cleanup-function)
448 cps--states)
449 (push loop-state cps--bindings)
450 eval-loop-condition-state))
452 ;; Process various kinds of `quote'.
454 (`(quote ,arg) (cps--add-state "quote"
455 `(setf ,cps--value-symbol (quote ,arg)
456 ,cps--state-symbol ,next-state)))
457 (`(function ,arg) (cps--add-state "function"
458 `(setf ,cps--value-symbol (function ,arg)
459 ,cps--state-symbol ,next-state)))
461 ;; Deal with `iter-yield'.
463 (`(cps-internal-yield ,value)
464 (cps--transform-1
465 value
466 (cps--add-state "iter-yield"
467 `(progn
468 (setf ,cps--state-symbol
469 ,(if cps--cleanup-function
470 (cps--add-state "after-yield"
471 `(setf ,cps--state-symbol ,next-state))
472 next-state))
473 (throw 'cps--yield ,cps--value-symbol)))))
475 ;; Catch any unhandled special forms.
477 ((and `(,name . ,_)
478 (guard (cps--special-form-p name))
479 (guard (not (memq name cps-standard-special-forms))))
480 name ; Shut up byte compiler
481 (error "special form %S incorrect or not supported" form))
483 ;; Process regular function applications with nontrivial
484 ;; parameters, converting them to applications of trivial
485 ;; let-bound parameters.
487 ((and `(,function . ,arguments)
488 (guard (not (cl-loop for argument in arguments
489 always (atom argument)))))
490 (let ((argument-symbols
491 (cl-loop for argument in arguments
492 collect (if (atom argument)
493 argument
494 (cps--gensym "cps-argument-")))))
496 (cps--transform-1
497 `(let* ,(cl-loop for argument in arguments
498 for argument-symbol in argument-symbols
499 unless (eq argument argument-symbol)
500 collect (list argument-symbol argument))
501 ,(cons function argument-symbols))
502 next-state)))
504 ;; Process everything else by just evaluating the form normally.
505 (_ (cps--make-atomic-state form next-state))))
507 (defun cps--make-catch-wrapper (tag-binding next-state)
508 (lambda (form)
509 (let ((normal-exit-symbol
510 (cps--gensym "cps-normal-exit-from-catch-")))
511 `(let (,normal-exit-symbol)
512 (prog1
513 (catch ,tag-binding
514 (prog1
515 ,form
516 (setf ,normal-exit-symbol t)))
517 (unless ,normal-exit-symbol
518 (setf ,cps--state-symbol ,next-state)))))))
520 (defun cps--make-condition-wrapper (var next-state handlers)
521 ;; Each handler is both one of the transformers with which we wrap
522 ;; evaluated atomic forms and a state to which we jump when we
523 ;; encounter the given error.
525 (let* ((error-symbol (cps--add-binding "condition-case-error"))
526 (lexical-error-symbol (cps--gensym "cps-lexical-error-"))
527 (processed-handlers
528 (cl-loop for (condition . body) in handlers
529 collect (cons condition
530 (cps--transform-1
531 (cps--replace-variable-references
532 var error-symbol
533 `(progn ,@body))
534 next-state)))))
536 (lambda (form)
537 `(condition-case
538 ,lexical-error-symbol
539 ,form
540 ,@(cl-loop
541 for (condition . error-state) in processed-handlers
542 collect
543 `(,condition
544 (setf ,error-symbol
545 ,lexical-error-symbol
546 ,cps--state-symbol
547 ,error-state)))))))
549 (defun cps--replace-variable-references (var new-var form)
550 "Replace all non-shadowed references to VAR with NEW-VAR in FORM.
551 This routine does not modify FORM. Instead, it returns a
552 modified copy."
553 (macroexpand-all
554 `(cl-symbol-macrolet ((,var ,new-var)) ,form)
555 macroexpand-all-environment))
557 (defun cps--make-unwind-wrapper (unwind-forms)
558 (cl-assert lexical-binding)
559 (lambda (form)
560 (let ((normal-exit-symbol
561 (cps--gensym "cps-normal-exit-from-unwind-")))
562 `(let (,normal-exit-symbol)
563 (unwind-protect
564 (prog1
565 ,form
566 (setf ,normal-exit-symbol t))
567 (unless ,normal-exit-symbol
568 ,@unwind-forms))))))
570 (put 'iter-end-of-sequence 'error-conditions '(iter-end-of-sequence))
571 (put 'iter-end-of-sequence 'error-message "iteration terminated")
573 (defun cps--make-close-iterator-form (terminal-state)
574 (if cps--cleanup-table-symbol
575 `(let ((cleanup (cdr (assq ,cps--state-symbol ,cps--cleanup-table-symbol))))
576 (setf ,cps--state-symbol ,terminal-state
577 ,cps--value-symbol nil)
578 (when cleanup (funcall cleanup)))
579 `(setf ,cps--state-symbol ,terminal-state
580 ,cps--value-symbol nil)))
582 (defun cps-generate-evaluator (body)
583 (let* (cps--states
584 cps--bindings
585 cps--cleanup-function
586 (cps--value-symbol (cps--gensym "cps-current-value-"))
587 (cps--state-symbol (cps--gensym "cps-current-state-"))
588 ;; We make *cps-cleanup-table-symbol** non-nil when we notice
589 ;; that we have cleanup processing to perform.
590 (cps--cleanup-table-symbol nil)
591 (terminal-state (cps--add-state "terminal"
592 `(signal 'iter-end-of-sequence
593 ,cps--value-symbol)))
594 (initial-state (cps--transform-1
595 (macroexpand-all
596 `(cl-macrolet
597 ((iter-yield (value)
598 `(cps-internal-yield ,value)))
599 ,@body)
600 macroexpand-all-environment)
601 terminal-state))
602 (finalizer-symbol
603 (when cps--cleanup-table-symbol
604 (when cps--cleanup-table-symbol
605 (cps--gensym "cps-iterator-finalizer-")))))
606 `(let ,(append (list cps--state-symbol cps--value-symbol)
607 (when cps--cleanup-table-symbol
608 (list cps--cleanup-table-symbol))
609 (when finalizer-symbol
610 (list finalizer-symbol))
611 (nreverse cps--bindings))
612 ;; Order state list so that cleanup states are always defined
613 ;; before they're referenced.
614 ,@(cl-loop for (state body cleanup) in (nreverse cps--states)
615 collect `(setf ,state (lambda () ,body))
616 when cleanup
617 do (cl-assert cps--cleanup-table-symbol)
618 and collect `(push (cons ,state ,cleanup) ,cps--cleanup-table-symbol))
619 (setf ,cps--state-symbol ,initial-state)
621 (let ((iterator
622 (lambda (op value)
623 (cond
624 ,@(when finalizer-symbol
625 `(((eq op :stash-finalizer)
626 (setf ,finalizer-symbol value))
627 ((eq op :get-finalizer)
628 ,finalizer-symbol)))
629 ((eq op :close)
630 ,(cps--make-close-iterator-form terminal-state))
631 ((eq op :next)
632 (setf ,cps--value-symbol value)
633 (let ((yielded nil))
634 (unwind-protect
635 (prog1
636 (catch 'cps--yield
637 (while t
638 (funcall ,cps--state-symbol)))
639 (setf yielded t))
640 (unless yielded
641 ;; If we're exiting non-locally (error, quit,
642 ;; etc.) close the iterator.
643 ,(cps--make-close-iterator-form terminal-state)))))
644 (t (error "unknown iterator operation %S" op))))))
645 ,(when finalizer-symbol
646 `(funcall iterator
647 :stash-finalizer
648 (make-finalizer
649 (lambda ()
650 (iter-close iterator)))))
651 iterator))))
653 (defun iter-yield (value)
654 "When used inside a generator, yield control to caller.
655 The caller of `iter-next' receives VALUE, and the next call to
656 `iter-next' resumes execution at the previous
657 `iter-yield' point."
658 (identity value)
659 (error "`iter-yield' used outside a generator"))
661 (defmacro iter-yield-from (value)
662 "When used inside a generator function, delegate to a sub-iterator.
663 The values that the sub-iterator yields are passed directly to
664 the caller, and values supplied to `iter-next' are sent to the
665 sub-iterator. `iter-yield-from' evaluates to the value that the
666 sub-iterator function returns via `iter-end-of-sequence'."
667 (let ((errsym (cps--gensym "yield-from-result"))
668 (valsym (cps--gensym "yield-from-value")))
669 `(let ((,valsym ,value))
670 (unwind-protect
671 (condition-case ,errsym
672 (let ((vs nil))
673 (while t
674 (setf vs (iter-yield (iter-next ,valsym vs)))))
675 (iter-end-of-sequence (cdr ,errsym)))
676 (iter-close ,valsym)))))
678 (defmacro iter-defun (name arglist &rest body)
679 "Creates a generator NAME.
680 When called as a function, NAME returns an iterator value that
681 encapsulates the state of a computation that produces a sequence
682 of values. Callers can retrieve each value using `iter-next'."
683 (declare (indent defun)
684 (debug (&define name lambda-list lambda-doc def-body))
685 (doc-string 3))
686 (cl-assert lexical-binding)
687 (let* ((parsed-body (macroexp-parse-body body))
688 (declarations (car parsed-body))
689 (exps (cdr parsed-body)))
690 `(defun ,name ,arglist
691 ,@declarations
692 ,(cps-generate-evaluator exps))))
694 (defmacro iter-lambda (arglist &rest body)
695 "Return a lambda generator.
696 `iter-lambda' is to `iter-defun' as `lambda' is to `defun'."
697 (declare (indent defun)
698 (debug (&define lambda-list lambda-doc def-body)))
699 (cl-assert lexical-binding)
700 `(lambda ,arglist
701 ,(cps-generate-evaluator body)))
703 (defun iter-next (iterator &optional yield-result)
704 "Extract a value from an iterator.
705 YIELD-RESULT becomes the return value of `iter-yield' in the
706 context of the generator.
708 This routine raises the `iter-end-of-sequence' condition if the
709 iterator cannot supply more values."
710 (funcall iterator :next yield-result))
712 (defun iter-close (iterator)
713 "Terminate an iterator early.
714 Run any unwind-protect handlers in scope at the point ITERATOR
715 is blocked."
716 (funcall iterator :close nil))
718 (cl-defmacro iter-do ((var iterator) &rest body)
719 "Loop over values from an iterator.
720 Evaluate BODY with VAR bound to each value from ITERATOR.
721 Return the value with which ITERATOR finished iteration."
722 (declare (indent 1)
723 (debug ((symbolp form) body)))
724 (let ((done-symbol (cps--gensym "iter-do-iterator-done"))
725 (condition-symbol (cps--gensym "iter-do-condition"))
726 (it-symbol (cps--gensym "iter-do-iterator"))
727 (result-symbol (cps--gensym "iter-do-result")))
728 `(let (,var
729 ,result-symbol
730 (,done-symbol nil)
731 (,it-symbol ,iterator))
732 (while (not ,done-symbol)
733 (condition-case ,condition-symbol
734 (setf ,var (iter-next ,it-symbol))
735 (iter-end-of-sequence
736 (setf ,result-symbol (cdr ,condition-symbol))
737 (setf ,done-symbol t)))
738 (unless ,done-symbol ,@body))
739 ,result-symbol)))
741 (defvar cl--loop-args)
743 (defmacro cps--advance-for (conscell)
744 ;; See cps--handle-loop-for
745 `(condition-case nil
746 (progn
747 (setcar ,conscell (iter-next (cdr ,conscell)))
748 ,conscell)
749 (iter-end-of-sequence
750 nil)))
752 (defmacro cps--initialize-for (iterator)
753 ;; See cps--handle-loop-for
754 (let ((cs (cps--gensym "cps--loop-temp")))
755 `(let ((,cs (cons nil ,iterator)))
756 (cps--advance-for ,cs))))
758 (defun cps--handle-loop-for (var)
759 "Support `iter-by' in `loop'. "
760 ;; N.B. While the cl-loop-for-handler is a documented interface,
761 ;; there's no documented way for cl-loop-for-handler callbacks to do
762 ;; anything useful! Additionally, cl-loop currently lexbinds useful
763 ;; internal variables, so our only option is to modify
764 ;; cl--loop-args. If we substitute a general-purpose for-clause for
765 ;; our iterating clause, however, we can't preserve the
766 ;; parallel-versus-sequential `loop' semantics for for clauses ---
767 ;; we need a terminating condition as well, which requires us to use
768 ;; while, and inserting a while would break and-sequencing.
770 ;; To work around this problem, we actually use the "for var in LIST
771 ;; by FUNCTION" syntax, creating a new fake list each time through
772 ;; the loop, this "list" being a cons cell (val . it).
773 (let ((it-form (pop cl--loop-args)))
774 (setf cl--loop-args
775 (append
776 `(for ,var
777 in (cps--initialize-for ,it-form)
778 by 'cps--advance-for)
779 cl--loop-args))))
781 (put 'iter-by 'cl-loop-for-handler 'cps--handle-loop-for)
783 (eval-after-load 'elisp-mode
784 (lambda ()
785 (font-lock-add-keywords
786 'emacs-lisp-mode
787 '(("(\\(iter-defun\\)\\_>\\s *\\(\\(?:\\sw\\|\\s_\\)+\\)?"
788 (1 font-lock-keyword-face nil t)
789 (2 font-lock-function-name-face nil t))
790 ("(\\(iter-\\(?:next\\|lambda\\|yield\\|yield-from\\)\\)\\_>"
791 (1 font-lock-keyword-face nil t))))))
793 (provide 'generator)
795 ;;; generator.el ends here