1 ;;; pcase.el --- ML-style pattern-matching macro for Elisp -*- lexical-binding: t -*-
3 ;; Copyright (C) 2010-2018 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
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 <https://www.gnu.org/licenses/>.
25 ;; ML-style pattern matching.
26 ;; The entry points are autoloaded.
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
42 ;; - provide a way to fallthrough to subsequent cases (not sure what I meant by
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.
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))
76 ("or" &rest pcase-PAT
)
77 ("and" &rest pcase-PAT
)
79 ("let" pcase-PAT form
)
81 ("app" pcase-FUN pcase-PAT
)
88 ;; Punt on macros/special forms.
89 (functionp &rest form
)
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)
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
))
107 (edebug-match cursor
(cons '&or specs
))))
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. The CODE
122 expression corresponding to the matching pattern determines the
123 return value. If there is no match the returned value is nil.
125 Another difference is that pattern elements may be quoted,
126 meaning they must match exactly: The pattern \\='(foo bar)
127 matches only against two element lists containing the symbols
128 `foo' and `bar' in that order. (As a short-hand, atoms always
129 match themselves, such as numbers or strings, and need not be
132 Lastly, a pattern can be logical, such as (pred numberp), that
133 matches any number-like element; or the symbol `_', that matches
134 anything. Also, when patterns are backquoted, a comma may be
135 used to introduce logical patterns inside backquoted patterns.
137 The complete list of standard patterns is as follows:
140 SYMBOL matches anything and binds it to SYMBOL.
141 If a SYMBOL is used twice in the same pattern
142 the second occurrence becomes an `eq'uality test.
143 (or PAT...) matches if any of the patterns matches.
144 (and PAT...) matches if all the patterns match.
145 \\='VAL matches if the object is `equal' to VAL.
146 ATOM is a shorthand for \\='ATOM.
147 ATOM can be a keyword, an integer, or a string.
148 (pred FUN) matches if FUN applied to the object returns non-nil.
149 (guard BOOLEXP) matches if BOOLEXP evaluates to non-nil.
150 (let PAT EXP) matches if EXP matches PAT.
151 (app FUN PAT) matches if FUN applied to the object matches PAT.
153 Additional patterns can be defined using `pcase-defmacro'.
155 The FUN argument in the `app' pattern may have the following forms:
156 SYMBOL or (lambda ARGS BODY) in which case it's called with one argument.
157 (F ARG1 .. ARGn) in which case F gets called with an n+1'th argument
158 which is the value being matched.
159 So a FUN of the form SYMBOL is equivalent to (FUN).
160 FUN can refer to variables bound earlier in the pattern.
162 See Info node `(elisp) Pattern matching case statement' in the
163 Emacs Lisp manual for more information and examples."
164 (declare (indent 1) (debug (form &rest
(pcase-PAT body
))))
165 ;; We want to use a weak hash table as a cache, but the key will unavoidably
166 ;; be based on `exp' and `cases', yet `cases' is a fresh new list each time
167 ;; we're called so it'll be immediately GC'd. So we use (car cases) as key
168 ;; which does come straight from the source code and should hence not be GC'd
170 (let ((data (gethash (car cases
) pcase--memoize
)))
171 ;; data = (EXP CASES . EXPANSION)
172 (if (and (equal exp
(car data
)) (equal cases
(cadr data
)))
173 ;; We have the right expansion.
175 ;; (when (gethash (car cases) pcase--memoize-1)
176 ;; (message "pcase-memoize failed because of weak key!!"))
177 ;; (when (gethash (car cases) pcase--memoize-2)
178 ;; (message "pcase-memoize failed because of eq test on %S"
181 ;; (message "pcase-memoize: equal first branch, yet different"))
182 (let ((expansion (pcase--expand exp cases
)))
183 (puthash (car cases
) `(,exp
,cases
,@expansion
) pcase--memoize
)
184 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-1)
185 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-2)
188 (declare-function help-fns--signature
"help-fns"
189 (function doc real-def real-function buffer
))
191 ;; FIXME: Obviously, this will collide with nadvice's use of
192 ;; function-documentation if we happen to advise `pcase'.
193 (put 'pcase
'function-documentation
'(pcase--make-docstring))
194 (defun pcase--make-docstring ()
195 (let* ((main (documentation (symbol-function 'pcase
) 'raw
))
196 (ud (help-split-fundoc main
'pcase
)))
197 ;; So that eg emacs -Q -l cl-lib --eval "(documentation 'pcase)" works,
198 ;; where cl-lib is anything using pcase-defmacro.
201 (insert (or (cdr ud
) main
))
204 (let ((me (get symbol
'pcase-macroexpander
)))
207 (let* ((doc (documentation me
'raw
)))
208 (setq doc
(help-fns--signature symbol doc me
209 (indirect-function me
) nil
))
210 (insert "\n" (or doc
"Not documented.")))))))
211 (let ((combined-doc (buffer-string)))
212 (if ud
(help-add-fundoc-usage combined-doc
(car ud
)) combined-doc
)))))
215 (defmacro pcase-exhaustive
(exp &rest cases
)
216 "The exhaustive version of `pcase' (which see).
217 If EXP fails to match any of the patterns in CASES, an error is signaled."
218 (declare (indent 1) (debug pcase
))
219 (let* ((x (gensym "x"))
220 (pcase--dontwarn-upats (cons x pcase--dontwarn-upats
)))
222 ;; FIXME: Could we add the FILE:LINE data in the error message?
223 exp
(append cases
`((,x
(error "No clause matching `%S'" ,x
)))))))
226 (defmacro pcase-lambda
(lambda-list &rest body
)
227 "Like `lambda' but allow each argument to be a pattern.
228 I.e. accepts the usual &optional and &rest keywords, but every
229 formal argument can be any pattern accepted by `pcase' (a mere
230 variable name being but a special case of it)."
231 (declare (doc-string 2) (indent defun
)
232 (debug (&define
(&rest pcase-PAT
) lambda-doc def-body
)))
234 (parsed-body (macroexp-parse-body body
))
235 (args (mapcar (lambda (pat)
237 ;; Simple vars and &rest/&optional are just passed
238 ;; through unchanged.
240 (let ((arg (make-symbol
241 (format "arg%s" (length bindings
)))))
242 (push `(,pat
,arg
) bindings
)
245 `(lambda ,args
,@(car parsed-body
)
246 (pcase-let* ,(nreverse bindings
) ,@(cdr parsed-body
)))))
248 (defun pcase--let* (bindings body
)
250 ((null bindings
) (macroexp-progn body
))
251 ((pcase--trivial-upat-p (caar bindings
))
252 (macroexp-let* `(,(car bindings
)) (pcase--let* (cdr bindings
) body
)))
254 (let ((binding (pop bindings
)))
257 `((,(car binding
) ,(pcase--let* bindings body
))
258 ;; We can either signal an error here, or just use `pcase--dontcare'
259 ;; which generates more efficient code. In practice, if we use
260 ;; `pcase--dontcare' we will still often get an error and the few
261 ;; cases where we don't do not matter that much, so
262 ;; it's a better choice.
263 (pcase--dontcare nil
)))))))
266 (defmacro pcase-let
* (bindings &rest body
)
267 "Like `let*' but where you can use `pcase' patterns for bindings.
268 BODY should be an expression, and BINDINGS should be a list of bindings
269 of the form (PAT EXP)."
271 (debug ((&rest
(pcase-PAT &optional form
)) body
)))
272 (let ((cached (gethash bindings pcase--memoize
)))
273 ;; cached = (BODY . EXPANSION)
274 (if (equal (car cached
) body
)
276 (let ((expansion (pcase--let* bindings body
)))
277 (puthash bindings
(cons body expansion
) pcase--memoize
)
281 (defmacro pcase-let
(bindings &rest body
)
282 "Like `let' but where you can use `pcase' patterns for bindings.
283 BODY should be a list of expressions, and BINDINGS should be a list of bindings
284 of the form (PAT EXP).
285 The macro is expanded and optimized under the assumption that those
286 patterns *will* match, so a mismatch may go undetected or may cause
288 (declare (indent 1) (debug pcase-let
*))
289 (if (null (cdr bindings
))
290 `(pcase-let* ,bindings
,@body
)
292 (dolist (binding (prog1 bindings
(setq bindings nil
)))
294 ((memq (car binding
) pcase--dontcare-upats
)
295 (push (cons (make-symbol "_") (cdr binding
)) bindings
))
296 ((pcase--trivial-upat-p (car binding
)) (push binding bindings
))
298 (let ((tmpvar (make-symbol (format "x%d" (length bindings
)))))
299 (push (cons tmpvar
(cdr binding
)) bindings
)
300 (push (list (car binding
) tmpvar
) matches
)))))
301 `(let ,(nreverse bindings
) (pcase-let* ,matches
,@body
)))))
304 (defmacro pcase-dolist
(spec &rest body
)
305 "Like `dolist' but where the binding can be a `pcase' pattern.
306 \n(fn (PATTERN LIST) BODY...)"
307 (declare (indent 1) (debug ((pcase-PAT form
) body
)))
308 (if (pcase--trivial-upat-p (car spec
))
309 `(dolist ,spec
,@body
)
310 (let ((tmpvar (gensym "x")))
311 `(dolist (,tmpvar
,@(cdr spec
))
312 (pcase-let* ((,(car spec
) ,tmpvar
))
316 (defun pcase--trivial-upat-p (upat)
317 (and (symbolp upat
) (not (memq upat pcase--dontcare-upats
))))
319 (defun pcase--expand (exp cases
)
320 ;; (message "pid=%S (pcase--expand %S ...hash=%S)"
321 ;; (emacs-pid) exp (sxhash cases))
322 (macroexp-let2 macroexp-copyable-p val exp
327 (let ((prev (assq code seen
)))
329 (let ((res (pcase-codegen code vars
)))
330 (push (list code vars res
) seen
)
332 ;; Since we use a tree-based pattern matching
333 ;; technique, the leaves (the places that contain the
334 ;; code to run once a pattern is matched) can get
335 ;; copied a very large number of times, so to avoid
336 ;; code explosion, we need to keep track of how many
337 ;; times we've used each leaf and move it
338 ;; to a separate function if that number is too high.
340 ;; We've already used this branch. So it is shared.
341 (let* ((code (car prev
)) (cdrprev (cdr prev
))
342 (prevvars (car cdrprev
)) (cddrprev (cdr cdrprev
))
343 (res (car cddrprev
)))
344 (unless (symbolp res
)
345 ;; This is the first repeat, so we have to move
346 ;; the branch to a separate function.
348 (make-symbol (format "pcase-%d" (length defs
)))))
349 (push `(,bsym
(lambda ,(mapcar #'car prevvars
) ,@code
))
351 (setcar res
'funcall
)
352 (setcdr res
(cons bsym
(mapcar #'cdr prevvars
)))
353 (setcar (cddr prev
) bsym
)
355 (setq vars
(copy-sequence vars
))
356 (let ((args (mapcar (lambda (pa)
357 (let ((v (assq (car pa
) vars
)))
358 (setq vars
(delq v vars
))
361 ;; If some of `vars' were not found in `prevvars', that's
362 ;; OK it just means those vars aren't present in all
363 ;; branches, so they can be used within the pattern
364 ;; (e.g. by a `guard/let/pred') but not in the branch.
365 ;; FIXME: But if some of `prevvars' are not in `vars' we
366 ;; should remove them from `prevvars'!
367 `(funcall ,res
,@args
)))))))
371 (mapcar (lambda (case)
372 `(,(pcase--match val
(pcase--macroexpand (car case
)))
374 (unless (memq case used-cases
)
375 ;; Keep track of the cases that are used.
376 (push case used-cases
))
378 (if (pcase--small-branch-p (cdr case
))
379 ;; Don't bother sharing multiple
380 ;; occurrences of this leaf since it's small.
381 #'pcase-codegen codegen
)
386 (unless (or (memq case used-cases
)
387 (memq (car case
) pcase--dontwarn-upats
))
388 (message "Redundant pcase pattern: %S" (car case
))))
389 (macroexp-let* defs main
))))
391 (defun pcase--macroexpand (pat)
392 "Expands all macro-patterns in PAT."
393 (let ((head (car-safe pat
)))
396 (if (pcase--self-quoting-p pat
) `',pat pat
))
397 ((memq head
'(pred guard quote
)) pat
)
398 ((memq head
'(or and
)) `(,head
,@(mapcar #'pcase--macroexpand
(cdr pat
))))
399 ((eq head
'let
) `(let ,(pcase--macroexpand (cadr pat
)) ,@(cddr pat
)))
400 ((eq head
'app
) `(app ,(nth 1 pat
) ,(pcase--macroexpand (nth 2 pat
))))
402 (let* ((expander (get head
'pcase-macroexpander
))
403 (npat (if expander
(apply expander
(cdr pat
)))))
406 "Unexpandable %s pattern: %S"
407 "Unknown %s pattern: %S")
409 (pcase--macroexpand npat
)))))))
412 (defmacro pcase-defmacro
(name args
&rest body
)
413 "Define a new kind of pcase PATTERN, by macro expansion.
414 Patterns of the form (NAME ...) will be expanded according
416 (declare (indent 2) (debug defun
) (doc-string 3))
417 ;; Add the function via `fsym', so that an autoload cookie placed
418 ;; on a pcase-defmacro will cause the macro to be loaded on demand.
419 (let ((fsym (intern (format "%s--pcase-macroexpander" name
)))
420 (decl (assq 'declare body
)))
421 (when decl
(setq body
(remove decl body
)))
423 (defun ,fsym
,args
,@body
)
424 (define-symbol-prop ',fsym
'edebug-form-spec
',(cadr (assq 'debug decl
)))
425 (define-symbol-prop ',name
'pcase-macroexpander
#',fsym
))))
427 (defun pcase--match (val upat
)
428 "Build a MATCH structure, hoisting all `or's and `and's outside."
430 ;; Hoist or/and patterns into or/and matches.
431 ((memq (car-safe upat
) '(or and
))
433 ,@(mapcar (lambda (upat)
434 (pcase--match val upat
))
437 `(match ,val .
,upat
))))
439 (defun pcase-codegen (code vars
)
440 ;; Don't use let*, otherwise macroexp-let* may merge it with some surrounding
441 ;; let* which might prevent the setcar/setcdr in pcase--expand's fancy
442 ;; codegen from later metamorphosing this let into a funcall.
444 `(let ,(mapcar (lambda (b) (list (car b
) (cdr b
))) vars
)
448 (defun pcase--small-branch-p (code)
449 (and (= 1 (length code
))
450 (or (not (consp (car code
)))
452 (dolist (e (car code
))
453 (if (consp e
) (setq small nil
)))
456 ;; Try to use `cond' rather than a sequence of `if's, so as to reduce
457 ;; the depth of the generated tree.
458 (defun pcase--if (test then else
)
460 ((eq else
:pcase--dontcare
) then
)
461 ((eq then
:pcase--dontcare
) (debug) else
) ;Can/should this ever happen?
462 (t (macroexp-if test then else
))))
465 ;; When we have patterns like `(PAT1 . PAT2), after performing the `consp'
466 ;; check, we want to turn all the similar patterns into ones of the form
467 ;; (and (match car PAT1) (match cdr PAT2)), so you naturally need conjunction.
468 ;; Earlier code hence used branches of the form (MATCHES . CODE) where
469 ;; MATCHES was a list (implicitly a conjunction) of (SYM . PAT).
470 ;; But if we have a pattern of the form (or `(PAT1 . PAT2) PAT3), there is
471 ;; no easy way to eliminate the `consp' check in such a representation.
472 ;; So we replaced the MATCHES by the MATCH below which can be made up
473 ;; of conjunctions and disjunctions, so if we know `foo' is a cons, we can
474 ;; turn (match foo . (or `(PAT1 . PAT2) PAT3)) into
475 ;; (or (and (match car . `PAT1) (match cdr . `PAT2)) (match foo . PAT3)).
476 ;; The downside is that we now have `or' and `and' both in MATCH and
477 ;; in PAT, so there are different equivalent representations and we
478 ;; need to handle them all. We do not try to systematically
479 ;; canonicalize them to one form over another, but we do occasionally
480 ;; turn one into the other.
482 (defun pcase--u (branches)
483 "Expand matcher for rules BRANCHES.
484 Each BRANCH has the form (MATCH CODE . VARS) where
485 CODE is the code generator for that branch.
486 VARS is the set of vars already bound by earlier matches.
487 MATCH is the pattern that needs to be matched, of the form:
491 (when (setq branches
(delq nil branches
))
492 (let* ((carbranch (car branches
))
493 (match (car carbranch
)) (cdarbranch (cdr carbranch
))
494 (code (car cdarbranch
))
495 (vars (cdr cdarbranch
)))
496 (pcase--u1 (list match
) code vars
(cdr branches
)))))
498 (defun pcase--and (match matches
)
499 (if matches
`(and ,match
,@matches
) match
))
501 (defconst pcase-mutually-exclusive-predicates
502 '((symbolp . integerp
)
508 (symbolp . byte-code-function-p
)
514 (integerp . byte-code-function-p
)
520 (numberp . byte-code-function-p
)
526 (consp . byte-code-function-p
)
528 (arrayp . byte-code-function-p
)
529 (vectorp . byte-code-function-p
)
533 (stringp . byte-code-function-p
)))
535 (defun pcase--mutually-exclusive-p (pred1 pred2
)
536 (or (member (cons pred1 pred2
)
537 pcase-mutually-exclusive-predicates
)
538 (member (cons pred2 pred1
)
539 pcase-mutually-exclusive-predicates
)))
541 (defun pcase--split-match (sym splitter match
)
543 ((eq (car-safe match
) 'match
)
544 (if (not (eq sym
(cadr match
)))
546 (let ((res (funcall splitter
(cddr match
))))
547 (cons (or (car res
) match
) (or (cdr res
) match
)))))
548 ((memq (car-safe match
) '(or and
))
549 (let ((then-alts '())
551 (neutral-elem (if (eq 'or
(car match
))
552 :pcase--fail
:pcase--succeed
))
553 (zero-elem (if (eq 'or
(car match
)) :pcase--succeed
:pcase--fail
)))
554 (dolist (alt (cdr match
))
555 (let ((split (pcase--split-match sym splitter alt
)))
556 (unless (eq (car split
) neutral-elem
)
557 (push (car split
) then-alts
))
558 (unless (eq (cdr split
) neutral-elem
)
559 (push (cdr split
) else-alts
))))
560 (cons (cond ((memq zero-elem then-alts
) zero-elem
)
561 ((null then-alts
) neutral-elem
)
562 ((null (cdr then-alts
)) (car then-alts
))
563 (t (cons (car match
) (nreverse then-alts
))))
564 (cond ((memq zero-elem else-alts
) zero-elem
)
565 ((null else-alts
) neutral-elem
)
566 ((null (cdr else-alts
)) (car else-alts
))
567 (t (cons (car match
) (nreverse else-alts
)))))))
568 ((memq match
'(:pcase--succeed
:pcase--fail
)) (cons match match
))
569 (t (error "Uknown MATCH %s" match
))))
571 (defun pcase--split-rest (sym splitter rest
)
572 (let ((then-rest '())
574 (dolist (branch rest
)
575 (let* ((match (car branch
))
576 (code&vars
(cdr branch
))
578 (pcase--split-match sym splitter match
)))
579 (unless (eq (car split
) :pcase--fail
)
580 (push (cons (car split
) code
&vars
) then-rest
))
581 (unless (eq (cdr split
) :pcase--fail
)
582 (push (cons (cdr split
) code
&vars
) else-rest
))))
583 (cons (nreverse then-rest
) (nreverse else-rest
))))
585 (defun pcase--split-equal (elem pat
)
587 ;; The same match will give the same result.
588 ((and (eq (car-safe pat
) 'quote
) (equal (cadr pat
) elem
))
589 '(:pcase--succeed .
:pcase--fail
))
590 ;; A different match will fail if this one succeeds.
591 ((and (eq (car-safe pat
) 'quote
)
592 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
593 ;; (consp (cadr pat)))
595 '(:pcase--fail . nil
))
596 ((and (eq (car-safe pat
) 'pred
)
598 (get (cadr pat
) 'side-effect-free
))
600 (if (funcall (cadr pat
) elem
)
601 '(:pcase--succeed . nil
)
602 '(:pcase--fail . nil
))))))
604 (defun pcase--split-member (elems pat
)
605 ;; FIXME: The new pred-based member code doesn't do these optimizations!
606 ;; Based on pcase--split-equal.
608 ;; The same match (or a match of membership in a superset) will
609 ;; give the same result, but we don't know how to check it.
611 ;; '(:pcase--succeed . nil))
612 ;; A match for one of the elements may succeed or fail.
613 ((and (eq (car-safe pat
) 'quote
) (member (cadr pat
) elems
))
615 ;; A different match will fail if this one succeeds.
616 ((and (eq (car-safe pat
) 'quote
)
617 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
618 ;; (consp (cadr pat)))
620 '(:pcase--fail . nil
))
621 ((and (eq (car-safe pat
) 'pred
)
623 (get (cadr pat
) 'side-effect-free
)
625 (let ((p (cadr pat
)) (all t
))
627 (unless (funcall p elem
) (setq all nil
)))
629 '(:pcase--succeed . nil
))))
631 (defun pcase--split-pred (vars upat pat
)
634 ((and (equal upat pat
)
635 ;; For predicates like (pred (> a)), two such predicates may
636 ;; actually refer to different variables `a'.
637 (or (and (eq 'pred
(car upat
)) (symbolp (cadr upat
)))
638 ;; FIXME: `vars' gives us the environment in which `upat' will
639 ;; run, but we don't have the environment in which `pat' will
640 ;; run, so we can't do a reliable verification. But let's try
641 ;; and catch at least the easy cases such as (bug#14773).
642 (not (pcase--fgrep (mapcar #'car vars
) (cadr upat
)))))
643 '(:pcase--succeed .
:pcase--fail
))
644 ((and (eq 'pred
(car upat
))
646 (cond ((eq 'pred
(car-safe pat
)) (cadr pat
))
647 ((not (eq 'quote
(car-safe pat
))) nil
)
648 ((consp (cadr pat
)) #'consp
)
649 ((stringp (cadr pat
)) #'stringp
)
650 ((vectorp (cadr pat
)) #'vectorp
)
651 ((byte-code-function-p (cadr pat
))
652 #'byte-code-function-p
))))
653 (pcase--mutually-exclusive-p (cadr upat
) otherpred
)))
654 '(:pcase--fail . nil
))
655 ((and (eq 'pred
(car upat
))
656 (eq 'quote
(car-safe pat
))
657 (symbolp (cadr upat
))
658 (or (symbolp (cadr pat
)) (stringp (cadr pat
)) (numberp (cadr pat
)))
659 (get (cadr upat
) 'side-effect-free
)
661 (setq test
(list (funcall (cadr upat
) (cadr pat
))))))
663 '(nil .
:pcase--fail
)
664 '(:pcase--fail . nil
))))))
666 (defun pcase--fgrep (vars sexp
)
667 "Check which of the symbols VARS appear in SEXP."
670 (dolist (var (pcase--fgrep vars
(pop sexp
)))
671 (unless (memq var res
) (push var res
))))
672 (and (memq sexp vars
) (not (memq sexp res
)) (push sexp res
))
675 (defun pcase--self-quoting-p (upat)
676 (or (keywordp upat
) (integerp upat
) (stringp upat
)))
678 (defun pcase--app-subst-match (match sym fun nsym
)
680 ((eq (car-safe match
) 'match
)
681 (if (and (eq sym
(cadr match
))
682 (eq 'app
(car-safe (cddr match
)))
683 (equal fun
(nth 1 (cddr match
))))
684 (pcase--match nsym
(nth 2 (cddr match
)))
686 ((memq (car-safe match
) '(or and
))
688 ,@(mapcar (lambda (match)
689 (pcase--app-subst-match match sym fun nsym
))
691 ((memq match
'(:pcase--succeed
:pcase--fail
)) match
)
692 (t (error "Uknown MATCH %s" match
))))
694 (defun pcase--app-subst-rest (rest sym fun nsym
)
695 (mapcar (lambda (branch)
696 `(,(pcase--app-subst-match (car branch
) sym fun nsym
)
700 (defsubst pcase--mark-used
(sym)
701 ;; Exceptionally, `sym' may be a constant expression rather than a symbol.
702 (if (symbolp sym
) (put sym
'pcase-used t
)))
704 (defmacro pcase--flip
(fun arg1 arg2
)
705 "Helper function, used internally to avoid (funcall (lambda ...) ...)."
706 (declare (debug (sexp body
)))
709 (defun pcase--funcall (fun arg vars
)
710 "Build a function call to FUN with arg ARG."
713 (let* (;; `vs' is an upper bound on the vars we need.
714 (vs (pcase--fgrep (mapcar #'car vars
) fun
))
715 (env (mapcar (lambda (var)
716 (list var
(cdr (assq var vars
))))
720 ;; `arg' is shadowed by `env'.
721 (let ((newsym (gensym "x")))
722 (push (list newsym arg
) env
)
725 `(funcall #',fun
,arg
)
729 ;; Let's not replace `vars' in `fun' since it's
730 ;; too difficult to do it right, instead just
731 ;; let-bind `vars' around `fun'.
732 `(let* ,env
,call
)))))
734 (defun pcase--eval (exp vars
)
735 "Build an expression that will evaluate EXP."
736 (let* ((found (assq exp vars
)))
737 (if found
(cdr found
)
738 (let* ((vs (pcase--fgrep (mapcar #'car vars
) exp
))
739 (env (mapcar (lambda (v) (list v
(cdr (assq v vars
))))
741 (if env
(macroexp-let* env exp
) exp
)))))
743 ;; It's very tempting to use `pcase' below, tho obviously, it'd create
744 ;; bootstrapping problems.
745 (defun pcase--u1 (matches code vars rest
)
746 "Return code that runs CODE (with VARS) if MATCHES match.
747 Otherwise, it defers to REST which is a list of branches of the form
748 \(ELSE-MATCH ELSE-CODE . ELSE-VARS)."
749 ;; Depending on the order in which we choose to check each of the MATCHES,
750 ;; the resulting tree may be smaller or bigger. So in general, we'd want
751 ;; to be careful to chose the "optimal" order. But predicate
752 ;; patterns make this harder because they create dependencies
753 ;; between matches. So we don't bother trying to reorder anything.
755 ((null matches
) (funcall code vars
))
756 ((eq :pcase--fail
(car matches
)) (pcase--u rest
))
757 ((eq :pcase--succeed
(car matches
))
758 (pcase--u1 (cdr matches
) code vars rest
))
759 ((eq 'and
(caar matches
))
760 (pcase--u1 (append (cdar matches
) (cdr matches
)) code vars rest
))
761 ((eq 'or
(caar matches
))
762 (let* ((alts (cdar matches
))
763 (var (if (eq (caar alts
) 'match
) (cadr (car alts
))))
764 (simples '()) (others '()) (memq-ok t
))
767 (if (and (eq (car alt
) 'match
) (eq var
(cadr alt
))
768 (let ((upat (cddr alt
)))
769 (eq (car-safe upat
) 'quote
)))
770 (let ((val (cadr (cddr alt
))))
771 (unless (or (integerp val
) (symbolp val
))
773 (push (cadr (cddr alt
)) simples
))
776 ((null alts
) (error "Please avoid it") (pcase--u rest
))
777 ;; Yes, we can use `memq' (or `member')!
778 ((> (length simples
) 1)
779 (pcase--u1 (cons `(match ,var
781 ,(if memq-ok
#'memq
#'member
)
785 (if (null others
) rest
787 (pcase--and (if (cdr others
)
788 (cons 'or
(nreverse others
))
794 (pcase--u1 (cons (pop alts
) (cdr matches
)) code vars
795 (if (null alts
) (progn (error "Please avoid it") rest
)
797 (pcase--and (if (cdr alts
)
798 (cons 'or alts
) (car alts
))
802 ((eq 'match
(caar matches
))
803 (let* ((popmatches (pop matches
))
804 (_op (car popmatches
)) (cdrpopmatches (cdr popmatches
))
805 (sym (car cdrpopmatches
))
806 (upat (cdr cdrpopmatches
)))
809 (let ((code (pcase--u1 matches code vars rest
)))
810 (if (eq upat
'_
) code
811 (macroexp--warn-and-return
812 "Pattern t is deprecated. Use `_' instead"
814 ((eq upat
'pcase--dontcare
) :pcase--dontcare
)
815 ((memq (car-safe upat
) '(guard pred
))
816 (if (eq (car upat
) 'pred
) (pcase--mark-used sym
))
819 sym
(lambda (pat) (pcase--split-pred vars upat pat
)) rest
))
820 (then-rest (car splitrest
))
821 (else-rest (cdr splitrest
)))
822 (pcase--if (if (eq (car upat
) 'pred
)
823 (pcase--funcall (cadr upat
) sym vars
)
824 (pcase--eval (cadr upat
) vars
))
825 (pcase--u1 matches code vars then-rest
)
826 (pcase--u else-rest
))))
827 ((and (symbolp upat
) upat
)
828 (pcase--mark-used sym
)
829 (if (not (assq upat vars
))
830 (pcase--u1 matches code
(cons (cons upat sym
) vars
) rest
)
831 ;; Non-linear pattern. Turn it into an `eq' test.
832 (pcase--u1 (cons `(match ,sym .
(pred (eq ,(cdr (assq upat vars
)))))
835 ((eq (car-safe upat
) 'let
)
836 ;; A upat of the form (let VAR EXP).
837 ;; (pcase--u1 matches code
838 ;; (cons (cons (nth 1 upat) (nth 2 upat)) vars) rest)
840 macroexp-copyable-p sym
841 (pcase--eval (nth 2 upat
) vars
)
842 (pcase--u1 (cons (pcase--match sym
(nth 1 upat
)) matches
)
844 ((eq (car-safe upat
) 'app
)
845 ;; A upat of the form (app FUN PAT)
846 (pcase--mark-used sym
)
847 (let* ((fun (nth 1 upat
))
850 ;; We don't change `matches' to reuse the newly computed value,
851 ;; because we assume there shouldn't be such redundancy in there.
852 (pcase--u1 (cons (pcase--match nsym
(nth 2 upat
)) matches
)
854 (pcase--app-subst-rest rest sym fun nsym
))))
855 (if (not (get nsym
'pcase-used
))
858 `((,nsym
,(pcase--funcall fun sym vars
)))
860 ((eq (car-safe upat
) 'quote
)
861 (pcase--mark-used sym
)
862 (let* ((val (cadr upat
))
863 (splitrest (pcase--split-rest
864 sym
(lambda (pat) (pcase--split-equal val pat
)) rest
))
865 (then-rest (car splitrest
))
866 (else-rest (cdr splitrest
)))
868 ((null val
) `(null ,sym
))
869 ((or (integerp val
) (symbolp val
))
870 (if (pcase--self-quoting-p val
)
873 (t `(equal ,sym
',val
)))
874 (pcase--u1 matches code vars then-rest
)
875 (pcase--u else-rest
))))
876 ((eq (car-safe upat
) 'not
)
877 ;; FIXME: The implementation below is naive and results in
879 ;; To make it work right, we would need to turn pcase--u1's
880 ;; `code' and `vars' into a single argument of the same form as
881 ;; `rest'. We would also need to split this new `then-rest' argument
882 ;; for every test (currently we don't bother to do it since
883 ;; it's only useful for odd patterns like (and `(PAT1 . PAT2)
884 ;; `(PAT3 . PAT4)) which the programmer can easily rewrite
885 ;; to the more efficient `(,(and PAT1 PAT3) . ,(and PAT2 PAT4))).
886 (pcase--u1 `((match ,sym .
,(cadr upat
)))
887 ;; FIXME: This codegen is not careful to share its
888 ;; code if used several times: code blow up is likely.
890 ;; `vars' will likely contain bindings which are
891 ;; not always available in other paths to
892 ;; `rest', so there' no point trying to pass
896 (list `((and .
,matches
) ,code .
,vars
))))
897 (t (error "Unknown pattern `%S'" upat
)))))
898 (t (error "Incorrect MATCH %S" (car matches
)))))
902 ;; Cf. edebug spec for `backquote-form' in edebug.el.
904 (pcase-QPAT [&rest
[¬
","] pcase-QPAT
]
905 .
[&or nil pcase-QPAT
])
906 (vector &rest pcase-QPAT
)
909 (pcase-defmacro \
` (qpat)
910 "Backquote-style pcase patterns.
911 QPAT can take the following forms:
912 (QPAT1 . QPAT2) matches if QPAT1 matches the car and QPAT2 the cdr.
913 [QPAT1 QPAT2..QPATn] matches a vector of length n and QPAT1..QPATn match
914 its 0..(n-1)th elements, respectively.
915 ,PAT matches if the pcase pattern PAT matches.
916 ATOM matches if the object is `equal' to ATOM.
917 ATOM can be a symbol, an integer, or a string."
918 (declare (debug (pcase-QPAT)))
920 ((eq (car-safe qpat
) '\
,) (cadr qpat
))
923 (app length
,(length qpat
))
925 (dotimes (i (length qpat
))
926 (push `(app (pcase--flip aref
,i
) ,(list '\
` (aref qpat i
)))
931 (app car
,(list '\
` (car qpat
)))
932 (app cdr
,(list '\
` (cdr qpat
)))))
933 ((or (stringp qpat
) (integerp qpat
) (symbolp qpat
)) `',qpat
)
934 (t (error "Unknown QPAT: %S" qpat
))))
937 ;;; pcase.el ends here