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