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