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