]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/pcase.el
Support debug declarations in pcase macros
[gnu-emacs] / lisp / emacs-lisp / pcase.el
1 ;;; pcase.el --- ML-style pattern-matching macro for Elisp -*- lexical-binding: t; coding: utf-8 -*-
2
3 ;; Copyright (C) 2010-2015 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 ;; FIXME: Now that macroexpansion is also performed when loading an interpreted
64 ;; file, this is not a real problem any more.
65 (defconst pcase--memoize (make-hash-table :weakness 'key :test 'eq))
66 ;; (defconst pcase--memoize-1 (make-hash-table :test 'eq))
67 ;; (defconst pcase--memoize-2 (make-hash-table :weakness 'key :test 'equal))
68
69 (defconst pcase--dontcare-upats '(t _ pcase--dontcare))
70
71 (defvar pcase--dontwarn-upats '(pcase--dontcare))
72
73 (def-edebug-spec
74 pcase-UPAT
75 (&or symbolp
76 ("or" &rest pcase-UPAT)
77 ("and" &rest pcase-UPAT)
78 ("guard" form)
79 ("let" pcase-UPAT form)
80 ("pred" pcase-FUN)
81 ("app" pcase-FUN pcase-UPAT)
82 pcase-MACRO
83 sexp))
84
85 (def-edebug-spec
86 pcase-FUN
87 (&or lambda-expr
88 ;; Punt on macros/special forms.
89 (functionp &rest form)
90 sexp))
91
92 (def-edebug-spec pcase-MACRO pcase--edebug-match-macro)
93
94 (defun pcase--edebug-match-macro (cursor)
95 (let (specs)
96 (mapatoms
97 (lambda (s)
98 (let ((m (get s 'pcase-macroexpander)))
99 (when (and m (get-edebug-spec m))
100 (push (cons (symbol-name s) (get-edebug-spec m))
101 specs)))))
102 (edebug-match cursor (cons '&or specs))))
103
104 ;;;###autoload
105 (defmacro pcase (exp &rest cases)
106 "Perform ML-style pattern matching on EXP.
107 CASES is a list of elements of the form (UPATTERN CODE...).
108
109 UPatterns can take the following forms:
110 _ matches anything.
111 SELFQUOTING matches itself. This includes keywords, numbers, and strings.
112 SYMBOL matches anything and binds it to SYMBOL.
113 (or UPAT...) matches if any of the patterns matches.
114 (and UPAT...) matches if all the patterns match.
115 'VAL matches if the object is `equal' to VAL
116 (pred FUN) matches if FUN applied to the object returns non-nil.
117 (guard BOOLEXP) matches if BOOLEXP evaluates to non-nil.
118 (let UPAT EXP) matches if EXP matches UPAT.
119 (app FUN UPAT) matches if FUN applied to the object matches UPAT.
120 If a SYMBOL is used twice in the same pattern (i.e. the pattern is
121 \"non-linear\"), then the second occurrence is turned into an `eq'uality test.
122
123 FUN can take the form
124 SYMBOL or (lambda ARGS BODY) in which case it's called with one argument.
125 (F ARG1 .. ARGn) in which case F gets called with an n+1'th argument
126 which is the value being matched.
127 So a FUN of the form SYMBOL is equivalent to one of the form (FUN).
128 FUN can refer to variables bound earlier in the pattern.
129 FUN is assumed to be pure, i.e. it can be dropped if its result is not used,
130 and two identical calls can be merged into one.
131 E.g. you can match pairs where the cdr is larger than the car with a pattern
132 like `(,a . ,(pred (< a))) or, with more checks:
133 `(,(and a (pred numberp)) . ,(and (pred numberp) (pred (< a))))
134
135 Additional patterns can be defined via `pcase-defmacro'.
136 Currently, the following patterns are provided this way:"
137 (declare (indent 1) (debug (form &rest (pcase-UPAT body))))
138 ;; We want to use a weak hash table as a cache, but the key will unavoidably
139 ;; be based on `exp' and `cases', yet `cases' is a fresh new list each time
140 ;; we're called so it'll be immediately GC'd. So we use (car cases) as key
141 ;; which does come straight from the source code and should hence not be GC'd
142 ;; so easily.
143 (let ((data (gethash (car cases) pcase--memoize)))
144 ;; data = (EXP CASES . EXPANSION)
145 (if (and (equal exp (car data)) (equal cases (cadr data)))
146 ;; We have the right expansion.
147 (cddr data)
148 ;; (when (gethash (car cases) pcase--memoize-1)
149 ;; (message "pcase-memoize failed because of weak key!!"))
150 ;; (when (gethash (car cases) pcase--memoize-2)
151 ;; (message "pcase-memoize failed because of eq test on %S"
152 ;; (car cases)))
153 (when data
154 (message "pcase-memoize: equal first branch, yet different"))
155 (let ((expansion (pcase--expand exp cases)))
156 (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize)
157 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-1)
158 ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-2)
159 expansion))))
160
161 ;; FIXME: Obviously, this will collide with nadvice's use of
162 ;; function-documentation if we happen to advise `pcase'.
163 (put 'pcase 'function-documentation '(pcase--make-docstring))
164 (defun pcase--make-docstring ()
165 (let* ((main (documentation (symbol-function 'pcase) 'raw))
166 (ud (help-split-fundoc main 'pcase)))
167 (with-temp-buffer
168 (insert (or (cdr ud) main))
169 (mapatoms
170 (lambda (symbol)
171 (let ((me (get symbol 'pcase-macroexpander)))
172 (when me
173 (insert "\n\n-- ")
174 (let* ((doc (documentation me 'raw)))
175 (setq doc (help-fns--signature symbol doc me
176 (indirect-function me)))
177 (insert "\n" (or doc "Not documented.")))))))
178 (let ((combined-doc (buffer-string)))
179 (if ud (help-add-fundoc-usage combined-doc (car ud)) combined-doc)))))
180
181 ;;;###autoload
182 (defmacro pcase-exhaustive (exp &rest cases)
183 "The exhaustive version of `pcase' (which see)."
184 (declare (indent 1) (debug pcase))
185 (let* ((x (make-symbol "x"))
186 (pcase--dontwarn-upats (cons x pcase--dontwarn-upats)))
187 (pcase--expand
188 ;; FIXME: Could we add the FILE:LINE data in the error message?
189 exp (append cases `((,x (error "No clause matching `%S'" ,x)))))))
190
191 ;;;###autoload
192 (defmacro pcase-lambda (lambda-list &rest body)
193 "Like `lambda' but allow each argument to be a UPattern.
194 I.e. accepts the usual &optional and &rest keywords, but every
195 formal argument can be any pattern accepted by `pcase' (a mere
196 variable name being but a special case of it)."
197 (declare (doc-string 2) (indent defun)
198 (debug ((&rest pcase-UPAT) body)))
199 (let* ((bindings ())
200 (parsed-body (macroexp-parse-body body))
201 (args (mapcar (lambda (pat)
202 (if (symbolp pat)
203 ;; Simple vars and &rest/&optional are just passed
204 ;; through unchanged.
205 pat
206 (let ((arg (make-symbol
207 (format "arg%s" (length bindings)))))
208 (push `(,pat ,arg) bindings)
209 arg)))
210 lambda-list)))
211 `(lambda ,args ,@(car parsed-body)
212 (pcase-let* ,(nreverse bindings) ,@(cdr parsed-body)))))
213
214 (defun pcase--let* (bindings body)
215 (cond
216 ((null bindings) (macroexp-progn body))
217 ((pcase--trivial-upat-p (caar bindings))
218 (macroexp-let* `(,(car bindings)) (pcase--let* (cdr bindings) body)))
219 (t
220 (let ((binding (pop bindings)))
221 (pcase--expand
222 (cadr binding)
223 `((,(car binding) ,(pcase--let* bindings body))
224 ;; We can either signal an error here, or just use `pcase--dontcare'
225 ;; which generates more efficient code. In practice, if we use
226 ;; `pcase--dontcare' we will still often get an error and the few
227 ;; cases where we don't do not matter that much, so
228 ;; it's a better choice.
229 (pcase--dontcare nil)))))))
230
231 ;;;###autoload
232 (defmacro pcase-let* (bindings &rest body)
233 "Like `let*' but where you can use `pcase' patterns for bindings.
234 BODY should be an expression, and BINDINGS should be a list of bindings
235 of the form (UPAT EXP)."
236 (declare (indent 1)
237 (debug ((&rest (pcase-UPAT &optional form)) body)))
238 (let ((cached (gethash bindings pcase--memoize)))
239 ;; cached = (BODY . EXPANSION)
240 (if (equal (car cached) body)
241 (cdr cached)
242 (let ((expansion (pcase--let* bindings body)))
243 (puthash bindings (cons body expansion) pcase--memoize)
244 expansion))))
245
246 ;;;###autoload
247 (defmacro pcase-let (bindings &rest body)
248 "Like `let' but where you can use `pcase' patterns for bindings.
249 BODY should be a list of expressions, and BINDINGS should be a list of bindings
250 of the form (UPAT EXP)."
251 (declare (indent 1) (debug pcase-let*))
252 (if (null (cdr bindings))
253 `(pcase-let* ,bindings ,@body)
254 (let ((matches '()))
255 (dolist (binding (prog1 bindings (setq bindings nil)))
256 (cond
257 ((memq (car binding) pcase--dontcare-upats)
258 (push (cons (make-symbol "_") (cdr binding)) bindings))
259 ((pcase--trivial-upat-p (car binding)) (push binding bindings))
260 (t
261 (let ((tmpvar (make-symbol (format "x%d" (length bindings)))))
262 (push (cons tmpvar (cdr binding)) bindings)
263 (push (list (car binding) tmpvar) matches)))))
264 `(let ,(nreverse bindings) (pcase-let* ,matches ,@body)))))
265
266 (defmacro pcase-dolist (spec &rest body)
267 (declare (indent 1) (debug ((pcase-UPAT form) body)))
268 (if (pcase--trivial-upat-p (car spec))
269 `(dolist ,spec ,@body)
270 (let ((tmpvar (make-symbol "x")))
271 `(dolist (,tmpvar ,@(cdr spec))
272 (pcase-let* ((,(car spec) ,tmpvar))
273 ,@body)))))
274
275
276 (defun pcase--trivial-upat-p (upat)
277 (and (symbolp upat) (not (memq upat pcase--dontcare-upats))))
278
279 (defun pcase--expand (exp cases)
280 ;; (message "pid=%S (pcase--expand %S ...hash=%S)"
281 ;; (emacs-pid) exp (sxhash cases))
282 (macroexp-let2 macroexp-copyable-p val exp
283 (let* ((defs ())
284 (seen '())
285 (codegen
286 (lambda (code vars)
287 (let ((prev (assq code seen)))
288 (if (not prev)
289 (let ((res (pcase-codegen code vars)))
290 (push (list code vars res) seen)
291 res)
292 ;; Since we use a tree-based pattern matching
293 ;; technique, the leaves (the places that contain the
294 ;; code to run once a pattern is matched) can get
295 ;; copied a very large number of times, so to avoid
296 ;; code explosion, we need to keep track of how many
297 ;; times we've used each leaf and move it
298 ;; to a separate function if that number is too high.
299 ;;
300 ;; We've already used this branch. So it is shared.
301 (let* ((code (car prev)) (cdrprev (cdr prev))
302 (prevvars (car cdrprev)) (cddrprev (cdr cdrprev))
303 (res (car cddrprev)))
304 (unless (symbolp res)
305 ;; This is the first repeat, so we have to move
306 ;; the branch to a separate function.
307 (let ((bsym
308 (make-symbol (format "pcase-%d" (length defs)))))
309 (push `(,bsym (lambda ,(mapcar #'car prevvars) ,@code))
310 defs)
311 (setcar res 'funcall)
312 (setcdr res (cons bsym (mapcar #'cdr prevvars)))
313 (setcar (cddr prev) bsym)
314 (setq res bsym)))
315 (setq vars (copy-sequence vars))
316 (let ((args (mapcar (lambda (pa)
317 (let ((v (assq (car pa) vars)))
318 (setq vars (delq v vars))
319 (cdr v)))
320 prevvars)))
321 ;; If some of `vars' were not found in `prevvars', that's
322 ;; OK it just means those vars aren't present in all
323 ;; branches, so they can be used within the pattern
324 ;; (e.g. by a `guard/let/pred') but not in the branch.
325 ;; FIXME: But if some of `prevvars' are not in `vars' we
326 ;; should remove them from `prevvars'!
327 `(funcall ,res ,@args)))))))
328 (used-cases ())
329 (main
330 (pcase--u
331 (mapcar (lambda (case)
332 `(,(pcase--match val (pcase--macroexpand (car case)))
333 ,(lambda (vars)
334 (unless (memq case used-cases)
335 ;; Keep track of the cases that are used.
336 (push case used-cases))
337 (funcall
338 (if (pcase--small-branch-p (cdr case))
339 ;; Don't bother sharing multiple
340 ;; occurrences of this leaf since it's small.
341 #'pcase-codegen codegen)
342 (cdr case)
343 vars))))
344 cases))))
345 (dolist (case cases)
346 (unless (or (memq case used-cases)
347 (memq (car case) pcase--dontwarn-upats))
348 (message "Redundant pcase pattern: %S" (car case))))
349 (macroexp-let* defs main))))
350
351 (defun pcase--macroexpand (pat)
352 "Expands all macro-patterns in PAT."
353 (let ((head (car-safe pat)))
354 (cond
355 ((null head)
356 (if (pcase--self-quoting-p pat) `',pat pat))
357 ((memq head '(pred guard quote)) pat)
358 ((memq head '(or and)) `(,head ,@(mapcar #'pcase--macroexpand (cdr pat))))
359 ((eq head 'let) `(let ,(pcase--macroexpand (cadr pat)) ,@(cddr pat)))
360 ((eq head 'app) `(app ,(nth 1 pat) ,(pcase--macroexpand (nth 2 pat))))
361 (t
362 (let* ((expander (get head 'pcase-macroexpander))
363 (npat (if expander (apply expander (cdr pat)))))
364 (if (null npat)
365 (error (if expander
366 "Unexpandable %s pattern: %S"
367 "Unknown %s pattern: %S")
368 head pat)
369 (pcase--macroexpand npat)))))))
370
371 ;;;###autoload
372 (defmacro pcase-defmacro (name args &rest body)
373 "Define a pcase UPattern macro."
374 (declare (indent 2) (debug defun) (doc-string 3))
375 ;; Add the function via `fsym', so that an autoload cookie placed
376 ;; on a pcase-defmacro will cause the macro to be loaded on demand.
377 (let ((fsym (intern (format "%s--pcase-macroexpander" name)))
378 (decl (assq 'declare body)))
379 (when decl (setq body (remove decl body)))
380 `(progn
381 (defun ,fsym ,args ,@body)
382 (put ',fsym 'edebug-form-spec ',(cadr (assq 'debug decl)))
383 (put ',name 'pcase-macroexpander #',fsym))))
384
385 (defun pcase--match (val upat)
386 "Build a MATCH structure, hoisting all `or's and `and's outside."
387 (cond
388 ;; Hoist or/and patterns into or/and matches.
389 ((memq (car-safe upat) '(or and))
390 `(,(car upat)
391 ,@(mapcar (lambda (upat)
392 (pcase--match val upat))
393 (cdr upat))))
394 (t
395 `(match ,val . ,upat))))
396
397 (defun pcase-codegen (code vars)
398 ;; Don't use let*, otherwise macroexp-let* may merge it with some surrounding
399 ;; let* which might prevent the setcar/setcdr in pcase--expand's fancy
400 ;; codegen from later metamorphosing this let into a funcall.
401 `(let ,(mapcar (lambda (b) (list (car b) (cdr b))) vars)
402 ,@code))
403
404 (defun pcase--small-branch-p (code)
405 (and (= 1 (length code))
406 (or (not (consp (car code)))
407 (let ((small t))
408 (dolist (e (car code))
409 (if (consp e) (setq small nil)))
410 small))))
411
412 ;; Try to use `cond' rather than a sequence of `if's, so as to reduce
413 ;; the depth of the generated tree.
414 (defun pcase--if (test then else)
415 (cond
416 ((eq else :pcase--dontcare) then)
417 ((eq then :pcase--dontcare) (debug) else) ;Can/should this ever happen?
418 (t (macroexp-if test then else))))
419
420 ;; Note about MATCH:
421 ;; When we have patterns like `(PAT1 . PAT2), after performing the `consp'
422 ;; check, we want to turn all the similar patterns into ones of the form
423 ;; (and (match car PAT1) (match cdr PAT2)), so you naturally need conjunction.
424 ;; Earlier code hence used branches of the form (MATCHES . CODE) where
425 ;; MATCHES was a list (implicitly a conjunction) of (SYM . PAT).
426 ;; But if we have a pattern of the form (or `(PAT1 . PAT2) PAT3), there is
427 ;; no easy way to eliminate the `consp' check in such a representation.
428 ;; So we replaced the MATCHES by the MATCH below which can be made up
429 ;; of conjunctions and disjunctions, so if we know `foo' is a cons, we can
430 ;; turn (match foo . (or `(PAT1 . PAT2) PAT3)) into
431 ;; (or (and (match car . `PAT1) (match cdr . `PAT2)) (match foo . PAT3)).
432 ;; The downside is that we now have `or' and `and' both in MATCH and
433 ;; in PAT, so there are different equivalent representations and we
434 ;; need to handle them all. We do not try to systematically
435 ;; canonicalize them to one form over another, but we do occasionally
436 ;; turn one into the other.
437
438 (defun pcase--u (branches)
439 "Expand matcher for rules BRANCHES.
440 Each BRANCH has the form (MATCH CODE . VARS) where
441 CODE is the code generator for that branch.
442 VARS is the set of vars already bound by earlier matches.
443 MATCH is the pattern that needs to be matched, of the form:
444 (match VAR . UPAT)
445 (and MATCH ...)
446 (or MATCH ...)"
447 (when (setq branches (delq nil branches))
448 (let* ((carbranch (car branches))
449 (match (car carbranch)) (cdarbranch (cdr carbranch))
450 (code (car cdarbranch))
451 (vars (cdr cdarbranch)))
452 (pcase--u1 (list match) code vars (cdr branches)))))
453
454 (defun pcase--and (match matches)
455 (if matches `(and ,match ,@matches) match))
456
457 (defconst pcase-mutually-exclusive-predicates
458 '((symbolp . integerp)
459 (symbolp . numberp)
460 (symbolp . consp)
461 (symbolp . arrayp)
462 (symbolp . vectorp)
463 (symbolp . stringp)
464 (symbolp . byte-code-function-p)
465 (integerp . consp)
466 (integerp . arrayp)
467 (integerp . vectorp)
468 (integerp . stringp)
469 (integerp . byte-code-function-p)
470 (numberp . consp)
471 (numberp . arrayp)
472 (numberp . vectorp)
473 (numberp . stringp)
474 (numberp . byte-code-function-p)
475 (consp . arrayp)
476 (consp . vectorp)
477 (consp . stringp)
478 (consp . byte-code-function-p)
479 (arrayp . byte-code-function-p)
480 (vectorp . byte-code-function-p)
481 (stringp . vectorp)
482 (stringp . byte-code-function-p)))
483
484 (defun pcase--mutually-exclusive-p (pred1 pred2)
485 (or (member (cons pred1 pred2)
486 pcase-mutually-exclusive-predicates)
487 (member (cons pred2 pred1)
488 pcase-mutually-exclusive-predicates)))
489
490 (defun pcase--split-match (sym splitter match)
491 (cond
492 ((eq (car-safe match) 'match)
493 (if (not (eq sym (cadr match)))
494 (cons match match)
495 (let ((res (funcall splitter (cddr match))))
496 (cons (or (car res) match) (or (cdr res) match)))))
497 ((memq (car-safe match) '(or and))
498 (let ((then-alts '())
499 (else-alts '())
500 (neutral-elem (if (eq 'or (car match))
501 :pcase--fail :pcase--succeed))
502 (zero-elem (if (eq 'or (car match)) :pcase--succeed :pcase--fail)))
503 (dolist (alt (cdr match))
504 (let ((split (pcase--split-match sym splitter alt)))
505 (unless (eq (car split) neutral-elem)
506 (push (car split) then-alts))
507 (unless (eq (cdr split) neutral-elem)
508 (push (cdr split) else-alts))))
509 (cons (cond ((memq zero-elem then-alts) zero-elem)
510 ((null then-alts) neutral-elem)
511 ((null (cdr then-alts)) (car then-alts))
512 (t (cons (car match) (nreverse then-alts))))
513 (cond ((memq zero-elem else-alts) zero-elem)
514 ((null else-alts) neutral-elem)
515 ((null (cdr else-alts)) (car else-alts))
516 (t (cons (car match) (nreverse else-alts)))))))
517 ((memq match '(:pcase--succeed :pcase--fail)) (cons match match))
518 (t (error "Uknown MATCH %s" match))))
519
520 (defun pcase--split-rest (sym splitter rest)
521 (let ((then-rest '())
522 (else-rest '()))
523 (dolist (branch rest)
524 (let* ((match (car branch))
525 (code&vars (cdr branch))
526 (split
527 (pcase--split-match sym splitter match)))
528 (unless (eq (car split) :pcase--fail)
529 (push (cons (car split) code&vars) then-rest))
530 (unless (eq (cdr split) :pcase--fail)
531 (push (cons (cdr split) code&vars) else-rest))))
532 (cons (nreverse then-rest) (nreverse else-rest))))
533
534 (defun pcase--split-equal (elem pat)
535 (cond
536 ;; The same match will give the same result.
537 ((and (eq (car-safe pat) 'quote) (equal (cadr pat) elem))
538 '(:pcase--succeed . :pcase--fail))
539 ;; A different match will fail if this one succeeds.
540 ((and (eq (car-safe pat) 'quote)
541 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
542 ;; (consp (cadr pat)))
543 )
544 '(:pcase--fail . nil))
545 ((and (eq (car-safe pat) 'pred)
546 (symbolp (cadr pat))
547 (get (cadr pat) 'side-effect-free))
548 (ignore-errors
549 (if (funcall (cadr pat) elem)
550 '(:pcase--succeed . nil)
551 '(:pcase--fail . nil))))))
552
553 (defun pcase--split-member (elems pat)
554 ;; FIXME: The new pred-based member code doesn't do these optimizations!
555 ;; Based on pcase--split-equal.
556 (cond
557 ;; The same match (or a match of membership in a superset) will
558 ;; give the same result, but we don't know how to check it.
559 ;; (???
560 ;; '(:pcase--succeed . nil))
561 ;; A match for one of the elements may succeed or fail.
562 ((and (eq (car-safe pat) 'quote) (member (cadr pat) elems))
563 nil)
564 ;; A different match will fail if this one succeeds.
565 ((and (eq (car-safe pat) 'quote)
566 ;; (or (integerp (cadr pat)) (symbolp (cadr pat))
567 ;; (consp (cadr pat)))
568 )
569 '(:pcase--fail . nil))
570 ((and (eq (car-safe pat) 'pred)
571 (symbolp (cadr pat))
572 (get (cadr pat) 'side-effect-free)
573 (ignore-errors
574 (let ((p (cadr pat)) (all t))
575 (dolist (elem elems)
576 (unless (funcall p elem) (setq all nil)))
577 all)))
578 '(:pcase--succeed . nil))))
579
580 (defun pcase--split-pred (vars upat pat)
581 (let (test)
582 (cond
583 ((and (equal upat pat)
584 ;; For predicates like (pred (> a)), two such predicates may
585 ;; actually refer to different variables `a'.
586 (or (and (eq 'pred (car upat)) (symbolp (cadr upat)))
587 ;; FIXME: `vars' gives us the environment in which `upat' will
588 ;; run, but we don't have the environment in which `pat' will
589 ;; run, so we can't do a reliable verification. But let's try
590 ;; and catch at least the easy cases such as (bug#14773).
591 (not (pcase--fgrep (mapcar #'car vars) (cadr upat)))))
592 '(:pcase--succeed . :pcase--fail))
593 ((and (eq 'pred (car upat))
594 (let ((otherpred
595 (cond ((eq 'pred (car-safe pat)) (cadr pat))
596 ((not (eq 'quote (car-safe pat))) nil)
597 ((consp (cadr pat)) #'consp)
598 ((stringp (cadr pat)) #'stringp)
599 ((vectorp (cadr pat)) #'vectorp)
600 ((byte-code-function-p (cadr pat))
601 #'byte-code-function-p))))
602 (pcase--mutually-exclusive-p (cadr upat) otherpred)))
603 '(:pcase--fail . nil))
604 ((and (eq 'pred (car upat))
605 (eq 'quote (car-safe pat))
606 (symbolp (cadr upat))
607 (or (symbolp (cadr pat)) (stringp (cadr pat)) (numberp (cadr pat)))
608 (get (cadr upat) 'side-effect-free)
609 (ignore-errors
610 (setq test (list (funcall (cadr upat) (cadr pat))))))
611 (if (car test)
612 '(nil . :pcase--fail)
613 '(:pcase--fail . nil))))))
614
615 (defun pcase--fgrep (vars sexp)
616 "Check which of the symbols VARS appear in SEXP."
617 (let ((res '()))
618 (while (consp sexp)
619 (dolist (var (pcase--fgrep vars (pop sexp)))
620 (unless (memq var res) (push var res))))
621 (and (memq sexp vars) (not (memq sexp res)) (push sexp res))
622 res))
623
624 (defun pcase--self-quoting-p (upat)
625 (or (keywordp upat) (numberp upat) (stringp upat)))
626
627 (defun pcase--app-subst-match (match sym fun nsym)
628 (cond
629 ((eq (car-safe match) 'match)
630 (if (and (eq sym (cadr match))
631 (eq 'app (car-safe (cddr match)))
632 (equal fun (nth 1 (cddr match))))
633 (pcase--match nsym (nth 2 (cddr match)))
634 match))
635 ((memq (car-safe match) '(or and))
636 `(,(car match)
637 ,@(mapcar (lambda (match)
638 (pcase--app-subst-match match sym fun nsym))
639 (cdr match))))
640 ((memq match '(:pcase--succeed :pcase--fail)) match)
641 (t (error "Uknown MATCH %s" match))))
642
643 (defun pcase--app-subst-rest (rest sym fun nsym)
644 (mapcar (lambda (branch)
645 `(,(pcase--app-subst-match (car branch) sym fun nsym)
646 ,@(cdr branch)))
647 rest))
648
649 (defsubst pcase--mark-used (sym)
650 ;; Exceptionally, `sym' may be a constant expression rather than a symbol.
651 (if (symbolp sym) (put sym 'pcase-used t)))
652
653 (defmacro pcase--flip (fun arg1 arg2)
654 "Helper function, used internally to avoid (funcall (lambda ...) ...)."
655 (declare (debug (sexp body)))
656 `(,fun ,arg2 ,arg1))
657
658 (defun pcase--funcall (fun arg vars)
659 "Build a function call to FUN with arg ARG."
660 (if (symbolp fun)
661 `(,fun ,arg)
662 (let* (;; `vs' is an upper bound on the vars we need.
663 (vs (pcase--fgrep (mapcar #'car vars) fun))
664 (env (mapcar (lambda (var)
665 (list var (cdr (assq var vars))))
666 vs))
667 (call (progn
668 (when (memq arg vs)
669 ;; `arg' is shadowed by `env'.
670 (let ((newsym (make-symbol "x")))
671 (push (list newsym arg) env)
672 (setq arg newsym)))
673 (if (functionp fun)
674 `(funcall #',fun ,arg)
675 `(,@fun ,arg)))))
676 (if (null vs)
677 call
678 ;; Let's not replace `vars' in `fun' since it's
679 ;; too difficult to do it right, instead just
680 ;; let-bind `vars' around `fun'.
681 `(let* ,env ,call)))))
682
683 (defun pcase--eval (exp vars)
684 "Build an expression that will evaluate EXP."
685 (let* ((found (assq exp vars)))
686 (if found (cdr found)
687 (let* ((vs (pcase--fgrep (mapcar #'car vars) exp))
688 (env (mapcar (lambda (v) (list v (cdr (assq v vars))))
689 vs)))
690 (if env (macroexp-let* env exp) exp)))))
691
692 ;; It's very tempting to use `pcase' below, tho obviously, it'd create
693 ;; bootstrapping problems.
694 (defun pcase--u1 (matches code vars rest)
695 "Return code that runs CODE (with VARS) if MATCHES match.
696 Otherwise, it defers to REST which is a list of branches of the form
697 \(ELSE-MATCH ELSE-CODE . ELSE-VARS)."
698 ;; Depending on the order in which we choose to check each of the MATCHES,
699 ;; the resulting tree may be smaller or bigger. So in general, we'd want
700 ;; to be careful to chose the "optimal" order. But predicate
701 ;; patterns make this harder because they create dependencies
702 ;; between matches. So we don't bother trying to reorder anything.
703 (cond
704 ((null matches) (funcall code vars))
705 ((eq :pcase--fail (car matches)) (pcase--u rest))
706 ((eq :pcase--succeed (car matches))
707 (pcase--u1 (cdr matches) code vars rest))
708 ((eq 'and (caar matches))
709 (pcase--u1 (append (cdar matches) (cdr matches)) code vars rest))
710 ((eq 'or (caar matches))
711 (let* ((alts (cdar matches))
712 (var (if (eq (caar alts) 'match) (cadr (car alts))))
713 (simples '()) (others '()) (memq-ok t))
714 (when var
715 (dolist (alt alts)
716 (if (and (eq (car alt) 'match) (eq var (cadr alt))
717 (let ((upat (cddr alt)))
718 (eq (car-safe upat) 'quote)))
719 (let ((val (cadr (cddr alt))))
720 (unless (or (integerp val) (symbolp val))
721 (setq memq-ok nil))
722 (push (cadr (cddr alt)) simples))
723 (push alt others))))
724 (cond
725 ((null alts) (error "Please avoid it") (pcase--u rest))
726 ;; Yes, we can use `memq' (or `member')!
727 ((> (length simples) 1)
728 (pcase--u1 (cons `(match ,var
729 . (pred (pcase--flip
730 ,(if memq-ok #'memq #'member)
731 ',simples)))
732 (cdr matches))
733 code vars
734 (if (null others) rest
735 (cons (cons
736 (pcase--and (if (cdr others)
737 (cons 'or (nreverse others))
738 (car others))
739 (cdr matches))
740 (cons code vars))
741 rest))))
742 (t
743 (pcase--u1 (cons (pop alts) (cdr matches)) code vars
744 (if (null alts) (progn (error "Please avoid it") rest)
745 (cons (cons
746 (pcase--and (if (cdr alts)
747 (cons 'or alts) (car alts))
748 (cdr matches))
749 (cons code vars))
750 rest)))))))
751 ((eq 'match (caar matches))
752 (let* ((popmatches (pop matches))
753 (_op (car popmatches)) (cdrpopmatches (cdr popmatches))
754 (sym (car cdrpopmatches))
755 (upat (cdr cdrpopmatches)))
756 (cond
757 ((memq upat '(t _)) (pcase--u1 matches code vars rest))
758 ((eq upat 'pcase--dontcare) :pcase--dontcare)
759 ((memq (car-safe upat) '(guard pred))
760 (if (eq (car upat) 'pred) (pcase--mark-used sym))
761 (let* ((splitrest
762 (pcase--split-rest
763 sym (lambda (pat) (pcase--split-pred vars upat pat)) rest))
764 (then-rest (car splitrest))
765 (else-rest (cdr splitrest)))
766 (pcase--if (if (eq (car upat) 'pred)
767 (pcase--funcall (cadr upat) sym vars)
768 (pcase--eval (cadr upat) vars))
769 (pcase--u1 matches code vars then-rest)
770 (pcase--u else-rest))))
771 ((symbolp upat)
772 (pcase--mark-used sym)
773 (if (not (assq upat vars))
774 (pcase--u1 matches code (cons (cons upat sym) vars) rest)
775 ;; Non-linear pattern. Turn it into an `eq' test.
776 (pcase--u1 (cons `(match ,sym . (pred (eq ,(cdr (assq upat vars)))))
777 matches)
778 code vars rest)))
779 ((eq (car-safe upat) 'let)
780 ;; A upat of the form (let VAR EXP).
781 ;; (pcase--u1 matches code
782 ;; (cons (cons (nth 1 upat) (nth 2 upat)) vars) rest)
783 (macroexp-let2
784 macroexp-copyable-p sym
785 (pcase--eval (nth 2 upat) vars)
786 (pcase--u1 (cons (pcase--match sym (nth 1 upat)) matches)
787 code vars rest)))
788 ((eq (car-safe upat) 'app)
789 ;; A upat of the form (app FUN UPAT)
790 (pcase--mark-used sym)
791 (let* ((fun (nth 1 upat))
792 (nsym (make-symbol "x"))
793 (body
794 ;; We don't change `matches' to reuse the newly computed value,
795 ;; because we assume there shouldn't be such redundancy in there.
796 (pcase--u1 (cons (pcase--match nsym (nth 2 upat)) matches)
797 code vars
798 (pcase--app-subst-rest rest sym fun nsym))))
799 (if (not (get nsym 'pcase-used))
800 body
801 (macroexp-let*
802 `((,nsym ,(pcase--funcall fun sym vars)))
803 body))))
804 ((eq (car-safe upat) 'quote)
805 (pcase--mark-used sym)
806 (let* ((val (cadr upat))
807 (splitrest (pcase--split-rest
808 sym (lambda (pat) (pcase--split-equal val pat)) rest))
809 (then-rest (car splitrest))
810 (else-rest (cdr splitrest)))
811 (pcase--if (cond
812 ((null val) `(null ,sym))
813 ((or (integerp val) (symbolp val))
814 (if (pcase--self-quoting-p val)
815 `(eq ,sym ,val)
816 `(eq ,sym ',val)))
817 (t `(equal ,sym ',val)))
818 (pcase--u1 matches code vars then-rest)
819 (pcase--u else-rest))))
820 ((eq (car-safe upat) 'not)
821 ;; FIXME: The implementation below is naive and results in
822 ;; inefficient code.
823 ;; To make it work right, we would need to turn pcase--u1's
824 ;; `code' and `vars' into a single argument of the same form as
825 ;; `rest'. We would also need to split this new `then-rest' argument
826 ;; for every test (currently we don't bother to do it since
827 ;; it's only useful for odd patterns like (and `(PAT1 . PAT2)
828 ;; `(PAT3 . PAT4)) which the programmer can easily rewrite
829 ;; to the more efficient `(,(and PAT1 PAT3) . ,(and PAT2 PAT4))).
830 (pcase--u1 `((match ,sym . ,(cadr upat)))
831 ;; FIXME: This codegen is not careful to share its
832 ;; code if used several times: code blow up is likely.
833 (lambda (_vars)
834 ;; `vars' will likely contain bindings which are
835 ;; not always available in other paths to
836 ;; `rest', so there' no point trying to pass
837 ;; them down.
838 (pcase--u rest))
839 vars
840 (list `((and . ,matches) ,code . ,vars))))
841 (t (error "Unknown internal pattern `%S'" upat)))))
842 (t (error "Incorrect MATCH %S" (car matches)))))
843
844 (def-edebug-spec
845 pcase-QPAT
846 (&or ("," pcase-UPAT)
847 (pcase-QPAT . pcase-QPAT)
848 (vector &rest pcase-QPAT)
849 sexp))
850
851 (pcase-defmacro \` (qpat)
852 "Backquote-style pcase patterns.
853 QPAT can take the following forms:
854 (QPAT1 . QPAT2) matches if QPAT1 matches the car and QPAT2 the cdr.
855 [QPAT1 QPAT2..QPATn] matches a vector of length n and QPAT1..QPATn match
856 its 0..(n-1)th elements, respectively.
857 ,UPAT matches if the UPattern UPAT matches.
858 STRING matches if the object is `equal' to STRING.
859 ATOM matches if the object is `eq' to ATOM."
860 (declare (debug (pcase-QPAT)))
861 (cond
862 ((eq (car-safe qpat) '\,) (cadr qpat))
863 ((vectorp qpat)
864 `(and (pred vectorp)
865 (app length ,(length qpat))
866 ,@(let ((upats nil))
867 (dotimes (i (length qpat))
868 (push `(app (pcase--flip aref ,i) ,(list '\` (aref qpat i)))
869 upats))
870 (nreverse upats))))
871 ((consp qpat)
872 `(and (pred consp)
873 (app car ,(list '\` (car qpat)))
874 (app cdr ,(list '\` (cdr qpat)))))
875 ((or (stringp qpat) (integerp qpat) (symbolp qpat)) `',qpat)))
876
877
878 (provide 'pcase)
879 ;;; pcase.el ends here