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