1 ;;; pcase.el --- ML-style pattern-matching macro for Elisp -*- lexical-binding: t; coding: utf-8 -*-
3 ;; Copyright (C) 2010-2015 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 <http://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
)
92 (def-edebug-spec pcase-MACRO pcase--edebug-match-macro
)
94 ;; Only called from edebug.
95 (declare-function get-edebug-spec
"edebug" (symbol))
96 (declare-function edebug-match
"edebug" (cursor specs
))
98 (defun pcase--edebug-match-macro (cursor)
102 (let ((m (get s
'pcase-macroexpander
)))
103 (when (and m
(get-edebug-spec m
))
104 (push (cons (symbol-name s
) (get-edebug-spec m
))
106 (edebug-match cursor
(cons '&or specs
))))
109 (defmacro pcase
(exp &rest cases
)
110 "Perform ML-style pattern matching on EXP.
111 CASES is a list of elements of the form (PATTERN CODE...).
113 Patterns can take the following forms:
115 SYMBOL matches anything and binds it to SYMBOL.
116 (or PAT...) matches if any of the patterns matches.
117 (and PAT...) matches if all the patterns match.
118 'VAL matches if the object is `equal' to VAL
119 ATOM is a shorthand for 'ATOM.
120 ATOM can be a keyword, an integer, or a string.
121 (pred FUN) matches if FUN applied to the object returns non-nil.
122 (guard BOOLEXP) matches if BOOLEXP evaluates to non-nil.
123 (let PAT EXP) matches if EXP matches PAT.
124 (app FUN PAT) matches if FUN applied to the object matches PAT.
125 If a SYMBOL is used twice in the same pattern (i.e. the pattern is
126 \"non-linear\"), then the second occurrence is turned into an `eq'uality test.
128 FUN can take the form
129 SYMBOL or (lambda ARGS BODY) in which case it's called with one argument.
130 (F ARG1 .. ARGn) in which case F gets called with an n+1'th argument
131 which is the value being matched.
132 So a FUN of the form SYMBOL is equivalent to one of the form (FUN).
133 FUN can refer to variables bound earlier in the pattern.
134 FUN is assumed to be pure, i.e. it can be dropped if its result is not used,
135 and two identical calls can be merged into one.
136 E.g. you can match pairs where the cdr is larger than the car with a pattern
137 like \\=`(,a . ,(pred (< a))) or, with more checks:
138 \\=`(,(and a (pred numberp)) . ,(and (pred numberp) (pred (< a))))
140 Additional patterns can be defined via `pcase-defmacro'.
141 Currently, the following patterns are provided this way:"
142 (declare (indent 1) (debug (form &rest
(pcase-PAT body
))))
143 ;; We want to use a weak hash table as a cache, but the key will unavoidably
144 ;; be based on `exp' and `cases', yet `cases' is a fresh new list each time
145 ;; we're called so it'll be immediately GC'd. So we use (car cases) as key
146 ;; which does come straight from the source code and should hence not be GC'd
148 (let ((data (gethash (car cases
) pcase--memoize
)))
149 ;; data = (EXP CASES . EXPANSION)
150 (if (and (equal exp
(car data
)) (equal cases
(cadr data
)))
151 ;; We have the right expansion.
153 ;; (when (gethash (car cases) pcase--memoize-1)
154 ;; (message "pcase-memoize failed because of weak key!!"))
155 ;; (when (gethash (car cases) pcase--memoize-2)
156 ;; (message "pcase-memoize failed because of eq test on %S"
159 (message "pcase-memoize: equal first branch, yet different"))
160 (let ((expansion (pcase--expand exp cases
)))
161 (puthash (car cases
) `(,exp
,cases
,@expansion
) pcase--memoize
)
162 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-1)
163 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-2)
166 (declare-function help-fns--signature
"help-fns"
167 (function doc real-def real-function raw
))
169 ;; FIXME: Obviously, this will collide with nadvice's use of
170 ;; function-documentation if we happen to advise `pcase'.
171 (put 'pcase
'function-documentation
'(pcase--make-docstring))
172 (defun pcase--make-docstring ()
173 (let* ((main (documentation (symbol-function 'pcase
) 'raw
))
174 (ud (help-split-fundoc main
'pcase
)))
175 ;; So that eg emacs -Q -l cl-lib --eval "(documentation 'pcase)" works,
176 ;; where cl-lib is anything using pcase-defmacro.
179 (insert (or (cdr ud
) main
))
182 (let ((me (get symbol
'pcase-macroexpander
)))
185 (let* ((doc (documentation me
'raw
)))
186 (setq doc
(help-fns--signature symbol doc me
187 (indirect-function me
) t
))
188 (insert "\n" (or doc
"Not documented.")))))))
189 (let ((combined-doc (buffer-string)))
190 (if ud
(help-add-fundoc-usage combined-doc
(car ud
)) combined-doc
)))))
193 (defmacro pcase-exhaustive
(exp &rest cases
)
194 "The exhaustive version of `pcase' (which see)."
195 (declare (indent 1) (debug pcase
))
196 (let* ((x (make-symbol "x"))
197 (pcase--dontwarn-upats (cons x pcase--dontwarn-upats
)))
199 ;; FIXME: Could we add the FILE:LINE data in the error message?
200 exp
(append cases
`((,x
(error "No clause matching `%S'" ,x
)))))))
203 (defmacro pcase-lambda
(lambda-list &rest body
)
204 "Like `lambda' but allow each argument to be a pattern.
205 I.e. accepts the usual &optional and &rest keywords, but every
206 formal argument can be any pattern accepted by `pcase' (a mere
207 variable name being but a special case of it)."
208 (declare (doc-string 2) (indent defun
)
209 (debug ((&rest pcase-PAT
) body
)))
211 (parsed-body (macroexp-parse-body body
))
212 (args (mapcar (lambda (pat)
214 ;; Simple vars and &rest/&optional are just passed
215 ;; through unchanged.
217 (let ((arg (make-symbol
218 (format "arg%s" (length bindings
)))))
219 (push `(,pat
,arg
) bindings
)
222 `(lambda ,args
,@(car parsed-body
)
223 (pcase-let* ,(nreverse bindings
) ,@(cdr parsed-body
)))))
225 (defun pcase--let* (bindings body
)
227 ((null bindings
) (macroexp-progn body
))
228 ((pcase--trivial-upat-p (caar bindings
))
229 (macroexp-let* `(,(car bindings
)) (pcase--let* (cdr bindings
) body
)))
231 (let ((binding (pop bindings
)))
234 `((,(car binding
) ,(pcase--let* bindings body
))
235 ;; We can either signal an error here, or just use `pcase--dontcare'
236 ;; which generates more efficient code. In practice, if we use
237 ;; `pcase--dontcare' we will still often get an error and the few
238 ;; cases where we don't do not matter that much, so
239 ;; it's a better choice.
240 (pcase--dontcare nil
)))))))
243 (defmacro pcase-let
* (bindings &rest body
)
244 "Like `let*' but where you can use `pcase' patterns for bindings.
245 BODY should be an expression, and BINDINGS should be a list of bindings
246 of the form (PAT EXP)."
248 (debug ((&rest
(pcase-PAT &optional form
)) body
)))
249 (let ((cached (gethash bindings pcase--memoize
)))
250 ;; cached = (BODY . EXPANSION)
251 (if (equal (car cached
) body
)
253 (let ((expansion (pcase--let* bindings body
)))
254 (puthash bindings
(cons body expansion
) pcase--memoize
)
258 (defmacro pcase-let
(bindings &rest body
)
259 "Like `let' but where you can use `pcase' patterns for bindings.
260 BODY should be a list of expressions, and BINDINGS should be a list of bindings
261 of the form (PAT EXP).
262 The macro is expanded and optimized under the assumption that those
263 patterns *will* match, so a mismatch may go undetected or may cause
265 (declare (indent 1) (debug pcase-let
*))
266 (if (null (cdr bindings
))
267 `(pcase-let* ,bindings
,@body
)
269 (dolist (binding (prog1 bindings
(setq bindings nil
)))
271 ((memq (car binding
) pcase--dontcare-upats
)
272 (push (cons (make-symbol "_") (cdr binding
)) bindings
))
273 ((pcase--trivial-upat-p (car binding
)) (push binding bindings
))
275 (let ((tmpvar (make-symbol (format "x%d" (length bindings
)))))
276 (push (cons tmpvar
(cdr binding
)) bindings
)
277 (push (list (car binding
) tmpvar
) matches
)))))
278 `(let ,(nreverse bindings
) (pcase-let* ,matches
,@body
)))))
281 (defmacro pcase-dolist
(spec &rest body
)
282 (declare (indent 1) (debug ((pcase-PAT form
) body
)))
283 (if (pcase--trivial-upat-p (car spec
))
284 `(dolist ,spec
,@body
)
285 (let ((tmpvar (make-symbol "x")))
286 `(dolist (,tmpvar
,@(cdr spec
))
287 (pcase-let* ((,(car spec
) ,tmpvar
))
291 (defun pcase--trivial-upat-p (upat)
292 (and (symbolp upat
) (not (memq upat pcase--dontcare-upats
))))
294 (defun pcase--expand (exp cases
)
295 ;; (message "pid=%S (pcase--expand %S ...hash=%S)"
296 ;; (emacs-pid) exp (sxhash cases))
297 (macroexp-let2 macroexp-copyable-p val exp
302 (let ((prev (assq code seen
)))
304 (let ((res (pcase-codegen code vars
)))
305 (push (list code vars res
) seen
)
307 ;; Since we use a tree-based pattern matching
308 ;; technique, the leaves (the places that contain the
309 ;; code to run once a pattern is matched) can get
310 ;; copied a very large number of times, so to avoid
311 ;; code explosion, we need to keep track of how many
312 ;; times we've used each leaf and move it
313 ;; to a separate function if that number is too high.
315 ;; We've already used this branch. So it is shared.
316 (let* ((code (car prev
)) (cdrprev (cdr prev
))
317 (prevvars (car cdrprev
)) (cddrprev (cdr cdrprev
))
318 (res (car cddrprev
)))
319 (unless (symbolp res
)
320 ;; This is the first repeat, so we have to move
321 ;; the branch to a separate function.
323 (make-symbol (format "pcase-%d" (length defs
)))))
324 (push `(,bsym
(lambda ,(mapcar #'car prevvars
) ,@code
))
326 (setcar res
'funcall
)
327 (setcdr res
(cons bsym
(mapcar #'cdr prevvars
)))
328 (setcar (cddr prev
) bsym
)
330 (setq vars
(copy-sequence vars
))
331 (let ((args (mapcar (lambda (pa)
332 (let ((v (assq (car pa
) vars
)))
333 (setq vars
(delq v vars
))
336 ;; If some of `vars' were not found in `prevvars', that's
337 ;; OK it just means those vars aren't present in all
338 ;; branches, so they can be used within the pattern
339 ;; (e.g. by a `guard/let/pred') but not in the branch.
340 ;; FIXME: But if some of `prevvars' are not in `vars' we
341 ;; should remove them from `prevvars'!
342 `(funcall ,res
,@args
)))))))
346 (mapcar (lambda (case)
347 `(,(pcase--match val
(pcase--macroexpand (car case
)))
349 (unless (memq case used-cases
)
350 ;; Keep track of the cases that are used.
351 (push case used-cases
))
353 (if (pcase--small-branch-p (cdr case
))
354 ;; Don't bother sharing multiple
355 ;; occurrences of this leaf since it's small.
356 #'pcase-codegen codegen
)
361 (unless (or (memq case used-cases
)
362 (memq (car case
) pcase--dontwarn-upats
))
363 (message "Redundant pcase pattern: %S" (car case
))))
364 (macroexp-let* defs main
))))
366 (defun pcase--macroexpand (pat)
367 "Expands all macro-patterns in PAT."
368 (let ((head (car-safe pat
)))
371 (if (pcase--self-quoting-p pat
) `',pat pat
))
372 ((memq head
'(pred guard quote
)) pat
)
373 ((memq head
'(or and
)) `(,head
,@(mapcar #'pcase--macroexpand
(cdr pat
))))
374 ((eq head
'let
) `(let ,(pcase--macroexpand (cadr pat
)) ,@(cddr pat
)))
375 ((eq head
'app
) `(app ,(nth 1 pat
) ,(pcase--macroexpand (nth 2 pat
))))
377 (let* ((expander (get head
'pcase-macroexpander
))
378 (npat (if expander
(apply expander
(cdr pat
)))))
381 "Unexpandable %s pattern: %S"
382 "Unknown %s pattern: %S")
384 (pcase--macroexpand npat
)))))))
387 (defmacro pcase-defmacro
(name args
&rest body
)
388 "Define a new kind of pcase PATTERN, by macro expansion.
389 Patterns of the form (NAME ...) will be expanded according
391 (declare (indent 2) (debug defun
) (doc-string 3))
392 ;; Add the function via `fsym', so that an autoload cookie placed
393 ;; on a pcase-defmacro will cause the macro to be loaded on demand.
394 (let ((fsym (intern (format "%s--pcase-macroexpander" name
)))
395 (decl (assq 'declare body
)))
396 (when decl
(setq body
(remove decl body
)))
398 (defun ,fsym
,args
,@body
)
399 (put ',fsym
'edebug-form-spec
',(cadr (assq 'debug decl
)))
400 (put ',name
'pcase-macroexpander
#',fsym
))))
402 (defun pcase--match (val upat
)
403 "Build a MATCH structure, hoisting all `or's and `and's outside."
405 ;; Hoist or/and patterns into or/and matches.
406 ((memq (car-safe upat
) '(or and
))
408 ,@(mapcar (lambda (upat)
409 (pcase--match val upat
))
412 `(match ,val .
,upat
))))
414 (defun pcase-codegen (code vars
)
415 ;; Don't use let*, otherwise macroexp-let* may merge it with some surrounding
416 ;; let* which might prevent the setcar/setcdr in pcase--expand's fancy
417 ;; codegen from later metamorphosing this let into a funcall.
418 `(let ,(mapcar (lambda (b) (list (car b
) (cdr b
))) vars
)
421 (defun pcase--small-branch-p (code)
422 (and (= 1 (length code
))
423 (or (not (consp (car code
)))
425 (dolist (e (car code
))
426 (if (consp e
) (setq small nil
)))
429 ;; Try to use `cond' rather than a sequence of `if's, so as to reduce
430 ;; the depth of the generated tree.
431 (defun pcase--if (test then else
)
433 ((eq else
:pcase--dontcare
) then
)
434 ((eq then
:pcase--dontcare
) (debug) else
) ;Can/should this ever happen?
435 (t (macroexp-if test then else
))))
438 ;; When we have patterns like `(PAT1 . PAT2), after performing the `consp'
439 ;; check, we want to turn all the similar patterns into ones of the form
440 ;; (and (match car PAT1) (match cdr PAT2)), so you naturally need conjunction.
441 ;; Earlier code hence used branches of the form (MATCHES . CODE) where
442 ;; MATCHES was a list (implicitly a conjunction) of (SYM . PAT).
443 ;; But if we have a pattern of the form (or `(PAT1 . PAT2) PAT3), there is
444 ;; no easy way to eliminate the `consp' check in such a representation.
445 ;; So we replaced the MATCHES by the MATCH below which can be made up
446 ;; of conjunctions and disjunctions, so if we know `foo' is a cons, we can
447 ;; turn (match foo . (or `(PAT1 . PAT2) PAT3)) into
448 ;; (or (and (match car . `PAT1) (match cdr . `PAT2)) (match foo . PAT3)).
449 ;; The downside is that we now have `or' and `and' both in MATCH and
450 ;; in PAT, so there are different equivalent representations and we
451 ;; need to handle them all. We do not try to systematically
452 ;; canonicalize them to one form over another, but we do occasionally
453 ;; turn one into the other.
455 (defun pcase--u (branches)
456 "Expand matcher for rules BRANCHES.
457 Each BRANCH has the form (MATCH CODE . VARS) where
458 CODE is the code generator for that branch.
459 VARS is the set of vars already bound by earlier matches.
460 MATCH is the pattern that needs to be matched, of the form:
464 (when (setq branches
(delq nil branches
))
465 (let* ((carbranch (car branches
))
466 (match (car carbranch
)) (cdarbranch (cdr carbranch
))
467 (code (car cdarbranch
))
468 (vars (cdr cdarbranch
)))
469 (pcase--u1 (list match
) code vars
(cdr branches
)))))
471 (defun pcase--and (match matches
)
472 (if matches
`(and ,match
,@matches
) match
))
474 (defconst pcase-mutually-exclusive-predicates
475 '((symbolp . integerp
)
481 (symbolp . byte-code-function-p
)
486 (integerp . byte-code-function-p
)
491 (numberp . byte-code-function-p
)
495 (consp . byte-code-function-p
)
496 (arrayp . byte-code-function-p
)
497 (vectorp . byte-code-function-p
)
499 (stringp . byte-code-function-p
)))
501 (defun pcase--mutually-exclusive-p (pred1 pred2
)
502 (or (member (cons pred1 pred2
)
503 pcase-mutually-exclusive-predicates
)
504 (member (cons pred2 pred1
)
505 pcase-mutually-exclusive-predicates
)))
507 (defun pcase--split-match (sym splitter match
)
509 ((eq (car-safe match
) 'match
)
510 (if (not (eq sym
(cadr match
)))
512 (let ((res (funcall splitter
(cddr match
))))
513 (cons (or (car res
) match
) (or (cdr res
) match
)))))
514 ((memq (car-safe match
) '(or and
))
515 (let ((then-alts '())
517 (neutral-elem (if (eq 'or
(car match
))
518 :pcase--fail
:pcase--succeed
))
519 (zero-elem (if (eq 'or
(car match
)) :pcase--succeed
:pcase--fail
)))
520 (dolist (alt (cdr match
))
521 (let ((split (pcase--split-match sym splitter alt
)))
522 (unless (eq (car split
) neutral-elem
)
523 (push (car split
) then-alts
))
524 (unless (eq (cdr split
) neutral-elem
)
525 (push (cdr split
) else-alts
))))
526 (cons (cond ((memq zero-elem then-alts
) zero-elem
)
527 ((null then-alts
) neutral-elem
)
528 ((null (cdr then-alts
)) (car then-alts
))
529 (t (cons (car match
) (nreverse then-alts
))))
530 (cond ((memq zero-elem else-alts
) zero-elem
)
531 ((null else-alts
) neutral-elem
)
532 ((null (cdr else-alts
)) (car else-alts
))
533 (t (cons (car match
) (nreverse else-alts
)))))))
534 ((memq match
'(:pcase--succeed
:pcase--fail
)) (cons match match
))
535 (t (error "Uknown MATCH %s" match
))))
537 (defun pcase--split-rest (sym splitter rest
)
538 (let ((then-rest '())
540 (dolist (branch rest
)
541 (let* ((match (car branch
))
542 (code&vars
(cdr branch
))
544 (pcase--split-match sym splitter match
)))
545 (unless (eq (car split
) :pcase--fail
)
546 (push (cons (car split
) code
&vars
) then-rest
))
547 (unless (eq (cdr split
) :pcase--fail
)
548 (push (cons (cdr split
) code
&vars
) else-rest
))))
549 (cons (nreverse then-rest
) (nreverse else-rest
))))
551 (defun pcase--split-equal (elem pat
)
553 ;; The same match will give the same result.
554 ((and (eq (car-safe pat
) 'quote
) (equal (cadr pat
) elem
))
555 '(:pcase--succeed .
:pcase--fail
))
556 ;; A different match will fail if this one succeeds.
557 ((and (eq (car-safe pat
) 'quote
)
558 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
559 ;; (consp (cadr pat)))
561 '(:pcase--fail . nil
))
562 ((and (eq (car-safe pat
) 'pred
)
564 (get (cadr pat
) 'side-effect-free
))
566 (if (funcall (cadr pat
) elem
)
567 '(:pcase--succeed . nil
)
568 '(:pcase--fail . nil
))))))
570 (defun pcase--split-member (elems pat
)
571 ;; FIXME: The new pred-based member code doesn't do these optimizations!
572 ;; Based on pcase--split-equal.
574 ;; The same match (or a match of membership in a superset) will
575 ;; give the same result, but we don't know how to check it.
577 ;; '(:pcase--succeed . nil))
578 ;; A match for one of the elements may succeed or fail.
579 ((and (eq (car-safe pat
) 'quote
) (member (cadr pat
) elems
))
581 ;; A different match will fail if this one succeeds.
582 ((and (eq (car-safe pat
) 'quote
)
583 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
584 ;; (consp (cadr pat)))
586 '(:pcase--fail . nil
))
587 ((and (eq (car-safe pat
) 'pred
)
589 (get (cadr pat
) 'side-effect-free
)
591 (let ((p (cadr pat
)) (all t
))
593 (unless (funcall p elem
) (setq all nil
)))
595 '(:pcase--succeed . nil
))))
597 (defun pcase--split-pred (vars upat pat
)
600 ((and (equal upat pat
)
601 ;; For predicates like (pred (> a)), two such predicates may
602 ;; actually refer to different variables `a'.
603 (or (and (eq 'pred
(car upat
)) (symbolp (cadr upat
)))
604 ;; FIXME: `vars' gives us the environment in which `upat' will
605 ;; run, but we don't have the environment in which `pat' will
606 ;; run, so we can't do a reliable verification. But let's try
607 ;; and catch at least the easy cases such as (bug#14773).
608 (not (pcase--fgrep (mapcar #'car vars
) (cadr upat
)))))
609 '(:pcase--succeed .
:pcase--fail
))
610 ((and (eq 'pred
(car upat
))
612 (cond ((eq 'pred
(car-safe pat
)) (cadr pat
))
613 ((not (eq 'quote
(car-safe pat
))) nil
)
614 ((consp (cadr pat
)) #'consp
)
615 ((stringp (cadr pat
)) #'stringp
)
616 ((vectorp (cadr pat
)) #'vectorp
)
617 ((byte-code-function-p (cadr pat
))
618 #'byte-code-function-p
))))
619 (pcase--mutually-exclusive-p (cadr upat
) otherpred
)))
620 '(:pcase--fail . nil
))
621 ((and (eq 'pred
(car upat
))
622 (eq 'quote
(car-safe pat
))
623 (symbolp (cadr upat
))
624 (or (symbolp (cadr pat
)) (stringp (cadr pat
)) (numberp (cadr pat
)))
625 (get (cadr upat
) 'side-effect-free
)
627 (setq test
(list (funcall (cadr upat
) (cadr pat
))))))
629 '(nil .
:pcase--fail
)
630 '(:pcase--fail . nil
))))))
632 (defun pcase--fgrep (vars sexp
)
633 "Check which of the symbols VARS appear in SEXP."
636 (dolist (var (pcase--fgrep vars
(pop sexp
)))
637 (unless (memq var res
) (push var res
))))
638 (and (memq sexp vars
) (not (memq sexp res
)) (push sexp res
))
641 (defun pcase--self-quoting-p (upat)
642 (or (keywordp upat
) (integerp upat
) (stringp upat
)))
644 (defun pcase--app-subst-match (match sym fun nsym
)
646 ((eq (car-safe match
) 'match
)
647 (if (and (eq sym
(cadr match
))
648 (eq 'app
(car-safe (cddr match
)))
649 (equal fun
(nth 1 (cddr match
))))
650 (pcase--match nsym
(nth 2 (cddr match
)))
652 ((memq (car-safe match
) '(or and
))
654 ,@(mapcar (lambda (match)
655 (pcase--app-subst-match match sym fun nsym
))
657 ((memq match
'(:pcase--succeed
:pcase--fail
)) match
)
658 (t (error "Uknown MATCH %s" match
))))
660 (defun pcase--app-subst-rest (rest sym fun nsym
)
661 (mapcar (lambda (branch)
662 `(,(pcase--app-subst-match (car branch
) sym fun nsym
)
666 (defsubst pcase--mark-used
(sym)
667 ;; Exceptionally, `sym' may be a constant expression rather than a symbol.
668 (if (symbolp sym
) (put sym
'pcase-used t
)))
670 (defmacro pcase--flip
(fun arg1 arg2
)
671 "Helper function, used internally to avoid (funcall (lambda ...) ...)."
672 (declare (debug (sexp body
)))
675 (defun pcase--funcall (fun arg vars
)
676 "Build a function call to FUN with arg ARG."
679 (let* (;; `vs' is an upper bound on the vars we need.
680 (vs (pcase--fgrep (mapcar #'car vars
) fun
))
681 (env (mapcar (lambda (var)
682 (list var
(cdr (assq var vars
))))
686 ;; `arg' is shadowed by `env'.
687 (let ((newsym (make-symbol "x")))
688 (push (list newsym arg
) env
)
691 `(funcall #',fun
,arg
)
695 ;; Let's not replace `vars' in `fun' since it's
696 ;; too difficult to do it right, instead just
697 ;; let-bind `vars' around `fun'.
698 `(let* ,env
,call
)))))
700 (defun pcase--eval (exp vars
)
701 "Build an expression that will evaluate EXP."
702 (let* ((found (assq exp vars
)))
703 (if found
(cdr found
)
704 (let* ((vs (pcase--fgrep (mapcar #'car vars
) exp
))
705 (env (mapcar (lambda (v) (list v
(cdr (assq v vars
))))
707 (if env
(macroexp-let* env exp
) exp
)))))
709 ;; It's very tempting to use `pcase' below, tho obviously, it'd create
710 ;; bootstrapping problems.
711 (defun pcase--u1 (matches code vars rest
)
712 "Return code that runs CODE (with VARS) if MATCHES match.
713 Otherwise, it defers to REST which is a list of branches of the form
714 \(ELSE-MATCH ELSE-CODE . ELSE-VARS)."
715 ;; Depending on the order in which we choose to check each of the MATCHES,
716 ;; the resulting tree may be smaller or bigger. So in general, we'd want
717 ;; to be careful to chose the "optimal" order. But predicate
718 ;; patterns make this harder because they create dependencies
719 ;; between matches. So we don't bother trying to reorder anything.
721 ((null matches
) (funcall code vars
))
722 ((eq :pcase--fail
(car matches
)) (pcase--u rest
))
723 ((eq :pcase--succeed
(car matches
))
724 (pcase--u1 (cdr matches
) code vars rest
))
725 ((eq 'and
(caar matches
))
726 (pcase--u1 (append (cdar matches
) (cdr matches
)) code vars rest
))
727 ((eq 'or
(caar matches
))
728 (let* ((alts (cdar matches
))
729 (var (if (eq (caar alts
) 'match
) (cadr (car alts
))))
730 (simples '()) (others '()) (memq-ok t
))
733 (if (and (eq (car alt
) 'match
) (eq var
(cadr alt
))
734 (let ((upat (cddr alt
)))
735 (eq (car-safe upat
) 'quote
)))
736 (let ((val (cadr (cddr alt
))))
737 (unless (or (integerp val
) (symbolp val
))
739 (push (cadr (cddr alt
)) simples
))
742 ((null alts
) (error "Please avoid it") (pcase--u rest
))
743 ;; Yes, we can use `memq' (or `member')!
744 ((> (length simples
) 1)
745 (pcase--u1 (cons `(match ,var
747 ,(if memq-ok
#'memq
#'member
)
751 (if (null others
) rest
753 (pcase--and (if (cdr others
)
754 (cons 'or
(nreverse others
))
760 (pcase--u1 (cons (pop alts
) (cdr matches
)) code vars
761 (if (null alts
) (progn (error "Please avoid it") rest
)
763 (pcase--and (if (cdr alts
)
764 (cons 'or alts
) (car alts
))
768 ((eq 'match
(caar matches
))
769 (let* ((popmatches (pop matches
))
770 (_op (car popmatches
)) (cdrpopmatches (cdr popmatches
))
771 (sym (car cdrpopmatches
))
772 (upat (cdr cdrpopmatches
)))
775 (let ((code (pcase--u1 matches code vars rest
)))
776 (if (eq upat
'_
) code
777 (macroexp--warn-and-return
778 "Pattern t is deprecated. Use `_' instead"
780 ((eq upat
'pcase--dontcare
) :pcase--dontcare
)
781 ((memq (car-safe upat
) '(guard pred
))
782 (if (eq (car upat
) 'pred
) (pcase--mark-used sym
))
785 sym
(lambda (pat) (pcase--split-pred vars upat pat
)) rest
))
786 (then-rest (car splitrest
))
787 (else-rest (cdr splitrest
)))
788 (pcase--if (if (eq (car upat
) 'pred
)
789 (pcase--funcall (cadr upat
) sym vars
)
790 (pcase--eval (cadr upat
) vars
))
791 (pcase--u1 matches code vars then-rest
)
792 (pcase--u else-rest
))))
793 ((and (symbolp upat
) upat
)
794 (pcase--mark-used sym
)
795 (if (not (assq upat vars
))
796 (pcase--u1 matches code
(cons (cons upat sym
) vars
) rest
)
797 ;; Non-linear pattern. Turn it into an `eq' test.
798 (pcase--u1 (cons `(match ,sym .
(pred (eq ,(cdr (assq upat vars
)))))
801 ((eq (car-safe upat
) 'let
)
802 ;; A upat of the form (let VAR EXP).
803 ;; (pcase--u1 matches code
804 ;; (cons (cons (nth 1 upat) (nth 2 upat)) vars) rest)
806 macroexp-copyable-p sym
807 (pcase--eval (nth 2 upat
) vars
)
808 (pcase--u1 (cons (pcase--match sym
(nth 1 upat
)) matches
)
810 ((eq (car-safe upat
) 'app
)
811 ;; A upat of the form (app FUN PAT)
812 (pcase--mark-used sym
)
813 (let* ((fun (nth 1 upat
))
814 (nsym (make-symbol "x"))
816 ;; We don't change `matches' to reuse the newly computed value,
817 ;; because we assume there shouldn't be such redundancy in there.
818 (pcase--u1 (cons (pcase--match nsym
(nth 2 upat
)) matches
)
820 (pcase--app-subst-rest rest sym fun nsym
))))
821 (if (not (get nsym
'pcase-used
))
824 `((,nsym
,(pcase--funcall fun sym vars
)))
826 ((eq (car-safe upat
) 'quote
)
827 (pcase--mark-used sym
)
828 (let* ((val (cadr upat
))
829 (splitrest (pcase--split-rest
830 sym
(lambda (pat) (pcase--split-equal val pat
)) rest
))
831 (then-rest (car splitrest
))
832 (else-rest (cdr splitrest
)))
834 ((null val
) `(null ,sym
))
835 ((or (integerp val
) (symbolp val
))
836 (if (pcase--self-quoting-p val
)
839 (t `(equal ,sym
',val
)))
840 (pcase--u1 matches code vars then-rest
)
841 (pcase--u else-rest
))))
842 ((eq (car-safe upat
) 'not
)
843 ;; FIXME: The implementation below is naive and results in
845 ;; To make it work right, we would need to turn pcase--u1's
846 ;; `code' and `vars' into a single argument of the same form as
847 ;; `rest'. We would also need to split this new `then-rest' argument
848 ;; for every test (currently we don't bother to do it since
849 ;; it's only useful for odd patterns like (and `(PAT1 . PAT2)
850 ;; `(PAT3 . PAT4)) which the programmer can easily rewrite
851 ;; to the more efficient `(,(and PAT1 PAT3) . ,(and PAT2 PAT4))).
852 (pcase--u1 `((match ,sym .
,(cadr upat
)))
853 ;; FIXME: This codegen is not careful to share its
854 ;; code if used several times: code blow up is likely.
856 ;; `vars' will likely contain bindings which are
857 ;; not always available in other paths to
858 ;; `rest', so there' no point trying to pass
862 (list `((and .
,matches
) ,code .
,vars
))))
863 (t (error "Unknown pattern `%S'" upat
)))))
864 (t (error "Incorrect MATCH %S" (car matches
)))))
869 (pcase-QPAT . pcase-QPAT
)
870 (vector &rest pcase-QPAT
)
873 (pcase-defmacro \
` (qpat)
874 "Backquote-style pcase patterns.
875 QPAT can take the following forms:
876 (QPAT1 . QPAT2) matches if QPAT1 matches the car and QPAT2 the cdr.
877 [QPAT1 QPAT2..QPATn] matches a vector of length n and QPAT1..QPATn match
878 its 0..(n-1)th elements, respectively.
879 ,PAT matches if the pcase pattern PAT matches.
880 ATOM matches if the object is `equal' to ATOM.
881 ATOM can be a symbol, an integer, or a string."
882 (declare (debug (pcase-QPAT)))
884 ((eq (car-safe qpat
) '\
,) (cadr qpat
))
887 (app length
,(length qpat
))
889 (dotimes (i (length qpat
))
890 (push `(app (pcase--flip aref
,i
) ,(list '\
` (aref qpat i
)))
895 (app car
,(list '\
` (car qpat
)))
896 (app cdr
,(list '\
` (cdr qpat
)))))
897 ((or (stringp qpat
) (integerp qpat
) (symbolp qpat
)) `',qpat
)
898 (t (error "Unknown QPAT: %S" qpat
))))
902 ;;; pcase.el ends here