In special-display-p signal an error if BUFFER-NAME is not a string (Bug#11713).
[emacs.git] / lisp / emacs-lisp / pcase.el
blob81cffae04bf6127691f06b19ad145e62eaad5f7c
1 ;;; pcase.el --- ML-style pattern-matching macro for Elisp -*- lexical-binding: t; coding: utf-8 -*-
3 ;; Copyright (C) 2010-2012 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords:
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; ML-style pattern matching.
26 ;; The entry points are autoloaded.
28 ;; Todo:
30 ;; - (pcase e (`(,x . ,x) foo)) signals an "x unused" warning if `foo' doesn't
31 ;; use x, because x is bound separately for the equality constraint
32 ;; (as well as any pred/guard) and for the body, so uses at one place don't
33 ;; count for the other.
34 ;; - provide ways to extend the set of primitives, with some kind of
35 ;; define-pcase-matcher. We could easily make it so that (guard BOOLEXP)
36 ;; could be defined this way, as a shorthand for (pred (lambda (_) BOOLEXP)).
37 ;; But better would be if we could define new ways to match by having the
38 ;; extension provide its own `pcase--split-<foo>' thingy.
39 ;; - along these lines, provide patterns to match CL structs.
40 ;; - provide something like (setq VAR) so a var can be set rather than
41 ;; let-bound.
42 ;; - provide a way to fallthrough to subsequent cases (not sure what I meant by
43 ;; this :-()
44 ;; - try and be more clever to reduce the size of the decision tree, and
45 ;; to reduce the number of leaves that need to be turned into function:
46 ;; - first, do the tests shared by all remaining branches (it will have
47 ;; to be performed anyway, so better do it first so it's shared).
48 ;; - then choose the test that discriminates more (?).
49 ;; - provide Agda's `with' (along with its `...' companion).
50 ;; - implement (not UPAT). This might require a significant redesign.
51 ;; - ideally we'd want (pcase s ((re RE1) E1) ((re RE2) E2)) to be able to
52 ;; generate a lex-style DFA to decide whether to run E1 or E2.
54 ;;; Code:
56 (require 'macroexp)
58 ;; Macro-expansion of pcase is reasonably fast, so it's not a problem
59 ;; when byte-compiling a file, but when interpreting the code, if the pcase
60 ;; is in a loop, the repeated macro-expansion becomes terribly costly, so we
61 ;; memoize previous macro expansions to try and avoid recomputing them
62 ;; over and over again.
63 (defconst pcase--memoize (make-hash-table :weakness 'key :test 'eq))
64 ;; (defconst pcase--memoize-1 (make-hash-table :test 'eq))
65 ;; (defconst pcase--memoize-2 (make-hash-table :weakness 'key :test 'equal))
67 (defconst pcase--dontcare-upats '(t _ dontcare))
69 (def-edebug-spec
70 pcase-UPAT
71 (&or symbolp
72 ("or" &rest pcase-UPAT)
73 ("and" &rest pcase-UPAT)
74 ("`" pcase-QPAT)
75 ("guard" form)
76 ("let" pcase-UPAT form)
77 ("pred"
78 &or lambda-expr
79 ;; Punt on macros/special forms.
80 (functionp &rest form)
81 sexp)
82 sexp))
84 (def-edebug-spec
85 pcase-QPAT
86 (&or ("," pcase-UPAT)
87 (pcase-QPAT . pcase-QPAT)
88 sexp))
90 ;;;###autoload
91 (defmacro pcase (exp &rest cases)
92 "Perform ML-style pattern matching on EXP.
93 CASES is a list of elements of the form (UPATTERN CODE...).
95 UPatterns can take the following forms:
96 _ matches anything.
97 SYMBOL matches anything and binds it to SYMBOL.
98 (or UPAT...) matches if any of the patterns matches.
99 (and UPAT...) matches if all the patterns match.
100 `QPAT matches if the QPattern QPAT matches.
101 (pred PRED) matches if PRED applied to the object returns non-nil.
102 (guard BOOLEXP) matches if BOOLEXP evaluates to non-nil.
103 (let UPAT EXP) matches if EXP matches UPAT.
104 If a SYMBOL is used twice in the same pattern (i.e. the pattern is
105 \"non-linear\"), then the second occurrence is turned into an `eq'uality test.
107 QPatterns can take the following forms:
108 (QPAT1 . QPAT2) matches if QPAT1 matches the car and QPAT2 the cdr.
109 ,UPAT matches if the UPattern UPAT matches.
110 STRING matches if the object is `equal' to STRING.
111 ATOM matches if the object is `eq' to ATOM.
112 QPatterns for vectors are not implemented yet.
114 PRED can take the form
115 FUNCTION in which case it gets called with one argument.
116 (FUN ARG1 .. ARGN) in which case it gets called with N+1 arguments.
117 A PRED of the form FUNCTION is equivalent to one of the form (FUNCTION).
118 PRED patterns can refer to variables bound earlier in the pattern.
119 E.g. you can match pairs where the cdr is larger than the car with a pattern
120 like `(,a . ,(pred (< a))) or, with more checks:
121 `(,(and a (pred numberp)) . ,(and (pred numberp) (pred (< a))))"
122 (declare (indent 1) (debug (form &rest (pcase-UPAT body))))
123 ;; We want to use a weak hash table as a cache, but the key will unavoidably
124 ;; be based on `exp' and `cases', yet `cases' is a fresh new list each time
125 ;; we're called so it'll be immediately GC'd. So we use (car cases) as key
126 ;; which does come straight from the source code and should hence not be GC'd
127 ;; so easily.
128 (let ((data (gethash (car cases) pcase--memoize)))
129 ;; data = (EXP CASES . EXPANSION)
130 (if (and (equal exp (car data)) (equal cases (cadr data)))
131 ;; We have the right expansion.
132 (cddr data)
133 ;; (when (gethash (car cases) pcase--memoize-1)
134 ;; (message "pcase-memoize failed because of weak key!!"))
135 ;; (when (gethash (car cases) pcase--memoize-2)
136 ;; (message "pcase-memoize failed because of eq test on %S"
137 ;; (car cases)))
138 (when data
139 (message "pcase-memoize: equal first branch, yet different"))
140 (let ((expansion (pcase--expand exp cases)))
141 (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize)
142 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-1)
143 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-2)
144 expansion))))
146 (defun pcase--let* (bindings body)
147 (cond
148 ((null bindings) (macroexp-progn body))
149 ((pcase--trivial-upat-p (caar bindings))
150 (macroexp-let* `(,(car bindings)) (pcase--let* (cdr bindings) body)))
152 (let ((binding (pop bindings)))
153 (pcase--expand
154 (cadr binding)
155 `((,(car binding) ,(pcase--let* bindings body))
156 ;; We can either signal an error here, or just use `dontcare' which
157 ;; generates more efficient code. In practice, if we use `dontcare'
158 ;; we will still often get an error and the few cases where we don't
159 ;; do not matter that much, so it's a better choice.
160 (dontcare nil)))))))
162 ;;;###autoload
163 (defmacro pcase-let* (bindings &rest body)
164 "Like `let*' but where you can use `pcase' patterns for bindings.
165 BODY should be an expression, and BINDINGS should be a list of bindings
166 of the form (UPAT EXP)."
167 (declare (indent 1)
168 (debug ((&rest (pcase-UPAT &optional form)) body)))
169 (let ((cached (gethash bindings pcase--memoize)))
170 ;; cached = (BODY . EXPANSION)
171 (if (equal (car cached) body)
172 (cdr cached)
173 (let ((expansion (pcase--let* bindings body)))
174 (puthash bindings (cons body expansion) pcase--memoize)
175 expansion))))
177 ;;;###autoload
178 (defmacro pcase-let (bindings &rest body)
179 "Like `let' but where you can use `pcase' patterns for bindings.
180 BODY should be a list of expressions, and BINDINGS should be a list of bindings
181 of the form (UPAT EXP)."
182 (declare (indent 1) (debug pcase-let*))
183 (if (null (cdr bindings))
184 `(pcase-let* ,bindings ,@body)
185 (let ((matches '()))
186 (dolist (binding (prog1 bindings (setq bindings nil)))
187 (cond
188 ((memq (car binding) pcase--dontcare-upats)
189 (push (cons (make-symbol "_") (cdr binding)) bindings))
190 ((pcase--trivial-upat-p (car binding)) (push binding bindings))
192 (let ((tmpvar (make-symbol (format "x%d" (length bindings)))))
193 (push (cons tmpvar (cdr binding)) bindings)
194 (push (list (car binding) tmpvar) matches)))))
195 `(let ,(nreverse bindings) (pcase-let* ,matches ,@body)))))
197 (defmacro pcase-dolist (spec &rest body)
198 (declare (indent 1) (debug ((pcase-UPAT form) body)))
199 (if (pcase--trivial-upat-p (car spec))
200 `(dolist ,spec ,@body)
201 (let ((tmpvar (make-symbol "x")))
202 `(dolist (,tmpvar ,@(cdr spec))
203 (pcase-let* ((,(car spec) ,tmpvar))
204 ,@body)))))
207 (defun pcase--trivial-upat-p (upat)
208 (and (symbolp upat) (not (memq upat pcase--dontcare-upats))))
210 (defun pcase--expand (exp cases)
211 ;; (message "pid=%S (pcase--expand %S ...hash=%S)"
212 ;; (emacs-pid) exp (sxhash cases))
213 (macroexp-let² macroexp-copyable-p val exp
214 (let* ((defs ())
215 (seen '())
216 (codegen
217 (lambda (code vars)
218 (let ((prev (assq code seen)))
219 (if (not prev)
220 (let ((res (pcase-codegen code vars)))
221 (push (list code vars res) seen)
222 res)
223 ;; Since we use a tree-based pattern matching
224 ;; technique, the leaves (the places that contain the
225 ;; code to run once a pattern is matched) can get
226 ;; copied a very large number of times, so to avoid
227 ;; code explosion, we need to keep track of how many
228 ;; times we've used each leaf and move it
229 ;; to a separate function if that number is too high.
231 ;; We've already used this branch. So it is shared.
232 (let* ((code (car prev)) (cdrprev (cdr prev))
233 (prevvars (car cdrprev)) (cddrprev (cdr cdrprev))
234 (res (car cddrprev)))
235 (unless (symbolp res)
236 ;; This is the first repeat, so we have to move
237 ;; the branch to a separate function.
238 (let ((bsym
239 (make-symbol (format "pcase-%d" (length defs)))))
240 (push `(,bsym (lambda ,(mapcar #'car prevvars) ,@code)) defs)
241 (setcar res 'funcall)
242 (setcdr res (cons bsym (mapcar #'cdr prevvars)))
243 (setcar (cddr prev) bsym)
244 (setq res bsym)))
245 (setq vars (copy-sequence vars))
246 (let ((args (mapcar (lambda (pa)
247 (let ((v (assq (car pa) vars)))
248 (setq vars (delq v vars))
249 (cdr v)))
250 prevvars)))
251 ;; If some of `vars' were not found in `prevvars', that's
252 ;; OK it just means those vars aren't present in all
253 ;; branches, so they can be used within the pattern
254 ;; (e.g. by a `guard/let/pred') but not in the branch.
255 ;; FIXME: But if some of `prevvars' are not in `vars' we
256 ;; should remove them from `prevvars'!
257 `(funcall ,res ,@args)))))))
258 (main
259 (pcase--u
260 (mapcar (lambda (case)
261 `((match ,val . ,(car case))
262 ,(apply-partially
263 (if (pcase--small-branch-p (cdr case))
264 ;; Don't bother sharing multiple
265 ;; occurrences of this leaf since it's small.
266 #'pcase-codegen codegen)
267 (cdr case))))
268 cases))))
269 (macroexp-let* defs main))))
271 (defun pcase-codegen (code vars)
272 ;; Don't use let*, otherwise macroexp-let* may merge it with some surrounding
273 ;; let* which might prevent the setcar/setcdr in pcase--expand's fancy
274 ;; codegen from later metamorphosing this let into a funcall.
275 `(let ,(mapcar (lambda (b) (list (car b) (cdr b))) vars)
276 ,@code))
278 (defun pcase--small-branch-p (code)
279 (and (= 1 (length code))
280 (or (not (consp (car code)))
281 (let ((small t))
282 (dolist (e (car code))
283 (if (consp e) (setq small nil)))
284 small))))
286 ;; Try to use `cond' rather than a sequence of `if's, so as to reduce
287 ;; the depth of the generated tree.
288 (defun pcase--if (test then else)
289 (cond
290 ((eq else :pcase--dontcare) then)
291 ((eq then :pcase--dontcare) (debug) else) ;Can/should this ever happen?
292 (t (macroexp-if test then else))))
294 (defun pcase--upat (qpattern)
295 (cond
296 ((eq (car-safe qpattern) '\,) (cadr qpattern))
297 (t (list '\` qpattern))))
299 ;; Note about MATCH:
300 ;; When we have patterns like `(PAT1 . PAT2), after performing the `consp'
301 ;; check, we want to turn all the similar patterns into ones of the form
302 ;; (and (match car PAT1) (match cdr PAT2)), so you naturally need conjunction.
303 ;; Earlier code hence used branches of the form (MATCHES . CODE) where
304 ;; MATCHES was a list (implicitly a conjunction) of (SYM . PAT).
305 ;; But if we have a pattern of the form (or `(PAT1 . PAT2) PAT3), there is
306 ;; no easy way to eliminate the `consp' check in such a representation.
307 ;; So we replaced the MATCHES by the MATCH below which can be made up
308 ;; of conjunctions and disjunctions, so if we know `foo' is a cons, we can
309 ;; turn (match foo . (or `(PAT1 . PAT2) PAT3)) into
310 ;; (or (and (match car . `PAT1) (match cdr . `PAT2)) (match foo . PAT3)).
311 ;; The downside is that we now have `or' and `and' both in MATCH and
312 ;; in PAT, so there are different equivalent representations and we
313 ;; need to handle them all. We do not try to systematically
314 ;; canonicalize them to one form over another, but we do occasionally
315 ;; turn one into the other.
317 (defun pcase--u (branches)
318 "Expand matcher for rules BRANCHES.
319 Each BRANCH has the form (MATCH CODE . VARS) where
320 CODE is the code generator for that branch.
321 VARS is the set of vars already bound by earlier matches.
322 MATCH is the pattern that needs to be matched, of the form:
323 (match VAR . UPAT)
324 (and MATCH ...)
325 (or MATCH ...)"
326 (when (setq branches (delq nil branches))
327 (let* ((carbranch (car branches))
328 (match (car carbranch)) (cdarbranch (cdr carbranch))
329 (code (car cdarbranch))
330 (vars (cdr cdarbranch)))
331 (pcase--u1 (list match) code vars (cdr branches)))))
333 (defun pcase--and (match matches)
334 (if matches `(and ,match ,@matches) match))
336 (defconst pcase-mutually-exclusive-predicates
337 '((symbolp . integerp)
338 (symbolp . numberp)
339 (symbolp . consp)
340 (symbolp . arrayp)
341 (symbolp . stringp)
342 (symbolp . byte-code-function-p)
343 (integerp . consp)
344 (integerp . arrayp)
345 (integerp . stringp)
346 (integerp . byte-code-function-p)
347 (numberp . consp)
348 (numberp . arrayp)
349 (numberp . stringp)
350 (numberp . byte-code-function-p)
351 (consp . arrayp)
352 (consp . stringp)
353 (consp . byte-code-function-p)
354 (arrayp . stringp)
355 (arrayp . byte-code-function-p)
356 (stringp . byte-code-function-p)))
358 (defun pcase--split-match (sym splitter match)
359 (cond
360 ((eq (car match) 'match)
361 (if (not (eq sym (cadr match)))
362 (cons match match)
363 (let ((pat (cddr match)))
364 (cond
365 ;; Hoist `or' and `and' patterns to `or' and `and' matches.
366 ((memq (car-safe pat) '(or and))
367 (pcase--split-match sym splitter
368 (cons (car pat)
369 (mapcar (lambda (alt)
370 `(match ,sym . ,alt))
371 (cdr pat)))))
372 (t (let ((res (funcall splitter (cddr match))))
373 (cons (or (car res) match) (or (cdr res) match))))))))
374 ((memq (car match) '(or and))
375 (let ((then-alts '())
376 (else-alts '())
377 (neutral-elem (if (eq 'or (car match))
378 :pcase--fail :pcase--succeed))
379 (zero-elem (if (eq 'or (car match)) :pcase--succeed :pcase--fail)))
380 (dolist (alt (cdr match))
381 (let ((split (pcase--split-match sym splitter alt)))
382 (unless (eq (car split) neutral-elem)
383 (push (car split) then-alts))
384 (unless (eq (cdr split) neutral-elem)
385 (push (cdr split) else-alts))))
386 (cons (cond ((memq zero-elem then-alts) zero-elem)
387 ((null then-alts) neutral-elem)
388 ((null (cdr then-alts)) (car then-alts))
389 (t (cons (car match) (nreverse then-alts))))
390 (cond ((memq zero-elem else-alts) zero-elem)
391 ((null else-alts) neutral-elem)
392 ((null (cdr else-alts)) (car else-alts))
393 (t (cons (car match) (nreverse else-alts)))))))
394 (t (error "Uknown MATCH %s" match))))
396 (defun pcase--split-rest (sym splitter rest)
397 (let ((then-rest '())
398 (else-rest '()))
399 (dolist (branch rest)
400 (let* ((match (car branch))
401 (code&vars (cdr branch))
402 (split
403 (pcase--split-match sym splitter match)))
404 (unless (eq (car split) :pcase--fail)
405 (push (cons (car split) code&vars) then-rest))
406 (unless (eq (cdr split) :pcase--fail)
407 (push (cons (cdr split) code&vars) else-rest))))
408 (cons (nreverse then-rest) (nreverse else-rest))))
410 (defun pcase--split-consp (syma symd pat)
411 (cond
412 ;; A QPattern for a cons, can only go the `then' side.
413 ((and (eq (car-safe pat) '\`) (consp (cadr pat)))
414 (let ((qpat (cadr pat)))
415 (cons `(and (match ,syma . ,(pcase--upat (car qpat)))
416 (match ,symd . ,(pcase--upat (cdr qpat))))
417 :pcase--fail)))
418 ;; A QPattern but not for a cons, can only go to the `else' side.
419 ((eq (car-safe pat) '\`) (cons :pcase--fail nil))
420 ((and (eq (car-safe pat) 'pred)
421 (or (member (cons 'consp (cadr pat))
422 pcase-mutually-exclusive-predicates)
423 (member (cons (cadr pat) 'consp)
424 pcase-mutually-exclusive-predicates)))
425 (cons :pcase--fail nil))))
427 (defun pcase--split-equal (elem pat)
428 (cond
429 ;; The same match will give the same result.
430 ((and (eq (car-safe pat) '\`) (equal (cadr pat) elem))
431 (cons :pcase--succeed :pcase--fail))
432 ;; A different match will fail if this one succeeds.
433 ((and (eq (car-safe pat) '\`)
434 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
435 ;; (consp (cadr pat)))
437 (cons :pcase--fail nil))
438 ((and (eq (car-safe pat) 'pred)
439 (symbolp (cadr pat))
440 (get (cadr pat) 'side-effect-free)
441 (funcall (cadr pat) elem))
442 (cons :pcase--succeed nil))))
444 (defun pcase--split-member (elems pat)
445 ;; Based on pcase--split-equal.
446 (cond
447 ;; The same match (or a match of membership in a superset) will
448 ;; give the same result, but we don't know how to check it.
449 ;; (???
450 ;; (cons :pcase--succeed nil))
451 ;; A match for one of the elements may succeed or fail.
452 ((and (eq (car-safe pat) '\`) (member (cadr pat) elems))
453 nil)
454 ;; A different match will fail if this one succeeds.
455 ((and (eq (car-safe pat) '\`)
456 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
457 ;; (consp (cadr pat)))
459 (cons :pcase--fail nil))
460 ((and (eq (car-safe pat) 'pred)
461 (symbolp (cadr pat))
462 (get (cadr pat) 'side-effect-free)
463 (let ((p (cadr pat)) (all t))
464 (dolist (elem elems)
465 (unless (funcall p elem) (setq all nil)))
466 all))
467 (cons :pcase--succeed nil))))
469 (defun pcase--split-pred (upat pat)
470 ;; FIXME: For predicates like (pred (> a)), two such predicates may
471 ;; actually refer to different variables `a'.
472 (let (test)
473 (cond
474 ((equal upat pat) (cons :pcase--succeed :pcase--fail))
475 ((and (eq 'pred (car upat))
476 (eq 'pred (car-safe pat))
477 (or (member (cons (cadr upat) (cadr pat))
478 pcase-mutually-exclusive-predicates)
479 (member (cons (cadr pat) (cadr upat))
480 pcase-mutually-exclusive-predicates)))
481 (cons :pcase--fail nil))
482 ((and (eq 'pred (car upat))
483 (eq '\` (car-safe pat))
484 (symbolp (cadr upat))
485 (or (symbolp (cadr pat)) (stringp (cadr pat)) (numberp (cadr pat)))
486 (get (cadr upat) 'side-effect-free)
487 (ignore-errors
488 (setq test (list (funcall (cadr upat) (cadr pat))))))
489 (if (car test)
490 (cons nil :pcase--fail)
491 (cons :pcase--fail nil))))))
493 (defun pcase--fgrep (vars sexp)
494 "Check which of the symbols VARS appear in SEXP."
495 (let ((res '()))
496 (while (consp sexp)
497 (dolist (var (pcase--fgrep vars (pop sexp)))
498 (unless (memq var res) (push var res))))
499 (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
500 res))
502 ;; It's very tempting to use `pcase' below, tho obviously, it'd create
503 ;; bootstrapping problems.
504 (defun pcase--u1 (matches code vars rest)
505 "Return code that runs CODE (with VARS) if MATCHES match.
506 Otherwise, it defers to REST which is a list of branches of the form
507 \(ELSE-MATCH ELSE-CODE . ELSE-VARS)."
508 ;; Depending on the order in which we choose to check each of the MATCHES,
509 ;; the resulting tree may be smaller or bigger. So in general, we'd want
510 ;; to be careful to chose the "optimal" order. But predicate
511 ;; patterns make this harder because they create dependencies
512 ;; between matches. So we don't bother trying to reorder anything.
513 (cond
514 ((null matches) (funcall code vars))
515 ((eq :pcase--fail (car matches)) (pcase--u rest))
516 ((eq :pcase--succeed (car matches))
517 (pcase--u1 (cdr matches) code vars rest))
518 ((eq 'and (caar matches))
519 (pcase--u1 (append (cdar matches) (cdr matches)) code vars rest))
520 ((eq 'or (caar matches))
521 (let* ((alts (cdar matches))
522 (var (if (eq (caar alts) 'match) (cadr (car alts))))
523 (simples '()) (others '()))
524 (when var
525 (dolist (alt alts)
526 (if (and (eq (car alt) 'match) (eq var (cadr alt))
527 (let ((upat (cddr alt)))
528 (and (eq (car-safe upat) '\`)
529 (or (integerp (cadr upat)) (symbolp (cadr upat))
530 (stringp (cadr upat))))))
531 (push (cddr alt) simples)
532 (push alt others))))
533 (cond
534 ((null alts) (error "Please avoid it") (pcase--u rest))
535 ((> (length simples) 1)
536 ;; De-hoist the `or' MATCH into an `or' pattern that will be
537 ;; turned into a `memq' below.
538 (pcase--u1 (cons `(match ,var or . ,(nreverse simples)) (cdr matches))
539 code vars
540 (if (null others) rest
541 (cons (cons
542 (pcase--and (if (cdr others)
543 (cons 'or (nreverse others))
544 (car others))
545 (cdr matches))
546 (cons code vars))
547 rest))))
549 (pcase--u1 (cons (pop alts) (cdr matches)) code vars
550 (if (null alts) (progn (error "Please avoid it") rest)
551 (cons (cons
552 (pcase--and (if (cdr alts)
553 (cons 'or alts) (car alts))
554 (cdr matches))
555 (cons code vars))
556 rest)))))))
557 ((eq 'match (caar matches))
558 (let* ((popmatches (pop matches))
559 (_op (car popmatches)) (cdrpopmatches (cdr popmatches))
560 (sym (car cdrpopmatches))
561 (upat (cdr cdrpopmatches)))
562 (cond
563 ((memq upat '(t _)) (pcase--u1 matches code vars rest))
564 ((eq upat 'dontcare) :pcase--dontcare)
565 ((memq (car-safe upat) '(guard pred))
566 (if (eq (car upat) 'pred) (put sym 'pcase-used t))
567 (let* ((splitrest
568 (pcase--split-rest
569 sym (apply-partially #'pcase--split-pred upat) rest))
570 (then-rest (car splitrest))
571 (else-rest (cdr splitrest)))
572 (pcase--if (if (and (eq (car upat) 'pred) (symbolp (cadr upat)))
573 `(,(cadr upat) ,sym)
574 (let* ((exp (cadr upat))
575 ;; `vs' is an upper bound on the vars we need.
576 (vs (pcase--fgrep (mapcar #'car vars) exp))
577 (env (mapcar (lambda (var)
578 (list var (cdr (assq var vars))))
579 vs))
580 (call (if (eq 'guard (car upat))
582 (when (memq sym vs)
583 ;; `sym' is shadowed by `env'.
584 (let ((newsym (make-symbol "x")))
585 (push (list newsym sym) env)
586 (setq sym newsym)))
587 (if (functionp exp)
588 `(funcall #',exp ,sym)
589 `(,@exp ,sym)))))
590 (if (null vs)
591 call
592 ;; Let's not replace `vars' in `exp' since it's
593 ;; too difficult to do it right, instead just
594 ;; let-bind `vars' around `exp'.
595 `(let* ,env ,call))))
596 (pcase--u1 matches code vars then-rest)
597 (pcase--u else-rest))))
598 ((symbolp upat)
599 (put sym 'pcase-used t)
600 (if (not (assq upat vars))
601 (pcase--u1 matches code (cons (cons upat sym) vars) rest)
602 ;; Non-linear pattern. Turn it into an `eq' test.
603 (pcase--u1 (cons `(match ,sym . (pred (eq ,(cdr (assq upat vars)))))
604 matches)
605 code vars rest)))
606 ((eq (car-safe upat) 'let)
607 ;; A upat of the form (let VAR EXP).
608 ;; (pcase--u1 matches code
609 ;; (cons (cons (nth 1 upat) (nth 2 upat)) vars) rest)
610 (macroexp-let²
611 macroexp-copyable-p sym
612 (let* ((exp (nth 2 upat))
613 (found (assq exp vars)))
614 (if found (cdr found)
615 (let* ((vs (pcase--fgrep (mapcar #'car vars) exp))
616 (env (mapcar (lambda (v) (list v (cdr (assq v vars))))
617 vs)))
618 (if env (macroexp-let* env exp) exp))))
619 (pcase--u1 (cons `(match ,sym . ,(nth 1 upat)) matches)
620 code vars rest)))
621 ((eq (car-safe upat) '\`)
622 (put sym 'pcase-used t)
623 (pcase--q1 sym (cadr upat) matches code vars rest))
624 ((eq (car-safe upat) 'or)
625 (let ((all (> (length (cdr upat)) 1))
626 (memq-fine t))
627 (when all
628 (dolist (alt (cdr upat))
629 (unless (and (eq (car-safe alt) '\`)
630 (or (symbolp (cadr alt)) (integerp (cadr alt))
631 (setq memq-fine nil)
632 (stringp (cadr alt))))
633 (setq all nil))))
634 (if all
635 ;; Use memq for (or `a `b `c `d) rather than a big tree.
636 (let* ((elems (mapcar 'cadr (cdr upat)))
637 (splitrest
638 (pcase--split-rest
639 sym (apply-partially #'pcase--split-member elems) rest))
640 (then-rest (car splitrest))
641 (else-rest (cdr splitrest)))
642 (put sym 'pcase-used t)
643 (pcase--if `(,(if memq-fine #'memq #'member) ,sym ',elems)
644 (pcase--u1 matches code vars then-rest)
645 (pcase--u else-rest)))
646 (pcase--u1 (cons `(match ,sym ,@(cadr upat)) matches) code vars
647 (append (mapcar (lambda (upat)
648 `((and (match ,sym . ,upat) ,@matches)
649 ,code ,@vars))
650 (cddr upat))
651 rest)))))
652 ((eq (car-safe upat) 'and)
653 (pcase--u1 (append (mapcar (lambda (upat) `(match ,sym ,@upat))
654 (cdr upat))
655 matches)
656 code vars rest))
657 ((eq (car-safe upat) 'not)
658 ;; FIXME: The implementation below is naive and results in
659 ;; inefficient code.
660 ;; To make it work right, we would need to turn pcase--u1's
661 ;; `code' and `vars' into a single argument of the same form as
662 ;; `rest'. We would also need to split this new `then-rest' argument
663 ;; for every test (currently we don't bother to do it since
664 ;; it's only useful for odd patterns like (and `(PAT1 . PAT2)
665 ;; `(PAT3 . PAT4)) which the programmer can easily rewrite
666 ;; to the more efficient `(,(and PAT1 PAT3) . ,(and PAT2 PAT4))).
667 (pcase--u1 `((match ,sym . ,(cadr upat)))
668 ;; FIXME: This codegen is not careful to share its
669 ;; code if used several times: code blow up is likely.
670 (lambda (_vars)
671 ;; `vars' will likely contain bindings which are
672 ;; not always available in other paths to
673 ;; `rest', so there' no point trying to pass
674 ;; them down.
675 (pcase--u rest))
676 vars
677 (list `((and . ,matches) ,code . ,vars))))
678 (t (error "Unknown upattern `%s'" upat)))))
679 (t (error "Incorrect MATCH %s" (car matches)))))
681 (defun pcase--q1 (sym qpat matches code vars rest)
682 "Return code that runs CODE if SYM matches QPAT and if MATCHES match.
683 Otherwise, it defers to REST which is a list of branches of the form
684 \(OTHER_MATCH OTHER-CODE . OTHER-VARS)."
685 (cond
686 ((eq (car-safe qpat) '\,) (error "Can't use `,UPATTERN"))
687 ((floatp qpat) (error "Floating point patterns not supported"))
688 ((vectorp qpat)
689 ;; FIXME.
690 (error "Vector QPatterns not implemented yet"))
691 ((consp qpat)
692 (let* ((syma (make-symbol "xcar"))
693 (symd (make-symbol "xcdr"))
694 (splitrest (pcase--split-rest
696 (apply-partially #'pcase--split-consp syma symd)
697 rest))
698 (then-rest (car splitrest))
699 (else-rest (cdr splitrest))
700 (then-body (pcase--u1 `((match ,syma . ,(pcase--upat (car qpat)))
701 (match ,symd . ,(pcase--upat (cdr qpat)))
702 ,@matches)
703 code vars then-rest)))
704 (pcase--if
705 `(consp ,sym)
706 ;; We want to be careful to only add bindings that are used.
707 ;; The byte-compiler could do that for us, but it would have to pay
708 ;; attention to the `consp' test in order to figure out that car/cdr
709 ;; can't signal errors and our byte-compiler is not that clever.
710 ;; FIXME: Some of those let bindings occur too early (they are used in
711 ;; `then-body', but only within some sub-branch).
712 (macroexp-let*
713 `(,@(if (get syma 'pcase-used) `((,syma (car ,sym))))
714 ,@(if (get symd 'pcase-used) `((,symd (cdr ,sym)))))
715 then-body)
716 (pcase--u else-rest))))
717 ((or (integerp qpat) (symbolp qpat) (stringp qpat))
718 (let* ((splitrest (pcase--split-rest
719 sym (apply-partially 'pcase--split-equal qpat) rest))
720 (then-rest (car splitrest))
721 (else-rest (cdr splitrest)))
722 (pcase--if (cond
723 ((stringp qpat) `(equal ,sym ,qpat))
724 ((null qpat) `(null ,sym))
725 (t `(eq ,sym ',qpat)))
726 (pcase--u1 matches code vars then-rest)
727 (pcase--u else-rest))))
728 (t (error "Unknown QPattern %s" qpat))))
731 (provide 'pcase)
732 ;;; pcase.el ends here