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