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