Rename globals in generator.el
[emacs.git] / lisp / emacs-lisp / generator.el
blobd41f13e29cae60ef99d196516e9912e49917c291
1 ;;; generator.el --- generators -*- lexical-binding: t -*-
3 ;;; Copyright (C) 2015 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 <http://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 facilties 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 soem 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)
80 (require 'pcase)
82 (defvar cps--bindings nil)
83 (defvar cps--states nil)
84 (defvar cps--value-symbol nil)
85 (defvar cps--state-symbol nil)
86 (defvar cps--cleanup-table-symbol nil)
87 (defvar cps--cleanup-function nil)
89 (defvar cps--dynamic-wrappers '(identity)
90 "List of transformer functions to apply to atomic forms we
91 evaluate in CPS context.")
93 (defconst cps-standard-special-forms
94 '(setq setq-default throw interactive)
95 "List of special forms that we treat just like ordinary
96 function applications." )
98 (defun cps--trace-funcall (func &rest args)
99 (message "%S: args=%S" func args)
100 (let ((result (apply func args)))
101 (message "%S: result=%S" func result)
102 result))
104 (defun cps--trace (fmt &rest args)
105 (princ (apply #'format (concat fmt "\n") args)))
107 (defun cps--special-form-p (definition)
108 "Non-nil if and only if DEFINITION is a special form."
109 ;; Copied from ad-special-form-p
110 (if (and (symbolp definition) (fboundp definition))
111 (setf definition (indirect-function definition)))
112 (and (subrp definition) (eq (cdr (subr-arity definition)) 'unevalled)))
114 (defmacro cps--define-unsupported (function)
115 `(defun ,(intern (format "cps--transform-%s" function))
116 (error "%s not supported in generators" ,function)))
118 (defmacro cps--with-value-wrapper (wrapper &rest body)
119 "Continue generating CPS code with an atomic-form wrapper
120 to the current stack of such wrappers. WRAPPER is a function that
121 takes a form and returns a wrapped form.
123 Whenever we generate an atomic form (i.e., a form that can't
124 iter-yield), we first (before actually inserting that form in our
125 generated code) pass that form through all the transformer
126 functions. We use this facility to wrap forms that can transfer
127 control flow non-locally in goo that diverts this control flow to
128 the CPS state machinery.
130 (declare (indent 1))
131 `(let ((cps--dynamic-wrappers
132 (cons
133 ,wrapper
134 cps--dynamic-wrappers)))
135 ,@body))
137 (defun cps--make-dynamic-binding-wrapper (dynamic-var static-var)
138 (cl-assert lexical-binding)
139 (lambda (form)
140 `(let ((,dynamic-var ,static-var))
141 (unwind-protect ; Update the static shadow after evaluation is done
142 ,form
143 (setf ,static-var ,dynamic-var))
144 ,form)))
146 (defmacro cps--with-dynamic-binding (dynamic-var static-var &rest body)
147 "Evaluate BODY such that generated atomic evaluations run with
148 DYNAMIC-VAR bound to STATIC-VAR."
149 (declare (indent 2))
150 `(cps--with-value-wrapper
151 (cps--make-dynamic-binding-wrapper ,dynamic-var ,static-var)
152 ,@body))
154 (defun cps--add-state (kind body)
155 "Create a new CPS state with body BODY and return the state's name."
156 (declare (indent 1))
157 (let* ((state (cl-gensym (format "cps-state-%s-" kind))))
158 (push (list state body cps--cleanup-function) cps--states)
159 (push state cps--bindings)
160 state))
162 (defun cps--add-binding (original-name)
163 (car (push (cl-gensym (format "cps-binding-%s-" original-name))
164 cps--bindings)))
166 (defun cps--find-special-form-handler (form)
167 (let* ((handler-name (format "cps--transform-%s" (car-safe form)))
168 (handler (intern-soft handler-name)))
169 (and (fboundp handler) handler)))
171 (defvar cps-disable-atomic-optimization nil
172 "When t, always rewrite forms into cps even when they
173 don't yield.")
175 (defvar cps--yield-seen)
177 (defun cps--atomic-p (form)
178 "Return whether the given form never yields."
180 (and (not cps-disable-atomic-optimization)
181 (let* ((cps--yield-seen))
182 (ignore (macroexpand-all
183 `(cl-macrolet ((cps-internal-yield
184 (_val)
185 (setf cps--yield-seen t)))
186 ,form)))
187 (not cps--yield-seen))))
189 (defun cps--make-atomic-state (form next-state)
190 (let ((tform `(prog1 ,form (setf ,cps--state-symbol ,next-state))))
191 (cl-loop for wrapper in cps--dynamic-wrappers
192 do (setf tform (funcall wrapper tform)))
193 ;; Bind cps--cleanup-function to nil here because the wrapper
194 ;; function mechanism is responsible for cleanup here, not the
195 ;; generic cleanup mechanism. If we didn't make this binding,
196 ;; we'd run cleanup handlers twice on anything that made it out
197 ;; to toplevel.
198 (let ((cps--cleanup-function nil))
199 (cps--add-state "atom"
200 `(setf ,cps--value-symbol ,tform)))))
202 (defun cps--transform-1 (form next-state)
203 (pcase form
205 ;; If we're looking at an "atomic" form (i.e., one that does not
206 ;; iter-yield), just evaluate the form as a whole instead of rewriting
207 ;; it into CPS.
209 ((guard (cps--atomic-p form))
210 (cps--make-atomic-state form next-state))
212 ;; Process `and'.
214 (`(and) ; (and) -> t
215 (cps--transform-1 t next-state))
216 (`(and ,condition) ; (and CONDITION) -> CONDITION
217 (cps--transform-1 condition next-state))
218 (`(and ,condition . ,rest)
219 ;; Evaluate CONDITION; if it's true, go on to evaluate the rest
220 ;; of the `and'.
221 (cps--transform-1
222 condition
223 (cps--add-state "and"
224 `(setf ,cps--state-symbol
225 (if ,cps--value-symbol
226 ,(cps--transform-1 `(and ,@rest)
227 next-state)
228 ,next-state)))))
230 ;; Process `catch'.
232 (`(catch ,tag . ,body)
233 (let ((tag-binding (cps--add-binding "catch-tag")))
234 (cps--transform-1 tag
235 (cps--add-state "cps-update-tag"
236 `(setf ,tag-binding ,cps--value-symbol
237 ,cps--state-symbol
238 ,(cps--with-value-wrapper
239 (cps--make-catch-wrapper
240 tag-binding next-state)
241 (cps--transform-1 `(progn ,@body)
242 next-state)))))))
244 ;; Process `cond': transform into `if' or `or' depending on the
245 ;; precise kind of the condition we're looking at.
247 (`(cond) ; (cond) -> nil
248 (cps--transform-1 nil next-state))
249 (`(cond (,condition) . ,rest)
250 (cps--transform-1 `(or ,condition (cond ,@rest))
251 next-state))
252 (`(cond (,condition . ,body) . ,rest)
253 (cps--transform-1 `(if ,condition
254 (progn ,@body)
255 (cond ,@rest))
256 next-state))
258 ;; Process `condition-case': do the heavy lifting in a helper
259 ;; function.
261 (`(condition-case ,var ,bodyform . ,handlers)
262 (cps--with-value-wrapper
263 (cps--make-condition-wrapper var next-state handlers)
264 (cps--transform-1 bodyform
265 next-state)))
267 ;; Process `if'.
269 (`(if ,cond ,then . ,else)
270 (cps--transform-1 cond
271 (cps--add-state "if"
272 `(setf ,cps--state-symbol
273 (if ,cps--value-symbol
274 ,(cps--transform-1 then
275 next-state)
276 ,(cps--transform-1 `(progn ,@else)
277 next-state))))))
279 ;; Process `progn' and `inline': they are identical except for the
280 ;; name, which has some significance to the byte compiler.
282 (`(inline) (cps--transform-1 nil next-state))
283 (`(inline ,form) (cps--transform-1 form next-state))
284 (`(inline ,form . ,rest)
285 (cps--transform-1 form
286 (cps--transform-1 `(inline ,@rest)
287 next-state)))
289 (`(progn) (cps--transform-1 nil next-state))
290 (`(progn ,form) (cps--transform-1 form next-state))
291 (`(progn ,form . ,rest)
292 (cps--transform-1 form
293 (cps--transform-1 `(progn ,@rest)
294 next-state)))
296 ;; Process `let' in a helper function that transforms it into a
297 ;; let* with temporaries.
299 (`(let ,bindings . ,body)
300 (let* ((bindings (cl-loop for binding in bindings
301 collect (if (symbolp binding)
302 (list binding nil)
303 binding)))
304 (temps (cl-loop for (var value-form) in bindings
305 collect (cps--add-binding var))))
306 (cps--transform-1
307 `(let* ,(append
308 (cl-loop for (var value-form) in bindings
309 for temp in temps
310 collect (list temp value-form))
311 (cl-loop for (var binding) in bindings
312 for temp in temps
313 collect (list var temp)))
314 ,@body)
315 next-state)))
317 ;; Process `let*' binding: process one binding at a time. Flatten
318 ;; lexical bindings.
320 (`(let* () . ,body)
321 (cps--transform-1 `(progn ,@body) next-state))
323 (`(let* (,binding . ,more-bindings) . ,body)
324 (let* ((var (if (symbolp binding) binding (car binding)))
325 (value-form (car (cdr-safe binding)))
326 (new-var (cps--add-binding var)))
328 (cps--transform-1
329 value-form
330 (cps--add-state "let*"
331 `(setf ,new-var ,cps--value-symbol
332 ,cps--state-symbol
333 ,(if (or (not lexical-binding) (special-variable-p var))
334 (cps--with-dynamic-binding var new-var
335 (cps--transform-1
336 `(let* ,more-bindings ,@body)
337 next-state))
338 (cps--transform-1
339 (cps--replace-variable-references
340 var new-var
341 `(let* ,more-bindings ,@body))
342 next-state)))))))
344 ;; Process `or'.
346 (`(or) (cps--transform-1 nil next-state))
347 (`(or ,condition) (cps--transform-1 condition next-state))
348 (`(or ,condition . ,rest)
349 (cps--transform-1
350 condition
351 (cps--add-state "or"
352 `(setf ,cps--state-symbol
353 (if ,cps--value-symbol
354 ,next-state
355 ,(cps--transform-1
356 `(or ,@rest) next-state))))))
358 ;; Process `prog1'.
360 (`(prog1 ,first) (cps--transform-1 first next-state))
361 (`(prog1 ,first . ,body)
362 (cps--transform-1
363 first
364 (let ((temp-var-symbol (cps--add-binding "prog1-temp")))
365 (cps--add-state "prog1"
366 `(setf ,temp-var-symbol
367 ,cps--value-symbol
368 ,cps--state-symbol
369 ,(cps--transform-1
370 `(progn ,@body)
371 (cps--add-state "prog1inner"
372 `(setf ,cps--value-symbol ,temp-var-symbol
373 ,cps--state-symbol ,next-state))))))))
375 ;; Process `prog2'.
377 (`(prog2 ,form1 ,form2 . ,body)
378 (cps--transform-1
379 `(progn ,form1 (prog1 ,form2 ,@body))
380 next-state))
382 ;; Process `unwind-protect': If we're inside an unwind-protect, we
383 ;; have a block of code UNWINDFORMS which we would like to run
384 ;; whenever control flows away from the main piece of code,
385 ;; BODYFORM. We deal with the local control flow case by
386 ;; generating BODYFORM such that it yields to a continuation that
387 ;; executes UNWINDFORMS, which then yields to NEXT-STATE.
389 ;; Non-local control flow is trickier: we need to ensure that we
390 ;; execute UNWINDFORMS even when control bypasses our normal
391 ;; continuation. To make this guarantee, we wrap every external
392 ;; application (i.e., every piece of elisp that can transfer
393 ;; control non-locally) in an unwind-protect that runs UNWINDFORMS
394 ;; before allowing the non-local control transfer to proceed.
396 ;; Unfortunately, because elisp lacks a mechanism for generically
397 ;; capturing the reason for an arbitrary non-local control
398 ;; transfer and restarting the transfer at a later point, we
399 ;; cannot reify non-local transfers and cannot allow
400 ;; continuation-passing code inside UNWINDFORMS.
402 (`(unwind-protect ,bodyform . ,unwindforms)
403 ;; Signal the evaluator-generator that it needs to generate code
404 ;; to handle cleanup forms.
405 (unless cps--cleanup-table-symbol
406 (setf cps--cleanup-table-symbol (cl-gensym "cps-cleanup-table-")))
407 (let* ((unwind-state
408 (cps--add-state
409 "unwind"
410 ;; N.B. It's safe to just substitute unwindforms by
411 ;; sexp-splicing: we've already replaced all variable
412 ;; references inside it with lifted equivalents.
413 `(progn
414 ,@unwindforms
415 (setf ,cps--state-symbol ,next-state))))
416 (old-cleanup cps--cleanup-function)
417 (cps--cleanup-function
418 (let ((cps--cleanup-function nil))
419 (cps--add-state "cleanup"
420 `(progn
421 ,(when old-cleanup `(funcall ,old-cleanup))
422 ,@unwindforms)))))
423 (cps--with-value-wrapper
424 (cps--make-unwind-wrapper unwindforms)
425 (cps--transform-1 bodyform unwind-state))))
427 ;; Process `while'.
429 (`(while ,test . ,body)
430 ;; Open-code state addition instead of using cps--add-state: we
431 ;; need our states to be self-referential. (That's what makes the
432 ;; state a loop.)
433 (let* ((loop-state
434 (cl-gensym "cps-state-while-"))
435 (eval-loop-condition-state
436 (cps--transform-1 test loop-state))
437 (loop-state-body
438 `(progn
439 (setf ,cps--state-symbol
440 (if ,cps--value-symbol
441 ,(cps--transform-1
442 `(progn ,@body)
443 eval-loop-condition-state)
444 ,next-state)))))
445 (push (list loop-state loop-state-body cps--cleanup-function)
446 cps--states)
447 (push loop-state cps--bindings)
448 eval-loop-condition-state))
450 ;; Process various kinds of `quote'.
452 (`(quote ,arg) (cps--add-state "quote"
453 `(setf ,cps--value-symbol (quote ,arg)
454 ,cps--state-symbol ,next-state)))
455 (`(function ,arg) (cps--add-state "function"
456 `(setf ,cps--value-symbol (function ,arg)
457 ,cps--state-symbol ,next-state)))
459 ;; Deal with `iter-yield'.
461 (`(cps-internal-yield ,value)
462 (cps--transform-1
463 value
464 (cps--add-state "iter-yield"
465 `(progn
466 (setf ,cps--state-symbol
467 ,(if cps--cleanup-function
468 (cps--add-state "after-yield"
469 `(setf ,cps--state-symbol ,next-state))
470 next-state))
471 (throw 'cps--yield ,cps--value-symbol)))))
473 ;; Catch any unhandled special forms.
475 ((and `(,name . ,_)
476 (guard (cps--special-form-p name))
477 (guard (not (memq name cps-standard-special-forms))))
478 name ; Shut up byte compiler
479 (error "special form %S incorrect or not supported" form))
481 ;; Process regular function applications with nontrivial
482 ;; parameters, converting them to applications of trivial
483 ;; let-bound parameters.
485 ((and `(,function . ,arguments)
486 (guard (not (cl-loop for argument in arguments
487 always (atom argument)))))
488 (let ((argument-symbols
489 (cl-loop for argument in arguments
490 collect (if (atom argument)
491 argument
492 (cl-gensym "cps-argument-")))))
494 (cps--transform-1
495 `(let* ,(cl-loop for argument in arguments
496 for argument-symbol in argument-symbols
497 unless (eq argument argument-symbol)
498 collect (list argument-symbol argument))
499 ,(cons function argument-symbols))
500 next-state)))
502 ;; Process everything else by just evaluating the form normally.
503 (t (cps--make-atomic-state form next-state))))
505 (defun cps--make-catch-wrapper (tag-binding next-state)
506 (lambda (form)
507 (let ((normal-exit-symbol
508 (cl-gensym "cps-normal-exit-from-catch-")))
509 `(let (,normal-exit-symbol)
510 (prog1
511 (catch ,tag-binding
512 (prog1
513 ,form
514 (setf ,normal-exit-symbol t)))
515 (unless ,normal-exit-symbol
516 (setf ,cps--state-symbol ,next-state)))))))
518 (defun cps--make-condition-wrapper (var next-state handlers)
519 ;; Each handler is both one of the transformers with which we wrap
520 ;; evaluated atomic forms and a state to which we jump when we
521 ;; encounter the given error.
523 (let* ((error-symbol (cps--add-binding "condition-case-error"))
524 (lexical-error-symbol (cl-gensym "cps-lexical-error-"))
525 (processed-handlers
526 (cl-loop for (condition . body) in handlers
527 collect (cons condition
528 (cps--transform-1
529 (cps--replace-variable-references
530 var error-symbol
531 `(progn ,@body))
532 next-state)))))
534 (lambda (form)
535 `(condition-case
536 ,lexical-error-symbol
537 ,form
538 ,@(cl-loop
539 for (condition . error-state) in processed-handlers
540 collect
541 `(,condition
542 (setf ,error-symbol
543 ,lexical-error-symbol
544 ,cps--state-symbol
545 ,error-state)))))))
547 (defun cps--replace-variable-references (var new-var form)
548 "Replace all non-shadowed references to VAR with NEW-VAR in FORM.
549 This routine does not modify FORM. Instead, it returns a
550 modified copy."
551 (macroexpand-all
552 `(cl-symbol-macrolet ((,var ,new-var)) ,form)))
554 (defun cps--make-unwind-wrapper (unwind-forms)
555 (cl-assert lexical-binding)
556 (lambda (form)
557 (let ((normal-exit-symbol
558 (cl-gensym "cps-normal-exit-from-unwind-")))
559 `(let (,normal-exit-symbol)
560 (unwind-protect
561 (prog1
562 ,form
563 (setf ,normal-exit-symbol t))
564 (unless ,normal-exit-symbol
565 ,@unwind-forms))))))
567 (put 'iter-end-of-sequence 'error-conditions '(iter-end-of-sequence))
568 (put 'iter-end-of-sequence 'error-message "iteration terminated")
570 (defun cps--make-close-iterator-form (terminal-state)
571 (if cps--cleanup-table-symbol
572 `(let ((cleanup (cdr (assq ,cps--state-symbol ,cps--cleanup-table-symbol))))
573 (setf ,cps--state-symbol ,terminal-state
574 ,cps--value-symbol nil)
575 (when cleanup (funcall cleanup)))
576 `(setf ,cps--state-symbol ,terminal-state
577 ,cps--value-symbol nil)))
579 (defun cps-generate-evaluator (form)
580 (let* (cps--states
581 cps--bindings
582 cps--cleanup-function
583 (cps--value-symbol (cl-gensym "cps-current-value-"))
584 (cps--state-symbol (cl-gensym "cps-current-state-"))
585 ;; We make *cps-cleanup-table-symbol** non-nil when we notice
586 ;; that we have cleanup processing to perform.
587 (cps--cleanup-table-symbol nil)
588 (terminal-state (cps--add-state "terminal"
589 `(signal 'iter-end-of-sequence
590 ,cps--value-symbol)))
591 (initial-state (cps--transform-1
592 (macroexpand-all form)
593 terminal-state))
594 (finalizer-symbol
595 (when cps--cleanup-table-symbol
596 (when cps--cleanup-table-symbol
597 (cl-gensym "cps-iterator-finalizer-")))))
598 `(let ,(append (list cps--state-symbol cps--value-symbol)
599 (when cps--cleanup-table-symbol
600 (list cps--cleanup-table-symbol))
601 (when finalizer-symbol
602 (list finalizer-symbol))
603 (nreverse cps--bindings))
604 ;; Order state list so that cleanup states are always defined
605 ;; before they're referenced.
606 ,@(cl-loop for (state body cleanup) in (nreverse cps--states)
607 collect `(setf ,state (lambda () ,body))
608 when cleanup
609 do (cl-assert cps--cleanup-table-symbol)
610 and collect `(push (cons ,state ,cleanup) ,cps--cleanup-table-symbol))
611 (setf ,cps--state-symbol ,initial-state)
613 (let ((iterator
614 (lambda (op value)
615 (cond
616 ,@(when finalizer-symbol
617 `(((eq op :stash-finalizer)
618 (setf ,finalizer-symbol value))
619 ((eq op :get-finalizer)
620 ,finalizer-symbol)))
621 ((eq op :close)
622 ,(cps--make-close-iterator-form terminal-state))
623 ((eq op :next)
624 (setf ,cps--value-symbol value)
625 (let ((yielded nil))
626 (unwind-protect
627 (prog1
628 (catch 'cps--yield
629 (while t
630 (funcall ,cps--state-symbol)))
631 (setf yielded t))
632 (unless yielded
633 ;; If we're exiting non-locally (error, quit,
634 ;; etc.) close the iterator.
635 ,(cps--make-close-iterator-form terminal-state)))))
636 (t (error "unknown iterator operation %S" op))))))
637 ,(when finalizer-symbol
638 `(funcall iterator
639 :stash-finalizer
640 (make-finalizer
641 (lambda ()
642 (iter-close iterator)))))
643 iterator))))
645 (defun iter-yield (value)
646 "When used inside a generator, yield control to caller.
647 The caller of `iter-next' receives VALUE, and the next call to
648 `iter-next' resumes execution at the previous
649 `iter-yield' point."
650 (identity value)
651 (error "`iter-yield' used outside a generator"))
653 (defmacro iter-yield-from (value)
654 "When used inside a generator function, delegate to a sub-iterator.
655 The values that the sub-iterator yields are passed directly to
656 the caller, and values supplied to `iter-next' are sent to the
657 sub-iterator. `iter-yield-from' evaluates to the value that the
658 sub-iterator function returns via `iter-end-of-sequence'."
659 (let ((errsym (cl-gensym "yield-from-result"))
660 (valsym (cl-gensym "yield-from-value")))
661 `(let ((,valsym ,value))
662 (unwind-protect
663 (condition-case ,errsym
664 (let ((vs nil))
665 (while t
666 (setf vs (iter-yield (iter-next ,valsym vs)))))
667 (iter-end-of-sequence (cdr ,errsym)))
668 (iter-close ,valsym)))))
670 (defmacro iter-defun (name arglist &rest body)
671 "Creates a generator NAME.
672 When called as a function, NAME returns an iterator value that
673 encapsulates the state of a computation that produces a sequence
674 of values. Callers can retrieve each value using `iter-next'."
675 (declare (indent defun))
676 (cl-assert lexical-binding)
677 (let (preamble)
678 (when (stringp (car body))
679 (push (pop body) preamble))
680 (when (eq (car-safe (car body)) 'declare)
681 (push (pop body) preamble))
682 `(defun ,name ,arglist
683 ,@(nreverse preamble)
684 ,(cps-generate-evaluator
685 `(cl-macrolet ((iter-yield (value) `(cps-internal-yield ,value)))
686 ,@body)))))
688 (defmacro iter-lambda (arglist &rest body)
689 "Return a lambda generator.
690 `iter-lambda' is to `iter-defun' as `lambda' is to `defun'."
691 (declare (indent defun))
692 (cl-assert lexical-binding)
693 `(lambda ,arglist
694 ,(cps-generate-evaluator
695 `(cl-macrolet ((iter-yield (value) `(cps-internal-yield ,value)))
696 ,@body))))
698 (defun iter-next (iterator &optional yield-result)
699 "Extract a value from an iterator.
700 YIELD-RESULT becomes the return value of `iter-yield` in the
701 context of the generator.
703 This routine raises the `iter-end-of-sequence' condition if the
704 iterator cannot supply more values."
705 (funcall iterator :next yield-result))
707 (defun iter-close (iterator)
708 "Terminate an iterator early.
709 Run any unwind-protect handlers in scope at the point ITERATOR
710 is blocked."
711 (funcall iterator :close nil))
713 (cl-defmacro iter-do ((var iterator) &rest body)
714 "Loop over values from an iterator.
715 Evaluate BODY with VAR bound to each value from ITERATOR.
716 Return the value with which ITERATOR finished iteration."
717 (declare (indent 1))
718 (let ((done-symbol (cl-gensym "iter-do-iterator-done"))
719 (condition-symbol (cl-gensym "iter-do-condition"))
720 (it-symbol (cl-gensym "iter-do-iterator"))
721 (result-symbol (cl-gensym "iter-do-result")))
722 `(let (,var
723 ,result-symbol
724 (,done-symbol nil)
725 (,it-symbol ,iterator))
726 (while (not ,done-symbol)
727 (condition-case ,condition-symbol
728 (setf ,var (iter-next ,it-symbol))
729 (iter-end-of-sequence
730 (setf ,result-symbol (cdr ,condition-symbol))
731 (setf ,done-symbol t)))
732 (unless ,done-symbol ,@body))
733 ,result-symbol)))
735 (defvar cl--loop-args)
737 (defmacro cps--advance-for (conscell)
738 ;; See cps--handle-loop-for
739 `(condition-case nil
740 (progn
741 (setcar ,conscell (iter-next (cdr ,conscell)))
742 ,conscell)
743 (iter-end-of-sequence
744 nil)))
746 (defmacro cps--initialize-for (iterator)
747 ;; See cps--handle-loop-for
748 (let ((cs (cl-gensym "cps--loop-temp")))
749 `(let ((,cs (cons nil ,iterator)))
750 (cps--advance-for ,cs))))
752 (defun cps--handle-loop-for (var)
753 "Support `iter-by' in `loop'. "
754 ;; N.B. While the cl-loop-for-handler is a documented interface,
755 ;; there's no documented way for cl-loop-for-handler callbacks to do
756 ;; anything useful! Additionally, cl-loop currently lexbinds useful
757 ;; internal variables, so our only option is to modify
758 ;; cl--loop-args. If we substitute a general-purpose for-clause for
759 ;; our iterating clause, however, we can't preserve the
760 ;; parallel-versus-sequential `loop' semantics for for clauses ---
761 ;; we need a terminating condition as well, which requires us to use
762 ;; while, and inserting a while would break and-sequencing.
764 ;; To work around this problem, we actually use the "for var in LIST
765 ;; by FUNCTION" syntax, creating a new fake list each time through
766 ;; the loop, this "list" being a cons cell (val . it).
767 (let ((it-form (pop cl--loop-args)))
768 (setf cl--loop-args
769 (append
770 `(for ,var
771 in (cps--initialize-for ,it-form)
772 by 'cps--advance-for)
773 cl--loop-args))))
775 (put 'iter-by 'cl-loop-for-handler 'cps--handle-loop-for)
777 (eval-after-load 'elisp-mode
778 (lambda ()
779 (font-lock-add-keywords
780 'emacs-lisp-mode
781 '(("(\\(iter-defun\\)\\_>\\s *\\(\\(?:\\sw\\|\\s_\\)+\\)?"
782 (1 font-lock-keyword-face nil t)
783 (2 font-lock-function-name-face nil t))
784 ("(\\(iter-next\\)\\_>"
785 (1 font-lock-keyword-face nil t))
786 ("(\\(iter-lambda\\)\\_>"
787 (1 font-lock-keyword-face nil t))
788 ("(\\(iter-yield\\)\\_>"
789 (1 font-lock-keyword-face nil t))
790 ("(\\(iter-yield-from\\)\\_>"
791 (1 font-lock-keyword-face nil t))))))
793 (provide 'generator)
795 ;;; generator.el ends here