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