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