Merge branch 'master' into comment-cache
[emacs.git] / lisp / emacs-lisp / pcase.el
blob46a5eedd15018c9d55fae485958b858eeee65f3e
1 ;;; pcase.el --- ML-style pattern-matching macro for Elisp -*- lexical-binding: t -*-
3 ;; Copyright (C) 2010-2017 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords:
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; ML-style pattern matching.
26 ;; The entry points are autoloaded.
28 ;; Todo:
30 ;; - (pcase e (`(,x . ,x) foo)) signals an "x unused" warning if `foo' doesn't
31 ;; use x, because x is bound separately for the equality constraint
32 ;; (as well as any pred/guard) and for the body, so uses at one place don't
33 ;; count for the other.
34 ;; - provide ways to extend the set of primitives, with some kind of
35 ;; define-pcase-matcher. We could easily make it so that (guard BOOLEXP)
36 ;; could be defined this way, as a shorthand for (pred (lambda (_) BOOLEXP)).
37 ;; But better would be if we could define new ways to match by having the
38 ;; extension provide its own `pcase--split-<foo>' thingy.
39 ;; - along these lines, provide patterns to match CL structs.
40 ;; - provide something like (setq VAR) so a var can be set rather than
41 ;; let-bound.
42 ;; - provide a way to fallthrough to subsequent cases (not sure what I meant by
43 ;; this :-()
44 ;; - try and be more clever to reduce the size of the decision tree, and
45 ;; to reduce the number of leaves that need to be turned into function:
46 ;; - first, do the tests shared by all remaining branches (it will have
47 ;; to be performed anyway, so better do it first so it's shared).
48 ;; - then choose the test that discriminates more (?).
49 ;; - provide Agda's `with' (along with its `...' companion).
50 ;; - implement (not PAT). This might require a significant redesign.
51 ;; - ideally we'd want (pcase s ((re RE1) E1) ((re RE2) E2)) to be able to
52 ;; generate a lex-style DFA to decide whether to run E1 or E2.
54 ;;; Code:
56 (require 'macroexp)
58 ;; Macro-expansion of pcase is reasonably fast, so it's not a problem
59 ;; when byte-compiling a file, but when interpreting the code, if the pcase
60 ;; is in a loop, the repeated macro-expansion becomes terribly costly, so we
61 ;; memoize previous macro expansions to try and avoid recomputing them
62 ;; over and over again.
63 ;; FIXME: Now that macroexpansion is also performed when loading an interpreted
64 ;; file, this is not a real problem any more.
65 (defconst pcase--memoize (make-hash-table :weakness 'key :test 'eq))
66 ;; (defconst pcase--memoize-1 (make-hash-table :test 'eq))
67 ;; (defconst pcase--memoize-2 (make-hash-table :weakness 'key :test 'equal))
69 (defconst pcase--dontcare-upats '(t _ pcase--dontcare))
71 (defvar pcase--dontwarn-upats '(pcase--dontcare))
73 (def-edebug-spec
74 pcase-PAT
75 (&or symbolp
76 ("or" &rest pcase-PAT)
77 ("and" &rest pcase-PAT)
78 ("guard" form)
79 ("let" pcase-PAT form)
80 ("pred" pcase-FUN)
81 ("app" pcase-FUN pcase-PAT)
82 pcase-MACRO
83 sexp))
85 (def-edebug-spec
86 pcase-FUN
87 (&or lambda-expr
88 ;; Punt on macros/special forms.
89 (functionp &rest form)
90 sexp))
92 ;; See bug#24717
93 (put 'pcase-MACRO 'edebug-form-spec 'pcase--edebug-match-macro)
95 ;; Only called from edebug.
96 (declare-function get-edebug-spec "edebug" (symbol))
97 (declare-function edebug-match "edebug" (cursor specs))
99 (defun pcase--edebug-match-macro (cursor)
100 (let (specs)
101 (mapatoms
102 (lambda (s)
103 (let ((m (get s 'pcase-macroexpander)))
104 (when (and m (get-edebug-spec m))
105 (push (cons (symbol-name s) (get-edebug-spec m))
106 specs)))))
107 (edebug-match cursor (cons '&or specs))))
109 ;;;###autoload
110 (defmacro pcase (exp &rest cases)
111 "Evaluate EXP and attempt to match it against structural patterns.
112 CASES is a list of elements of the form (PATTERN CODE...).
114 A structural PATTERN describes a template that identifies a class
115 of values. For example, the pattern \\=`(,foo ,bar) matches any
116 two element list, binding its elements to symbols named `foo' and
117 `bar' -- in much the same way that `cl-destructuring-bind' would.
119 A significant difference from `cl-destructuring-bind' is that, if
120 a pattern match fails, the next case is tried until either a
121 successful match is found or there are no more cases.
123 Another difference is that pattern elements may be quoted,
124 meaning they must match exactly: The pattern \\='(foo bar)
125 matches only against two element lists containing the symbols
126 `foo' and `bar' in that order. (As a short-hand, atoms always
127 match themselves, such as numbers or strings, and need not be
128 quoted.)
130 Lastly, a pattern can be logical, such as (pred numberp), that
131 matches any number-like element; or the symbol `_', that matches
132 anything. Also, when patterns are backquoted, a comma may be
133 used to introduce logical patterns inside backquoted patterns.
135 The complete list of standard patterns is as follows:
137 _ matches anything.
138 SYMBOL matches anything and binds it to SYMBOL.
139 If a SYMBOL is used twice in the same pattern
140 the second occurrence becomes an `eq'uality test.
141 (or PAT...) matches if any of the patterns matches.
142 (and PAT...) matches if all the patterns match.
143 \\='VAL matches if the object is `equal' to VAL.
144 ATOM is a shorthand for \\='ATOM.
145 ATOM can be a keyword, an integer, or a string.
146 (pred FUN) matches if FUN applied to the object returns non-nil.
147 (guard BOOLEXP) matches if BOOLEXP evaluates to non-nil.
148 (let PAT EXP) matches if EXP matches PAT.
149 (app FUN PAT) matches if FUN applied to the object matches PAT.
151 Additional patterns can be defined using `pcase-defmacro'.
153 The FUN argument in the `app' pattern may have the following forms:
154 SYMBOL or (lambda ARGS BODY) in which case it's called with one argument.
155 (F ARG1 .. ARGn) in which case F gets called with an n+1'th argument
156 which is the value being matched.
157 So a FUN of the form SYMBOL is equivalent to (FUN).
158 FUN can refer to variables bound earlier in the pattern.
160 See Info node `(elisp) Pattern matching case statement' in the
161 Emacs Lisp manual for more information and examples."
162 (declare (indent 1) (debug (form &rest (pcase-PAT body))))
163 ;; We want to use a weak hash table as a cache, but the key will unavoidably
164 ;; be based on `exp' and `cases', yet `cases' is a fresh new list each time
165 ;; we're called so it'll be immediately GC'd. So we use (car cases) as key
166 ;; which does come straight from the source code and should hence not be GC'd
167 ;; so easily.
168 (let ((data (gethash (car cases) pcase--memoize)))
169 ;; data = (EXP CASES . EXPANSION)
170 (if (and (equal exp (car data)) (equal cases (cadr data)))
171 ;; We have the right expansion.
172 (cddr data)
173 ;; (when (gethash (car cases) pcase--memoize-1)
174 ;; (message "pcase-memoize failed because of weak key!!"))
175 ;; (when (gethash (car cases) pcase--memoize-2)
176 ;; (message "pcase-memoize failed because of eq test on %S"
177 ;; (car cases)))
178 (when data
179 (message "pcase-memoize: equal first branch, yet different"))
180 (let ((expansion (pcase--expand exp cases)))
181 (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize)
182 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-1)
183 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-2)
184 expansion))))
186 (declare-function help-fns--signature "help-fns"
187 (function doc real-def real-function buffer))
189 ;; FIXME: Obviously, this will collide with nadvice's use of
190 ;; function-documentation if we happen to advise `pcase'.
191 (put 'pcase 'function-documentation '(pcase--make-docstring))
192 (defun pcase--make-docstring ()
193 (let* ((main (documentation (symbol-function 'pcase) 'raw))
194 (ud (help-split-fundoc main 'pcase)))
195 ;; So that eg emacs -Q -l cl-lib --eval "(documentation 'pcase)" works,
196 ;; where cl-lib is anything using pcase-defmacro.
197 (require 'help-fns)
198 (with-temp-buffer
199 (insert (or (cdr ud) main))
200 (mapatoms
201 (lambda (symbol)
202 (let ((me (get symbol 'pcase-macroexpander)))
203 (when me
204 (insert "\n\n-- ")
205 (let* ((doc (documentation me 'raw)))
206 (setq doc (help-fns--signature symbol doc me
207 (indirect-function me) nil))
208 (insert "\n" (or doc "Not documented.")))))))
209 (let ((combined-doc (buffer-string)))
210 (if ud (help-add-fundoc-usage combined-doc (car ud)) combined-doc)))))
212 ;;;###autoload
213 (defmacro pcase-exhaustive (exp &rest cases)
214 "The exhaustive version of `pcase' (which see)."
215 (declare (indent 1) (debug pcase))
216 (let* ((x (make-symbol "x"))
217 (pcase--dontwarn-upats (cons x pcase--dontwarn-upats)))
218 (pcase--expand
219 ;; FIXME: Could we add the FILE:LINE data in the error message?
220 exp (append cases `((,x (error "No clause matching `%S'" ,x)))))))
222 ;;;###autoload
223 (defmacro pcase-lambda (lambda-list &rest body)
224 "Like `lambda' but allow each argument to be a pattern.
225 I.e. accepts the usual &optional and &rest keywords, but every
226 formal argument can be any pattern accepted by `pcase' (a mere
227 variable name being but a special case of it)."
228 (declare (doc-string 2) (indent defun)
229 (debug ((&rest pcase-PAT) body)))
230 (let* ((bindings ())
231 (parsed-body (macroexp-parse-body body))
232 (args (mapcar (lambda (pat)
233 (if (symbolp pat)
234 ;; Simple vars and &rest/&optional are just passed
235 ;; through unchanged.
237 (let ((arg (make-symbol
238 (format "arg%s" (length bindings)))))
239 (push `(,pat ,arg) bindings)
240 arg)))
241 lambda-list)))
242 `(lambda ,args ,@(car parsed-body)
243 (pcase-let* ,(nreverse bindings) ,@(cdr parsed-body)))))
245 (defun pcase--let* (bindings body)
246 (cond
247 ((null bindings) (macroexp-progn body))
248 ((pcase--trivial-upat-p (caar bindings))
249 (macroexp-let* `(,(car bindings)) (pcase--let* (cdr bindings) body)))
251 (let ((binding (pop bindings)))
252 (pcase--expand
253 (cadr binding)
254 `((,(car binding) ,(pcase--let* bindings body))
255 ;; We can either signal an error here, or just use `pcase--dontcare'
256 ;; which generates more efficient code. In practice, if we use
257 ;; `pcase--dontcare' we will still often get an error and the few
258 ;; cases where we don't do not matter that much, so
259 ;; it's a better choice.
260 (pcase--dontcare nil)))))))
262 ;;;###autoload
263 (defmacro pcase-let* (bindings &rest body)
264 "Like `let*' but where you can use `pcase' patterns for bindings.
265 BODY should be an expression, and BINDINGS should be a list of bindings
266 of the form (PAT EXP)."
267 (declare (indent 1)
268 (debug ((&rest (pcase-PAT &optional form)) body)))
269 (let ((cached (gethash bindings pcase--memoize)))
270 ;; cached = (BODY . EXPANSION)
271 (if (equal (car cached) body)
272 (cdr cached)
273 (let ((expansion (pcase--let* bindings body)))
274 (puthash bindings (cons body expansion) pcase--memoize)
275 expansion))))
277 ;;;###autoload
278 (defmacro pcase-let (bindings &rest body)
279 "Like `let' but where you can use `pcase' patterns for bindings.
280 BODY should be a list of expressions, and BINDINGS should be a list of bindings
281 of the form (PAT EXP).
282 The macro is expanded and optimized under the assumption that those
283 patterns *will* match, so a mismatch may go undetected or may cause
284 any kind of error."
285 (declare (indent 1) (debug pcase-let*))
286 (if (null (cdr bindings))
287 `(pcase-let* ,bindings ,@body)
288 (let ((matches '()))
289 (dolist (binding (prog1 bindings (setq bindings nil)))
290 (cond
291 ((memq (car binding) pcase--dontcare-upats)
292 (push (cons (make-symbol "_") (cdr binding)) bindings))
293 ((pcase--trivial-upat-p (car binding)) (push binding bindings))
295 (let ((tmpvar (make-symbol (format "x%d" (length bindings)))))
296 (push (cons tmpvar (cdr binding)) bindings)
297 (push (list (car binding) tmpvar) matches)))))
298 `(let ,(nreverse bindings) (pcase-let* ,matches ,@body)))))
300 ;;;###autoload
301 (defmacro pcase-dolist (spec &rest body)
302 "Like `dolist' but where the binding can be a `pcase' pattern.
303 \n(fn (PATTERN LIST) BODY...)"
304 (declare (indent 1) (debug ((pcase-PAT form) body)))
305 (if (pcase--trivial-upat-p (car spec))
306 `(dolist ,spec ,@body)
307 (let ((tmpvar (make-symbol "x")))
308 `(dolist (,tmpvar ,@(cdr spec))
309 (pcase-let* ((,(car spec) ,tmpvar))
310 ,@body)))))
313 (defun pcase--trivial-upat-p (upat)
314 (and (symbolp upat) (not (memq upat pcase--dontcare-upats))))
316 (defun pcase--expand (exp cases)
317 ;; (message "pid=%S (pcase--expand %S ...hash=%S)"
318 ;; (emacs-pid) exp (sxhash cases))
319 (macroexp-let2 macroexp-copyable-p val exp
320 (let* ((defs ())
321 (seen '())
322 (codegen
323 (lambda (code vars)
324 (let ((prev (assq code seen)))
325 (if (not prev)
326 (let ((res (pcase-codegen code vars)))
327 (push (list code vars res) seen)
328 res)
329 ;; Since we use a tree-based pattern matching
330 ;; technique, the leaves (the places that contain the
331 ;; code to run once a pattern is matched) can get
332 ;; copied a very large number of times, so to avoid
333 ;; code explosion, we need to keep track of how many
334 ;; times we've used each leaf and move it
335 ;; to a separate function if that number is too high.
337 ;; We've already used this branch. So it is shared.
338 (let* ((code (car prev)) (cdrprev (cdr prev))
339 (prevvars (car cdrprev)) (cddrprev (cdr cdrprev))
340 (res (car cddrprev)))
341 (unless (symbolp res)
342 ;; This is the first repeat, so we have to move
343 ;; the branch to a separate function.
344 (let ((bsym
345 (make-symbol (format "pcase-%d" (length defs)))))
346 (push `(,bsym (lambda ,(mapcar #'car prevvars) ,@code))
347 defs)
348 (setcar res 'funcall)
349 (setcdr res (cons bsym (mapcar #'cdr prevvars)))
350 (setcar (cddr prev) bsym)
351 (setq res bsym)))
352 (setq vars (copy-sequence vars))
353 (let ((args (mapcar (lambda (pa)
354 (let ((v (assq (car pa) vars)))
355 (setq vars (delq v vars))
356 (cdr v)))
357 prevvars)))
358 ;; If some of `vars' were not found in `prevvars', that's
359 ;; OK it just means those vars aren't present in all
360 ;; branches, so they can be used within the pattern
361 ;; (e.g. by a `guard/let/pred') but not in the branch.
362 ;; FIXME: But if some of `prevvars' are not in `vars' we
363 ;; should remove them from `prevvars'!
364 `(funcall ,res ,@args)))))))
365 (used-cases ())
366 (main
367 (pcase--u
368 (mapcar (lambda (case)
369 `(,(pcase--match val (pcase--macroexpand (car case)))
370 ,(lambda (vars)
371 (unless (memq case used-cases)
372 ;; Keep track of the cases that are used.
373 (push case used-cases))
374 (funcall
375 (if (pcase--small-branch-p (cdr case))
376 ;; Don't bother sharing multiple
377 ;; occurrences of this leaf since it's small.
378 #'pcase-codegen codegen)
379 (cdr case)
380 vars))))
381 cases))))
382 (dolist (case cases)
383 (unless (or (memq case used-cases)
384 (memq (car case) pcase--dontwarn-upats))
385 (message "Redundant pcase pattern: %S" (car case))))
386 (macroexp-let* defs main))))
388 (defun pcase--macroexpand (pat)
389 "Expands all macro-patterns in PAT."
390 (let ((head (car-safe pat)))
391 (cond
392 ((null head)
393 (if (pcase--self-quoting-p pat) `',pat pat))
394 ((memq head '(pred guard quote)) pat)
395 ((memq head '(or and)) `(,head ,@(mapcar #'pcase--macroexpand (cdr pat))))
396 ((eq head 'let) `(let ,(pcase--macroexpand (cadr pat)) ,@(cddr pat)))
397 ((eq head 'app) `(app ,(nth 1 pat) ,(pcase--macroexpand (nth 2 pat))))
399 (let* ((expander (get head 'pcase-macroexpander))
400 (npat (if expander (apply expander (cdr pat)))))
401 (if (null npat)
402 (error (if expander
403 "Unexpandable %s pattern: %S"
404 "Unknown %s pattern: %S")
405 head pat)
406 (pcase--macroexpand npat)))))))
408 ;;;###autoload
409 (defmacro pcase-defmacro (name args &rest body)
410 "Define a new kind of pcase PATTERN, by macro expansion.
411 Patterns of the form (NAME ...) will be expanded according
412 to this macro."
413 (declare (indent 2) (debug defun) (doc-string 3))
414 ;; Add the function via `fsym', so that an autoload cookie placed
415 ;; on a pcase-defmacro will cause the macro to be loaded on demand.
416 (let ((fsym (intern (format "%s--pcase-macroexpander" name)))
417 (decl (assq 'declare body)))
418 (when decl (setq body (remove decl body)))
419 `(progn
420 (defun ,fsym ,args ,@body)
421 (put ',fsym 'edebug-form-spec ',(cadr (assq 'debug decl)))
422 (put ',name 'pcase-macroexpander #',fsym))))
424 (defun pcase--match (val upat)
425 "Build a MATCH structure, hoisting all `or's and `and's outside."
426 (cond
427 ;; Hoist or/and patterns into or/and matches.
428 ((memq (car-safe upat) '(or and))
429 `(,(car upat)
430 ,@(mapcar (lambda (upat)
431 (pcase--match val upat))
432 (cdr upat))))
434 `(match ,val . ,upat))))
436 (defun pcase-codegen (code vars)
437 ;; Don't use let*, otherwise macroexp-let* may merge it with some surrounding
438 ;; let* which might prevent the setcar/setcdr in pcase--expand's fancy
439 ;; codegen from later metamorphosing this let into a funcall.
440 `(let ,(mapcar (lambda (b) (list (car b) (cdr b))) vars)
441 ,@code))
443 (defun pcase--small-branch-p (code)
444 (and (= 1 (length code))
445 (or (not (consp (car code)))
446 (let ((small t))
447 (dolist (e (car code))
448 (if (consp e) (setq small nil)))
449 small))))
451 ;; Try to use `cond' rather than a sequence of `if's, so as to reduce
452 ;; the depth of the generated tree.
453 (defun pcase--if (test then else)
454 (cond
455 ((eq else :pcase--dontcare) then)
456 ((eq then :pcase--dontcare) (debug) else) ;Can/should this ever happen?
457 (t (macroexp-if test then else))))
459 ;; Note about MATCH:
460 ;; When we have patterns like `(PAT1 . PAT2), after performing the `consp'
461 ;; check, we want to turn all the similar patterns into ones of the form
462 ;; (and (match car PAT1) (match cdr PAT2)), so you naturally need conjunction.
463 ;; Earlier code hence used branches of the form (MATCHES . CODE) where
464 ;; MATCHES was a list (implicitly a conjunction) of (SYM . PAT).
465 ;; But if we have a pattern of the form (or `(PAT1 . PAT2) PAT3), there is
466 ;; no easy way to eliminate the `consp' check in such a representation.
467 ;; So we replaced the MATCHES by the MATCH below which can be made up
468 ;; of conjunctions and disjunctions, so if we know `foo' is a cons, we can
469 ;; turn (match foo . (or `(PAT1 . PAT2) PAT3)) into
470 ;; (or (and (match car . `PAT1) (match cdr . `PAT2)) (match foo . PAT3)).
471 ;; The downside is that we now have `or' and `and' both in MATCH and
472 ;; in PAT, so there are different equivalent representations and we
473 ;; need to handle them all. We do not try to systematically
474 ;; canonicalize them to one form over another, but we do occasionally
475 ;; turn one into the other.
477 (defun pcase--u (branches)
478 "Expand matcher for rules BRANCHES.
479 Each BRANCH has the form (MATCH CODE . VARS) where
480 CODE is the code generator for that branch.
481 VARS is the set of vars already bound by earlier matches.
482 MATCH is the pattern that needs to be matched, of the form:
483 (match VAR . PAT)
484 (and MATCH ...)
485 (or MATCH ...)"
486 (when (setq branches (delq nil branches))
487 (let* ((carbranch (car branches))
488 (match (car carbranch)) (cdarbranch (cdr carbranch))
489 (code (car cdarbranch))
490 (vars (cdr cdarbranch)))
491 (pcase--u1 (list match) code vars (cdr branches)))))
493 (defun pcase--and (match matches)
494 (if matches `(and ,match ,@matches) match))
496 (defconst pcase-mutually-exclusive-predicates
497 '((symbolp . integerp)
498 (symbolp . numberp)
499 (symbolp . consp)
500 (symbolp . arrayp)
501 (symbolp . vectorp)
502 (symbolp . stringp)
503 (symbolp . byte-code-function-p)
504 (integerp . consp)
505 (integerp . arrayp)
506 (integerp . vectorp)
507 (integerp . stringp)
508 (integerp . byte-code-function-p)
509 (numberp . consp)
510 (numberp . arrayp)
511 (numberp . vectorp)
512 (numberp . stringp)
513 (numberp . byte-code-function-p)
514 (consp . arrayp)
515 (consp . atom)
516 (consp . vectorp)
517 (consp . stringp)
518 (consp . byte-code-function-p)
519 (arrayp . byte-code-function-p)
520 (vectorp . byte-code-function-p)
521 (stringp . vectorp)
522 (stringp . byte-code-function-p)))
524 (defun pcase--mutually-exclusive-p (pred1 pred2)
525 (or (member (cons pred1 pred2)
526 pcase-mutually-exclusive-predicates)
527 (member (cons pred2 pred1)
528 pcase-mutually-exclusive-predicates)))
530 (defun pcase--split-match (sym splitter match)
531 (cond
532 ((eq (car-safe match) 'match)
533 (if (not (eq sym (cadr match)))
534 (cons match match)
535 (let ((res (funcall splitter (cddr match))))
536 (cons (or (car res) match) (or (cdr res) match)))))
537 ((memq (car-safe match) '(or and))
538 (let ((then-alts '())
539 (else-alts '())
540 (neutral-elem (if (eq 'or (car match))
541 :pcase--fail :pcase--succeed))
542 (zero-elem (if (eq 'or (car match)) :pcase--succeed :pcase--fail)))
543 (dolist (alt (cdr match))
544 (let ((split (pcase--split-match sym splitter alt)))
545 (unless (eq (car split) neutral-elem)
546 (push (car split) then-alts))
547 (unless (eq (cdr split) neutral-elem)
548 (push (cdr split) else-alts))))
549 (cons (cond ((memq zero-elem then-alts) zero-elem)
550 ((null then-alts) neutral-elem)
551 ((null (cdr then-alts)) (car then-alts))
552 (t (cons (car match) (nreverse then-alts))))
553 (cond ((memq zero-elem else-alts) zero-elem)
554 ((null else-alts) neutral-elem)
555 ((null (cdr else-alts)) (car else-alts))
556 (t (cons (car match) (nreverse else-alts)))))))
557 ((memq match '(:pcase--succeed :pcase--fail)) (cons match match))
558 (t (error "Uknown MATCH %s" match))))
560 (defun pcase--split-rest (sym splitter rest)
561 (let ((then-rest '())
562 (else-rest '()))
563 (dolist (branch rest)
564 (let* ((match (car branch))
565 (code&vars (cdr branch))
566 (split
567 (pcase--split-match sym splitter match)))
568 (unless (eq (car split) :pcase--fail)
569 (push (cons (car split) code&vars) then-rest))
570 (unless (eq (cdr split) :pcase--fail)
571 (push (cons (cdr split) code&vars) else-rest))))
572 (cons (nreverse then-rest) (nreverse else-rest))))
574 (defun pcase--split-equal (elem pat)
575 (cond
576 ;; The same match will give the same result.
577 ((and (eq (car-safe pat) 'quote) (equal (cadr pat) elem))
578 '(:pcase--succeed . :pcase--fail))
579 ;; A different match will fail if this one succeeds.
580 ((and (eq (car-safe pat) 'quote)
581 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
582 ;; (consp (cadr pat)))
584 '(:pcase--fail . nil))
585 ((and (eq (car-safe pat) 'pred)
586 (symbolp (cadr pat))
587 (get (cadr pat) 'side-effect-free))
588 (ignore-errors
589 (if (funcall (cadr pat) elem)
590 '(:pcase--succeed . nil)
591 '(:pcase--fail . nil))))))
593 (defun pcase--split-member (elems pat)
594 ;; FIXME: The new pred-based member code doesn't do these optimizations!
595 ;; Based on pcase--split-equal.
596 (cond
597 ;; The same match (or a match of membership in a superset) will
598 ;; give the same result, but we don't know how to check it.
599 ;; (???
600 ;; '(:pcase--succeed . nil))
601 ;; A match for one of the elements may succeed or fail.
602 ((and (eq (car-safe pat) 'quote) (member (cadr pat) elems))
603 nil)
604 ;; A different match will fail if this one succeeds.
605 ((and (eq (car-safe pat) 'quote)
606 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
607 ;; (consp (cadr pat)))
609 '(:pcase--fail . nil))
610 ((and (eq (car-safe pat) 'pred)
611 (symbolp (cadr pat))
612 (get (cadr pat) 'side-effect-free)
613 (ignore-errors
614 (let ((p (cadr pat)) (all t))
615 (dolist (elem elems)
616 (unless (funcall p elem) (setq all nil)))
617 all)))
618 '(:pcase--succeed . nil))))
620 (defun pcase--split-pred (vars upat pat)
621 (let (test)
622 (cond
623 ((and (equal upat pat)
624 ;; For predicates like (pred (> a)), two such predicates may
625 ;; actually refer to different variables `a'.
626 (or (and (eq 'pred (car upat)) (symbolp (cadr upat)))
627 ;; FIXME: `vars' gives us the environment in which `upat' will
628 ;; run, but we don't have the environment in which `pat' will
629 ;; run, so we can't do a reliable verification. But let's try
630 ;; and catch at least the easy cases such as (bug#14773).
631 (not (pcase--fgrep (mapcar #'car vars) (cadr upat)))))
632 '(:pcase--succeed . :pcase--fail))
633 ((and (eq 'pred (car upat))
634 (let ((otherpred
635 (cond ((eq 'pred (car-safe pat)) (cadr pat))
636 ((not (eq 'quote (car-safe pat))) nil)
637 ((consp (cadr pat)) #'consp)
638 ((stringp (cadr pat)) #'stringp)
639 ((vectorp (cadr pat)) #'vectorp)
640 ((byte-code-function-p (cadr pat))
641 #'byte-code-function-p))))
642 (pcase--mutually-exclusive-p (cadr upat) otherpred)))
643 '(:pcase--fail . nil))
644 ((and (eq 'pred (car upat))
645 (eq 'quote (car-safe pat))
646 (symbolp (cadr upat))
647 (or (symbolp (cadr pat)) (stringp (cadr pat)) (numberp (cadr pat)))
648 (get (cadr upat) 'side-effect-free)
649 (ignore-errors
650 (setq test (list (funcall (cadr upat) (cadr pat))))))
651 (if (car test)
652 '(nil . :pcase--fail)
653 '(:pcase--fail . nil))))))
655 (defun pcase--fgrep (vars sexp)
656 "Check which of the symbols VARS appear in SEXP."
657 (let ((res '()))
658 (while (consp sexp)
659 (dolist (var (pcase--fgrep vars (pop sexp)))
660 (unless (memq var res) (push var res))))
661 (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
662 res))
664 (defun pcase--self-quoting-p (upat)
665 (or (keywordp upat) (integerp upat) (stringp upat)))
667 (defun pcase--app-subst-match (match sym fun nsym)
668 (cond
669 ((eq (car-safe match) 'match)
670 (if (and (eq sym (cadr match))
671 (eq 'app (car-safe (cddr match)))
672 (equal fun (nth 1 (cddr match))))
673 (pcase--match nsym (nth 2 (cddr match)))
674 match))
675 ((memq (car-safe match) '(or and))
676 `(,(car match)
677 ,@(mapcar (lambda (match)
678 (pcase--app-subst-match match sym fun nsym))
679 (cdr match))))
680 ((memq match '(:pcase--succeed :pcase--fail)) match)
681 (t (error "Uknown MATCH %s" match))))
683 (defun pcase--app-subst-rest (rest sym fun nsym)
684 (mapcar (lambda (branch)
685 `(,(pcase--app-subst-match (car branch) sym fun nsym)
686 ,@(cdr branch)))
687 rest))
689 (defsubst pcase--mark-used (sym)
690 ;; Exceptionally, `sym' may be a constant expression rather than a symbol.
691 (if (symbolp sym) (put sym 'pcase-used t)))
693 (defmacro pcase--flip (fun arg1 arg2)
694 "Helper function, used internally to avoid (funcall (lambda ...) ...)."
695 (declare (debug (sexp body)))
696 `(,fun ,arg2 ,arg1))
698 (defun pcase--funcall (fun arg vars)
699 "Build a function call to FUN with arg ARG."
700 (if (symbolp fun)
701 `(,fun ,arg)
702 (let* (;; `vs' is an upper bound on the vars we need.
703 (vs (pcase--fgrep (mapcar #'car vars) fun))
704 (env (mapcar (lambda (var)
705 (list var (cdr (assq var vars))))
706 vs))
707 (call (progn
708 (when (memq arg vs)
709 ;; `arg' is shadowed by `env'.
710 (let ((newsym (make-symbol "x")))
711 (push (list newsym arg) env)
712 (setq arg newsym)))
713 (if (functionp fun)
714 `(funcall #',fun ,arg)
715 `(,@fun ,arg)))))
716 (if (null vs)
717 call
718 ;; Let's not replace `vars' in `fun' since it's
719 ;; too difficult to do it right, instead just
720 ;; let-bind `vars' around `fun'.
721 `(let* ,env ,call)))))
723 (defun pcase--eval (exp vars)
724 "Build an expression that will evaluate EXP."
725 (let* ((found (assq exp vars)))
726 (if found (cdr found)
727 (let* ((vs (pcase--fgrep (mapcar #'car vars) exp))
728 (env (mapcar (lambda (v) (list v (cdr (assq v vars))))
729 vs)))
730 (if env (macroexp-let* env exp) exp)))))
732 ;; It's very tempting to use `pcase' below, tho obviously, it'd create
733 ;; bootstrapping problems.
734 (defun pcase--u1 (matches code vars rest)
735 "Return code that runs CODE (with VARS) if MATCHES match.
736 Otherwise, it defers to REST which is a list of branches of the form
737 \(ELSE-MATCH ELSE-CODE . ELSE-VARS)."
738 ;; Depending on the order in which we choose to check each of the MATCHES,
739 ;; the resulting tree may be smaller or bigger. So in general, we'd want
740 ;; to be careful to chose the "optimal" order. But predicate
741 ;; patterns make this harder because they create dependencies
742 ;; between matches. So we don't bother trying to reorder anything.
743 (cond
744 ((null matches) (funcall code vars))
745 ((eq :pcase--fail (car matches)) (pcase--u rest))
746 ((eq :pcase--succeed (car matches))
747 (pcase--u1 (cdr matches) code vars rest))
748 ((eq 'and (caar matches))
749 (pcase--u1 (append (cdar matches) (cdr matches)) code vars rest))
750 ((eq 'or (caar matches))
751 (let* ((alts (cdar matches))
752 (var (if (eq (caar alts) 'match) (cadr (car alts))))
753 (simples '()) (others '()) (memq-ok t))
754 (when var
755 (dolist (alt alts)
756 (if (and (eq (car alt) 'match) (eq var (cadr alt))
757 (let ((upat (cddr alt)))
758 (eq (car-safe upat) 'quote)))
759 (let ((val (cadr (cddr alt))))
760 (unless (or (integerp val) (symbolp val))
761 (setq memq-ok nil))
762 (push (cadr (cddr alt)) simples))
763 (push alt others))))
764 (cond
765 ((null alts) (error "Please avoid it") (pcase--u rest))
766 ;; Yes, we can use `memq' (or `member')!
767 ((> (length simples) 1)
768 (pcase--u1 (cons `(match ,var
769 . (pred (pcase--flip
770 ,(if memq-ok #'memq #'member)
771 ',simples)))
772 (cdr matches))
773 code vars
774 (if (null others) rest
775 (cons (cons
776 (pcase--and (if (cdr others)
777 (cons 'or (nreverse others))
778 (car others))
779 (cdr matches))
780 (cons code vars))
781 rest))))
783 (pcase--u1 (cons (pop alts) (cdr matches)) code vars
784 (if (null alts) (progn (error "Please avoid it") rest)
785 (cons (cons
786 (pcase--and (if (cdr alts)
787 (cons 'or alts) (car alts))
788 (cdr matches))
789 (cons code vars))
790 rest)))))))
791 ((eq 'match (caar matches))
792 (let* ((popmatches (pop matches))
793 (_op (car popmatches)) (cdrpopmatches (cdr popmatches))
794 (sym (car cdrpopmatches))
795 (upat (cdr cdrpopmatches)))
796 (cond
797 ((memq upat '(t _))
798 (let ((code (pcase--u1 matches code vars rest)))
799 (if (eq upat '_) code
800 (macroexp--warn-and-return
801 "Pattern t is deprecated. Use `_' instead"
802 code))))
803 ((eq upat 'pcase--dontcare) :pcase--dontcare)
804 ((memq (car-safe upat) '(guard pred))
805 (if (eq (car upat) 'pred) (pcase--mark-used sym))
806 (let* ((splitrest
807 (pcase--split-rest
808 sym (lambda (pat) (pcase--split-pred vars upat pat)) rest))
809 (then-rest (car splitrest))
810 (else-rest (cdr splitrest)))
811 (pcase--if (if (eq (car upat) 'pred)
812 (pcase--funcall (cadr upat) sym vars)
813 (pcase--eval (cadr upat) vars))
814 (pcase--u1 matches code vars then-rest)
815 (pcase--u else-rest))))
816 ((and (symbolp upat) upat)
817 (pcase--mark-used sym)
818 (if (not (assq upat vars))
819 (pcase--u1 matches code (cons (cons upat sym) vars) rest)
820 ;; Non-linear pattern. Turn it into an `eq' test.
821 (pcase--u1 (cons `(match ,sym . (pred (eq ,(cdr (assq upat vars)))))
822 matches)
823 code vars rest)))
824 ((eq (car-safe upat) 'let)
825 ;; A upat of the form (let VAR EXP).
826 ;; (pcase--u1 matches code
827 ;; (cons (cons (nth 1 upat) (nth 2 upat)) vars) rest)
828 (macroexp-let2
829 macroexp-copyable-p sym
830 (pcase--eval (nth 2 upat) vars)
831 (pcase--u1 (cons (pcase--match sym (nth 1 upat)) matches)
832 code vars rest)))
833 ((eq (car-safe upat) 'app)
834 ;; A upat of the form (app FUN PAT)
835 (pcase--mark-used sym)
836 (let* ((fun (nth 1 upat))
837 (nsym (make-symbol "x"))
838 (body
839 ;; We don't change `matches' to reuse the newly computed value,
840 ;; because we assume there shouldn't be such redundancy in there.
841 (pcase--u1 (cons (pcase--match nsym (nth 2 upat)) matches)
842 code vars
843 (pcase--app-subst-rest rest sym fun nsym))))
844 (if (not (get nsym 'pcase-used))
845 body
846 (macroexp-let*
847 `((,nsym ,(pcase--funcall fun sym vars)))
848 body))))
849 ((eq (car-safe upat) 'quote)
850 (pcase--mark-used sym)
851 (let* ((val (cadr upat))
852 (splitrest (pcase--split-rest
853 sym (lambda (pat) (pcase--split-equal val pat)) rest))
854 (then-rest (car splitrest))
855 (else-rest (cdr splitrest)))
856 (pcase--if (cond
857 ((null val) `(null ,sym))
858 ((or (integerp val) (symbolp val))
859 (if (pcase--self-quoting-p val)
860 `(eq ,sym ,val)
861 `(eq ,sym ',val)))
862 (t `(equal ,sym ',val)))
863 (pcase--u1 matches code vars then-rest)
864 (pcase--u else-rest))))
865 ((eq (car-safe upat) 'not)
866 ;; FIXME: The implementation below is naive and results in
867 ;; inefficient code.
868 ;; To make it work right, we would need to turn pcase--u1's
869 ;; `code' and `vars' into a single argument of the same form as
870 ;; `rest'. We would also need to split this new `then-rest' argument
871 ;; for every test (currently we don't bother to do it since
872 ;; it's only useful for odd patterns like (and `(PAT1 . PAT2)
873 ;; `(PAT3 . PAT4)) which the programmer can easily rewrite
874 ;; to the more efficient `(,(and PAT1 PAT3) . ,(and PAT2 PAT4))).
875 (pcase--u1 `((match ,sym . ,(cadr upat)))
876 ;; FIXME: This codegen is not careful to share its
877 ;; code if used several times: code blow up is likely.
878 (lambda (_vars)
879 ;; `vars' will likely contain bindings which are
880 ;; not always available in other paths to
881 ;; `rest', so there' no point trying to pass
882 ;; them down.
883 (pcase--u rest))
884 vars
885 (list `((and . ,matches) ,code . ,vars))))
886 (t (error "Unknown pattern `%S'" upat)))))
887 (t (error "Incorrect MATCH %S" (car matches)))))
889 (def-edebug-spec
890 pcase-QPAT
891 ;; Cf. edebug spec for `backquote-form' in edebug.el.
892 (&or ("," pcase-PAT)
893 (pcase-QPAT [&rest [&not ","] pcase-QPAT]
894 . [&or nil pcase-QPAT])
895 (vector &rest pcase-QPAT)
896 sexp))
898 (pcase-defmacro \` (qpat)
899 "Backquote-style pcase patterns.
900 QPAT can take the following forms:
901 (QPAT1 . QPAT2) matches if QPAT1 matches the car and QPAT2 the cdr.
902 [QPAT1 QPAT2..QPATn] matches a vector of length n and QPAT1..QPATn match
903 its 0..(n-1)th elements, respectively.
904 ,PAT matches if the pcase pattern PAT matches.
905 ATOM matches if the object is `equal' to ATOM.
906 ATOM can be a symbol, an integer, or a string."
907 (declare (debug (pcase-QPAT)))
908 (cond
909 ((eq (car-safe qpat) '\,) (cadr qpat))
910 ((vectorp qpat)
911 `(and (pred vectorp)
912 (app length ,(length qpat))
913 ,@(let ((upats nil))
914 (dotimes (i (length qpat))
915 (push `(app (pcase--flip aref ,i) ,(list '\` (aref qpat i)))
916 upats))
917 (nreverse upats))))
918 ((consp qpat)
919 `(and (pred consp)
920 (app car ,(list '\` (car qpat)))
921 (app cdr ,(list '\` (cdr qpat)))))
922 ((or (stringp qpat) (integerp qpat) (symbolp qpat)) `',qpat)
923 (t (error "Unknown QPAT: %S" qpat))))
926 (provide 'pcase)
927 ;;; pcase.el ends here