-@c -*-texinfo-*-
+@c -*- mode: texinfo; coding: utf-8 -*-
@c This is part of the GNU Emacs Lisp Reference Manual.
-@c Copyright (C) 1990-1995, 1998-1999, 2001-2014 Free Software
+@c Copyright (C) 1990-1995, 1998-1999, 2001-2016 Free Software
@c Foundation, Inc.
@c See the file elisp.texi for copying conditions.
@node Control Structures
* Conditionals:: @code{if}, @code{cond}, @code{when}, @code{unless}.
* Combining Conditions:: @code{and}, @code{or}, @code{not}.
* Iteration:: @code{while} loops.
+* Generators:: Generic sequences and coroutines.
* Nonlocal Exits:: Jumping out of a sequence.
@end menu
two or more forms in succession and use the value of the last of them.
But programmers found they often needed to use a @code{progn} in the
body of a function, where (at that time) only one form was allowed. So
-the body of a function was made into an ``implicit @code{progn}'':
+the body of a function was made into an implicit @code{progn}:
several forms are allowed just as in the body of an actual @code{progn}.
Many other control structures likewise contain an implicit @code{progn}.
As a result, @code{progn} is not used as much as it was many years ago.
@code{cond} tries the clauses in textual order, by evaluating the
@var{condition} of each clause. If the value of @var{condition} is
-non-@code{nil}, the clause ``succeeds''; then @code{cond} evaluates its
+non-@code{nil}, the clause succeeds; then @code{cond} evaluates its
@var{body-forms}, and returns the value of the last of @var{body-forms}.
Any remaining clauses are ignored.
-If the value of @var{condition} is @code{nil}, the clause ``fails'', so
+If the value of @var{condition} is @code{nil}, the clause fails, so
the @code{cond} moves on to the following clause, trying its @var{condition}.
A clause may also look like this:
@cindex pcase
@cindex pattern matching
-To compare a particular value against various possible cases, the macro
-@code{pcase} can come handy. It takes the following form:
+The @code{cond} form lets you choose between alternatives using
+predicate conditions that compare values of expressions against
+specific values known and written in advance. However, sometimes it
+is useful to select alternatives based on more general conditions that
+distinguish between broad classes of values. The @code{pcase} macro
+allows you to choose between alternatives based on matching the value
+of an expression against a series of patterns. A pattern can be a
+literal value (for comparisons to literal values you'd use
+@code{cond}), or it can be a more general description of the expected
+structure of the expression's value.
+
+@defmac pcase expression &rest clauses
+Evaluate @var{expression} and choose among an arbitrary number of
+alternatives based on the value of @var{expression}. The possible
+alternatives are specified by @var{clauses}, each of which must be a
+list of the form @code{(@var{pattern} @var{body-forms}@dots{})}.
+@code{pcase} tries to match the value of @var{expression} to the
+@var{pattern} of each clause, in textual order. If the value matches,
+the clause succeeds; @code{pcase} then evaluates its @var{body-forms},
+and returns the value of the last of @var{body-forms}. Any remaining
+@var{clauses} are ignored.
+
+The @var{pattern} part of a clause can be of one of two types:
+@dfn{QPattern}, a pattern quoted with a backquote; or a
+@dfn{UPattern}, which is not quoted. UPatterns are simpler, so we
+describe them first.
+
+Note: In the description of the patterns below, we use ``the value
+being matched'' to refer to the value of the @var{expression} that is
+the first argument of @code{pcase}.
+
+A UPattern can have the following forms:
-@example
-(pcase @var{exp} @var{branch}1 @var{branch}2 @var{branch}3 @dots{})
-@end example
+@table @code
+
+@item '@var{val}
+Matches if the value being matched is @code{equal} to @var{val}.
+@item @var{atom}
+Matches any @var{atom}, which can be a keyword, a number, or a string.
+(These are self-quoting, so this kind of UPattern is actually a
+shorthand for @code{'@var{atom}}.) Note that a string or a float
+matches any string or float with the same contents/value.
+@item _
+Matches any value. This is known as @dfn{don't care} or @dfn{wildcard}.
+@item @var{symbol}
+Matches any value, and additionally let-binds @var{symbol} to the
+value it matched, so that you can later refer to it, either in the
+@var{body-forms} or also later in the pattern.
+@item (pred @var{predfun})
+Matches if the predicate function @var{predfun} returns non-@code{nil}
+when called with the value being matched as its argument.
+@var{predfun} can be one of the possible forms described below.
+@item (guard @var{boolean-expression})
+Matches if @var{boolean-expression} evaluates to non-@code{nil}. This
+allows you to include in a UPattern boolean conditions that refer to
+symbols bound to values (including the value being matched) by
+previous UPatterns. Typically used inside an @code{and} UPattern, see
+below. For example, @w{@code{(and x (guard (< x 10)))}} is a pattern
+which matches any number smaller than 10 and let-binds the variable
+@code{x} to that number.
+@item (let @var{upattern} @var{expression})
+Matches if the specified @var{expression} matches the specified
+@var{upattern}. This allows matching a pattern against the value of
+an @emph{arbitrary} expression, not just the expression that is the
+first argument to @code{pcase}. (It is called @code{let} because
+@var{upattern} can bind symbols to values using the @var{symbol}
+UPattern. For example:
+@w{@code{((or `(key . ,val) (let val 5)) val)}}.)
+@item (app @var{function} @var{upattern})
+Matches if @var{function} applied to the value being matched returns a
+value that matches @var{upattern}. This is like the @code{pred}
+UPattern, except that it tests the result against @var{UPattern},
+rather than against a boolean truth value. The @var{function} call can
+use one of the forms described below.
+@item (or @var{upattern1} @var{upattern2}@dots{})
+Matches if one the argument UPatterns matches. As soon as the first
+matching UPattern is found, the rest are not tested. For this reason,
+if any of the UPatterns let-bind symbols to the matched value, they
+should all bind the same symbols.
+@item (and @var{upattern1} @var{upattern2}@dots{})
+Matches if all the argument UPatterns match.
+@end table
-where each @var{branch} takes the form @code{(@var{upattern}
-@var{body-forms}@dots{})}.
+The function calls used in the @code{pred} and @code{app} UPatterns
+can have one of the following forms:
+
+@table @asis
+@item function symbol, like @code{integerp}
+In this case, the named function is applied to the value being
+matched.
+@item lambda-function @code{(lambda (@var{arg}) @var{body})}
+In this case, the lambda-function is called with one argument, the
+value being matched.
+@item @code{(@var{func} @var{args}@dots{})}
+This is a function call with @var{n} specified arguments; the function
+is called with these @var{n} arguments and an additional @var{n}+1-th
+argument that is the value being matched.
+@end table
-It will first evaluate @var{exp} and then compare the value against each
-@var{upattern} to see which @var{branch} to use, after which it will run the
-corresponding @var{body-forms}. A common use case is to distinguish
-between a few different constant values:
+Here's an illustrative example of using UPatterns:
+@c FIXME: This example should use every one of the UPatterns described
+@c above at least once.
@example
(pcase (get-return-code x)
- (`success (message "Done!"))
- (`would-block (message "Sorry, can't do it now"))
- (`read-only (message "The shmliblick is read-only"))
- (`access-denied (message "You do not have the needed rights"))
+ ('success (message "Done!"))
+ ('would-block (message "Sorry, can't do it now"))
+ ('read-only (message "The shmliblick is read-only"))
+ ('access-denied (message "You do not have the needed rights"))
(code (message "Unknown return code %S" code)))
@end example
-In the last clause, @code{code} is a variable that gets bound to the value that
-was returned by @code{(get-return-code x)}.
+In addition, you can use backquoted patterns that are more powerful.
+They allow matching the value of the @var{expression} that is the
+first argument of @code{pcase} against specifications of its
+@emph{structure}. For example, you can specify that the value must be
+a list of 2 elements whose first element is a specific string and the
+second element is any value with a backquoted pattern like
+@code{`("first" ,second-elem)}.
-To give a more complex example, a simple interpreter for a little
-expression language could look like (note that this example requires
-lexical binding):
+Backquoted patterns have the form @code{`@var{qpattern}} where
+@var{qpattern} can have the following forms:
+
+@table @code
+@item (@var{qpattern1} . @var{qpattern2})
+Matches if the value being matched is a cons cell whose @code{car}
+matches @var{qpattern1} and whose @code{cdr} matches @var{qpattern2}.
+This readily generalizes to backquoted lists as in
+@w{@code{(@var{qpattern1} @var{qpattern2} @dots{})}}.
+@item [@var{qpattern1} @var{qpattern2} @dots{} @var{qpatternm}]
+Matches if the value being matched is a vector of length @var{m} whose
+@code{0}..@code{(@var{m}-1)}th elements match @var{qpattern1},
+@var{qpattern2} @dots{} @var{qpatternm}, respectively.
+@item @var{atom}
+Matches if corresponding element of the value being matched is
+@code{equal} to the specified @var{atom}.
+@item ,@var{upattern}
+Matches if the corresponding element of the value being matched
+matches the specified @var{upattern}.
+@end table
+
+Note that uses of QPatterns can be expressed using only UPatterns, as
+QPatterns are implemented on top of UPatterns using
+@code{pcase-defmacro}, described below. However, using QPatterns will
+in many cases lead to a more readable code.
+@c FIXME: There should be an example here showing how a 'pcase' that
+@c uses QPatterns can be rewritten using UPatterns.
+
+@end defmac
+
+Here is an example of using @code{pcase} to implement a simple
+interpreter for a little expression language (note that this example
+requires lexical binding, @pxref{Lexical Binding}):
@example
(defun evaluate (exp env)
(_ (error "Unknown expression %S" exp))))
@end example
-Where @code{`(add ,x ,y)} is a pattern that checks that @code{exp} is a three
-element list starting with the symbol @code{add}, then extracts the second and
-third elements and binds them to the variables @code{x} and @code{y}.
-@code{(pred numberp)} is a pattern that simply checks that @code{exp}
-is a number, and @code{_} is the catch-all pattern that matches anything.
+Here @code{`(add ,x ,y)} is a pattern that checks that @code{exp} is a
+three-element list starting with the literal symbol @code{add}, then
+extracts the second and third elements and binds them to the variables
+@code{x} and @code{y}. Then it evaluates @code{x} and @code{y} and
+adds the results. The @code{call} and @code{fn} patterns similarly
+implement two flavors of function calls. @code{(pred numberp)} is a
+pattern that simply checks that @code{exp} is a number and if so,
+evaluates it. @code{(pred symbolp)} matches symbols, and returns
+their association. Finally, @code{_} is the catch-all pattern that
+matches anything, so it's suitable for reporting syntax errors.
-Here are some sample programs including their evaluation results:
+Here are some sample programs in this small language, including their
+evaluation results:
@example
(evaluate '(add 1 2) nil) ;=> 3
(evaluate '(sub 1 2) nil) ;=> error
@end example
-There are two kinds of patterns involved in @code{pcase}, called
-@emph{U-patterns} and @emph{Q-patterns}. The @var{upattern} mentioned above
-are U-patterns and can take the following forms:
+Additional UPatterns can be defined using the @code{pcase-defmacro}
+macro.
-@table @code
-@item `@var{qpattern}
-This is one of the most common form of patterns. The intention is to mimic the
-backquote macro: this pattern matches those values that could have been built
-by such a backquote expression. Since we're pattern matching rather than
-building a value, the unquote does not indicate where to plug an expression,
-but instead it lets one specify a U-pattern that should match the value at
-that location.
-
-More specifically, a Q-pattern can take the following forms:
-@table @code
-@item (@var{qpattern1} . @var{qpattern2})
-This pattern matches any cons cell whose @code{car} matches @var{QPATTERN1} and
-whose @code{cdr} matches @var{PATTERN2}.
-@item [@var{qpattern1} @var{qpattern2} @dots{} @var{qpatternm}]
-This pattern matches a vector of length @var{M} whose 0..(@var{M}-1)th
-elements match @var{qpattern1}, @var{qpattern2} @dots{} @var{qpatternm},
-respectively.
-@item @var{atom}
-This pattern matches any atom @code{equal} to @var{atom}.
-@item ,@var{upattern}
-This pattern matches any object that matches the @var{upattern}.
-@end table
-
-@item @var{symbol}
-A mere symbol in a U-pattern matches anything, and additionally let-binds this
-symbol to the value that it matched, so that you can later refer to it, either
-in the @var{body-forms} or also later in the pattern.
-@item _
-This so-called @emph{don't care} pattern matches anything, like the previous
-one, but unlike symbol patterns it does not bind any variable.
-@item (pred @var{pred})
-This pattern matches if the function @var{pred} returns non-@code{nil} when
-called with the object being matched.
-@item (or @var{upattern1} @var{upattern2}@dots{})
-This pattern matches as soon as one of the argument patterns succeeds.
-All argument patterns should let-bind the same variables.
-@item (and @var{upattern1} @var{upattern2}@dots{})
-This pattern matches only if all the argument patterns succeed.
-@item (guard @var{exp})
-This pattern ignores the object being examined and simply succeeds if @var{exp}
-evaluates to non-@code{nil} and fails otherwise. It is typically used inside
-an @code{and} pattern. For example, @code{(and x (guard (< x 10)))}
-is a pattern which matches any number smaller than 10 and let-binds it to
-the variable @code{x}.
-@end table
+@defmac pcase-defmacro name args &rest body
+Define a new kind of UPattern for @code{pcase}. The new UPattern will
+be invoked as @code{(@var{name} @var{actual-args})}. The @var{body}
+should describe how to rewrite the UPattern @var{name} into some other
+UPattern. The rewriting will be the result of evaluating @var{body}
+in an environment where @var{args} are bound to @var{actual-args}.
+@end defmac
@node Combining Conditions
@section Constructs for Combining Conditions
@end group
@end example
-To write a ``repeat...until'' loop, which will execute something on each
+To write a repeat-until loop, which will execute something on each
iteration and then do the end-test, put the body followed by the
end-test in a @code{progn} as the first argument of @code{while}, as
shown here:
@end example
@end defmac
+@node Generators
+@section Generators
+@cindex generators
+
+ A @dfn{generator} is a function that produces a potentially-infinite
+stream of values. Each time the function produces a value, it
+suspends itself and waits for a caller to request the next value.
+
+@defmac iter-defun name args [doc] [declare] [interactive] body@dots{}
+@code{iter-defun} defines a generator function. A generator function
+has the same signature as a normal function, but works differently.
+Instead of executing @var{body} when called, a generator function
+returns an iterator object. That iterator runs @var{body} to generate
+values, emitting a value and pausing where @code{iter-yield} or
+@code{iter-yield-from} appears. When @var{body} returns normally,
+@code{iter-next} signals @code{iter-end-of-sequence} with @var{body}'s
+result as its condition data.
+
+Any kind of Lisp code is valid inside @var{body}, but
+@code{iter-yield} and @code{iter-yield-from} cannot appear inside
+@code{unwind-protect} forms.
+
+@end defmac
+
+@defmac iter-lambda args [doc] [interactive] body@dots{}
+@code{iter-lambda} produces an unnamed generator function that works
+just like a generator function produced with @code{iter-defun}.
+@end defmac
+
+@defmac iter-yield value
+When it appears inside a generator function, @code{iter-yield}
+indicates that the current iterator should pause and return
+@var{value} from @code{iter-next}. @code{iter-yield} evaluates to the
+@code{value} parameter of next call to @code{iter-next}.
+@end defmac
+
+@defmac iter-yield-from iterator
+@code{iter-yield-from} yields all the values that @var{iterator}
+produces and evaluates to the value that @var{iterator}'s generator
+function returns normally. While it has control, @var{iterator}
+receives values sent to the iterator using @code{iter-next}.
+@end defmac
+
+ To use a generator function, first call it normally, producing a
+@dfn{iterator} object. An iterator is a specific instance of a
+generator. Then use @code{iter-next} to retrieve values from this
+iterator. When there are no more values to pull from an iterator,
+@code{iter-next} raises an @code{iter-end-of-sequence} condition with
+the iterator's final value.
+
+It's important to note that generator function bodies only execute
+inside calls to @code{iter-next}. A call to a function defined with
+@code{iter-defun} produces an iterator; you must drive this
+iterator with @code{iter-next} for anything interesting to happen.
+Each call to a generator function produces a @emph{different}
+iterator, each with its own state.
+
+@defun iter-next iterator value
+Retrieve the next value from @var{iterator}. If there are no more
+values to be generated (because @var{iterator}'s generator function
+returned), @code{iter-next} signals the @code{iter-end-of-sequence}
+condition; the data value associated with this condition is the value
+with which @var{iterator}'s generator function returned.
+
+@var{value} is sent into the iterator and becomes the value to which
+@code{iter-yield} evaluates. @var{value} is ignored for the first
+@code{iter-next} call to a given iterator, since at the start of
+@var{iterator}'s generator function, the generator function is not
+evaluating any @code{iter-yield} form.
+@end defun
+
+@defun iter-close iterator
+If @var{iterator} is suspended inside an @code{unwind-protect}'s
+@code{bodyform} and becomes unreachable, Emacs will eventually run
+unwind handlers after a garbage collection pass. (Note that
+@code{iter-yield} is illegal inside an @code{unwind-protect}'s
+@code{unwindforms}.) To ensure that these handlers are run before
+then, use @code{iter-close}.
+@end defun
+
+Some convenience functions are provided to make working with
+iterators easier:
+
+@defmac iter-do (var iterator) body @dots{}
+Run @var{body} with @var{var} bound to each value that
+@var{iterator} produces.
+@end defmac
+
+The Common Lisp loop facility also contains features for working with
+iterators. See @xref{Loop Facility,,,cl,Common Lisp Extensions}.
+
+The following piece of code demonstrates some important principles of
+working with iterators.
+
+@example
+(iter-defun my-iter (x)
+ (iter-yield (1+ (iter-yield (1+ x))))
+ ;; Return normally
+ -1)
+
+(let* ((iter (my-iter 5))
+ (iter2 (my-iter 0)))
+ ;; Prints 6
+ (print (iter-next iter))
+ ;; Prints 9
+ (print (iter-next iter 8))
+ ;; Prints 1; iter and iter2 have distinct states
+ (print (iter-next iter2 nil))
+
+ ;; We expect the iter sequence to end now
+ (condition-case x
+ (iter-next iter)
+ (iter-end-of-sequence
+ ;; Prints -1, which my-iter returned normally
+ (print (cdr x)))))
+@end example
+
@node Nonlocal Exits
@section Nonlocal Exits
@cindex nonlocal exits
@subsection Examples of @code{catch} and @code{throw}
One way to use @code{catch} and @code{throw} is to exit from a doubly
-nested loop. (In most languages, this would be done with a ``goto''.)
+nested loop. (In most languages, this would be done with a @code{goto}.)
Here we compute @code{(foo @var{i} @var{j})} for @var{i} and @var{j}
varying from 0 to 9:
(@pxref{Processing of Errors}). Here we describe how to signal an
error.
- Most errors are signaled ``automatically'' within Lisp primitives
+ Most errors are signaled automatically within Lisp primitives
which you call for other purposes, such as if you try to take the
@sc{car} of an integer or move forward a character at the end of the
buffer. You can also signal errors explicitly with the functions
@defun error format-string &rest args
This function signals an error with an error message constructed by
-applying @code{format} (@pxref{Formatting Strings}) to
+applying @code{format-message} (@pxref{Formatting Strings}) to
@var{format-string} and @var{args}.
These examples show typical uses of @code{error}:
@end group
@group
-(error "You have committed %d errors" 10)
- @error{} You have committed 10 errors
+(error "Invalid name `%s'" "A%%B")
+ @error{} Invalid name ‘A%%B’
@end group
@end example
@code{error} works by calling @code{signal} with two arguments: the
error symbol @code{error}, and a list containing the string returned by
-@code{format}.
+@code{format-message}.
+
+A format that quotes with grave accents and apostrophes @t{`like
+this'} typically generates curved quotes @t{‘like this’}. In
+contrast, a format that quotes with only apostrophes @t{'like this'}
+typically generates two closing curved quotes @t{’like this’}, an
+unusual style in English. @xref{Keys in Documentation}, for how the
+@code{text-quoting-style} variable affects generated quotes.
@strong{Warning:} If you want to use your own string as an error message
verbatim, don't just write @code{(error @var{string})}. If @var{string}
-contains @samp{%}, it will be interpreted as a format specifier, with
-undesirable results. Instead, use @code{(error "%s" @var{string})}.
+@var{string} contains @samp{%}, @samp{`}, or @samp{'} it may be
+reformatted, with undesirable results. Instead, use @code{(error "%s"
+@var{string})}.
@end defun
@defun signal error-symbol data
The argument @var{error-symbol} must be an @dfn{error symbol}---a symbol
defined with @code{define-error}. This is how Emacs Lisp classifies different
-sorts of errors. @xref{Error Symbols}, for a description of error symbols,
+sorts of errors. @xref{Error Symbols}, for a description of error symbols,
error conditions and condition names.
If the error is not handled, the two arguments are used in printing