Merge from origin/emacs-24
[emacs.git] / lisp / emacs-lisp / pcase.el
blob3a2fa4fdc81bdcf59242a2220fe3a2f9bc66a66c
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>
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 UPAT). 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-UPAT
75 (&or symbolp
76 ("or" &rest pcase-UPAT)
77 ("and" &rest pcase-UPAT)
78 ("`" pcase-QPAT)
79 ("guard" form)
80 ("let" pcase-UPAT form)
81 ("pred"
82 &or lambda-expr
83 ;; Punt on macros/special forms.
84 (functionp &rest form)
85 sexp)
86 sexp))
88 (def-edebug-spec
89 pcase-QPAT
90 (&or ("," pcase-UPAT)
91 (pcase-QPAT . pcase-QPAT)
92 sexp))
94 ;;;###autoload
95 (defmacro pcase (exp &rest cases)
96 "Perform ML-style pattern matching on EXP.
97 CASES is a list of elements of the form (UPATTERN CODE...).
99 UPatterns can take the following forms:
100 _ matches anything.
101 SELFQUOTING matches itself. This includes keywords, numbers, and strings.
102 SYMBOL matches anything and binds it to SYMBOL.
103 (or UPAT...) matches if any of the patterns matches.
104 (and UPAT...) matches if all the patterns match.
105 'VAL matches if the object is `equal' to VAL
106 (pred FUN) matches if FUN applied to the object returns non-nil.
107 (guard BOOLEXP) matches if BOOLEXP evaluates to non-nil.
108 (let UPAT EXP) matches if EXP matches UPAT.
109 (app FUN UPAT) matches if FUN applied to the object matches UPAT.
110 If a SYMBOL is used twice in the same pattern (i.e. the pattern is
111 \"non-linear\"), then the second occurrence is turned into an `eq'uality test.
113 FUN can take the form
114 SYMBOL or (lambda ARGS BODY) in which case it's called with one argument.
115 (F ARG1 .. ARGn) in which case F gets called with an n+1'th argument
116 which is the value being matched.
117 So a FUN of the form SYMBOL is equivalent to one of the form (FUN).
118 FUN can refer to variables bound earlier in the pattern.
119 FUN is assumed to be pure, i.e. it can be dropped if its result is not used,
120 and two identical calls can be merged into one.
121 E.g. you can match pairs where the cdr is larger than the car with a pattern
122 like `(,a . ,(pred (< a))) or, with more checks:
123 `(,(and a (pred numberp)) . ,(and (pred numberp) (pred (< a))))
125 Additional patterns can be defined via `pcase-defmacro'.
126 Currently, the following patterns are provided this way:"
127 (declare (indent 1) (debug (form &rest (pcase-UPAT body))))
128 ;; We want to use a weak hash table as a cache, but the key will unavoidably
129 ;; be based on `exp' and `cases', yet `cases' is a fresh new list each time
130 ;; we're called so it'll be immediately GC'd. So we use (car cases) as key
131 ;; which does come straight from the source code and should hence not be GC'd
132 ;; so easily.
133 (let ((data (gethash (car cases) pcase--memoize)))
134 ;; data = (EXP CASES . EXPANSION)
135 (if (and (equal exp (car data)) (equal cases (cadr data)))
136 ;; We have the right expansion.
137 (cddr data)
138 ;; (when (gethash (car cases) pcase--memoize-1)
139 ;; (message "pcase-memoize failed because of weak key!!"))
140 ;; (when (gethash (car cases) pcase--memoize-2)
141 ;; (message "pcase-memoize failed because of eq test on %S"
142 ;; (car cases)))
143 (when data
144 (message "pcase-memoize: equal first branch, yet different"))
145 (let ((expansion (pcase--expand exp cases)))
146 (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize)
147 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-1)
148 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-2)
149 expansion))))
151 ;; FIXME: Obviously, this will collide with nadvice's use of
152 ;; function-documentation if we happen to advise `pcase'.
153 (put 'pcase 'function-documentation '(pcase--make-docstring))
154 (defun pcase--make-docstring ()
155 (let* ((main (documentation (symbol-function 'pcase) 'raw))
156 (ud (help-split-fundoc main 'pcase)))
157 (with-temp-buffer
158 (insert (or (cdr ud) main))
159 (mapatoms
160 (lambda (symbol)
161 (let ((me (get symbol 'pcase-macroexpander)))
162 (when me
163 (insert "\n\n-- ")
164 (let* ((doc (documentation me 'raw)))
165 (setq doc (help-fns--signature symbol doc me
166 (indirect-function me)))
167 (insert "\n" (or doc "Not documented.")))))))
168 (let ((combined-doc (buffer-string)))
169 (if ud (help-add-fundoc-usage combined-doc (car ud)) combined-doc)))))
171 ;;;###autoload
172 (defmacro pcase-exhaustive (exp &rest cases)
173 "The exhaustive version of `pcase' (which see)."
174 (declare (indent 1) (debug pcase))
175 (let* ((x (make-symbol "x"))
176 (pcase--dontwarn-upats (cons x pcase--dontwarn-upats)))
177 (pcase--expand
178 ;; FIXME: Could we add the FILE:LINE data in the error message?
179 exp (append cases `((,x (error "No clause matching `%S'" ,x)))))))
181 ;;;###autoload
182 (defmacro pcase-lambda (lambda-list &rest body)
183 "Like `lambda' but allow each argument to be a UPattern.
184 I.e. accepts the usual &optional and &rest keywords, but every
185 formal argument can be any pattern accepted by `pcase' (a mere
186 variable name being but a special case of it)."
187 (declare (doc-string 2) (indent defun)
188 (debug ((&rest pcase-UPAT) body)))
189 (let* ((bindings ())
190 (parsed-body (macroexp-parse-body body))
191 (args (mapcar (lambda (pat)
192 (if (symbolp pat)
193 ;; Simple vars and &rest/&optional are just passed
194 ;; through unchanged.
196 (let ((arg (make-symbol
197 (format "arg%s" (length bindings)))))
198 (push `(,pat ,arg) bindings)
199 arg)))
200 lambda-list)))
201 `(lambda ,args ,@(car parsed-body)
202 (pcase-let* ,(nreverse bindings) ,@(cdr parsed-body)))))
204 (defun pcase--let* (bindings body)
205 (cond
206 ((null bindings) (macroexp-progn body))
207 ((pcase--trivial-upat-p (caar bindings))
208 (macroexp-let* `(,(car bindings)) (pcase--let* (cdr bindings) body)))
210 (let ((binding (pop bindings)))
211 (pcase--expand
212 (cadr binding)
213 `((,(car binding) ,(pcase--let* bindings body))
214 ;; We can either signal an error here, or just use `pcase--dontcare'
215 ;; which generates more efficient code. In practice, if we use
216 ;; `pcase--dontcare' we will still often get an error and the few
217 ;; cases where we don't do not matter that much, so
218 ;; it's a better choice.
219 (pcase--dontcare nil)))))))
221 ;;;###autoload
222 (defmacro pcase-let* (bindings &rest body)
223 "Like `let*' but where you can use `pcase' patterns for bindings.
224 BODY should be an expression, and BINDINGS should be a list of bindings
225 of the form (UPAT EXP)."
226 (declare (indent 1)
227 (debug ((&rest (pcase-UPAT &optional form)) body)))
228 (let ((cached (gethash bindings pcase--memoize)))
229 ;; cached = (BODY . EXPANSION)
230 (if (equal (car cached) body)
231 (cdr cached)
232 (let ((expansion (pcase--let* bindings body)))
233 (puthash bindings (cons body expansion) pcase--memoize)
234 expansion))))
236 ;;;###autoload
237 (defmacro pcase-let (bindings &rest body)
238 "Like `let' but where you can use `pcase' patterns for bindings.
239 BODY should be a list of expressions, and BINDINGS should be a list of bindings
240 of the form (UPAT EXP)."
241 (declare (indent 1) (debug pcase-let*))
242 (if (null (cdr bindings))
243 `(pcase-let* ,bindings ,@body)
244 (let ((matches '()))
245 (dolist (binding (prog1 bindings (setq bindings nil)))
246 (cond
247 ((memq (car binding) pcase--dontcare-upats)
248 (push (cons (make-symbol "_") (cdr binding)) bindings))
249 ((pcase--trivial-upat-p (car binding)) (push binding bindings))
251 (let ((tmpvar (make-symbol (format "x%d" (length bindings)))))
252 (push (cons tmpvar (cdr binding)) bindings)
253 (push (list (car binding) tmpvar) matches)))))
254 `(let ,(nreverse bindings) (pcase-let* ,matches ,@body)))))
256 (defmacro pcase-dolist (spec &rest body)
257 (declare (indent 1) (debug ((pcase-UPAT form) body)))
258 (if (pcase--trivial-upat-p (car spec))
259 `(dolist ,spec ,@body)
260 (let ((tmpvar (make-symbol "x")))
261 `(dolist (,tmpvar ,@(cdr spec))
262 (pcase-let* ((,(car spec) ,tmpvar))
263 ,@body)))))
266 (defun pcase--trivial-upat-p (upat)
267 (and (symbolp upat) (not (memq upat pcase--dontcare-upats))))
269 (defun pcase--expand (exp cases)
270 ;; (message "pid=%S (pcase--expand %S ...hash=%S)"
271 ;; (emacs-pid) exp (sxhash cases))
272 (macroexp-let2 macroexp-copyable-p val exp
273 (let* ((defs ())
274 (seen '())
275 (codegen
276 (lambda (code vars)
277 (let ((prev (assq code seen)))
278 (if (not prev)
279 (let ((res (pcase-codegen code vars)))
280 (push (list code vars res) seen)
281 res)
282 ;; Since we use a tree-based pattern matching
283 ;; technique, the leaves (the places that contain the
284 ;; code to run once a pattern is matched) can get
285 ;; copied a very large number of times, so to avoid
286 ;; code explosion, we need to keep track of how many
287 ;; times we've used each leaf and move it
288 ;; to a separate function if that number is too high.
290 ;; We've already used this branch. So it is shared.
291 (let* ((code (car prev)) (cdrprev (cdr prev))
292 (prevvars (car cdrprev)) (cddrprev (cdr cdrprev))
293 (res (car cddrprev)))
294 (unless (symbolp res)
295 ;; This is the first repeat, so we have to move
296 ;; the branch to a separate function.
297 (let ((bsym
298 (make-symbol (format "pcase-%d" (length defs)))))
299 (push `(,bsym (lambda ,(mapcar #'car prevvars) ,@code))
300 defs)
301 (setcar res 'funcall)
302 (setcdr res (cons bsym (mapcar #'cdr prevvars)))
303 (setcar (cddr prev) bsym)
304 (setq res bsym)))
305 (setq vars (copy-sequence vars))
306 (let ((args (mapcar (lambda (pa)
307 (let ((v (assq (car pa) vars)))
308 (setq vars (delq v vars))
309 (cdr v)))
310 prevvars)))
311 ;; If some of `vars' were not found in `prevvars', that's
312 ;; OK it just means those vars aren't present in all
313 ;; branches, so they can be used within the pattern
314 ;; (e.g. by a `guard/let/pred') but not in the branch.
315 ;; FIXME: But if some of `prevvars' are not in `vars' we
316 ;; should remove them from `prevvars'!
317 `(funcall ,res ,@args)))))))
318 (used-cases ())
319 (main
320 (pcase--u
321 (mapcar (lambda (case)
322 `(,(pcase--match val (pcase--macroexpand (car case)))
323 ,(lambda (vars)
324 (unless (memq case used-cases)
325 ;; Keep track of the cases that are used.
326 (push case used-cases))
327 (funcall
328 (if (pcase--small-branch-p (cdr case))
329 ;; Don't bother sharing multiple
330 ;; occurrences of this leaf since it's small.
331 #'pcase-codegen codegen)
332 (cdr case)
333 vars))))
334 cases))))
335 (dolist (case cases)
336 (unless (or (memq case used-cases)
337 (memq (car case) pcase--dontwarn-upats))
338 (message "Redundant pcase pattern: %S" (car case))))
339 (macroexp-let* defs main))))
341 (defun pcase--macroexpand (pat)
342 "Expands all macro-patterns in PAT."
343 (let ((head (car-safe pat)))
344 (cond
345 ((null head)
346 (if (pcase--self-quoting-p pat) `',pat pat))
347 ((memq head '(pred guard quote)) pat)
348 ((memq head '(or and)) `(,head ,@(mapcar #'pcase--macroexpand (cdr pat))))
349 ((eq head 'let) `(let ,(pcase--macroexpand (cadr pat)) ,@(cddr pat)))
350 ((eq head 'app) `(app ,(nth 1 pat) ,(pcase--macroexpand (nth 2 pat))))
352 (let* ((expander (get head 'pcase-macroexpander))
353 (npat (if expander (apply expander (cdr pat)))))
354 (if (null npat)
355 (error (if expander
356 "Unexpandable %s pattern: %S"
357 "Unknown %s pattern: %S")
358 head pat)
359 (pcase--macroexpand npat)))))))
361 ;;;###autoload
362 (defmacro pcase-defmacro (name args &rest body)
363 "Define a pcase UPattern macro."
364 (declare (indent 2) (debug defun) (doc-string 3))
365 (let ((fsym (intern (format "%s--pcase-macroexpander" name))))
366 ;; Add the function via `fsym', so that an autoload cookie placed
367 ;; on a pcase-defmacro will cause the macro to be loaded on demand.
368 `(progn
369 (defun ,fsym ,args ,@body)
370 (put ',name 'pcase-macroexpander #',fsym))))
372 (defun pcase--match (val upat)
373 "Build a MATCH structure, hoisting all `or's and `and's outside."
374 (cond
375 ;; Hoist or/and patterns into or/and matches.
376 ((memq (car-safe upat) '(or and))
377 `(,(car upat)
378 ,@(mapcar (lambda (upat)
379 (pcase--match val upat))
380 (cdr upat))))
382 `(match ,val . ,upat))))
384 (defun pcase-codegen (code vars)
385 ;; Don't use let*, otherwise macroexp-let* may merge it with some surrounding
386 ;; let* which might prevent the setcar/setcdr in pcase--expand's fancy
387 ;; codegen from later metamorphosing this let into a funcall.
388 `(let ,(mapcar (lambda (b) (list (car b) (cdr b))) vars)
389 ,@code))
391 (defun pcase--small-branch-p (code)
392 (and (= 1 (length code))
393 (or (not (consp (car code)))
394 (let ((small t))
395 (dolist (e (car code))
396 (if (consp e) (setq small nil)))
397 small))))
399 ;; Try to use `cond' rather than a sequence of `if's, so as to reduce
400 ;; the depth of the generated tree.
401 (defun pcase--if (test then else)
402 (cond
403 ((eq else :pcase--dontcare) then)
404 ((eq then :pcase--dontcare) (debug) else) ;Can/should this ever happen?
405 (t (macroexp-if test then else))))
407 ;; Note about MATCH:
408 ;; When we have patterns like `(PAT1 . PAT2), after performing the `consp'
409 ;; check, we want to turn all the similar patterns into ones of the form
410 ;; (and (match car PAT1) (match cdr PAT2)), so you naturally need conjunction.
411 ;; Earlier code hence used branches of the form (MATCHES . CODE) where
412 ;; MATCHES was a list (implicitly a conjunction) of (SYM . PAT).
413 ;; But if we have a pattern of the form (or `(PAT1 . PAT2) PAT3), there is
414 ;; no easy way to eliminate the `consp' check in such a representation.
415 ;; So we replaced the MATCHES by the MATCH below which can be made up
416 ;; of conjunctions and disjunctions, so if we know `foo' is a cons, we can
417 ;; turn (match foo . (or `(PAT1 . PAT2) PAT3)) into
418 ;; (or (and (match car . `PAT1) (match cdr . `PAT2)) (match foo . PAT3)).
419 ;; The downside is that we now have `or' and `and' both in MATCH and
420 ;; in PAT, so there are different equivalent representations and we
421 ;; need to handle them all. We do not try to systematically
422 ;; canonicalize them to one form over another, but we do occasionally
423 ;; turn one into the other.
425 (defun pcase--u (branches)
426 "Expand matcher for rules BRANCHES.
427 Each BRANCH has the form (MATCH CODE . VARS) where
428 CODE is the code generator for that branch.
429 VARS is the set of vars already bound by earlier matches.
430 MATCH is the pattern that needs to be matched, of the form:
431 (match VAR . UPAT)
432 (and MATCH ...)
433 (or MATCH ...)"
434 (when (setq branches (delq nil branches))
435 (let* ((carbranch (car branches))
436 (match (car carbranch)) (cdarbranch (cdr carbranch))
437 (code (car cdarbranch))
438 (vars (cdr cdarbranch)))
439 (pcase--u1 (list match) code vars (cdr branches)))))
441 (defun pcase--and (match matches)
442 (if matches `(and ,match ,@matches) match))
444 (defconst pcase-mutually-exclusive-predicates
445 '((symbolp . integerp)
446 (symbolp . numberp)
447 (symbolp . consp)
448 (symbolp . arrayp)
449 (symbolp . vectorp)
450 (symbolp . stringp)
451 (symbolp . byte-code-function-p)
452 (integerp . consp)
453 (integerp . arrayp)
454 (integerp . vectorp)
455 (integerp . stringp)
456 (integerp . byte-code-function-p)
457 (numberp . consp)
458 (numberp . arrayp)
459 (numberp . vectorp)
460 (numberp . stringp)
461 (numberp . byte-code-function-p)
462 (consp . arrayp)
463 (consp . vectorp)
464 (consp . stringp)
465 (consp . byte-code-function-p)
466 (arrayp . byte-code-function-p)
467 (vectorp . byte-code-function-p)
468 (stringp . vectorp)
469 (stringp . byte-code-function-p)))
471 (defun pcase--mutually-exclusive-p (pred1 pred2)
472 (or (member (cons pred1 pred2)
473 pcase-mutually-exclusive-predicates)
474 (member (cons pred2 pred1)
475 pcase-mutually-exclusive-predicates)))
477 (defun pcase--split-match (sym splitter match)
478 (cond
479 ((eq (car-safe match) 'match)
480 (if (not (eq sym (cadr match)))
481 (cons match match)
482 (let ((res (funcall splitter (cddr match))))
483 (cons (or (car res) match) (or (cdr res) match)))))
484 ((memq (car-safe match) '(or and))
485 (let ((then-alts '())
486 (else-alts '())
487 (neutral-elem (if (eq 'or (car match))
488 :pcase--fail :pcase--succeed))
489 (zero-elem (if (eq 'or (car match)) :pcase--succeed :pcase--fail)))
490 (dolist (alt (cdr match))
491 (let ((split (pcase--split-match sym splitter alt)))
492 (unless (eq (car split) neutral-elem)
493 (push (car split) then-alts))
494 (unless (eq (cdr split) neutral-elem)
495 (push (cdr split) else-alts))))
496 (cons (cond ((memq zero-elem then-alts) zero-elem)
497 ((null then-alts) neutral-elem)
498 ((null (cdr then-alts)) (car then-alts))
499 (t (cons (car match) (nreverse then-alts))))
500 (cond ((memq zero-elem else-alts) zero-elem)
501 ((null else-alts) neutral-elem)
502 ((null (cdr else-alts)) (car else-alts))
503 (t (cons (car match) (nreverse else-alts)))))))
504 ((memq match '(:pcase--succeed :pcase--fail)) (cons match match))
505 (t (error "Uknown MATCH %s" match))))
507 (defun pcase--split-rest (sym splitter rest)
508 (let ((then-rest '())
509 (else-rest '()))
510 (dolist (branch rest)
511 (let* ((match (car branch))
512 (code&vars (cdr branch))
513 (split
514 (pcase--split-match sym splitter match)))
515 (unless (eq (car split) :pcase--fail)
516 (push (cons (car split) code&vars) then-rest))
517 (unless (eq (cdr split) :pcase--fail)
518 (push (cons (cdr split) code&vars) else-rest))))
519 (cons (nreverse then-rest) (nreverse else-rest))))
521 (defun pcase--split-equal (elem pat)
522 (cond
523 ;; The same match will give the same result.
524 ((and (eq (car-safe pat) 'quote) (equal (cadr pat) elem))
525 '(:pcase--succeed . :pcase--fail))
526 ;; A different match will fail if this one succeeds.
527 ((and (eq (car-safe pat) 'quote)
528 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
529 ;; (consp (cadr pat)))
531 '(:pcase--fail . nil))
532 ((and (eq (car-safe pat) 'pred)
533 (symbolp (cadr pat))
534 (get (cadr pat) 'side-effect-free))
535 (ignore-errors
536 (if (funcall (cadr pat) elem)
537 '(:pcase--succeed . nil)
538 '(:pcase--fail . nil))))))
540 (defun pcase--split-member (elems pat)
541 ;; FIXME: The new pred-based member code doesn't do these optimizations!
542 ;; Based on pcase--split-equal.
543 (cond
544 ;; The same match (or a match of membership in a superset) will
545 ;; give the same result, but we don't know how to check it.
546 ;; (???
547 ;; '(:pcase--succeed . nil))
548 ;; A match for one of the elements may succeed or fail.
549 ((and (eq (car-safe pat) 'quote) (member (cadr pat) elems))
550 nil)
551 ;; A different match will fail if this one succeeds.
552 ((and (eq (car-safe pat) 'quote)
553 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
554 ;; (consp (cadr pat)))
556 '(:pcase--fail . nil))
557 ((and (eq (car-safe pat) 'pred)
558 (symbolp (cadr pat))
559 (get (cadr pat) 'side-effect-free)
560 (ignore-errors
561 (let ((p (cadr pat)) (all t))
562 (dolist (elem elems)
563 (unless (funcall p elem) (setq all nil)))
564 all)))
565 '(:pcase--succeed . nil))))
567 (defun pcase--split-pred (vars upat pat)
568 (let (test)
569 (cond
570 ((and (equal upat pat)
571 ;; For predicates like (pred (> a)), two such predicates may
572 ;; actually refer to different variables `a'.
573 (or (and (eq 'pred (car upat)) (symbolp (cadr upat)))
574 ;; FIXME: `vars' gives us the environment in which `upat' will
575 ;; run, but we don't have the environment in which `pat' will
576 ;; run, so we can't do a reliable verification. But let's try
577 ;; and catch at least the easy cases such as (bug#14773).
578 (not (pcase--fgrep (mapcar #'car vars) (cadr upat)))))
579 '(:pcase--succeed . :pcase--fail))
580 ((and (eq 'pred (car upat))
581 (let ((otherpred
582 (cond ((eq 'pred (car-safe pat)) (cadr pat))
583 ((not (eq 'quote (car-safe pat))) nil)
584 ((consp (cadr pat)) #'consp)
585 ((stringp (cadr pat)) #'stringp)
586 ((vectorp (cadr pat)) #'vectorp)
587 ((byte-code-function-p (cadr pat))
588 #'byte-code-function-p))))
589 (pcase--mutually-exclusive-p (cadr upat) otherpred)))
590 '(:pcase--fail . nil))
591 ((and (eq 'pred (car upat))
592 (eq 'quote (car-safe pat))
593 (symbolp (cadr upat))
594 (or (symbolp (cadr pat)) (stringp (cadr pat)) (numberp (cadr pat)))
595 (get (cadr upat) 'side-effect-free)
596 (ignore-errors
597 (setq test (list (funcall (cadr upat) (cadr pat))))))
598 (if (car test)
599 '(nil . :pcase--fail)
600 '(:pcase--fail . nil))))))
602 (defun pcase--fgrep (vars sexp)
603 "Check which of the symbols VARS appear in SEXP."
604 (let ((res '()))
605 (while (consp sexp)
606 (dolist (var (pcase--fgrep vars (pop sexp)))
607 (unless (memq var res) (push var res))))
608 (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
609 res))
611 (defun pcase--self-quoting-p (upat)
612 (or (keywordp upat) (numberp upat) (stringp upat)))
614 (defun pcase--app-subst-match (match sym fun nsym)
615 (cond
616 ((eq (car-safe match) 'match)
617 (if (and (eq sym (cadr match))
618 (eq 'app (car-safe (cddr match)))
619 (equal fun (nth 1 (cddr match))))
620 (pcase--match nsym (nth 2 (cddr match)))
621 match))
622 ((memq (car-safe match) '(or and))
623 `(,(car match)
624 ,@(mapcar (lambda (match)
625 (pcase--app-subst-match match sym fun nsym))
626 (cdr match))))
627 ((memq match '(:pcase--succeed :pcase--fail)) match)
628 (t (error "Uknown MATCH %s" match))))
630 (defun pcase--app-subst-rest (rest sym fun nsym)
631 (mapcar (lambda (branch)
632 `(,(pcase--app-subst-match (car branch) sym fun nsym)
633 ,@(cdr branch)))
634 rest))
636 (defsubst pcase--mark-used (sym)
637 ;; Exceptionally, `sym' may be a constant expression rather than a symbol.
638 (if (symbolp sym) (put sym 'pcase-used t)))
640 (defmacro pcase--flip (fun arg1 arg2)
641 "Helper function, used internally to avoid (funcall (lambda ...) ...)."
642 (declare (debug (sexp body)))
643 `(,fun ,arg2 ,arg1))
645 (defun pcase--funcall (fun arg vars)
646 "Build a function call to FUN with arg ARG."
647 (if (symbolp fun)
648 `(,fun ,arg)
649 (let* (;; `vs' is an upper bound on the vars we need.
650 (vs (pcase--fgrep (mapcar #'car vars) fun))
651 (env (mapcar (lambda (var)
652 (list var (cdr (assq var vars))))
653 vs))
654 (call (progn
655 (when (memq arg vs)
656 ;; `arg' is shadowed by `env'.
657 (let ((newsym (make-symbol "x")))
658 (push (list newsym arg) env)
659 (setq arg newsym)))
660 (if (functionp fun)
661 `(funcall #',fun ,arg)
662 `(,@fun ,arg)))))
663 (if (null vs)
664 call
665 ;; Let's not replace `vars' in `fun' since it's
666 ;; too difficult to do it right, instead just
667 ;; let-bind `vars' around `fun'.
668 `(let* ,env ,call)))))
670 (defun pcase--eval (exp vars)
671 "Build an expression that will evaluate EXP."
672 (let* ((found (assq exp vars)))
673 (if found (cdr found)
674 (let* ((vs (pcase--fgrep (mapcar #'car vars) exp))
675 (env (mapcar (lambda (v) (list v (cdr (assq v vars))))
676 vs)))
677 (if env (macroexp-let* env exp) exp)))))
679 ;; It's very tempting to use `pcase' below, tho obviously, it'd create
680 ;; bootstrapping problems.
681 (defun pcase--u1 (matches code vars rest)
682 "Return code that runs CODE (with VARS) if MATCHES match.
683 Otherwise, it defers to REST which is a list of branches of the form
684 \(ELSE-MATCH ELSE-CODE . ELSE-VARS)."
685 ;; Depending on the order in which we choose to check each of the MATCHES,
686 ;; the resulting tree may be smaller or bigger. So in general, we'd want
687 ;; to be careful to chose the "optimal" order. But predicate
688 ;; patterns make this harder because they create dependencies
689 ;; between matches. So we don't bother trying to reorder anything.
690 (cond
691 ((null matches) (funcall code vars))
692 ((eq :pcase--fail (car matches)) (pcase--u rest))
693 ((eq :pcase--succeed (car matches))
694 (pcase--u1 (cdr matches) code vars rest))
695 ((eq 'and (caar matches))
696 (pcase--u1 (append (cdar matches) (cdr matches)) code vars rest))
697 ((eq 'or (caar matches))
698 (let* ((alts (cdar matches))
699 (var (if (eq (caar alts) 'match) (cadr (car alts))))
700 (simples '()) (others '()) (memq-ok t))
701 (when var
702 (dolist (alt alts)
703 (if (and (eq (car alt) 'match) (eq var (cadr alt))
704 (let ((upat (cddr alt)))
705 (eq (car-safe upat) 'quote)))
706 (let ((val (cadr (cddr alt))))
707 (unless (or (integerp val) (symbolp val))
708 (setq memq-ok nil))
709 (push (cadr (cddr alt)) simples))
710 (push alt others))))
711 (cond
712 ((null alts) (error "Please avoid it") (pcase--u rest))
713 ;; Yes, we can use `memq' (or `member')!
714 ((> (length simples) 1)
715 (pcase--u1 (cons `(match ,var
716 . (pred (pcase--flip
717 ,(if memq-ok #'memq #'member)
718 ',simples)))
719 (cdr matches))
720 code vars
721 (if (null others) rest
722 (cons (cons
723 (pcase--and (if (cdr others)
724 (cons 'or (nreverse others))
725 (car others))
726 (cdr matches))
727 (cons code vars))
728 rest))))
730 (pcase--u1 (cons (pop alts) (cdr matches)) code vars
731 (if (null alts) (progn (error "Please avoid it") rest)
732 (cons (cons
733 (pcase--and (if (cdr alts)
734 (cons 'or alts) (car alts))
735 (cdr matches))
736 (cons code vars))
737 rest)))))))
738 ((eq 'match (caar matches))
739 (let* ((popmatches (pop matches))
740 (_op (car popmatches)) (cdrpopmatches (cdr popmatches))
741 (sym (car cdrpopmatches))
742 (upat (cdr cdrpopmatches)))
743 (cond
744 ((memq upat '(t _)) (pcase--u1 matches code vars rest))
745 ((eq upat 'pcase--dontcare) :pcase--dontcare)
746 ((memq (car-safe upat) '(guard pred))
747 (if (eq (car upat) 'pred) (pcase--mark-used sym))
748 (let* ((splitrest
749 (pcase--split-rest
750 sym (lambda (pat) (pcase--split-pred vars upat pat)) rest))
751 (then-rest (car splitrest))
752 (else-rest (cdr splitrest)))
753 (pcase--if (if (eq (car upat) 'pred)
754 (pcase--funcall (cadr upat) sym vars)
755 (pcase--eval (cadr upat) vars))
756 (pcase--u1 matches code vars then-rest)
757 (pcase--u else-rest))))
758 ((symbolp upat)
759 (pcase--mark-used sym)
760 (if (not (assq upat vars))
761 (pcase--u1 matches code (cons (cons upat sym) vars) rest)
762 ;; Non-linear pattern. Turn it into an `eq' test.
763 (pcase--u1 (cons `(match ,sym . (pred (eq ,(cdr (assq upat vars)))))
764 matches)
765 code vars rest)))
766 ((eq (car-safe upat) 'let)
767 ;; A upat of the form (let VAR EXP).
768 ;; (pcase--u1 matches code
769 ;; (cons (cons (nth 1 upat) (nth 2 upat)) vars) rest)
770 (macroexp-let2
771 macroexp-copyable-p sym
772 (pcase--eval (nth 2 upat) vars)
773 (pcase--u1 (cons (pcase--match sym (nth 1 upat)) matches)
774 code vars rest)))
775 ((eq (car-safe upat) 'app)
776 ;; A upat of the form (app FUN UPAT)
777 (pcase--mark-used sym)
778 (let* ((fun (nth 1 upat))
779 (nsym (make-symbol "x"))
780 (body
781 ;; We don't change `matches' to reuse the newly computed value,
782 ;; because we assume there shouldn't be such redundancy in there.
783 (pcase--u1 (cons (pcase--match nsym (nth 2 upat)) matches)
784 code vars
785 (pcase--app-subst-rest rest sym fun nsym))))
786 (if (not (get nsym 'pcase-used))
787 body
788 (macroexp-let*
789 `((,nsym ,(pcase--funcall fun sym vars)))
790 body))))
791 ((eq (car-safe upat) 'quote)
792 (pcase--mark-used sym)
793 (let* ((val (cadr upat))
794 (splitrest (pcase--split-rest
795 sym (lambda (pat) (pcase--split-equal val pat)) rest))
796 (then-rest (car splitrest))
797 (else-rest (cdr splitrest)))
798 (pcase--if (cond
799 ((null val) `(null ,sym))
800 ((or (integerp val) (symbolp val))
801 (if (pcase--self-quoting-p val)
802 `(eq ,sym ,val)
803 `(eq ,sym ',val)))
804 (t `(equal ,sym ',val)))
805 (pcase--u1 matches code vars then-rest)
806 (pcase--u else-rest))))
807 ((eq (car-safe upat) 'not)
808 ;; FIXME: The implementation below is naive and results in
809 ;; inefficient code.
810 ;; To make it work right, we would need to turn pcase--u1's
811 ;; `code' and `vars' into a single argument of the same form as
812 ;; `rest'. We would also need to split this new `then-rest' argument
813 ;; for every test (currently we don't bother to do it since
814 ;; it's only useful for odd patterns like (and `(PAT1 . PAT2)
815 ;; `(PAT3 . PAT4)) which the programmer can easily rewrite
816 ;; to the more efficient `(,(and PAT1 PAT3) . ,(and PAT2 PAT4))).
817 (pcase--u1 `((match ,sym . ,(cadr upat)))
818 ;; FIXME: This codegen is not careful to share its
819 ;; code if used several times: code blow up is likely.
820 (lambda (_vars)
821 ;; `vars' will likely contain bindings which are
822 ;; not always available in other paths to
823 ;; `rest', so there' no point trying to pass
824 ;; them down.
825 (pcase--u rest))
826 vars
827 (list `((and . ,matches) ,code . ,vars))))
828 (t (error "Unknown internal pattern `%S'" upat)))))
829 (t (error "Incorrect MATCH %S" (car matches)))))
831 (pcase-defmacro \` (qpat)
832 "Backquote-style pcase patterns.
833 QPAT can take the following forms:
834 (QPAT1 . QPAT2) matches if QPAT1 matches the car and QPAT2 the cdr.
835 [QPAT1 QPAT2..QPATn] matches a vector of length n and QPAT1..QPATn match
836 its 0..(n-1)th elements, respectively.
837 ,UPAT matches if the UPattern UPAT matches.
838 STRING matches if the object is `equal' to STRING.
839 ATOM matches if the object is `eq' to ATOM."
840 (cond
841 ((eq (car-safe qpat) '\,) (cadr qpat))
842 ((vectorp qpat)
843 `(and (pred vectorp)
844 (app length ,(length qpat))
845 ,@(let ((upats nil))
846 (dotimes (i (length qpat))
847 (push `(app (pcase--flip aref ,i) ,(list '\` (aref qpat i)))
848 upats))
849 (nreverse upats))))
850 ((consp qpat)
851 `(and (pred consp)
852 (app car ,(list '\` (car qpat)))
853 (app cdr ,(list '\` (cdr qpat)))))
854 ((or (stringp qpat) (integerp qpat) (symbolp qpat)) `',qpat)))
857 (provide 'pcase)
858 ;;; pcase.el ends here