Subject: Re: bug#43100: 28.0.50; pcase not binding variables conditionally

From: Stefan Monnier <[email-masked]>
Date: Sat, 29 Aug 2020 12:06:15 -0400

>> > I'm having trouble with pcase's behavior.
>> >
>> > (pcase "a"
>> >   ((or (pred symbolp) name)
>> >    (let ((foo 'bar)) name)))
>> >
>> > throws an error. It shouldn't.
>>
>> Isn't this case documented in the manual? The last section of
>> https://www.gnu.org/software/emacs/manual/html_node/elisp/pcase-Macro.html
>> states:
>> "It makes no sense for each sub-pattern [in an `or' sequence] to
>> let-bind a different set of symbols because the body forms have no way
>> to distinguish which sub-pattern matched and choose among the
>> different sets."
>
> Thanks for pointing this out.
>
> I disagree with what the documentation says there: it does make
> perfect sense, to me, to conditionally shadow a (lexical) let binding
> with a pcase-let one, and body forms will have no trouble in practice
> distinguishing between the outer and the inner let-binding.

How do you expect them to distinguish?

IIUC you want 

    (pcase V
      ((or (pred symbolp) name)
       (let ((foo 'bar)) name)))

to behave like

    (cond
     ((symbolp V) (let ((foo 'bar)) name))
     (t (let ((name V)) (let ((foo 'bar)) name))))

?

I'd rather not go there since it means that the single occurrence of the
`name` identifier in the branch's body refers to two different variable
bindings depending on which pattern was matched.  It smells of dynamic
scoping, tho it is admittedly compatible with lexical-scoping but only at
the cost of having to duplicate the branch's body.

The "intended" behavior instead would be to behave like

    (cond
     ((symbolp V) (let ((name nil)) (let ((foo 'bar)) name)))
     (t (let ((name V)) (let ((foo 'bar)) name))))

That's already the behavior you get if you switch the two:

    (macroexpand '(pcase V
                    ((or (and (pred foo) name) (pred symbolp))
                     (let ((foo 'bar)) name))))
    =>
    (let* ((pcase-0 (lambda (name) (let ((foo 'bar)) name))))
      (cond ((foo V) (funcall pcase-0 V))
            ((symbolp V) (funcall pcase-0 nil))
            (t nil)))

the fact that the behavior depends on the order of elements in `or` is
an undesirable side effect of the implementation technique.

> Things like the behavior of
>
> (pcase-let ((`(,a ,@b) (list 3 4)))
>   a)
>
> just seem puzzling to me. There are good reasons not to implement
> sublist matching (though I don't think those reasons are sufficient
> not to have a simple implementation anyway),

I don't know of a simple implementation.

> so an error message would be acceptable,

You're probably right.

> Sorry for complaining. Here's a patch.

LGTM,

        Stefan