;; -*- lexical-binding: t; -*- (defun f (hello world) (cons hello world)) (defun pcall-collect-symbols-1 (expr pusher) (cond ((consp expr) (pcall-collect-symbols-1 (car expr) pusher) (pcall-collect-symbols-1 (cdr expr) pusher)) ((symbolp expr) (funcall pusher expr)))) (defun pcall-collect-symbols (bindings) (let (list) (dolist (binding bindings) (pcall-collect-symbols-1 binding (lambda (x) (unless (memq x list) (push x list))))) list)) (defun pcall-make-environment (syms) (let (env) (dolist (sym syms) (push (list 'cons (list 'quote sym) `(condition-case error ,sym (void-variable (push ',sym unbound-syms)))) env)) (cons 'list (nreverse env)))) (defun pcaller (func pats) (let* ((arglist (arglist func)) (arg-symbols (pcall-collect-symbols arglist))) `(lambda (env vals) (dolist (sym ',arglist) ;; (if (assq sym env) ;; (warn "shadowing variable binding for %S" ;; sym)) (setq env (assq-delete-all sym env))) (eval '(filtered-pcase vals (lambda (x) (assq x env)) (,(list '\` (mapcar (lambda (x) (list '\, x)) pats)) (funcall ',func ,@arglist))) env)))) (defun arglist (func) (while (and (symbolp func) (setq func (symbol-function func)))) (pcase func ((or `(lambda ,arglist . ,body) `(closure ,lexenv ,arglist . ,body)) arglist) (_ (cdr (read (downcase (car (help-split-fundoc (documentation func t) func t)))))))) (defmacro pcall (func &rest bindings) (let* ((syms (pcall-collect-symbols bindings)) (env (pcall-make-environment syms)) (pats (mapcar #'car bindings)) (vals (mapcar #'cadr bindings))) `(let ((func ',func)) (while (and (symbolp func) (setq func (symbol-function func)))) (let ((pcaller (funcall #'pcaller func ',pats))) (let* ((unbound-syms (list nil)) (env ,env) (pcase--env env)) (dolist (sym unbound-syms) (setq env (assq-delete-all sym env))) (funcall pcaller env (list ,@vals))))))) (defun pcase--expand (exp cases filter) ;; (message "pid=%S (pcase--expand %S ...hash=%S)" ;; (emacs-pid) exp (sxhash cases)) (macroexp-let2 macroexp-copyable-p val exp (let* ((defs ()) (seen '()) (codegen (lambda (code vars) (let ((vars (pcase--fgrep vars code)) (prev (assq code seen))) (if (not prev) (let ((res (pcase-codegen code vars))) (push (list code vars res) seen) res) ;; Since we use a tree-based pattern matching ;; technique, the leaves (the places that contain the ;; code to run once a pattern is matched) can get ;; copied a very large number of times, so to avoid ;; code explosion, we need to keep track of how many ;; times we've used each leaf and move it ;; to a separate function if that number is too high. ;; ;; We've already used this branch. So it is shared. (let* ((code (car prev)) (cdrprev (cdr prev)) (prevvars (car cdrprev)) (cddrprev (cdr cdrprev)) (res (car cddrprev))) (unless (symbolp res) ;; This is the first repeat, so we have to move ;; the branch to a separate function. (let ((bsym (make-symbol (format "pcase-%d" (length defs))))) (push `(,bsym (lambda ,(mapcar #'car prevvars) ,@code)) defs) (setcar res 'funcall) (setcdr res (cons bsym (mapcar #'cdr prevvars))) (setcar (cddr prev) bsym) (setq res bsym))) (setq vars (copy-sequence vars)) (let ((args (mapcar (lambda (pa) (let ((v (assq (car pa) vars))) (setq vars (delq v vars)) (cdr v))) prevvars))) ;; If some of `vars' were not found in `prevvars', that's ;; OK it just means those vars aren't present in all ;; branches, so they can be used within the pattern ;; (e.g. by a `guard/let/pred') but not in the branch. ;; FIXME: But if some of `prevvars' are not in `vars' we ;; should remove them from `prevvars'! `(funcall ,res ,@args))))))) (used-cases ()) (main (pcase--u (mapcar (lambda (case) `(,(pcase--match val (pcase--macroexpand (car case))) ,(lambda (vars) (unless (memq case used-cases) ;; Keep track of the cases that are used. (push case used-cases)) (funcall (if (pcase--small-branch-p (cdr case)) ;; Don't bother sharing multiple ;; occurrences of this leaf since it's small. (lambda (code vars) (pcase-codegen code (pcase--fgrep vars code))) codegen) (cdr case) vars)))) cases) filter))) (dolist (case cases) (unless (or (memq case used-cases) (memq (car case) pcase--dontwarn-upats)) (message "Redundant pcase pattern: %S" (car case)))) (macroexp-let* defs main)))) (defvar pcase--env nil) (pcase-defmacro concat (&rest patterns) (if patterns (let* ((pat (list '\` (cons (list '\, (car patterns)) (list '\, (cons 'concat (cdr patterns)))))) (f `(lambda (l) (catch 'pcase--call (dotimes (i (1+ (length l))) (let* ((lc (cons (seq-subseq l 0 i) (seq-subseq l i)))) (filtered-pcase lc (lambda (x) (assq x pcase--env)) (,pat (throw 'pcase--call lc))))))))) `(app ,f ,pat)) `(pred seq-empty-p))) (defmacro filtered-pcase (exp filter &rest cases) (declare (indent 1) (debug (form &rest (pcase-PAT body)))) (pcase--expand exp cases filter)) (defmacro pcase (exp &rest cases) "Evaluate EXP to get EXPVAL; try passing control to one of CASES. CASES is a list of elements of the form (PATTERN CODE...). For the first CASE whose PATTERN \"matches\" EXPVAL, evaluate its CODE..., and return the value of the last form. If no CASE has a PATTERN that matches, return nil. Each PATTERN expands, in essence, to a predicate to call on EXPVAL. When the return value of that call is non-nil, PATTERN matches. PATTERN can take one of the forms: _ matches anything. \\='VAL matches if EXPVAL is `equal' to VAL. KEYWORD shorthand for \\='KEYWORD INTEGER shorthand for \\='INTEGER STRING shorthand for \\='STRING SYMBOL matches anything and binds it to SYMBOL. If a SYMBOL is used twice in the same pattern the second occurrence becomes an `eq'uality test. (pred FUN) matches if FUN called on EXPVAL returns non-nil. (app FUN PAT) matches if FUN called on EXPVAL matches PAT. (guard BOOLEXP) matches if BOOLEXP evaluates to non-nil. (let PAT EXPR) matches if EXPR matches PAT. (and PAT...) matches if all the patterns match. (or PAT...) matches if any of the patterns matches. FUN in `pred' and `app' can take one of the forms: SYMBOL or (lambda ARGS BODY) call it with one argument (F ARG1 .. ARGn) call F with ARG1..ARGn and EXPVAL as n+1'th argument FUN, BOOLEXP, EXPR, and subsequent PAT can refer to variables bound earlier in the pattern by a SYMBOL pattern. Additional patterns can be defined using `pcase-defmacro'. See Info node `(elisp) Pattern-Matching Conditional' in the Emacs Lisp manual for more information and examples." (declare (indent 1) (debug (form &rest (pcase-PAT body)))) ;; We want to use a weak hash table as a cache, but the key will unavoidably ;; be based on `exp' and `cases', yet `cases' is a fresh new list each time ;; we're called so it'll be immediately GC'd. So we use (car cases) as key ;; which does come straight from the source code and should hence not be GC'd ;; so easily. (let ((data (gethash (car cases) pcase--memoize)) (filter nil)) ;; data = (EXP CASES . EXPANSION) (if (and (equal exp (car data)) (equal cases (cadr data))) ;; We have the right expansion. (cddr data) ;; (when (gethash (car cases) pcase--memoize-1) ;; (message "pcase-memoize failed because of weak key!!")) ;; (when (gethash (car cases) pcase--memoize-2) ;; (message "pcase-memoize failed because of eq test on %S" ;; (car cases))) ;; (when data ;; (message "pcase-memoize: equal first branch, yet different")) (let ((expansion (pcase--expand exp cases filter))) (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize) ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-1) ;; (puthash (car cases) `(,exp ,cases ,@expansion) pcase--memoize-2) expansion)))) (defun pcase--u (branches filter) "Expand matcher for rules BRANCHES. Each BRANCH has the form (MATCH CODE . VARS) where CODE is the code generator for that branch. VARS is the set of vars already bound by earlier matches. MATCH is the pattern that needs to be matched, of the form: (match VAR . PAT) (and MATCH ...) (or MATCH ...)" (when (setq branches (delq nil branches)) (let* ((carbranch (car branches)) (match (car carbranch)) (cdarbranch (cdr carbranch)) (code (car cdarbranch)) (vars (cdr cdarbranch))) (pcase--u1 (list match) code vars (cdr branches) filter)))) (defun pcase--u1 (matches code vars rest filter) "Return code that runs CODE (with VARS) if MATCHES match. Otherwise, it defers to REST which is a list of branches of the form \(ELSE-MATCH ELSE-CODE . ELSE-VARS)." ;; Depending on the order in which we choose to check each of the MATCHES, ;; the resulting tree may be smaller or bigger. So in general, we'd want ;; to be careful to chose the "optimal" order. But predicate ;; patterns make this harder because they create dependencies ;; between matches. So we don't bother trying to reorder anything. (cond ((null matches) (funcall code vars)) ((eq :pcase--fail (car matches)) (pcase--u rest filter)) ((eq :pcase--succeed (car matches)) (pcase--u1 (cdr matches) code vars rest filter)) ((eq 'and (caar matches)) (pcase--u1 (append (cdar matches) (cdr matches)) code vars rest filter)) ((eq 'or (caar matches)) (let* ((alts (cdar matches)) (var (if (eq (caar alts) 'match) (cadr (car alts)))) (simples '()) (others '()) (mem-fun 'memq)) (when var (dolist (alt alts) (if (and (eq (car alt) 'match) (eq var (cadr alt)) (let ((upat (cddr alt))) (eq (car-safe upat) 'quote))) (let ((val (cadr (cddr alt)))) (cond ((integerp val) (when (eq mem-fun 'memq) (setq mem-fun 'memql))) ((not (symbolp val)) (setq mem-fun 'member))) (push val simples)) (push alt others)))) (cond ((null alts) (error "Please avoid it") (pcase--u rest filter)) ;; Yes, we can use `memql' (or `member')! ((> (length simples) 1) (pcase--u1 (cons `(match ,var . (pred (pcase--flip ,mem-fun ',simples))) (cdr matches)) code vars (if (null others) rest (cons (cons (pcase--and (if (cdr others) (cons 'or (nreverse others)) (car others)) (cdr matches)) (cons code vars)) rest)) filter)) (t (pcase--u1 (cons (pop alts) (cdr matches)) code vars (if (null alts) (progn (error "Please avoid it") rest) (cons (cons (pcase--and (if (cdr alts) (cons 'or alts) (car alts)) (cdr matches)) (cons code vars)) rest)) filter))))) ((eq 'match (caar matches)) (let* ((popmatches (pop matches)) (_op (car popmatches)) (cdrpopmatches (cdr popmatches)) (sym (car cdrpopmatches)) (upat (cdr cdrpopmatches))) (cond ((memq upat '(t _)) (let ((code (pcase--u1 matches code vars rest filter))) (if (eq upat '_) code (macroexp--warn-and-return "Pattern t is deprecated. Use `_' instead" code)))) ((eq upat 'pcase--dontcare) :pcase--dontcare) ((memq (car-safe upat) '(guard pred)) (if (eq (car upat) 'pred) (pcase--mark-used sym)) (let* ((splitrest (pcase--split-rest sym (lambda (pat) (pcase--split-pred vars upat pat)) rest)) (then-rest (car splitrest)) (else-rest (cdr splitrest))) (pcase--if (if (eq (car upat) 'pred) (pcase--funcall (cadr upat) sym vars) (pcase--eval (cadr upat) vars)) (pcase--u1 matches code vars then-rest filter) (pcase--u else-rest filter)))) ((and (symbolp upat) upat) (pcase--mark-used sym) (cond ((and filter (funcall filter upat)) (pcase--u1 (cons `(match ,sym . (pred (lambda (x) (equal ,(cdr (funcall filter upat)) x)))) matches) code vars rest filter)) ((not (assq upat vars)) (pcase--u1 matches code (cons (cons upat sym) vars) rest filter)) (;; Non-linear pattern. Turn it into an `eq' test. (pcase--u1 (cons `(match ,sym . (pred (eq ,(cdr (assq upat vars))))) matches) code vars rest filter)))) ((eq (car-safe upat) 'let) ;; A upat of the form (let VAR EXP). ;; (pcase--u1 matches code ;; (cons (cons (nth 1 upat) (nth 2 upat)) vars) rest) (macroexp-let2 macroexp-copyable-p sym (pcase--eval (nth 2 upat) vars) (pcase--u1 (cons (pcase--match sym (nth 1 upat)) matches) code vars rest filter))) ((eq (car-safe upat) 'app) ;; A upat of the form (app FUN PAT) (pcase--mark-used sym) (let* ((fun (nth 1 upat)) (nsym (gensym "x")) (body ;; We don't change `matches' to reuse the newly computed value, ;; because we assume there shouldn't be such redundancy in there. (pcase--u1 (cons (pcase--match nsym (nth 2 upat)) matches) code vars (pcase--app-subst-rest rest sym fun nsym) (lambda (x) (and (not (eq x nsym))) (and filter (funcall filter x)))))) (if (not (get nsym 'pcase-used)) body (macroexp-let* `((,nsym ,(pcase--funcall fun sym vars))) body)))) ((eq (car-safe upat) 'quote) (pcase--mark-used sym) (let* ((val (cadr upat)) (splitrest (pcase--split-rest sym (lambda (pat) (pcase--split-equal val pat)) rest)) (then-rest (car splitrest)) (else-rest (cdr splitrest))) (pcase--if (cond ((null val) `(null ,sym)) ((integerp val) `(eql ,sym ,val)) ((symbolp val) (if (pcase--self-quoting-p val) `(eq ,sym ,val) `(eq ,sym ',val))) (t `(equal ,sym ',val))) (pcase--u1 matches code vars then-rest filter) (pcase--u else-rest filter)))) ((eq (car-safe upat) 'not) ;; FIXME: The implementation below is naive and results in ;; inefficient code. ;; To make it work right, we would need to turn pcase--u1's ;; `code' and `vars' into a single argument of the same form as ;; `rest'. We would also need to split this new `then-rest' argument ;; for every test (currently we don't bother to do it since ;; it's only useful for odd patterns like (and `(PAT1 . PAT2) ;; `(PAT3 . PAT4)) which the programmer can easily rewrite ;; to the more efficient `(,(and PAT1 PAT3) . ,(and PAT2 PAT4))). (pcase--u1 `((match ,sym . ,(cadr upat))) ;; FIXME: This codegen is not careful to share its ;; code if used several times: code blow up is likely. (lambda (_vars) ;; `vars' will likely contain bindings which are ;; not always available in other paths to ;; `rest', so there' no point trying to pass ;; them down. (pcase--u rest filter)) vars (list `((and . ,matches) ,code . ,vars)) filter)) (t (error "Unknown pattern `%S'" upat))))) (t (error "Incorrect MATCH %S" (car matches))))) (let ((space " ")) (pcall f ((concat hello space world) "hello world"))) (defun pcase--length (pattern) (setq pattern (pcase--macroexpand pattern)) (pcase pattern (`(pred null) (cons 0 0)) (`'nil (cons 0 0)) (`(pred consp) (cons 1 1.0e+INF)) (`(app cdr ,pattern) (let ((length (pcase--length pattern))) (if (> (car length) 0) (cons (1+ (car length)) (1+ (cdr length))) (cons 0 (1+ (cdr length)))))) (`(or . ,patterns) (let ((inf 0) (sup 1.0e+INF)) (dolist (pattern patterns) (let* ((is (pcase--length pattern)) (i (car is)) (s (cdr is))) (setq inf (min inf i)) (setq sup (max sup s)))) (cons inf sup))) (`(and . ,patterns) (let ((inf 0) (sup 1.0e+INF)) (dolist (pattern patterns) (let* ((is (pcase--length pattern)) (i (car is)) (s (cdr is))) (setq inf (max inf i)) (setq sup (min sup s)))) (cons inf sup))) (_ (cons 0 1.0e+INF)))) (pcase-defmacro not (pat) `(app (lambda (expval) (not (pcase expval (,pat t)))) (pred identity)))