* lisp/emacs-lisp/pcase.el (pcase--split-pred): Add `vars' argument to try
[bpt/emacs.git] / lisp / emacs-lisp / pcase.el
CommitLineData
513749ee 1;;; pcase.el --- ML-style pattern-matching macro for Elisp -*- lexical-binding: t; coding: utf-8 -*-
d02c9bcd 2
ab422c4d 3;; Copyright (C) 2010-2013 Free Software Foundation, Inc.
d02c9bcd
SM
4
5;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
ca3afb79 6;; Keywords:
d02c9bcd
SM
7
8;; This file is part of GNU Emacs.
9
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.
14
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.
19
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/>.
22
23;;; Commentary:
24
25;; ML-style pattern matching.
26;; The entry points are autoloaded.
27
dcc029e0
SM
28;; Todo:
29
ca105506
SM
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.
dcc029e0
SM
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
872ab164 38;; extension provide its own `pcase--split-<foo>' thingy.
ca105506 39;; - along these lines, provide patterns to match CL structs.
1f0816b6
SM
40;; - provide something like (setq VAR) so a var can be set rather than
41;; let-bound.
a179e3f7
SM
42;; - provide a way to fallthrough to subsequent cases (not sure what I meant by
43;; this :-()
1f0816b6 44;; - try and be more clever to reduce the size of the decision tree, and
ca105506 45;; to reduce the number of leaves that need to be turned into function:
1f0816b6 46;; - first, do the tests shared by all remaining branches (it will have
a179e3f7 47;; to be performed anyway, so better do it first so it's shared).
1f0816b6 48;; - then choose the test that discriminates more (?).
a179e3f7
SM
49;; - provide Agda's `with' (along with its `...' companion).
50;; - implement (not UPAT). This might require a significant redesign.
dcc029e0
SM
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.
53
d02c9bcd
SM
54;;; Code:
55
4dd1c416
SM
56(require 'macroexp)
57
d02c9bcd
SM
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.
972debf2
SM
63;; FIXME: Now that macroexpansion is also performed when loading an interpreted
64;; file, this is not a real problem any more.
e2abe5a1 65(defconst pcase--memoize (make-hash-table :weakness 'key :test 'eq))
82ad98e3
SM
66;; (defconst pcase--memoize-1 (make-hash-table :test 'eq))
67;; (defconst pcase--memoize-2 (make-hash-table :weakness 'key :test 'equal))
d02c9bcd 68
a464a6c7 69(defconst pcase--dontcare-upats '(t _ pcase--dontcare))
872ab164 70
a4712e11
JB
71(def-edebug-spec
72 pcase-UPAT
73 (&or symbolp
74 ("or" &rest pcase-UPAT)
75 ("and" &rest pcase-UPAT)
76 ("`" pcase-QPAT)
77 ("guard" form)
78 ("let" pcase-UPAT form)
79 ("pred"
80 &or lambda-expr
81 ;; Punt on macros/special forms.
82 (functionp &rest form)
83 sexp)
84 sexp))
85
86(def-edebug-spec
87 pcase-QPAT
88 (&or ("," pcase-UPAT)
89 (pcase-QPAT . pcase-QPAT)
90 sexp))
91
d02c9bcd
SM
92;;;###autoload
93(defmacro pcase (exp &rest cases)
94 "Perform ML-style pattern matching on EXP.
95CASES is a list of elements of the form (UPATTERN CODE...).
96
97UPatterns can take the following forms:
98 _ matches anything.
19faa8e8 99 SELFQUOTING matches itself. This includes keywords, numbers, and strings.
d02c9bcd
SM
100 SYMBOL matches anything and binds it to SYMBOL.
101 (or UPAT...) matches if any of the patterns matches.
102 (and UPAT...) matches if all the patterns match.
103 `QPAT matches if the QPattern QPAT matches.
104 (pred PRED) matches if PRED applied to the object returns non-nil.
dcc029e0 105 (guard BOOLEXP) matches if BOOLEXP evaluates to non-nil.
ca105506 106 (let UPAT EXP) matches if EXP matches UPAT.
f9d554dd
SM
107If a SYMBOL is used twice in the same pattern (i.e. the pattern is
108\"non-linear\"), then the second occurrence is turned into an `eq'uality test.
d02c9bcd
SM
109
110QPatterns can take the following forms:
111 (QPAT1 . QPAT2) matches if QPAT1 matches the car and QPAT2 the cdr.
112 ,UPAT matches if the UPattern UPAT matches.
ca3afb79 113 STRING matches if the object is `equal' to STRING.
d02c9bcd
SM
114 ATOM matches if the object is `eq' to ATOM.
115QPatterns for vectors are not implemented yet.
116
117PRED can take the form
ca3afb79 118 FUNCTION in which case it gets called with one argument.
7abaf5cc
SM
119 (FUN ARG1 .. ARGN) in which case it gets called with an N+1'th argument
120 which is the value being matched.
d02c9bcd
SM
121A PRED of the form FUNCTION is equivalent to one of the form (FUNCTION).
122PRED patterns can refer to variables bound earlier in the pattern.
123E.g. you can match pairs where the cdr is larger than the car with a pattern
124like `(,a . ,(pred (< a))) or, with more checks:
125`(,(and a (pred numberp)) . ,(and (pred numberp) (pred (< a))))"
a4712e11 126 (declare (indent 1) (debug (form &rest (pcase-UPAT body))))
e2abe5a1
SM
127 ;; We want to use a weak hash table as a cache, but the key will unavoidably
128 ;; be based on `exp' and `cases', yet `cases' is a fresh new list each time
129 ;; we're called so it'll be immediately GC'd. So we use (car cases) as key
130 ;; which does come straight from the source code and should hence not be GC'd
131 ;; so easily.
132 (let ((data (gethash (car cases) pcase--memoize)))
133 ;; data = (EXP CASES . EXPANSION)
134 (if (and (equal exp (car data)) (equal cases (cadr data)))
135 ;; We have the right expansion.
136 (cddr data)
82ad98e3
SM
137 ;; (when (gethash (car cases) pcase--memoize-1)
138 ;; (message "pcase-memoize failed because of weak key!!"))
139 ;; (when (gethash (car cases) pcase--memoize-2)
140 ;; (message "pcase-memoize failed because of eq test on %S"
141 ;; (car cases)))
e2abe5a1
SM
142 (when data
143 (message "pcase-memoize: equal first branch, yet different"))
144 (let ((expansion (pcase--expand exp cases)))
82ad98e3
SM
145 (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize)
146 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-1)
147 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-2)
e2abe5a1 148 expansion))))
d02c9bcd 149
82ad98e3
SM
150(defun pcase--let* (bindings body)
151 (cond
152 ((null bindings) (macroexp-progn body))
153 ((pcase--trivial-upat-p (caar bindings))
154 (macroexp-let* `(,(car bindings)) (pcase--let* (cdr bindings) body)))
155 (t
156 (let ((binding (pop bindings)))
157 (pcase--expand
158 (cadr binding)
159 `((,(car binding) ,(pcase--let* bindings body))
a464a6c7
SM
160 ;; We can either signal an error here, or just use `pcase--dontcare'
161 ;; which generates more efficient code. In practice, if we use
162 ;; `pcase--dontcare' we will still often get an error and the few
163 ;; cases where we don't do not matter that much, so
164 ;; it's a better choice.
165 (pcase--dontcare nil)))))))
82ad98e3 166
d02c9bcd 167;;;###autoload
872ab164 168(defmacro pcase-let* (bindings &rest body)
d02c9bcd
SM
169 "Like `let*' but where you can use `pcase' patterns for bindings.
170BODY should be an expression, and BINDINGS should be a list of bindings
171of the form (UPAT EXP)."
c41045e6 172 (declare (indent 1)
a4712e11 173 (debug ((&rest (pcase-UPAT &optional form)) body)))
82ad98e3
SM
174 (let ((cached (gethash bindings pcase--memoize)))
175 ;; cached = (BODY . EXPANSION)
176 (if (equal (car cached) body)
177 (cdr cached)
178 (let ((expansion (pcase--let* bindings body)))
179 (puthash bindings (cons body expansion) pcase--memoize)
180 expansion))))
d02c9bcd
SM
181
182;;;###autoload
872ab164 183(defmacro pcase-let (bindings &rest body)
d02c9bcd 184 "Like `let' but where you can use `pcase' patterns for bindings.
872ab164 185BODY should be a list of expressions, and BINDINGS should be a list of bindings
d02c9bcd 186of the form (UPAT EXP)."
c41045e6 187 (declare (indent 1) (debug pcase-let*))
d02c9bcd 188 (if (null (cdr bindings))
872ab164
SM
189 `(pcase-let* ,bindings ,@body)
190 (let ((matches '()))
191 (dolist (binding (prog1 bindings (setq bindings nil)))
192 (cond
193 ((memq (car binding) pcase--dontcare-upats)
194 (push (cons (make-symbol "_") (cdr binding)) bindings))
195 ((pcase--trivial-upat-p (car binding)) (push binding bindings))
196 (t
197 (let ((tmpvar (make-symbol (format "x%d" (length bindings)))))
198 (push (cons tmpvar (cdr binding)) bindings)
199 (push (list (car binding) tmpvar) matches)))))
200 `(let ,(nreverse bindings) (pcase-let* ,matches ,@body)))))
201
202(defmacro pcase-dolist (spec &rest body)
a4712e11 203 (declare (indent 1) (debug ((pcase-UPAT form) body)))
872ab164
SM
204 (if (pcase--trivial-upat-p (car spec))
205 `(dolist ,spec ,@body)
206 (let ((tmpvar (make-symbol "x")))
207 `(dolist (,tmpvar ,@(cdr spec))
208 (pcase-let* ((,(car spec) ,tmpvar))
209 ,@body)))))
210
211
212(defun pcase--trivial-upat-p (upat)
213 (and (symbolp upat) (not (memq upat pcase--dontcare-upats))))
214
215(defun pcase--expand (exp cases)
e2abe5a1
SM
216 ;; (message "pid=%S (pcase--expand %S ...hash=%S)"
217 ;; (emacs-pid) exp (sxhash cases))
2ee3d7f0 218 (macroexp-let2 macroexp-copyable-p val exp
82ad98e3
SM
219 (let* ((defs ())
220 (seen '())
221 (codegen
222 (lambda (code vars)
223 (let ((prev (assq code seen)))
224 (if (not prev)
225 (let ((res (pcase-codegen code vars)))
226 (push (list code vars res) seen)
227 res)
228 ;; Since we use a tree-based pattern matching
229 ;; technique, the leaves (the places that contain the
230 ;; code to run once a pattern is matched) can get
231 ;; copied a very large number of times, so to avoid
232 ;; code explosion, we need to keep track of how many
233 ;; times we've used each leaf and move it
234 ;; to a separate function if that number is too high.
235 ;;
236 ;; We've already used this branch. So it is shared.
237 (let* ((code (car prev)) (cdrprev (cdr prev))
238 (prevvars (car cdrprev)) (cddrprev (cdr cdrprev))
239 (res (car cddrprev)))
240 (unless (symbolp res)
241 ;; This is the first repeat, so we have to move
242 ;; the branch to a separate function.
243 (let ((bsym
244 (make-symbol (format "pcase-%d" (length defs)))))
ee4b1330
SM
245 (push `(,bsym (lambda ,(mapcar #'car prevvars) ,@code))
246 defs)
82ad98e3
SM
247 (setcar res 'funcall)
248 (setcdr res (cons bsym (mapcar #'cdr prevvars)))
249 (setcar (cddr prev) bsym)
250 (setq res bsym)))
251 (setq vars (copy-sequence vars))
252 (let ((args (mapcar (lambda (pa)
253 (let ((v (assq (car pa) vars)))
254 (setq vars (delq v vars))
255 (cdr v)))
256 prevvars)))
257 ;; If some of `vars' were not found in `prevvars', that's
258 ;; OK it just means those vars aren't present in all
259 ;; branches, so they can be used within the pattern
260 ;; (e.g. by a `guard/let/pred') but not in the branch.
261 ;; FIXME: But if some of `prevvars' are not in `vars' we
262 ;; should remove them from `prevvars'!
263 `(funcall ,res ,@args)))))))
ee4b1330 264 (used-cases ())
82ad98e3
SM
265 (main
266 (pcase--u
267 (mapcar (lambda (case)
268 `((match ,val . ,(car case))
ee4b1330
SM
269 ,(lambda (vars)
270 (unless (memq case used-cases)
271 ;; Keep track of the cases that are used.
272 (push case used-cases))
273 (funcall
274 (if (pcase--small-branch-p (cdr case))
275 ;; Don't bother sharing multiple
276 ;; occurrences of this leaf since it's small.
277 #'pcase-codegen codegen)
278 (cdr case)
279 vars))))
82ad98e3 280 cases))))
ee4b1330 281 (dolist (case cases)
a464a6c7 282 (unless (or (memq case used-cases) (eq (car case) 'pcase--dontcare))
ee4b1330 283 (message "Redundant pcase pattern: %S" (car case))))
4dd1c416 284 (macroexp-let* defs main))))
d02c9bcd
SM
285
286(defun pcase-codegen (code vars)
4dd1c416 287 ;; Don't use let*, otherwise macroexp-let* may merge it with some surrounding
6876a58d
SM
288 ;; let* which might prevent the setcar/setcdr in pcase--expand's fancy
289 ;; codegen from later metamorphosing this let into a funcall.
290 `(let ,(mapcar (lambda (b) (list (car b) (cdr b))) vars)
d02c9bcd
SM
291 ,@code))
292
872ab164 293(defun pcase--small-branch-p (code)
d02c9bcd
SM
294 (and (= 1 (length code))
295 (or (not (consp (car code)))
296 (let ((small t))
297 (dolist (e (car code))
298 (if (consp e) (setq small nil)))
299 small))))
300
301;; Try to use `cond' rather than a sequence of `if's, so as to reduce
302;; the depth of the generated tree.
872ab164 303(defun pcase--if (test then else)
d02c9bcd 304 (cond
872ab164 305 ((eq else :pcase--dontcare) then)
1f0816b6 306 ((eq then :pcase--dontcare) (debug) else) ;Can/should this ever happen?
4dd1c416 307 (t (macroexp-if test then else))))
5342bb06 308
872ab164 309(defun pcase--upat (qpattern)
d02c9bcd
SM
310 (cond
311 ((eq (car-safe qpattern) '\,) (cadr qpattern))
312 (t (list '\` qpattern))))
313
314;; Note about MATCH:
315;; When we have patterns like `(PAT1 . PAT2), after performing the `consp'
316;; check, we want to turn all the similar patterns into ones of the form
317;; (and (match car PAT1) (match cdr PAT2)), so you naturally need conjunction.
318;; Earlier code hence used branches of the form (MATCHES . CODE) where
319;; MATCHES was a list (implicitly a conjunction) of (SYM . PAT).
320;; But if we have a pattern of the form (or `(PAT1 . PAT2) PAT3), there is
321;; no easy way to eliminate the `consp' check in such a representation.
322;; So we replaced the MATCHES by the MATCH below which can be made up
323;; of conjunctions and disjunctions, so if we know `foo' is a cons, we can
324;; turn (match foo . (or `(PAT1 . PAT2) PAT3)) into
325;; (or (and (match car . `PAT1) (match cdr . `PAT2)) (match foo . PAT3)).
326;; The downside is that we now have `or' and `and' both in MATCH and
327;; in PAT, so there are different equivalent representations and we
328;; need to handle them all. We do not try to systematically
329;; canonicalize them to one form over another, but we do occasionally
330;; turn one into the other.
331
872ab164 332(defun pcase--u (branches)
d02c9bcd
SM
333 "Expand matcher for rules BRANCHES.
334Each BRANCH has the form (MATCH CODE . VARS) where
335CODE is the code generator for that branch.
336VARS is the set of vars already bound by earlier matches.
337MATCH is the pattern that needs to be matched, of the form:
338 (match VAR . UPAT)
339 (and MATCH ...)
340 (or MATCH ...)"
341 (when (setq branches (delq nil branches))
9a05edc4
SM
342 (let* ((carbranch (car branches))
343 (match (car carbranch)) (cdarbranch (cdr carbranch))
344 (code (car cdarbranch))
345 (vars (cdr cdarbranch)))
872ab164 346 (pcase--u1 (list match) code vars (cdr branches)))))
d02c9bcd 347
872ab164 348(defun pcase--and (match matches)
d02c9bcd
SM
349 (if matches `(and ,match ,@matches) match))
350
1f0816b6
SM
351(defconst pcase-mutually-exclusive-predicates
352 '((symbolp . integerp)
353 (symbolp . numberp)
354 (symbolp . consp)
355 (symbolp . arrayp)
356 (symbolp . stringp)
ca105506 357 (symbolp . byte-code-function-p)
1f0816b6
SM
358 (integerp . consp)
359 (integerp . arrayp)
360 (integerp . stringp)
ca105506 361 (integerp . byte-code-function-p)
1f0816b6
SM
362 (numberp . consp)
363 (numberp . arrayp)
364 (numberp . stringp)
ca105506 365 (numberp . byte-code-function-p)
1f0816b6
SM
366 (consp . arrayp)
367 (consp . stringp)
ca105506
SM
368 (consp . byte-code-function-p)
369 (arrayp . stringp)
370 (arrayp . byte-code-function-p)
371 (stringp . byte-code-function-p)))
1f0816b6 372
872ab164 373(defun pcase--split-match (sym splitter match)
9a05edc4
SM
374 (cond
375 ((eq (car match) 'match)
d02c9bcd
SM
376 (if (not (eq sym (cadr match)))
377 (cons match match)
378 (let ((pat (cddr match)))
379 (cond
380 ;; Hoist `or' and `and' patterns to `or' and `and' matches.
381 ((memq (car-safe pat) '(or and))
872ab164
SM
382 (pcase--split-match sym splitter
383 (cons (car pat)
384 (mapcar (lambda (alt)
385 `(match ,sym . ,alt))
386 (cdr pat)))))
d02c9bcd
SM
387 (t (let ((res (funcall splitter (cddr match))))
388 (cons (or (car res) match) (or (cdr res) match))))))))
9a05edc4 389 ((memq (car match) '(or and))
d02c9bcd
SM
390 (let ((then-alts '())
391 (else-alts '())
872ab164
SM
392 (neutral-elem (if (eq 'or (car match))
393 :pcase--fail :pcase--succeed))
394 (zero-elem (if (eq 'or (car match)) :pcase--succeed :pcase--fail)))
d02c9bcd 395 (dolist (alt (cdr match))
872ab164 396 (let ((split (pcase--split-match sym splitter alt)))
d02c9bcd
SM
397 (unless (eq (car split) neutral-elem)
398 (push (car split) then-alts))
399 (unless (eq (cdr split) neutral-elem)
400 (push (cdr split) else-alts))))
401 (cons (cond ((memq zero-elem then-alts) zero-elem)
402 ((null then-alts) neutral-elem)
403 ((null (cdr then-alts)) (car then-alts))
404 (t (cons (car match) (nreverse then-alts))))
405 (cond ((memq zero-elem else-alts) zero-elem)
406 ((null else-alts) neutral-elem)
407 ((null (cdr else-alts)) (car else-alts))
408 (t (cons (car match) (nreverse else-alts)))))))
409 (t (error "Uknown MATCH %s" match))))
410
872ab164 411(defun pcase--split-rest (sym splitter rest)
d02c9bcd
SM
412 (let ((then-rest '())
413 (else-rest '()))
414 (dolist (branch rest)
415 (let* ((match (car branch))
416 (code&vars (cdr branch))
bbd240ce 417 (split
872ab164 418 (pcase--split-match sym splitter match)))
bbd240ce
PE
419 (unless (eq (car split) :pcase--fail)
420 (push (cons (car split) code&vars) then-rest))
421 (unless (eq (cdr split) :pcase--fail)
422 (push (cons (cdr split) code&vars) else-rest))))
d02c9bcd
SM
423 (cons (nreverse then-rest) (nreverse else-rest))))
424
872ab164 425(defun pcase--split-consp (syma symd pat)
d02c9bcd
SM
426 (cond
427 ;; A QPattern for a cons, can only go the `then' side.
428 ((and (eq (car-safe pat) '\`) (consp (cadr pat)))
429 (let ((qpat (cadr pat)))
872ab164
SM
430 (cons `(and (match ,syma . ,(pcase--upat (car qpat)))
431 (match ,symd . ,(pcase--upat (cdr qpat))))
432 :pcase--fail)))
1f0816b6 433 ;; A QPattern but not for a cons, can only go to the `else' side.
4bdc3526 434 ((eq (car-safe pat) '\`) '(:pcase--fail . nil))
1f0816b6
SM
435 ((and (eq (car-safe pat) 'pred)
436 (or (member (cons 'consp (cadr pat))
437 pcase-mutually-exclusive-predicates)
438 (member (cons (cadr pat) 'consp)
439 pcase-mutually-exclusive-predicates)))
4bdc3526 440 '(:pcase--fail . nil))))
d02c9bcd 441
872ab164 442(defun pcase--split-equal (elem pat)
d02c9bcd
SM
443 (cond
444 ;; The same match will give the same result.
445 ((and (eq (car-safe pat) '\`) (equal (cadr pat) elem))
4bdc3526 446 '(:pcase--succeed . :pcase--fail))
d02c9bcd
SM
447 ;; A different match will fail if this one succeeds.
448 ((and (eq (car-safe pat) '\`)
449 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
450 ;; (consp (cadr pat)))
451 )
4bdc3526 452 '(:pcase--fail . nil))
1f0816b6
SM
453 ((and (eq (car-safe pat) 'pred)
454 (symbolp (cadr pat))
4bdc3526
SM
455 (get (cadr pat) 'side-effect-free))
456 (if (funcall (cadr pat) elem)
457 '(:pcase--succeed . nil)
458 '(:pcase--fail . nil)))))
d02c9bcd 459
872ab164
SM
460(defun pcase--split-member (elems pat)
461 ;; Based on pcase--split-equal.
d02c9bcd 462 (cond
dcc029e0
SM
463 ;; The same match (or a match of membership in a superset) will
464 ;; give the same result, but we don't know how to check it.
4de81ee0 465 ;; (???
4bdc3526 466 ;; '(:pcase--succeed . nil))
4de81ee0 467 ;; A match for one of the elements may succeed or fail.
d02c9bcd 468 ((and (eq (car-safe pat) '\`) (member (cadr pat) elems))
4de81ee0 469 nil)
d02c9bcd
SM
470 ;; A different match will fail if this one succeeds.
471 ((and (eq (car-safe pat) '\`)
472 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
473 ;; (consp (cadr pat)))
474 )
4bdc3526 475 '(:pcase--fail . nil))
1f0816b6
SM
476 ((and (eq (car-safe pat) 'pred)
477 (symbolp (cadr pat))
478 (get (cadr pat) 'side-effect-free)
479 (let ((p (cadr pat)) (all t))
480 (dolist (elem elems)
481 (unless (funcall p elem) (setq all nil)))
482 all))
4bdc3526 483 '(:pcase--succeed . nil))))
d02c9bcd 484
0b64b838 485(defun pcase--split-pred (vars upat pat)
5342bb06
SM
486 (let (test)
487 (cond
0b64b838
SM
488 ((and (equal upat pat)
489 ;; For predicates like (pred (> a)), two such predicates may
490 ;; actually refer to different variables `a'.
491 (or (and (eq 'pred (car upat)) (symbolp (cadr upat)))
492 ;; FIXME: `vars' gives us the environment in which `upat' will
493 ;; run, but we don't have the environment in which `pat' will
494 ;; run, so we can't do a reliable verification. But let's try
495 ;; and catch at least the easy cases such as (bug#14773).
496 (not (pcase--fgrep (mapcar #'car vars) (cadr upat)))))
497 '(:pcase--succeed . :pcase--fail))
5342bb06
SM
498 ((and (eq 'pred (car upat))
499 (eq 'pred (car-safe pat))
500 (or (member (cons (cadr upat) (cadr pat))
501 pcase-mutually-exclusive-predicates)
502 (member (cons (cadr pat) (cadr upat))
503 pcase-mutually-exclusive-predicates)))
4bdc3526 504 '(:pcase--fail . nil))
5342bb06
SM
505 ((and (eq 'pred (car upat))
506 (eq '\` (car-safe pat))
507 (symbolp (cadr upat))
508 (or (symbolp (cadr pat)) (stringp (cadr pat)) (numberp (cadr pat)))
509 (get (cadr upat) 'side-effect-free)
510 (ignore-errors
511 (setq test (list (funcall (cadr upat) (cadr pat))))))
512 (if (car test)
4bdc3526
SM
513 '(nil . :pcase--fail)
514 '(:pcase--fail . nil))))))
d02c9bcd 515
872ab164 516(defun pcase--fgrep (vars sexp)
d02c9bcd
SM
517 "Check which of the symbols VARS appear in SEXP."
518 (let ((res '()))
519 (while (consp sexp)
872ab164 520 (dolist (var (pcase--fgrep vars (pop sexp)))
d02c9bcd
SM
521 (unless (memq var res) (push var res))))
522 (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
523 res))
524
19faa8e8
SM
525(defun pcase--self-quoting-p (upat)
526 (or (keywordp upat) (numberp upat) (stringp upat)))
527
7f457c06
SM
528(defsubst pcase--mark-used (sym)
529 ;; Exceptionally, `sym' may be a constant expression rather than a symbol.
530 (if (symbolp sym) (put sym 'pcase-used t)))
531
d02c9bcd
SM
532;; It's very tempting to use `pcase' below, tho obviously, it'd create
533;; bootstrapping problems.
872ab164 534(defun pcase--u1 (matches code vars rest)
d02c9bcd 535 "Return code that runs CODE (with VARS) if MATCHES match.
ca3afb79 536Otherwise, it defers to REST which is a list of branches of the form
d02c9bcd
SM
537\(ELSE-MATCH ELSE-CODE . ELSE-VARS)."
538 ;; Depending on the order in which we choose to check each of the MATCHES,
539 ;; the resulting tree may be smaller or bigger. So in general, we'd want
540 ;; to be careful to chose the "optimal" order. But predicate
541 ;; patterns make this harder because they create dependencies
542 ;; between matches. So we don't bother trying to reorder anything.
543 (cond
544 ((null matches) (funcall code vars))
872ab164
SM
545 ((eq :pcase--fail (car matches)) (pcase--u rest))
546 ((eq :pcase--succeed (car matches))
547 (pcase--u1 (cdr matches) code vars rest))
d02c9bcd 548 ((eq 'and (caar matches))
872ab164 549 (pcase--u1 (append (cdar matches) (cdr matches)) code vars rest))
d02c9bcd
SM
550 ((eq 'or (caar matches))
551 (let* ((alts (cdar matches))
552 (var (if (eq (caar alts) 'match) (cadr (car alts))))
553 (simples '()) (others '()))
554 (when var
555 (dolist (alt alts)
556 (if (and (eq (car alt) 'match) (eq var (cadr alt))
557 (let ((upat (cddr alt)))
558 (and (eq (car-safe upat) '\`)
dcc029e0
SM
559 (or (integerp (cadr upat)) (symbolp (cadr upat))
560 (stringp (cadr upat))))))
d02c9bcd
SM
561 (push (cddr alt) simples)
562 (push alt others))))
563 (cond
872ab164 564 ((null alts) (error "Please avoid it") (pcase--u rest))
d02c9bcd
SM
565 ((> (length simples) 1)
566 ;; De-hoist the `or' MATCH into an `or' pattern that will be
567 ;; turned into a `memq' below.
872ab164
SM
568 (pcase--u1 (cons `(match ,var or . ,(nreverse simples)) (cdr matches))
569 code vars
570 (if (null others) rest
9a05edc4 571 (cons (cons
872ab164
SM
572 (pcase--and (if (cdr others)
573 (cons 'or (nreverse others))
574 (car others))
575 (cdr matches))
9a05edc4 576 (cons code vars))
872ab164 577 rest))))
d02c9bcd 578 (t
872ab164
SM
579 (pcase--u1 (cons (pop alts) (cdr matches)) code vars
580 (if (null alts) (progn (error "Please avoid it") rest)
9a05edc4 581 (cons (cons
872ab164
SM
582 (pcase--and (if (cdr alts)
583 (cons 'or alts) (car alts))
584 (cdr matches))
9a05edc4 585 (cons code vars))
872ab164 586 rest)))))))
d02c9bcd 587 ((eq 'match (caar matches))
9a05edc4 588 (let* ((popmatches (pop matches))
d032d5e7 589 (_op (car popmatches)) (cdrpopmatches (cdr popmatches))
9a05edc4
SM
590 (sym (car cdrpopmatches))
591 (upat (cdr cdrpopmatches)))
d02c9bcd 592 (cond
872ab164 593 ((memq upat '(t _)) (pcase--u1 matches code vars rest))
a464a6c7 594 ((eq upat 'pcase--dontcare) :pcase--dontcare)
dcc029e0 595 ((memq (car-safe upat) '(guard pred))
7f457c06 596 (if (eq (car upat) 'pred) (pcase--mark-used sym))
9a05edc4 597 (let* ((splitrest
ca105506 598 (pcase--split-rest
0b64b838 599 sym (lambda (pat) (pcase--split-pred vars upat pat)) rest))
9a05edc4
SM
600 (then-rest (car splitrest))
601 (else-rest (cdr splitrest)))
872ab164
SM
602 (pcase--if (if (and (eq (car upat) 'pred) (symbolp (cadr upat)))
603 `(,(cadr upat) ,sym)
604 (let* ((exp (cadr upat))
605 ;; `vs' is an upper bound on the vars we need.
606 (vs (pcase--fgrep (mapcar #'car vars) exp))
ca105506
SM
607 (env (mapcar (lambda (var)
608 (list var (cdr (assq var vars))))
609 vs))
610 (call (if (eq 'guard (car upat))
611 exp
612 (when (memq sym vs)
613 ;; `sym' is shadowed by `env'.
614 (let ((newsym (make-symbol "x")))
615 (push (list newsym sym) env)
616 (setq sym newsym)))
9abdc45d
SM
617 (if (functionp exp)
618 `(funcall #',exp ,sym)
ca105506 619 `(,@exp ,sym)))))
872ab164
SM
620 (if (null vs)
621 call
622 ;; Let's not replace `vars' in `exp' since it's
623 ;; too difficult to do it right, instead just
624 ;; let-bind `vars' around `exp'.
ca105506 625 `(let* ,env ,call))))
872ab164
SM
626 (pcase--u1 matches code vars then-rest)
627 (pcase--u else-rest))))
19faa8e8 628 ((pcase--self-quoting-p upat)
7f457c06 629 (pcase--mark-used sym)
19faa8e8 630 (pcase--q1 sym upat matches code vars rest))
d02c9bcd 631 ((symbolp upat)
7f457c06 632 (pcase--mark-used sym)
f9d554dd
SM
633 (if (not (assq upat vars))
634 (pcase--u1 matches code (cons (cons upat sym) vars) rest)
635 ;; Non-linear pattern. Turn it into an `eq' test.
636 (pcase--u1 (cons `(match ,sym . (pred (eq ,(cdr (assq upat vars)))))
637 matches)
638 code vars rest)))
ca105506
SM
639 ((eq (car-safe upat) 'let)
640 ;; A upat of the form (let VAR EXP).
641 ;; (pcase--u1 matches code
642 ;; (cons (cons (nth 1 upat) (nth 2 upat)) vars) rest)
2ee3d7f0 643 (macroexp-let2
4dd1c416
SM
644 macroexp-copyable-p sym
645 (let* ((exp (nth 2 upat))
646 (found (assq exp vars)))
647 (if found (cdr found)
648 (let* ((vs (pcase--fgrep (mapcar #'car vars) exp))
649 (env (mapcar (lambda (v) (list v (cdr (assq v vars))))
650 vs)))
651 (if env (macroexp-let* env exp) exp))))
652 (pcase--u1 (cons `(match ,sym . ,(nth 1 upat)) matches)
653 code vars rest)))
d02c9bcd 654 ((eq (car-safe upat) '\`)
7f457c06 655 (pcase--mark-used sym)
872ab164 656 (pcase--q1 sym (cadr upat) matches code vars rest))
d02c9bcd 657 ((eq (car-safe upat) 'or)
dcc029e0
SM
658 (let ((all (> (length (cdr upat)) 1))
659 (memq-fine t))
d02c9bcd
SM
660 (when all
661 (dolist (alt (cdr upat))
19faa8e8
SM
662 (unless (or (pcase--self-quoting-p alt)
663 (and (eq (car-safe alt) '\`)
664 (or (symbolp (cadr alt)) (integerp (cadr alt))
665 (setq memq-fine nil)
666 (stringp (cadr alt)))))
d02c9bcd
SM
667 (setq all nil))))
668 (if all
669 ;; Use memq for (or `a `b `c `d) rather than a big tree.
19faa8e8
SM
670 (let* ((elems (mapcar (lambda (x) (if (consp x) (cadr x) x))
671 (cdr upat)))
9a05edc4
SM
672 (splitrest
673 (pcase--split-rest
ee4b1330 674 sym (lambda (pat) (pcase--split-member elems pat)) rest))
9a05edc4
SM
675 (then-rest (car splitrest))
676 (else-rest (cdr splitrest)))
7f457c06 677 (pcase--mark-used sym)
9a05edc4
SM
678 (pcase--if `(,(if memq-fine #'memq #'member) ,sym ',elems)
679 (pcase--u1 matches code vars then-rest)
680 (pcase--u else-rest)))
872ab164
SM
681 (pcase--u1 (cons `(match ,sym ,@(cadr upat)) matches) code vars
682 (append (mapcar (lambda (upat)
683 `((and (match ,sym . ,upat) ,@matches)
684 ,code ,@vars))
685 (cddr upat))
686 rest)))))
d02c9bcd 687 ((eq (car-safe upat) 'and)
872ab164
SM
688 (pcase--u1 (append (mapcar (lambda (upat) `(match ,sym ,@upat))
689 (cdr upat))
690 matches)
691 code vars rest))
d02c9bcd
SM
692 ((eq (car-safe upat) 'not)
693 ;; FIXME: The implementation below is naive and results in
694 ;; inefficient code.
872ab164 695 ;; To make it work right, we would need to turn pcase--u1's
d02c9bcd
SM
696 ;; `code' and `vars' into a single argument of the same form as
697 ;; `rest'. We would also need to split this new `then-rest' argument
698 ;; for every test (currently we don't bother to do it since
699 ;; it's only useful for odd patterns like (and `(PAT1 . PAT2)
700 ;; `(PAT3 . PAT4)) which the programmer can easily rewrite
701 ;; to the more efficient `(,(and PAT1 PAT3) . ,(and PAT2 PAT4))).
872ab164 702 (pcase--u1 `((match ,sym . ,(cadr upat)))
94d11cb5
IK
703 ;; FIXME: This codegen is not careful to share its
704 ;; code if used several times: code blow up is likely.
d032d5e7 705 (lambda (_vars)
94d11cb5
IK
706 ;; `vars' will likely contain bindings which are
707 ;; not always available in other paths to
708 ;; `rest', so there' no point trying to pass
709 ;; them down.
710 (pcase--u rest))
872ab164
SM
711 vars
712 (list `((and . ,matches) ,code . ,vars))))
d02c9bcd
SM
713 (t (error "Unknown upattern `%s'" upat)))))
714 (t (error "Incorrect MATCH %s" (car matches)))))
715
872ab164 716(defun pcase--q1 (sym qpat matches code vars rest)
d02c9bcd 717 "Return code that runs CODE if SYM matches QPAT and if MATCHES match.
ca3afb79 718Otherwise, it defers to REST which is a list of branches of the form
d02c9bcd
SM
719\(OTHER_MATCH OTHER-CODE . OTHER-VARS)."
720 (cond
721 ((eq (car-safe qpat) '\,) (error "Can't use `,UPATTERN"))
722 ((floatp qpat) (error "Floating point patterns not supported"))
723 ((vectorp qpat)
724 ;; FIXME.
725 (error "Vector QPatterns not implemented yet"))
726 ((consp qpat)
0d6459df
SM
727 (let* ((syma (make-symbol "xcar"))
728 (symd (make-symbol "xcdr"))
729 (splitrest (pcase--split-rest
730 sym
ee4b1330 731 (lambda (pat) (pcase--split-consp syma symd pat))
0d6459df
SM
732 rest))
733 (then-rest (car splitrest))
734 (else-rest (cdr splitrest))
735 (then-body (pcase--u1 `((match ,syma . ,(pcase--upat (car qpat)))
736 (match ,symd . ,(pcase--upat (cdr qpat)))
737 ,@matches)
738 code vars then-rest)))
739 (pcase--if
740 `(consp ,sym)
741 ;; We want to be careful to only add bindings that are used.
742 ;; The byte-compiler could do that for us, but it would have to pay
743 ;; attention to the `consp' test in order to figure out that car/cdr
744 ;; can't signal errors and our byte-compiler is not that clever.
5342bb06
SM
745 ;; FIXME: Some of those let bindings occur too early (they are used in
746 ;; `then-body', but only within some sub-branch).
4dd1c416 747 (macroexp-let*
5342bb06 748 `(,@(if (get syma 'pcase-used) `((,syma (car ,sym))))
0d6459df 749 ,@(if (get symd 'pcase-used) `((,symd (cdr ,sym)))))
5342bb06 750 then-body)
0d6459df 751 (pcase--u else-rest))))
dcc029e0 752 ((or (integerp qpat) (symbolp qpat) (stringp qpat))
9a05edc4 753 (let* ((splitrest (pcase--split-rest
ee4b1330 754 sym (lambda (pat) (pcase--split-equal qpat pat)) rest))
9a05edc4
SM
755 (then-rest (car splitrest))
756 (else-rest (cdr splitrest)))
5342bb06
SM
757 (pcase--if (cond
758 ((stringp qpat) `(equal ,sym ,qpat))
759 ((null qpat) `(null ,sym))
760 (t `(eq ,sym ',qpat)))
872ab164
SM
761 (pcase--u1 matches code vars then-rest)
762 (pcase--u else-rest))))
22bcf204 763 (t (error "Unknown QPattern %s" qpat))))
97eedd1b 764
d02c9bcd
SM
765
766(provide 'pcase)
767;;; pcase.el ends here