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