merge from trunk, fix conflicts
[emacs.git] / lisp / emacs-lisp / pcase.el
blob0b46eb2a3019e4b18224d84bca266f97c105d98a
1 ;;; pcase.el --- ML-style pattern-matching macro for Elisp
3 ;; Copyright (C) 2010 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 ;;; Code:
30 (eval-when-compile (require 'cl))
32 ;; Macro-expansion of pcase is reasonably fast, so it's not a problem
33 ;; when byte-compiling a file, but when interpreting the code, if the pcase
34 ;; is in a loop, the repeated macro-expansion becomes terribly costly, so we
35 ;; memoize previous macro expansions to try and avoid recomputing them
36 ;; over and over again.
37 (defconst pcase-memoize (make-hash-table :weakness t :test 'equal))
39 ;;;###autoload
40 (defmacro pcase (exp &rest cases)
41 "Perform ML-style pattern matching on EXP.
42 CASES is a list of elements of the form (UPATTERN CODE...).
44 UPatterns can take the following forms:
45 _ matches anything.
46 SYMBOL matches anything and binds it to SYMBOL.
47 (or UPAT...) matches if any of the patterns matches.
48 (and UPAT...) matches if all the patterns match.
49 `QPAT matches if the QPattern QPAT matches.
50 (pred PRED) matches if PRED applied to the object returns non-nil.
52 QPatterns can take the following forms:
53 (QPAT1 . QPAT2) matches if QPAT1 matches the car and QPAT2 the cdr.
54 ,UPAT matches if the UPattern UPAT matches.
55 ATOM matches if the object is `eq' to ATOM.
56 QPatterns for vectors are not implemented yet.
58 PRED can take the form
59 FUNCTION in which case it gets called with one argument.
60 (FUN ARG1 .. ARGN) in which case it gets called with N+1 arguments.
61 A PRED of the form FUNCTION is equivalent to one of the form (FUNCTION).
62 PRED patterns can refer to variables bound earlier in the pattern.
63 E.g. you can match pairs where the cdr is larger than the car with a pattern
64 like `(,a . ,(pred (< a))) or, with more checks:
65 `(,(and a (pred numberp)) . ,(and (pred numberp) (pred (< a))))"
66 (declare (indent 1) (debug case))
67 (or (gethash (cons exp cases) pcase-memoize)
68 (puthash (cons exp cases)
69 (pcase-expand exp cases)
70 pcase-memoize)))
72 ;;;###autoload
73 (defmacro pcase-let* (bindings body)
74 "Like `let*' but where you can use `pcase' patterns for bindings.
75 BODY should be an expression, and BINDINGS should be a list of bindings
76 of the form (UPAT EXP)."
77 (if (null bindings) body
78 `(pcase ,(cadr (car bindings))
79 (,(caar bindings) (plet* ,(cdr bindings) ,body))
80 (t (error "Pattern match failure in `plet'")))))
82 ;;;###autoload
83 (defmacro pcase-let (bindings body)
84 "Like `let' but where you can use `pcase' patterns for bindings.
85 BODY should be an expression, and BINDINGS should be a list of bindings
86 of the form (UPAT EXP)."
87 (if (null (cdr bindings))
88 `(plet* ,bindings ,body)
89 (setq bindings (mapcar (lambda (x) (cons (make-symbol "x") x)) bindings))
90 `(let ,(mapcar (lambda (binding) (list (nth 0 binding) (nth 2 binding)))
91 bindings)
92 (plet* ,(mapcar (lambda (binding) (list (nth 1 binding) (nth 0 binding)))
93 bindings)
94 ,body))))
96 (defun pcase-expand (exp cases)
97 (let* ((defs (if (symbolp exp) '()
98 (let ((sym (make-symbol "x")))
99 (prog1 `((,sym ,exp)) (setq exp sym)))))
100 (seen '())
101 (codegen
102 (lambda (code vars)
103 (let ((prev (assq code seen)))
104 (if (not prev)
105 (let ((res (pcase-codegen code vars)))
106 (push (list code vars res) seen)
107 res)
108 ;; Since we use a tree-based pattern matching
109 ;; technique, the leaves (the places that contain the
110 ;; code to run once a pattern is matched) can get
111 ;; copied a very large number of times, so to avoid
112 ;; code explosion, we need to keep track of how many
113 ;; times we've used each leaf and move it
114 ;; to a separate function if that number is too high.
116 ;; We've already used this branch. So it is shared.
117 (destructuring-bind (code prevvars res) prev
118 (unless (symbolp res)
119 ;; This is the first repeat, so we have to move
120 ;; the branch to a separate function.
121 (let ((bsym
122 (make-symbol (format "pcase-%d" (length defs)))))
123 (push `(,bsym (lambda ,(mapcar #'car prevvars) ,@code)) defs)
124 (setcar res 'funcall)
125 (setcdr res (cons bsym (mapcar #'cdr prevvars)))
126 (setcar (cddr prev) bsym)
127 (setq res bsym)))
128 (setq vars (copy-sequence vars))
129 (let ((args (mapcar (lambda (pa)
130 (let ((v (assq (car pa) vars)))
131 (setq vars (delq v vars))
132 (cdr v)))
133 prevvars)))
134 (when vars ;New additional vars.
135 (error "The vars %s are only bound in some paths"
136 (mapcar #'car vars)))
137 `(funcall ,res ,@args)))))))
138 (main
139 (pcase-u
140 (mapcar (lambda (case)
141 `((match ,exp . ,(car case))
142 ,(apply-partially
143 (if (pcase-small-branch-p (cdr case))
144 ;; Don't bother sharing multiple
145 ;; occurrences of this leaf since it's small.
146 #'pcase-codegen codegen)
147 (cdr case))))
148 cases))))
149 `(let ,defs ,main)))
151 (defun pcase-codegen (code vars)
152 `(let ,(mapcar (lambda (b) (list (car b) (cdr b))) vars)
153 ,@code))
155 (defun pcase-small-branch-p (code)
156 (and (= 1 (length code))
157 (or (not (consp (car code)))
158 (let ((small t))
159 (dolist (e (car code))
160 (if (consp e) (setq small nil)))
161 small))))
163 ;; Try to use `cond' rather than a sequence of `if's, so as to reduce
164 ;; the depth of the generated tree.
165 (defun pcase-if (test then else)
166 (cond
167 ((eq else :pcase-dontcare) then)
168 ((eq (car-safe else) 'if)
169 `(cond (,test ,then)
170 (,(nth 1 else) ,(nth 2 else))
171 (t ,@(nthcdr 3 else))))
172 ((eq (car-safe else) 'cond)
173 `(cond (,test ,then)
174 ,@(cdr else)))
175 (t `(if ,test ,then ,else))))
177 (defun pcase-upat (qpattern)
178 (cond
179 ((eq (car-safe qpattern) '\,) (cadr qpattern))
180 (t (list '\` qpattern))))
182 ;; Note about MATCH:
183 ;; When we have patterns like `(PAT1 . PAT2), after performing the `consp'
184 ;; check, we want to turn all the similar patterns into ones of the form
185 ;; (and (match car PAT1) (match cdr PAT2)), so you naturally need conjunction.
186 ;; Earlier code hence used branches of the form (MATCHES . CODE) where
187 ;; MATCHES was a list (implicitly a conjunction) of (SYM . PAT).
188 ;; But if we have a pattern of the form (or `(PAT1 . PAT2) PAT3), there is
189 ;; no easy way to eliminate the `consp' check in such a representation.
190 ;; So we replaced the MATCHES by the MATCH below which can be made up
191 ;; of conjunctions and disjunctions, so if we know `foo' is a cons, we can
192 ;; turn (match foo . (or `(PAT1 . PAT2) PAT3)) into
193 ;; (or (and (match car . `PAT1) (match cdr . `PAT2)) (match foo . PAT3)).
194 ;; The downside is that we now have `or' and `and' both in MATCH and
195 ;; in PAT, so there are different equivalent representations and we
196 ;; need to handle them all. We do not try to systematically
197 ;; canonicalize them to one form over another, but we do occasionally
198 ;; turn one into the other.
200 (defun pcase-u (branches)
201 "Expand matcher for rules BRANCHES.
202 Each BRANCH has the form (MATCH CODE . VARS) where
203 CODE is the code generator for that branch.
204 VARS is the set of vars already bound by earlier matches.
205 MATCH is the pattern that needs to be matched, of the form:
206 (match VAR . UPAT)
207 (and MATCH ...)
208 (or MATCH ...)"
209 (when (setq branches (delq nil branches))
210 (destructuring-bind (match code &rest vars) (car branches)
211 (pcase-u1 (list match) code vars (cdr branches)))))
213 (defun pcase-and (match matches)
214 (if matches `(and ,match ,@matches) match))
216 (defun pcase-split-match (sym splitter match)
217 (case (car match)
218 ((match)
219 (if (not (eq sym (cadr match)))
220 (cons match match)
221 (let ((pat (cddr match)))
222 (cond
223 ;; Hoist `or' and `and' patterns to `or' and `and' matches.
224 ((memq (car-safe pat) '(or and))
225 (pcase-split-match sym splitter
226 (cons (car pat)
227 (mapcar (lambda (alt)
228 `(match ,sym . ,alt))
229 (cdr pat)))))
230 (t (let ((res (funcall splitter (cddr match))))
231 (cons (or (car res) match) (or (cdr res) match))))))))
232 ((or and)
233 (let ((then-alts '())
234 (else-alts '())
235 (neutral-elem (if (eq 'or (car match)) :pcase-fail :pcase-succeed))
236 (zero-elem (if (eq 'or (car match)) :pcase-succeed :pcase-fail)))
237 (dolist (alt (cdr match))
238 (let ((split (pcase-split-match sym splitter alt)))
239 (unless (eq (car split) neutral-elem)
240 (push (car split) then-alts))
241 (unless (eq (cdr split) neutral-elem)
242 (push (cdr split) else-alts))))
243 (cons (cond ((memq zero-elem then-alts) zero-elem)
244 ((null then-alts) neutral-elem)
245 ((null (cdr then-alts)) (car then-alts))
246 (t (cons (car match) (nreverse then-alts))))
247 (cond ((memq zero-elem else-alts) zero-elem)
248 ((null else-alts) neutral-elem)
249 ((null (cdr else-alts)) (car else-alts))
250 (t (cons (car match) (nreverse else-alts)))))))
251 (t (error "Uknown MATCH %s" match))))
253 (defun pcase-split-rest (sym splitter rest)
254 (let ((then-rest '())
255 (else-rest '()))
256 (dolist (branch rest)
257 (let* ((match (car branch))
258 (code&vars (cdr branch))
259 (splitted
260 (pcase-split-match sym splitter match)))
261 (unless (eq (car splitted) :pcase-fail)
262 (push (cons (car splitted) code&vars) then-rest))
263 (unless (eq (cdr splitted) :pcase-fail)
264 (push (cons (cdr splitted) code&vars) else-rest))))
265 (cons (nreverse then-rest) (nreverse else-rest))))
267 (defun pcase-split-consp (syma symd pat)
268 (cond
269 ;; A QPattern for a cons, can only go the `then' side.
270 ((and (eq (car-safe pat) '\`) (consp (cadr pat)))
271 (let ((qpat (cadr pat)))
272 (cons `(and (match ,syma . ,(pcase-upat (car qpat)))
273 (match ,symd . ,(pcase-upat (cdr qpat))))
274 :pcase-fail)))
275 ;; A QPattern but not for a cons, can only go the `else' side.
276 ((eq (car-safe pat) '\`) (cons :pcase-fail nil))))
278 (defun pcase-split-eq (elem pat)
279 (cond
280 ;; The same match will give the same result.
281 ((and (eq (car-safe pat) '\`) (equal (cadr pat) elem))
282 (cons :pcase-succeed :pcase-fail))
283 ;; A different match will fail if this one succeeds.
284 ((and (eq (car-safe pat) '\`)
285 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
286 ;; (consp (cadr pat)))
288 (cons :pcase-fail nil))))
290 (defun pcase-split-memq (elems pat)
291 ;; Based on pcase-split-eq.
292 (cond
293 ;; The same match will give the same result.
294 ((and (eq (car-safe pat) '\`) (member (cadr pat) elems))
295 (cons :pcase-succeed nil))
296 ;; A different match will fail if this one succeeds.
297 ((and (eq (car-safe pat) '\`)
298 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
299 ;; (consp (cadr pat)))
301 (cons :pcase-fail nil))))
303 (defun pcase-split-pred (upat pat)
304 ;; FIXME: For predicates like (pred (> a)), two such predicates may
305 ;; actually refer to different variables `a'.
306 (if (equal upat pat)
307 (cons :pcase-succeed :pcase-fail)))
309 (defun pcase-fgrep (vars sexp)
310 "Check which of the symbols VARS appear in SEXP."
311 (let ((res '()))
312 (while (consp sexp)
313 (dolist (var (pcase-fgrep vars (pop sexp)))
314 (unless (memq var res) (push var res))))
315 (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
316 res))
318 ;; It's very tempting to use `pcase' below, tho obviously, it'd create
319 ;; bootstrapping problems.
320 (defun pcase-u1 (matches code vars rest)
321 "Return code that runs CODE (with VARS) if MATCHES match.
322 and otherwise defers to REST which is a list of branches of the form
323 \(ELSE-MATCH ELSE-CODE . ELSE-VARS)."
324 ;; Depending on the order in which we choose to check each of the MATCHES,
325 ;; the resulting tree may be smaller or bigger. So in general, we'd want
326 ;; to be careful to chose the "optimal" order. But predicate
327 ;; patterns make this harder because they create dependencies
328 ;; between matches. So we don't bother trying to reorder anything.
329 (cond
330 ((null matches) (funcall code vars))
331 ((eq :pcase-fail (car matches)) (pcase-u rest))
332 ((eq :pcase-succeed (car matches))
333 (pcase-u1 (cdr matches) code vars rest))
334 ((eq 'and (caar matches))
335 (pcase-u1 (append (cdar matches) (cdr matches)) code vars rest))
336 ((eq 'or (caar matches))
337 (let* ((alts (cdar matches))
338 (var (if (eq (caar alts) 'match) (cadr (car alts))))
339 (simples '()) (others '()))
340 (when var
341 (dolist (alt alts)
342 (if (and (eq (car alt) 'match) (eq var (cadr alt))
343 (let ((upat (cddr alt)))
344 (and (eq (car-safe upat) '\`)
345 (or (integerp (cadr upat)) (symbolp (cadr upat))))))
346 (push (cddr alt) simples)
347 (push alt others))))
348 (cond
349 ((null alts) (error "Please avoid it") (pcase-u rest))
350 ((> (length simples) 1)
351 ;; De-hoist the `or' MATCH into an `or' pattern that will be
352 ;; turned into a `memq' below.
353 (pcase-u1 (cons `(match ,var or . ,(nreverse simples)) (cdr matches))
354 code vars
355 (if (null others) rest
356 (cons (list*
357 (pcase-and (if (cdr others)
358 (cons 'or (nreverse others))
359 (car others))
360 (cdr matches))
361 code vars)
362 rest))))
364 (pcase-u1 (cons (pop alts) (cdr matches)) code vars
365 (if (null alts) (progn (error "Please avoid it") rest)
366 (cons (list*
367 (pcase-and (if (cdr alts)
368 (cons 'or alts) (car alts))
369 (cdr matches))
370 code vars)
371 rest)))))))
372 ((eq 'match (caar matches))
373 (destructuring-bind (op sym &rest upat) (pop matches)
374 (cond
375 ((memq upat '(t _)) (pcase-u1 matches code vars rest))
376 ((eq upat 'dontcare) :pcase-dontcare)
377 ((functionp upat) (error "Feature removed, use (pred %s)" upat))
378 ((eq (car-safe upat) 'pred)
379 (destructuring-bind (then-rest &rest else-rest)
380 (pcase-split-rest
381 sym (apply-partially 'pcase-split-pred upat) rest)
382 (pcase-if (if (symbolp (cadr upat))
383 `(,(cadr upat) ,sym)
384 (let* ((exp (cadr upat))
385 ;; `vs' is an upper bound on the vars we need.
386 (vs (pcase-fgrep (mapcar #'car vars) exp)))
387 (if vs
388 ;; Let's not replace `vars' in `exp' since it's
389 ;; too difficult to do it right, instead just
390 ;; let-bind `vars' around `exp'.
391 `(let ,(mapcar (lambda (var)
392 (list var (cdr (assq var vars))))
394 ;; FIXME: `vars' can capture `sym'. E.g.
395 ;; (pcase x ((and `(,x . ,y) (pred (fun x)))))
396 (,@exp ,sym))
397 `(,@exp ,sym))))
398 (pcase-u1 matches code vars then-rest)
399 (pcase-u else-rest))))
400 ((symbolp upat)
401 (pcase-u1 matches code (cons (cons upat sym) vars) rest))
402 ((eq (car-safe upat) '\`)
403 (pcase-q1 sym (cadr upat) matches code vars rest))
404 ((eq (car-safe upat) 'or)
405 (let ((all (> (length (cdr upat)) 1)))
406 (when all
407 (dolist (alt (cdr upat))
408 (unless (and (eq (car-safe alt) '\`)
409 (or (symbolp (cadr alt)) (integerp (cadr alt))))
410 (setq all nil))))
411 (if all
412 ;; Use memq for (or `a `b `c `d) rather than a big tree.
413 (let ((elems (mapcar 'cadr (cdr upat))))
414 (destructuring-bind (then-rest &rest else-rest)
415 (pcase-split-rest
416 sym (apply-partially 'pcase-split-memq elems) rest)
417 (pcase-if `(memq ,sym ',elems)
418 (pcase-u1 matches code vars then-rest)
419 (pcase-u else-rest))))
420 (pcase-u1 (cons `(match ,sym ,@(cadr upat)) matches) code vars
421 (append (mapcar (lambda (upat)
422 `((and (match ,sym . ,upat) ,@matches)
423 ,code ,@vars))
424 (cddr upat))
425 rest)))))
426 ((eq (car-safe upat) 'and)
427 (pcase-u1 (append (mapcar (lambda (upat) `(match ,sym ,@upat)) (cdr upat))
428 matches)
429 code vars rest))
430 ((eq (car-safe upat) 'not)
431 ;; FIXME: The implementation below is naive and results in
432 ;; inefficient code.
433 ;; To make it work right, we would need to turn pcase-u1's
434 ;; `code' and `vars' into a single argument of the same form as
435 ;; `rest'. We would also need to split this new `then-rest' argument
436 ;; for every test (currently we don't bother to do it since
437 ;; it's only useful for odd patterns like (and `(PAT1 . PAT2)
438 ;; `(PAT3 . PAT4)) which the programmer can easily rewrite
439 ;; to the more efficient `(,(and PAT1 PAT3) . ,(and PAT2 PAT4))).
440 (pcase-u1 `((match ,sym . ,(cadr upat)))
441 (lexical-let ((rest rest))
442 ;; FIXME: This codegen is not careful to share its
443 ;; code if used several times: code blow up is likely.
444 (lambda (vars)
445 ;; `vars' will likely contain bindings which are
446 ;; not always available in other paths to
447 ;; `rest', so there' no point trying to pass
448 ;; them down.
449 (pcase-u rest)))
450 vars
451 (list `((and . ,matches) ,code . ,vars))))
452 (t (error "Unknown upattern `%s'" upat)))))
453 (t (error "Incorrect MATCH %s" (car matches)))))
455 (defun pcase-q1 (sym qpat matches code vars rest)
456 "Return code that runs CODE if SYM matches QPAT and if MATCHES match.
457 and if not, defers to REST which is a list of branches of the form
458 \(OTHER_MATCH OTHER-CODE . OTHER-VARS)."
459 (cond
460 ((eq (car-safe qpat) '\,) (error "Can't use `,UPATTERN"))
461 ((floatp qpat) (error "Floating point patterns not supported"))
462 ((vectorp qpat)
463 ;; FIXME.
464 (error "Vector QPatterns not implemented yet"))
465 ((consp qpat)
466 (let ((syma (make-symbol "xcar"))
467 (symd (make-symbol "xcdr")))
468 (destructuring-bind (then-rest &rest else-rest)
469 (pcase-split-rest sym (apply-partially 'pcase-split-consp syma symd)
470 rest)
471 (pcase-if `(consp ,sym)
472 `(let ((,syma (car ,sym))
473 (,symd (cdr ,sym)))
474 ,(pcase-u1 `((match ,syma . ,(pcase-upat (car qpat)))
475 (match ,symd . ,(pcase-upat (cdr qpat)))
476 ,@matches)
477 code vars then-rest))
478 (pcase-u else-rest)))))
479 ((or (integerp qpat) (symbolp qpat))
480 (destructuring-bind (then-rest &rest else-rest)
481 (pcase-split-rest sym (apply-partially 'pcase-split-eq qpat) rest)
482 (pcase-if `(eq ,sym ',qpat)
483 (pcase-u1 matches code vars then-rest)
484 (pcase-u else-rest))))
485 (t (error "Unkown QPattern %s" qpat))))
488 (provide 'pcase)
489 ;;; pcase.el ends here