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