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