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>
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/>.
25 ;; ML-style pattern matching.
26 ;; The entry points are autoloaded.
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
42 ;; - provide a way to fallthrough to subsequent cases (not sure what I meant by
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.
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 _ pcase--dontcare
))
72 ("or" &rest pcase-UPAT
)
73 ("and" &rest pcase-UPAT
)
76 ("let" pcase-UPAT form
)
79 ;; Punt on macros/special forms.
80 (functionp &rest form
)
87 (pcase-QPAT . pcase-QPAT
)
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:
97 SELFQUOTING matches itself. This includes keywords, numbers, and strings.
98 SYMBOL matches anything and binds it to SYMBOL.
99 (or UPAT...) matches if any of the patterns matches.
100 (and UPAT...) matches if all the patterns match.
101 `QPAT matches if the QPattern QPAT matches.
102 (pred PRED) matches if PRED applied to the object returns non-nil.
103 (guard BOOLEXP) matches if BOOLEXP evaluates to non-nil.
104 (let UPAT EXP) matches if EXP matches UPAT.
105 If a SYMBOL is used twice in the same pattern (i.e. the pattern is
106 \"non-linear\"), then the second occurrence is turned into an `eq'uality test.
108 QPatterns can take the following forms:
109 (QPAT1 . QPAT2) matches if QPAT1 matches the car and QPAT2 the cdr.
110 ,UPAT matches if the UPattern UPAT matches.
111 STRING matches if the object is `equal' to STRING.
112 ATOM matches if the object is `eq' to ATOM.
113 QPatterns for vectors are not implemented yet.
115 PRED can take the form
116 FUNCTION in which case it gets called with one argument.
117 (FUN ARG1 .. ARGN) in which case it gets called with an N+1'th argument
118 which is the value being matched.
119 A PRED of the form FUNCTION is equivalent to one of the form (FUNCTION).
120 PRED patterns can refer to variables bound earlier in the pattern.
121 E.g. you can match pairs where the cdr is larger than the car with a pattern
122 like `(,a . ,(pred (< a))) or, with more checks:
123 `(,(and a (pred numberp)) . ,(and (pred numberp) (pred (< a))))"
124 (declare (indent 1) (debug (form &rest
(pcase-UPAT body
))))
125 ;; We want to use a weak hash table as a cache, but the key will unavoidably
126 ;; be based on `exp' and `cases', yet `cases' is a fresh new list each time
127 ;; we're called so it'll be immediately GC'd. So we use (car cases) as key
128 ;; which does come straight from the source code and should hence not be GC'd
130 (let ((data (gethash (car cases
) pcase--memoize
)))
131 ;; data = (EXP CASES . EXPANSION)
132 (if (and (equal exp
(car data
)) (equal cases
(cadr data
)))
133 ;; We have the right expansion.
135 ;; (when (gethash (car cases) pcase--memoize-1)
136 ;; (message "pcase-memoize failed because of weak key!!"))
137 ;; (when (gethash (car cases) pcase--memoize-2)
138 ;; (message "pcase-memoize failed because of eq test on %S"
141 (message "pcase-memoize: equal first branch, yet different"))
142 (let ((expansion (pcase--expand exp cases
)))
143 (puthash (car cases
) `(,exp
,cases
,@expansion
) pcase--memoize
)
144 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-1)
145 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-2)
148 (defun pcase--let* (bindings body
)
150 ((null bindings
) (macroexp-progn body
))
151 ((pcase--trivial-upat-p (caar bindings
))
152 (macroexp-let* `(,(car bindings
)) (pcase--let* (cdr bindings
) body
)))
154 (let ((binding (pop bindings
)))
157 `((,(car binding
) ,(pcase--let* bindings body
))
158 ;; We can either signal an error here, or just use `pcase--dontcare'
159 ;; which generates more efficient code. In practice, if we use
160 ;; `pcase--dontcare' we will still often get an error and the few
161 ;; cases where we don't do not matter that much, so
162 ;; it's a better choice.
163 (pcase--dontcare nil
)))))))
166 (defmacro pcase-let
* (bindings &rest body
)
167 "Like `let*' but where you can use `pcase' patterns for bindings.
168 BODY should be an expression, and BINDINGS should be a list of bindings
169 of the form (UPAT EXP)."
171 (debug ((&rest
(pcase-UPAT &optional form
)) body
)))
172 (let ((cached (gethash bindings pcase--memoize
)))
173 ;; cached = (BODY . EXPANSION)
174 (if (equal (car cached
) body
)
176 (let ((expansion (pcase--let* bindings body
)))
177 (puthash bindings
(cons body expansion
) pcase--memoize
)
181 (defmacro pcase-let
(bindings &rest body
)
182 "Like `let' but where you can use `pcase' patterns for bindings.
183 BODY should be a list of expressions, and BINDINGS should be a list of bindings
184 of the form (UPAT EXP)."
185 (declare (indent 1) (debug pcase-let
*))
186 (if (null (cdr bindings
))
187 `(pcase-let* ,bindings
,@body
)
189 (dolist (binding (prog1 bindings
(setq bindings nil
)))
191 ((memq (car binding
) pcase--dontcare-upats
)
192 (push (cons (make-symbol "_") (cdr binding
)) bindings
))
193 ((pcase--trivial-upat-p (car binding
)) (push binding bindings
))
195 (let ((tmpvar (make-symbol (format "x%d" (length bindings
)))))
196 (push (cons tmpvar
(cdr binding
)) bindings
)
197 (push (list (car binding
) tmpvar
) matches
)))))
198 `(let ,(nreverse bindings
) (pcase-let* ,matches
,@body
)))))
200 (defmacro pcase-dolist
(spec &rest body
)
201 (declare (indent 1) (debug ((pcase-UPAT form
) body
)))
202 (if (pcase--trivial-upat-p (car spec
))
203 `(dolist ,spec
,@body
)
204 (let ((tmpvar (make-symbol "x")))
205 `(dolist (,tmpvar
,@(cdr spec
))
206 (pcase-let* ((,(car spec
) ,tmpvar
))
210 (defun pcase--trivial-upat-p (upat)
211 (and (symbolp upat
) (not (memq upat pcase--dontcare-upats
))))
213 (defun pcase--expand (exp cases
)
214 ;; (message "pid=%S (pcase--expand %S ...hash=%S)"
215 ;; (emacs-pid) exp (sxhash cases))
216 (macroexp-let2 macroexp-copyable-p val exp
221 (let ((prev (assq code seen
)))
223 (let ((res (pcase-codegen code vars
)))
224 (push (list code vars res
) seen
)
226 ;; Since we use a tree-based pattern matching
227 ;; technique, the leaves (the places that contain the
228 ;; code to run once a pattern is matched) can get
229 ;; copied a very large number of times, so to avoid
230 ;; code explosion, we need to keep track of how many
231 ;; times we've used each leaf and move it
232 ;; to a separate function if that number is too high.
234 ;; We've already used this branch. So it is shared.
235 (let* ((code (car prev
)) (cdrprev (cdr prev
))
236 (prevvars (car cdrprev
)) (cddrprev (cdr cdrprev
))
237 (res (car cddrprev
)))
238 (unless (symbolp res
)
239 ;; This is the first repeat, so we have to move
240 ;; the branch to a separate function.
242 (make-symbol (format "pcase-%d" (length defs
)))))
243 (push `(,bsym
(lambda ,(mapcar #'car prevvars
) ,@code
))
245 (setcar res
'funcall
)
246 (setcdr res
(cons bsym
(mapcar #'cdr prevvars
)))
247 (setcar (cddr prev
) bsym
)
249 (setq vars
(copy-sequence vars
))
250 (let ((args (mapcar (lambda (pa)
251 (let ((v (assq (car pa
) vars
)))
252 (setq vars
(delq v vars
))
255 ;; If some of `vars' were not found in `prevvars', that's
256 ;; OK it just means those vars aren't present in all
257 ;; branches, so they can be used within the pattern
258 ;; (e.g. by a `guard/let/pred') but not in the branch.
259 ;; FIXME: But if some of `prevvars' are not in `vars' we
260 ;; should remove them from `prevvars'!
261 `(funcall ,res
,@args
)))))))
265 (mapcar (lambda (case)
266 `((match ,val .
,(car case
))
268 (unless (memq case used-cases
)
269 ;; Keep track of the cases that are used.
270 (push case used-cases
))
272 (if (pcase--small-branch-p (cdr case
))
273 ;; Don't bother sharing multiple
274 ;; occurrences of this leaf since it's small.
275 #'pcase-codegen codegen
)
280 (unless (or (memq case used-cases
) (eq (car case
) 'pcase--dontcare
))
281 (message "Redundant pcase pattern: %S" (car case
))))
282 (macroexp-let* defs main
))))
284 (defun pcase-codegen (code vars
)
285 ;; Don't use let*, otherwise macroexp-let* may merge it with some surrounding
286 ;; let* which might prevent the setcar/setcdr in pcase--expand's fancy
287 ;; codegen from later metamorphosing this let into a funcall.
288 `(let ,(mapcar (lambda (b) (list (car b
) (cdr b
))) vars
)
291 (defun pcase--small-branch-p (code)
292 (and (= 1 (length code
))
293 (or (not (consp (car code
)))
295 (dolist (e (car code
))
296 (if (consp e
) (setq small nil
)))
299 ;; Try to use `cond' rather than a sequence of `if's, so as to reduce
300 ;; the depth of the generated tree.
301 (defun pcase--if (test then else
)
303 ((eq else
:pcase--dontcare
) then
)
304 ((eq then
:pcase--dontcare
) (debug) else
) ;Can/should this ever happen?
305 (t (macroexp-if test then else
))))
307 (defun pcase--upat (qpattern)
309 ((eq (car-safe qpattern
) '\
,) (cadr qpattern
))
310 (t (list '\
` qpattern
))))
313 ;; When we have patterns like `(PAT1 . PAT2), after performing the `consp'
314 ;; check, we want to turn all the similar patterns into ones of the form
315 ;; (and (match car PAT1) (match cdr PAT2)), so you naturally need conjunction.
316 ;; Earlier code hence used branches of the form (MATCHES . CODE) where
317 ;; MATCHES was a list (implicitly a conjunction) of (SYM . PAT).
318 ;; But if we have a pattern of the form (or `(PAT1 . PAT2) PAT3), there is
319 ;; no easy way to eliminate the `consp' check in such a representation.
320 ;; So we replaced the MATCHES by the MATCH below which can be made up
321 ;; of conjunctions and disjunctions, so if we know `foo' is a cons, we can
322 ;; turn (match foo . (or `(PAT1 . PAT2) PAT3)) into
323 ;; (or (and (match car . `PAT1) (match cdr . `PAT2)) (match foo . PAT3)).
324 ;; The downside is that we now have `or' and `and' both in MATCH and
325 ;; in PAT, so there are different equivalent representations and we
326 ;; need to handle them all. We do not try to systematically
327 ;; canonicalize them to one form over another, but we do occasionally
328 ;; turn one into the other.
330 (defun pcase--u (branches)
331 "Expand matcher for rules BRANCHES.
332 Each BRANCH has the form (MATCH CODE . VARS) where
333 CODE is the code generator for that branch.
334 VARS is the set of vars already bound by earlier matches.
335 MATCH is the pattern that needs to be matched, of the form:
339 (when (setq branches
(delq nil branches
))
340 (let* ((carbranch (car branches
))
341 (match (car carbranch
)) (cdarbranch (cdr carbranch
))
342 (code (car cdarbranch
))
343 (vars (cdr cdarbranch
)))
344 (pcase--u1 (list match
) code vars
(cdr branches
)))))
346 (defun pcase--and (match matches
)
347 (if matches
`(and ,match
,@matches
) match
))
349 (defconst pcase-mutually-exclusive-predicates
350 '((symbolp . integerp
)
355 (symbolp . byte-code-function-p
)
359 (integerp . byte-code-function-p
)
363 (numberp . byte-code-function-p
)
366 (consp . byte-code-function-p
)
368 (arrayp . byte-code-function-p
)
369 (stringp . byte-code-function-p
)))
371 (defun pcase--split-match (sym splitter match
)
373 ((eq (car match
) 'match
)
374 (if (not (eq sym
(cadr match
)))
376 (let ((pat (cddr match
)))
378 ;; Hoist `or' and `and' patterns to `or' and `and' matches.
379 ((memq (car-safe pat
) '(or and
))
380 (pcase--split-match sym splitter
382 (mapcar (lambda (alt)
383 `(match ,sym .
,alt
))
385 (t (let ((res (funcall splitter
(cddr match
))))
386 (cons (or (car res
) match
) (or (cdr res
) match
))))))))
387 ((memq (car match
) '(or and
))
388 (let ((then-alts '())
390 (neutral-elem (if (eq 'or
(car match
))
391 :pcase--fail
:pcase--succeed
))
392 (zero-elem (if (eq 'or
(car match
)) :pcase--succeed
:pcase--fail
)))
393 (dolist (alt (cdr match
))
394 (let ((split (pcase--split-match sym splitter alt
)))
395 (unless (eq (car split
) neutral-elem
)
396 (push (car split
) then-alts
))
397 (unless (eq (cdr split
) neutral-elem
)
398 (push (cdr split
) else-alts
))))
399 (cons (cond ((memq zero-elem then-alts
) zero-elem
)
400 ((null then-alts
) neutral-elem
)
401 ((null (cdr then-alts
)) (car then-alts
))
402 (t (cons (car match
) (nreverse then-alts
))))
403 (cond ((memq zero-elem else-alts
) zero-elem
)
404 ((null else-alts
) neutral-elem
)
405 ((null (cdr else-alts
)) (car else-alts
))
406 (t (cons (car match
) (nreverse else-alts
)))))))
407 (t (error "Uknown MATCH %s" match
))))
409 (defun pcase--split-rest (sym splitter rest
)
410 (let ((then-rest '())
412 (dolist (branch rest
)
413 (let* ((match (car branch
))
414 (code&vars
(cdr branch
))
416 (pcase--split-match sym splitter match
)))
417 (unless (eq (car split
) :pcase--fail
)
418 (push (cons (car split
) code
&vars
) then-rest
))
419 (unless (eq (cdr split
) :pcase--fail
)
420 (push (cons (cdr split
) code
&vars
) else-rest
))))
421 (cons (nreverse then-rest
) (nreverse else-rest
))))
423 (defun pcase--split-consp (syma symd pat
)
425 ;; A QPattern for a cons, can only go the `then' side.
426 ((and (eq (car-safe pat
) '\
`) (consp (cadr pat
)))
427 (let ((qpat (cadr pat
)))
428 (cons `(and (match ,syma .
,(pcase--upat (car qpat
)))
429 (match ,symd .
,(pcase--upat (cdr qpat
))))
431 ;; A QPattern but not for a cons, can only go to the `else' side.
432 ((eq (car-safe pat
) '\
`) (cons :pcase--fail nil
))
433 ((and (eq (car-safe pat
) 'pred
)
434 (or (member (cons 'consp
(cadr pat
))
435 pcase-mutually-exclusive-predicates
)
436 (member (cons (cadr pat
) 'consp
)
437 pcase-mutually-exclusive-predicates
)))
438 (cons :pcase--fail nil
))))
440 (defun pcase--split-equal (elem pat
)
442 ;; The same match will give the same result.
443 ((and (eq (car-safe pat
) '\
`) (equal (cadr pat
) elem
))
444 (cons :pcase--succeed
:pcase--fail
))
445 ;; A different match will fail if this one succeeds.
446 ((and (eq (car-safe pat
) '\
`)
447 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
448 ;; (consp (cadr pat)))
450 (cons :pcase--fail nil
))
451 ((and (eq (car-safe pat
) 'pred
)
453 (get (cadr pat
) 'side-effect-free
)
454 (funcall (cadr pat
) elem
))
455 (cons :pcase--succeed nil
))))
457 (defun pcase--split-member (elems pat
)
458 ;; Based on pcase--split-equal.
460 ;; The same match (or a match of membership in a superset) will
461 ;; give the same result, but we don't know how to check it.
463 ;; (cons :pcase--succeed nil))
464 ;; A match for one of the elements may succeed or fail.
465 ((and (eq (car-safe pat
) '\
`) (member (cadr pat
) elems
))
467 ;; A different match will fail if this one succeeds.
468 ((and (eq (car-safe pat
) '\
`)
469 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
470 ;; (consp (cadr pat)))
472 (cons :pcase--fail nil
))
473 ((and (eq (car-safe pat
) 'pred
)
475 (get (cadr pat
) 'side-effect-free
)
476 (let ((p (cadr pat
)) (all t
))
478 (unless (funcall p elem
) (setq all nil
)))
480 (cons :pcase--succeed nil
))))
482 (defun pcase--split-pred (upat pat
)
483 ;; FIXME: For predicates like (pred (> a)), two such predicates may
484 ;; actually refer to different variables `a'.
487 ((equal upat pat
) (cons :pcase--succeed
:pcase--fail
))
488 ((and (eq 'pred
(car upat
))
489 (eq 'pred
(car-safe pat
))
490 (or (member (cons (cadr upat
) (cadr pat
))
491 pcase-mutually-exclusive-predicates
)
492 (member (cons (cadr pat
) (cadr upat
))
493 pcase-mutually-exclusive-predicates
)))
494 (cons :pcase--fail nil
))
495 ((and (eq 'pred
(car upat
))
496 (eq '\
` (car-safe pat
))
497 (symbolp (cadr upat
))
498 (or (symbolp (cadr pat
)) (stringp (cadr pat
)) (numberp (cadr pat
)))
499 (get (cadr upat
) 'side-effect-free
)
501 (setq test
(list (funcall (cadr upat
) (cadr pat
))))))
503 (cons nil
:pcase--fail
)
504 (cons :pcase--fail nil
))))))
506 (defun pcase--fgrep (vars sexp
)
507 "Check which of the symbols VARS appear in SEXP."
510 (dolist (var (pcase--fgrep vars
(pop sexp
)))
511 (unless (memq var res
) (push var res
))))
512 (and (memq sexp vars
) (not (memq sexp res
)) (push sexp res
))
515 (defun pcase--self-quoting-p (upat)
516 (or (keywordp upat
) (numberp upat
) (stringp upat
)))
518 ;; It's very tempting to use `pcase' below, tho obviously, it'd create
519 ;; bootstrapping problems.
520 (defun pcase--u1 (matches code vars rest
)
521 "Return code that runs CODE (with VARS) if MATCHES match.
522 Otherwise, it defers to REST which is a list of branches of the form
523 \(ELSE-MATCH ELSE-CODE . ELSE-VARS)."
524 ;; Depending on the order in which we choose to check each of the MATCHES,
525 ;; the resulting tree may be smaller or bigger. So in general, we'd want
526 ;; to be careful to chose the "optimal" order. But predicate
527 ;; patterns make this harder because they create dependencies
528 ;; between matches. So we don't bother trying to reorder anything.
530 ((null matches
) (funcall code vars
))
531 ((eq :pcase--fail
(car matches
)) (pcase--u rest
))
532 ((eq :pcase--succeed
(car matches
))
533 (pcase--u1 (cdr matches
) code vars rest
))
534 ((eq 'and
(caar matches
))
535 (pcase--u1 (append (cdar matches
) (cdr matches
)) code vars rest
))
536 ((eq 'or
(caar matches
))
537 (let* ((alts (cdar matches
))
538 (var (if (eq (caar alts
) 'match
) (cadr (car alts
))))
539 (simples '()) (others '()))
542 (if (and (eq (car alt
) 'match
) (eq var
(cadr alt
))
543 (let ((upat (cddr alt
)))
544 (and (eq (car-safe upat
) '\
`)
545 (or (integerp (cadr upat
)) (symbolp (cadr upat
))
546 (stringp (cadr upat
))))))
547 (push (cddr alt
) simples
)
550 ((null alts
) (error "Please avoid it") (pcase--u rest
))
551 ((> (length simples
) 1)
552 ;; De-hoist the `or' MATCH into an `or' pattern that will be
553 ;; turned into a `memq' below.
554 (pcase--u1 (cons `(match ,var or .
,(nreverse simples
)) (cdr matches
))
556 (if (null others
) rest
558 (pcase--and (if (cdr others
)
559 (cons 'or
(nreverse others
))
565 (pcase--u1 (cons (pop alts
) (cdr matches
)) code vars
566 (if (null alts
) (progn (error "Please avoid it") rest
)
568 (pcase--and (if (cdr alts
)
569 (cons 'or alts
) (car alts
))
573 ((eq 'match
(caar matches
))
574 (let* ((popmatches (pop matches
))
575 (_op (car popmatches
)) (cdrpopmatches (cdr popmatches
))
576 (sym (car cdrpopmatches
))
577 (upat (cdr cdrpopmatches
)))
579 ((memq upat
'(t _
)) (pcase--u1 matches code vars rest
))
580 ((eq upat
'pcase--dontcare
) :pcase--dontcare
)
581 ((memq (car-safe upat
) '(guard pred
))
582 (if (eq (car upat
) 'pred
) (put sym
'pcase-used t
))
585 sym
(lambda (pat) (pcase--split-pred upat pat
)) rest
))
586 (then-rest (car splitrest
))
587 (else-rest (cdr splitrest
)))
588 (pcase--if (if (and (eq (car upat
) 'pred
) (symbolp (cadr upat
)))
590 (let* ((exp (cadr upat
))
591 ;; `vs' is an upper bound on the vars we need.
592 (vs (pcase--fgrep (mapcar #'car vars
) exp
))
593 (env (mapcar (lambda (var)
594 (list var
(cdr (assq var vars
))))
596 (call (if (eq 'guard
(car upat
))
599 ;; `sym' is shadowed by `env'.
600 (let ((newsym (make-symbol "x")))
601 (push (list newsym sym
) env
)
604 `(funcall #',exp
,sym
)
608 ;; Let's not replace `vars' in `exp' since it's
609 ;; too difficult to do it right, instead just
610 ;; let-bind `vars' around `exp'.
611 `(let* ,env
,call
))))
612 (pcase--u1 matches code vars then-rest
)
613 (pcase--u else-rest
))))
614 ((pcase--self-quoting-p upat
)
615 (put sym
'pcase-used t
)
616 (pcase--q1 sym upat matches code vars rest
))
618 (put sym
'pcase-used t
)
619 (if (not (assq upat vars
))
620 (pcase--u1 matches code
(cons (cons upat sym
) vars
) rest
)
621 ;; Non-linear pattern. Turn it into an `eq' test.
622 (pcase--u1 (cons `(match ,sym .
(pred (eq ,(cdr (assq upat vars
)))))
625 ((eq (car-safe upat
) 'let
)
626 ;; A upat of the form (let VAR EXP).
627 ;; (pcase--u1 matches code
628 ;; (cons (cons (nth 1 upat) (nth 2 upat)) vars) rest)
630 macroexp-copyable-p sym
631 (let* ((exp (nth 2 upat
))
632 (found (assq exp vars
)))
633 (if found
(cdr found
)
634 (let* ((vs (pcase--fgrep (mapcar #'car vars
) exp
))
635 (env (mapcar (lambda (v) (list v
(cdr (assq v vars
))))
637 (if env
(macroexp-let* env exp
) exp
))))
638 (pcase--u1 (cons `(match ,sym .
,(nth 1 upat
)) matches
)
640 ((eq (car-safe upat
) '\
`)
641 (put sym
'pcase-used t
)
642 (pcase--q1 sym
(cadr upat
) matches code vars rest
))
643 ((eq (car-safe upat
) 'or
)
644 (let ((all (> (length (cdr upat
)) 1))
647 (dolist (alt (cdr upat
))
648 (unless (or (pcase--self-quoting-p alt
)
649 (and (eq (car-safe alt
) '\
`)
650 (or (symbolp (cadr alt
)) (integerp (cadr alt
))
652 (stringp (cadr alt
)))))
655 ;; Use memq for (or `a `b `c `d) rather than a big tree.
656 (let* ((elems (mapcar (lambda (x) (if (consp x
) (cadr x
) x
))
660 sym
(lambda (pat) (pcase--split-member elems pat
)) rest
))
661 (then-rest (car splitrest
))
662 (else-rest (cdr splitrest
)))
663 (put sym
'pcase-used t
)
664 (pcase--if `(,(if memq-fine
#'memq
#'member
) ,sym
',elems
)
665 (pcase--u1 matches code vars then-rest
)
666 (pcase--u else-rest
)))
667 (pcase--u1 (cons `(match ,sym
,@(cadr upat
)) matches
) code vars
668 (append (mapcar (lambda (upat)
669 `((and (match ,sym .
,upat
) ,@matches
)
673 ((eq (car-safe upat
) 'and
)
674 (pcase--u1 (append (mapcar (lambda (upat) `(match ,sym
,@upat
))
678 ((eq (car-safe upat
) 'not
)
679 ;; FIXME: The implementation below is naive and results in
681 ;; To make it work right, we would need to turn pcase--u1's
682 ;; `code' and `vars' into a single argument of the same form as
683 ;; `rest'. We would also need to split this new `then-rest' argument
684 ;; for every test (currently we don't bother to do it since
685 ;; it's only useful for odd patterns like (and `(PAT1 . PAT2)
686 ;; `(PAT3 . PAT4)) which the programmer can easily rewrite
687 ;; to the more efficient `(,(and PAT1 PAT3) . ,(and PAT2 PAT4))).
688 (pcase--u1 `((match ,sym .
,(cadr upat
)))
689 ;; FIXME: This codegen is not careful to share its
690 ;; code if used several times: code blow up is likely.
692 ;; `vars' will likely contain bindings which are
693 ;; not always available in other paths to
694 ;; `rest', so there' no point trying to pass
698 (list `((and .
,matches
) ,code .
,vars
))))
699 (t (error "Unknown upattern `%s'" upat
)))))
700 (t (error "Incorrect MATCH %s" (car matches
)))))
702 (defun pcase--q1 (sym qpat matches code vars rest
)
703 "Return code that runs CODE if SYM matches QPAT and if MATCHES match.
704 Otherwise, it defers to REST which is a list of branches of the form
705 \(OTHER_MATCH OTHER-CODE . OTHER-VARS)."
707 ((eq (car-safe qpat
) '\
,) (error "Can't use `,UPATTERN"))
708 ((floatp qpat
) (error "Floating point patterns not supported"))
711 (error "Vector QPatterns not implemented yet"))
713 (let* ((syma (make-symbol "xcar"))
714 (symd (make-symbol "xcdr"))
715 (splitrest (pcase--split-rest
717 (lambda (pat) (pcase--split-consp syma symd pat
))
719 (then-rest (car splitrest
))
720 (else-rest (cdr splitrest
))
721 (then-body (pcase--u1 `((match ,syma .
,(pcase--upat (car qpat
)))
722 (match ,symd .
,(pcase--upat (cdr qpat
)))
724 code vars then-rest
)))
727 ;; We want to be careful to only add bindings that are used.
728 ;; The byte-compiler could do that for us, but it would have to pay
729 ;; attention to the `consp' test in order to figure out that car/cdr
730 ;; can't signal errors and our byte-compiler is not that clever.
731 ;; FIXME: Some of those let bindings occur too early (they are used in
732 ;; `then-body', but only within some sub-branch).
734 `(,@(if (get syma
'pcase-used
) `((,syma
(car ,sym
))))
735 ,@(if (get symd
'pcase-used
) `((,symd
(cdr ,sym
)))))
737 (pcase--u else-rest
))))
738 ((or (integerp qpat
) (symbolp qpat
) (stringp qpat
))
739 (let* ((splitrest (pcase--split-rest
740 sym
(lambda (pat) (pcase--split-equal qpat pat
)) rest
))
741 (then-rest (car splitrest
))
742 (else-rest (cdr splitrest
)))
744 ((stringp qpat
) `(equal ,sym
,qpat
))
745 ((null qpat
) `(null ,sym
))
746 (t `(eq ,sym
',qpat
)))
747 (pcase--u1 matches code vars then-rest
)
748 (pcase--u else-rest
))))
749 (t (error "Unknown QPattern %s" qpat
))))
753 ;;; pcase.el ends here