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