Fix quoting of help for functions with odd names
[emacs.git] / lisp / emacs-lisp / pcase.el
blob0d3b21b8330e223c133d16c4fcaa4dbf5f0d479f
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 PAT). 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-PAT
75 (&or symbolp
76 ("or" &rest pcase-PAT)
77 ("and" &rest pcase-PAT)
78 ("guard" form)
79 ("let" pcase-PAT form)
80 ("pred" pcase-FUN)
81 ("app" pcase-FUN pcase-PAT)
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 (PATTERN CODE...).
113 Patterns 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 PAT...) matches if any of the patterns matches.
118 (and PAT...) 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 PAT EXP) matches if EXP matches PAT.
123 (app FUN PAT) matches if FUN applied to the object matches PAT.
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-PAT 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 raw))
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) t))
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 pattern.
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-PAT) 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.
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)))
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 (PAT EXP)."
246 (declare (indent 1)
247 (debug ((&rest (pcase-PAT &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 (PAT EXP).
261 The macro is expanded and optimized under the assumption that those
262 patterns *will* match, so a mismatch may go undetected or may cause
263 any kind of error."
264 (declare (indent 1) (debug pcase-let*))
265 (if (null (cdr bindings))
266 `(pcase-let* ,bindings ,@body)
267 (let ((matches '()))
268 (dolist (binding (prog1 bindings (setq bindings nil)))
269 (cond
270 ((memq (car binding) pcase--dontcare-upats)
271 (push (cons (make-symbol "_") (cdr binding)) bindings))
272 ((pcase--trivial-upat-p (car binding)) (push binding bindings))
274 (let ((tmpvar (make-symbol (format "x%d" (length bindings)))))
275 (push (cons tmpvar (cdr binding)) bindings)
276 (push (list (car binding) tmpvar) matches)))))
277 `(let ,(nreverse bindings) (pcase-let* ,matches ,@body)))))
279 ;;;###autoload
280 (defmacro pcase-dolist (spec &rest body)
281 (declare (indent 1) (debug ((pcase-PAT form) body)))
282 (if (pcase--trivial-upat-p (car spec))
283 `(dolist ,spec ,@body)
284 (let ((tmpvar (make-symbol "x")))
285 `(dolist (,tmpvar ,@(cdr spec))
286 (pcase-let* ((,(car spec) ,tmpvar))
287 ,@body)))))
290 (defun pcase--trivial-upat-p (upat)
291 (and (symbolp upat) (not (memq upat pcase--dontcare-upats))))
293 (defun pcase--expand (exp cases)
294 ;; (message "pid=%S (pcase--expand %S ...hash=%S)"
295 ;; (emacs-pid) exp (sxhash cases))
296 (macroexp-let2 macroexp-copyable-p val exp
297 (let* ((defs ())
298 (seen '())
299 (codegen
300 (lambda (code vars)
301 (let ((prev (assq code seen)))
302 (if (not prev)
303 (let ((res (pcase-codegen code vars)))
304 (push (list code vars res) seen)
305 res)
306 ;; Since we use a tree-based pattern matching
307 ;; technique, the leaves (the places that contain the
308 ;; code to run once a pattern is matched) can get
309 ;; copied a very large number of times, so to avoid
310 ;; code explosion, we need to keep track of how many
311 ;; times we've used each leaf and move it
312 ;; to a separate function if that number is too high.
314 ;; We've already used this branch. So it is shared.
315 (let* ((code (car prev)) (cdrprev (cdr prev))
316 (prevvars (car cdrprev)) (cddrprev (cdr cdrprev))
317 (res (car cddrprev)))
318 (unless (symbolp res)
319 ;; This is the first repeat, so we have to move
320 ;; the branch to a separate function.
321 (let ((bsym
322 (make-symbol (format "pcase-%d" (length defs)))))
323 (push `(,bsym (lambda ,(mapcar #'car prevvars) ,@code))
324 defs)
325 (setcar res 'funcall)
326 (setcdr res (cons bsym (mapcar #'cdr prevvars)))
327 (setcar (cddr prev) bsym)
328 (setq res bsym)))
329 (setq vars (copy-sequence vars))
330 (let ((args (mapcar (lambda (pa)
331 (let ((v (assq (car pa) vars)))
332 (setq vars (delq v vars))
333 (cdr v)))
334 prevvars)))
335 ;; If some of `vars' were not found in `prevvars', that's
336 ;; OK it just means those vars aren't present in all
337 ;; branches, so they can be used within the pattern
338 ;; (e.g. by a `guard/let/pred') but not in the branch.
339 ;; FIXME: But if some of `prevvars' are not in `vars' we
340 ;; should remove them from `prevvars'!
341 `(funcall ,res ,@args)))))))
342 (used-cases ())
343 (main
344 (pcase--u
345 (mapcar (lambda (case)
346 `(,(pcase--match val (pcase--macroexpand (car case)))
347 ,(lambda (vars)
348 (unless (memq case used-cases)
349 ;; Keep track of the cases that are used.
350 (push case used-cases))
351 (funcall
352 (if (pcase--small-branch-p (cdr case))
353 ;; Don't bother sharing multiple
354 ;; occurrences of this leaf since it's small.
355 #'pcase-codegen codegen)
356 (cdr case)
357 vars))))
358 cases))))
359 (dolist (case cases)
360 (unless (or (memq case used-cases)
361 (memq (car case) pcase--dontwarn-upats))
362 (message "Redundant pcase pattern: %S" (car case))))
363 (macroexp-let* defs main))))
365 (defun pcase--macroexpand (pat)
366 "Expands all macro-patterns in PAT."
367 (let ((head (car-safe pat)))
368 (cond
369 ((null head)
370 (if (pcase--self-quoting-p pat) `',pat pat))
371 ((memq head '(pred guard quote)) pat)
372 ((memq head '(or and)) `(,head ,@(mapcar #'pcase--macroexpand (cdr pat))))
373 ((eq head 'let) `(let ,(pcase--macroexpand (cadr pat)) ,@(cddr pat)))
374 ((eq head 'app) `(app ,(nth 1 pat) ,(pcase--macroexpand (nth 2 pat))))
376 (let* ((expander (get head 'pcase-macroexpander))
377 (npat (if expander (apply expander (cdr pat)))))
378 (if (null npat)
379 (error (if expander
380 "Unexpandable %s pattern: %S"
381 "Unknown %s pattern: %S")
382 head pat)
383 (pcase--macroexpand npat)))))))
385 ;;;###autoload
386 (defmacro pcase-defmacro (name args &rest body)
387 "Define a new kind of pcase PATTERN, by macro expansion.
388 Patterns of the form (NAME ...) will be expanded according
389 to this macro."
390 (declare (indent 2) (debug defun) (doc-string 3))
391 ;; Add the function via `fsym', so that an autoload cookie placed
392 ;; on a pcase-defmacro will cause the macro to be loaded on demand.
393 (let ((fsym (intern (format "%s--pcase-macroexpander" name)))
394 (decl (assq 'declare body)))
395 (when decl (setq body (remove decl body)))
396 `(progn
397 (defun ,fsym ,args ,@body)
398 (put ',fsym 'edebug-form-spec ',(cadr (assq 'debug decl)))
399 (put ',name 'pcase-macroexpander #',fsym))))
401 (defun pcase--match (val upat)
402 "Build a MATCH structure, hoisting all `or's and `and's outside."
403 (cond
404 ;; Hoist or/and patterns into or/and matches.
405 ((memq (car-safe upat) '(or and))
406 `(,(car upat)
407 ,@(mapcar (lambda (upat)
408 (pcase--match val upat))
409 (cdr upat))))
411 `(match ,val . ,upat))))
413 (defun pcase-codegen (code vars)
414 ;; Don't use let*, otherwise macroexp-let* may merge it with some surrounding
415 ;; let* which might prevent the setcar/setcdr in pcase--expand's fancy
416 ;; codegen from later metamorphosing this let into a funcall.
417 `(let ,(mapcar (lambda (b) (list (car b) (cdr b))) vars)
418 ,@code))
420 (defun pcase--small-branch-p (code)
421 (and (= 1 (length code))
422 (or (not (consp (car code)))
423 (let ((small t))
424 (dolist (e (car code))
425 (if (consp e) (setq small nil)))
426 small))))
428 ;; Try to use `cond' rather than a sequence of `if's, so as to reduce
429 ;; the depth of the generated tree.
430 (defun pcase--if (test then else)
431 (cond
432 ((eq else :pcase--dontcare) then)
433 ((eq then :pcase--dontcare) (debug) else) ;Can/should this ever happen?
434 (t (macroexp-if test then else))))
436 ;; Note about MATCH:
437 ;; When we have patterns like `(PAT1 . PAT2), after performing the `consp'
438 ;; check, we want to turn all the similar patterns into ones of the form
439 ;; (and (match car PAT1) (match cdr PAT2)), so you naturally need conjunction.
440 ;; Earlier code hence used branches of the form (MATCHES . CODE) where
441 ;; MATCHES was a list (implicitly a conjunction) of (SYM . PAT).
442 ;; But if we have a pattern of the form (or `(PAT1 . PAT2) PAT3), there is
443 ;; no easy way to eliminate the `consp' check in such a representation.
444 ;; So we replaced the MATCHES by the MATCH below which can be made up
445 ;; of conjunctions and disjunctions, so if we know `foo' is a cons, we can
446 ;; turn (match foo . (or `(PAT1 . PAT2) PAT3)) into
447 ;; (or (and (match car . `PAT1) (match cdr . `PAT2)) (match foo . PAT3)).
448 ;; The downside is that we now have `or' and `and' both in MATCH and
449 ;; in PAT, so there are different equivalent representations and we
450 ;; need to handle them all. We do not try to systematically
451 ;; canonicalize them to one form over another, but we do occasionally
452 ;; turn one into the other.
454 (defun pcase--u (branches)
455 "Expand matcher for rules BRANCHES.
456 Each BRANCH has the form (MATCH CODE . VARS) where
457 CODE is the code generator for that branch.
458 VARS is the set of vars already bound by earlier matches.
459 MATCH is the pattern that needs to be matched, of the form:
460 (match VAR . PAT)
461 (and MATCH ...)
462 (or MATCH ...)"
463 (when (setq branches (delq nil branches))
464 (let* ((carbranch (car branches))
465 (match (car carbranch)) (cdarbranch (cdr carbranch))
466 (code (car cdarbranch))
467 (vars (cdr cdarbranch)))
468 (pcase--u1 (list match) code vars (cdr branches)))))
470 (defun pcase--and (match matches)
471 (if matches `(and ,match ,@matches) match))
473 (defconst pcase-mutually-exclusive-predicates
474 '((symbolp . integerp)
475 (symbolp . numberp)
476 (symbolp . consp)
477 (symbolp . arrayp)
478 (symbolp . vectorp)
479 (symbolp . stringp)
480 (symbolp . byte-code-function-p)
481 (integerp . consp)
482 (integerp . arrayp)
483 (integerp . vectorp)
484 (integerp . stringp)
485 (integerp . byte-code-function-p)
486 (numberp . consp)
487 (numberp . arrayp)
488 (numberp . vectorp)
489 (numberp . stringp)
490 (numberp . byte-code-function-p)
491 (consp . arrayp)
492 (consp . vectorp)
493 (consp . stringp)
494 (consp . byte-code-function-p)
495 (arrayp . byte-code-function-p)
496 (vectorp . byte-code-function-p)
497 (stringp . vectorp)
498 (stringp . byte-code-function-p)))
500 (defun pcase--mutually-exclusive-p (pred1 pred2)
501 (or (member (cons pred1 pred2)
502 pcase-mutually-exclusive-predicates)
503 (member (cons pred2 pred1)
504 pcase-mutually-exclusive-predicates)))
506 (defun pcase--split-match (sym splitter match)
507 (cond
508 ((eq (car-safe match) 'match)
509 (if (not (eq sym (cadr match)))
510 (cons match match)
511 (let ((res (funcall splitter (cddr match))))
512 (cons (or (car res) match) (or (cdr res) match)))))
513 ((memq (car-safe match) '(or and))
514 (let ((then-alts '())
515 (else-alts '())
516 (neutral-elem (if (eq 'or (car match))
517 :pcase--fail :pcase--succeed))
518 (zero-elem (if (eq 'or (car match)) :pcase--succeed :pcase--fail)))
519 (dolist (alt (cdr match))
520 (let ((split (pcase--split-match sym splitter alt)))
521 (unless (eq (car split) neutral-elem)
522 (push (car split) then-alts))
523 (unless (eq (cdr split) neutral-elem)
524 (push (cdr split) else-alts))))
525 (cons (cond ((memq zero-elem then-alts) zero-elem)
526 ((null then-alts) neutral-elem)
527 ((null (cdr then-alts)) (car then-alts))
528 (t (cons (car match) (nreverse then-alts))))
529 (cond ((memq zero-elem else-alts) zero-elem)
530 ((null else-alts) neutral-elem)
531 ((null (cdr else-alts)) (car else-alts))
532 (t (cons (car match) (nreverse else-alts)))))))
533 ((memq match '(:pcase--succeed :pcase--fail)) (cons match match))
534 (t (error "Uknown MATCH %s" match))))
536 (defun pcase--split-rest (sym splitter rest)
537 (let ((then-rest '())
538 (else-rest '()))
539 (dolist (branch rest)
540 (let* ((match (car branch))
541 (code&vars (cdr branch))
542 (split
543 (pcase--split-match sym splitter match)))
544 (unless (eq (car split) :pcase--fail)
545 (push (cons (car split) code&vars) then-rest))
546 (unless (eq (cdr split) :pcase--fail)
547 (push (cons (cdr split) code&vars) else-rest))))
548 (cons (nreverse then-rest) (nreverse else-rest))))
550 (defun pcase--split-equal (elem pat)
551 (cond
552 ;; The same match will give the same result.
553 ((and (eq (car-safe pat) 'quote) (equal (cadr pat) elem))
554 '(:pcase--succeed . :pcase--fail))
555 ;; A different match will fail if this one succeeds.
556 ((and (eq (car-safe pat) 'quote)
557 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
558 ;; (consp (cadr pat)))
560 '(:pcase--fail . nil))
561 ((and (eq (car-safe pat) 'pred)
562 (symbolp (cadr pat))
563 (get (cadr pat) 'side-effect-free))
564 (ignore-errors
565 (if (funcall (cadr pat) elem)
566 '(:pcase--succeed . nil)
567 '(:pcase--fail . nil))))))
569 (defun pcase--split-member (elems pat)
570 ;; FIXME: The new pred-based member code doesn't do these optimizations!
571 ;; Based on pcase--split-equal.
572 (cond
573 ;; The same match (or a match of membership in a superset) will
574 ;; give the same result, but we don't know how to check it.
575 ;; (???
576 ;; '(:pcase--succeed . nil))
577 ;; A match for one of the elements may succeed or fail.
578 ((and (eq (car-safe pat) 'quote) (member (cadr pat) elems))
579 nil)
580 ;; A different match will fail if this one succeeds.
581 ((and (eq (car-safe pat) 'quote)
582 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
583 ;; (consp (cadr pat)))
585 '(:pcase--fail . nil))
586 ((and (eq (car-safe pat) 'pred)
587 (symbolp (cadr pat))
588 (get (cadr pat) 'side-effect-free)
589 (ignore-errors
590 (let ((p (cadr pat)) (all t))
591 (dolist (elem elems)
592 (unless (funcall p elem) (setq all nil)))
593 all)))
594 '(:pcase--succeed . nil))))
596 (defun pcase--split-pred (vars upat pat)
597 (let (test)
598 (cond
599 ((and (equal upat pat)
600 ;; For predicates like (pred (> a)), two such predicates may
601 ;; actually refer to different variables `a'.
602 (or (and (eq 'pred (car upat)) (symbolp (cadr upat)))
603 ;; FIXME: `vars' gives us the environment in which `upat' will
604 ;; run, but we don't have the environment in which `pat' will
605 ;; run, so we can't do a reliable verification. But let's try
606 ;; and catch at least the easy cases such as (bug#14773).
607 (not (pcase--fgrep (mapcar #'car vars) (cadr upat)))))
608 '(:pcase--succeed . :pcase--fail))
609 ((and (eq 'pred (car upat))
610 (let ((otherpred
611 (cond ((eq 'pred (car-safe pat)) (cadr pat))
612 ((not (eq 'quote (car-safe pat))) nil)
613 ((consp (cadr pat)) #'consp)
614 ((stringp (cadr pat)) #'stringp)
615 ((vectorp (cadr pat)) #'vectorp)
616 ((byte-code-function-p (cadr pat))
617 #'byte-code-function-p))))
618 (pcase--mutually-exclusive-p (cadr upat) otherpred)))
619 '(:pcase--fail . nil))
620 ((and (eq 'pred (car upat))
621 (eq 'quote (car-safe pat))
622 (symbolp (cadr upat))
623 (or (symbolp (cadr pat)) (stringp (cadr pat)) (numberp (cadr pat)))
624 (get (cadr upat) 'side-effect-free)
625 (ignore-errors
626 (setq test (list (funcall (cadr upat) (cadr pat))))))
627 (if (car test)
628 '(nil . :pcase--fail)
629 '(:pcase--fail . nil))))))
631 (defun pcase--fgrep (vars sexp)
632 "Check which of the symbols VARS appear in SEXP."
633 (let ((res '()))
634 (while (consp sexp)
635 (dolist (var (pcase--fgrep vars (pop sexp)))
636 (unless (memq var res) (push var res))))
637 (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
638 res))
640 (defun pcase--self-quoting-p (upat)
641 (or (keywordp upat) (numberp upat) (stringp upat)))
643 (defun pcase--app-subst-match (match sym fun nsym)
644 (cond
645 ((eq (car-safe match) 'match)
646 (if (and (eq sym (cadr match))
647 (eq 'app (car-safe (cddr match)))
648 (equal fun (nth 1 (cddr match))))
649 (pcase--match nsym (nth 2 (cddr match)))
650 match))
651 ((memq (car-safe match) '(or and))
652 `(,(car match)
653 ,@(mapcar (lambda (match)
654 (pcase--app-subst-match match sym fun nsym))
655 (cdr match))))
656 ((memq match '(:pcase--succeed :pcase--fail)) match)
657 (t (error "Uknown MATCH %s" match))))
659 (defun pcase--app-subst-rest (rest sym fun nsym)
660 (mapcar (lambda (branch)
661 `(,(pcase--app-subst-match (car branch) sym fun nsym)
662 ,@(cdr branch)))
663 rest))
665 (defsubst pcase--mark-used (sym)
666 ;; Exceptionally, `sym' may be a constant expression rather than a symbol.
667 (if (symbolp sym) (put sym 'pcase-used t)))
669 (defmacro pcase--flip (fun arg1 arg2)
670 "Helper function, used internally to avoid (funcall (lambda ...) ...)."
671 (declare (debug (sexp body)))
672 `(,fun ,arg2 ,arg1))
674 (defun pcase--funcall (fun arg vars)
675 "Build a function call to FUN with arg ARG."
676 (if (symbolp fun)
677 `(,fun ,arg)
678 (let* (;; `vs' is an upper bound on the vars we need.
679 (vs (pcase--fgrep (mapcar #'car vars) fun))
680 (env (mapcar (lambda (var)
681 (list var (cdr (assq var vars))))
682 vs))
683 (call (progn
684 (when (memq arg vs)
685 ;; `arg' is shadowed by `env'.
686 (let ((newsym (make-symbol "x")))
687 (push (list newsym arg) env)
688 (setq arg newsym)))
689 (if (functionp fun)
690 `(funcall #',fun ,arg)
691 `(,@fun ,arg)))))
692 (if (null vs)
693 call
694 ;; Let's not replace `vars' in `fun' since it's
695 ;; too difficult to do it right, instead just
696 ;; let-bind `vars' around `fun'.
697 `(let* ,env ,call)))))
699 (defun pcase--eval (exp vars)
700 "Build an expression that will evaluate EXP."
701 (let* ((found (assq exp vars)))
702 (if found (cdr found)
703 (let* ((vs (pcase--fgrep (mapcar #'car vars) exp))
704 (env (mapcar (lambda (v) (list v (cdr (assq v vars))))
705 vs)))
706 (if env (macroexp-let* env exp) exp)))))
708 ;; It's very tempting to use `pcase' below, tho obviously, it'd create
709 ;; bootstrapping problems.
710 (defun pcase--u1 (matches code vars rest)
711 "Return code that runs CODE (with VARS) if MATCHES match.
712 Otherwise, it defers to REST which is a list of branches of the form
713 \(ELSE-MATCH ELSE-CODE . ELSE-VARS)."
714 ;; Depending on the order in which we choose to check each of the MATCHES,
715 ;; the resulting tree may be smaller or bigger. So in general, we'd want
716 ;; to be careful to chose the "optimal" order. But predicate
717 ;; patterns make this harder because they create dependencies
718 ;; between matches. So we don't bother trying to reorder anything.
719 (cond
720 ((null matches) (funcall code vars))
721 ((eq :pcase--fail (car matches)) (pcase--u rest))
722 ((eq :pcase--succeed (car matches))
723 (pcase--u1 (cdr matches) code vars rest))
724 ((eq 'and (caar matches))
725 (pcase--u1 (append (cdar matches) (cdr matches)) code vars rest))
726 ((eq 'or (caar matches))
727 (let* ((alts (cdar matches))
728 (var (if (eq (caar alts) 'match) (cadr (car alts))))
729 (simples '()) (others '()) (memq-ok t))
730 (when var
731 (dolist (alt alts)
732 (if (and (eq (car alt) 'match) (eq var (cadr alt))
733 (let ((upat (cddr alt)))
734 (eq (car-safe upat) 'quote)))
735 (let ((val (cadr (cddr alt))))
736 (unless (or (integerp val) (symbolp val))
737 (setq memq-ok nil))
738 (push (cadr (cddr alt)) simples))
739 (push alt others))))
740 (cond
741 ((null alts) (error "Please avoid it") (pcase--u rest))
742 ;; Yes, we can use `memq' (or `member')!
743 ((> (length simples) 1)
744 (pcase--u1 (cons `(match ,var
745 . (pred (pcase--flip
746 ,(if memq-ok #'memq #'member)
747 ',simples)))
748 (cdr matches))
749 code vars
750 (if (null others) rest
751 (cons (cons
752 (pcase--and (if (cdr others)
753 (cons 'or (nreverse others))
754 (car others))
755 (cdr matches))
756 (cons code vars))
757 rest))))
759 (pcase--u1 (cons (pop alts) (cdr matches)) code vars
760 (if (null alts) (progn (error "Please avoid it") rest)
761 (cons (cons
762 (pcase--and (if (cdr alts)
763 (cons 'or alts) (car alts))
764 (cdr matches))
765 (cons code vars))
766 rest)))))))
767 ((eq 'match (caar matches))
768 (let* ((popmatches (pop matches))
769 (_op (car popmatches)) (cdrpopmatches (cdr popmatches))
770 (sym (car cdrpopmatches))
771 (upat (cdr cdrpopmatches)))
772 (cond
773 ((memq upat '(t _)) (pcase--u1 matches code vars rest))
774 ((eq upat 'pcase--dontcare) :pcase--dontcare)
775 ((memq (car-safe upat) '(guard pred))
776 (if (eq (car upat) 'pred) (pcase--mark-used sym))
777 (let* ((splitrest
778 (pcase--split-rest
779 sym (lambda (pat) (pcase--split-pred vars upat pat)) rest))
780 (then-rest (car splitrest))
781 (else-rest (cdr splitrest)))
782 (pcase--if (if (eq (car upat) 'pred)
783 (pcase--funcall (cadr upat) sym vars)
784 (pcase--eval (cadr upat) vars))
785 (pcase--u1 matches code vars then-rest)
786 (pcase--u else-rest))))
787 ((symbolp upat)
788 (pcase--mark-used sym)
789 (if (not (assq upat vars))
790 (pcase--u1 matches code (cons (cons upat sym) vars) rest)
791 ;; Non-linear pattern. Turn it into an `eq' test.
792 (pcase--u1 (cons `(match ,sym . (pred (eq ,(cdr (assq upat vars)))))
793 matches)
794 code vars rest)))
795 ((eq (car-safe upat) 'let)
796 ;; A upat of the form (let VAR EXP).
797 ;; (pcase--u1 matches code
798 ;; (cons (cons (nth 1 upat) (nth 2 upat)) vars) rest)
799 (macroexp-let2
800 macroexp-copyable-p sym
801 (pcase--eval (nth 2 upat) vars)
802 (pcase--u1 (cons (pcase--match sym (nth 1 upat)) matches)
803 code vars rest)))
804 ((eq (car-safe upat) 'app)
805 ;; A upat of the form (app FUN PAT)
806 (pcase--mark-used sym)
807 (let* ((fun (nth 1 upat))
808 (nsym (make-symbol "x"))
809 (body
810 ;; We don't change `matches' to reuse the newly computed value,
811 ;; because we assume there shouldn't be such redundancy in there.
812 (pcase--u1 (cons (pcase--match nsym (nth 2 upat)) matches)
813 code vars
814 (pcase--app-subst-rest rest sym fun nsym))))
815 (if (not (get nsym 'pcase-used))
816 body
817 (macroexp-let*
818 `((,nsym ,(pcase--funcall fun sym vars)))
819 body))))
820 ((eq (car-safe upat) 'quote)
821 (pcase--mark-used sym)
822 (let* ((val (cadr upat))
823 (splitrest (pcase--split-rest
824 sym (lambda (pat) (pcase--split-equal val pat)) rest))
825 (then-rest (car splitrest))
826 (else-rest (cdr splitrest)))
827 (pcase--if (cond
828 ((null val) `(null ,sym))
829 ((or (integerp val) (symbolp val))
830 (if (pcase--self-quoting-p val)
831 `(eq ,sym ,val)
832 `(eq ,sym ',val)))
833 (t `(equal ,sym ',val)))
834 (pcase--u1 matches code vars then-rest)
835 (pcase--u else-rest))))
836 ((eq (car-safe upat) 'not)
837 ;; FIXME: The implementation below is naive and results in
838 ;; inefficient code.
839 ;; To make it work right, we would need to turn pcase--u1's
840 ;; `code' and `vars' into a single argument of the same form as
841 ;; `rest'. We would also need to split this new `then-rest' argument
842 ;; for every test (currently we don't bother to do it since
843 ;; it's only useful for odd patterns like (and `(PAT1 . PAT2)
844 ;; `(PAT3 . PAT4)) which the programmer can easily rewrite
845 ;; to the more efficient `(,(and PAT1 PAT3) . ,(and PAT2 PAT4))).
846 (pcase--u1 `((match ,sym . ,(cadr upat)))
847 ;; FIXME: This codegen is not careful to share its
848 ;; code if used several times: code blow up is likely.
849 (lambda (_vars)
850 ;; `vars' will likely contain bindings which are
851 ;; not always available in other paths to
852 ;; `rest', so there' no point trying to pass
853 ;; them down.
854 (pcase--u rest))
855 vars
856 (list `((and . ,matches) ,code . ,vars))))
857 (t (error "Unknown internal pattern `%S'" upat)))))
858 (t (error "Incorrect MATCH %S" (car matches)))))
860 (def-edebug-spec
861 pcase-QPAT
862 (&or ("," pcase-PAT)
863 (pcase-QPAT . pcase-QPAT)
864 (vector &rest pcase-QPAT)
865 sexp))
867 (pcase-defmacro \` (qpat)
868 "Backquote-style pcase patterns.
869 QPAT can take the following forms:
870 (QPAT1 . QPAT2) matches if QPAT1 matches the car and QPAT2 the cdr.
871 [QPAT1 QPAT2..QPATn] matches a vector of length n and QPAT1..QPATn match
872 its 0..(n-1)th elements, respectively.
873 ,PAT matches if the pattern PAT matches.
874 STRING matches if the object is `equal' to STRING.
875 ATOM matches if the object is `eq' to ATOM."
876 (declare (debug (pcase-QPAT)))
877 (cond
878 ((eq (car-safe qpat) '\,) (cadr qpat))
879 ((vectorp qpat)
880 `(and (pred vectorp)
881 (app length ,(length qpat))
882 ,@(let ((upats nil))
883 (dotimes (i (length qpat))
884 (push `(app (pcase--flip aref ,i) ,(list '\` (aref qpat i)))
885 upats))
886 (nreverse upats))))
887 ((consp qpat)
888 `(and (pred consp)
889 (app car ,(list '\` (car qpat)))
890 (app cdr ,(list '\` (cdr qpat)))))
891 ((or (stringp qpat) (integerp qpat) (symbolp qpat)) `',qpat)))
894 (provide 'pcase)
895 ;;; pcase.el ends here