Subject: bug#68509: 30.0.50; pcase-dolist matches backquote pattern incorrectly

From: Stefan Monnier <[email-masked]>
Date: Fri, 23 Feb 2024 09:58:55 -0500

>> How 'bout the patch below?
>> ...
>> +The precise behavior when the object does not actually match the pattern
>> +depends on the types, although the body will not be silently skipped:
                   ^^^^^
                  pattern

>> +either an error is signaled or the body is run with some of the
>> +variables bound to arbitrary values like @code{nil}.
>> +For example, the above pattern will result in @var{x} and @var{y}
>> +being extracted with operations like @code{car} or @code{nth}, so they
>> +will get value @code{nil} when @var{my-list} is too short.  In contrast,
>> +with a pattern like @code{`[add ,x ,y]}, those same variables would
>> +be extracted using @code{aref} which would signal an error if
>> +@var{my-list} is not an array or is too short.
>
> This is confusing. In particular, "for example" implies that other
> situations are possible. It is unclear how the reader will know when
> "variables bound to arbitrary values" happen, when variables are bound
> to nil, and when an error is signaled.

This part of the doc is generic, so it can't guarantee anything: the
behavior depends on the actual pattern and the way that pattern is defined.
In order to intuit what will happen, the reader needs to guess which
primitives are used to extract the info from value (e.g. `car/cdr/nth`
for cons cells, `aref` for arrays, ...).

> I would re-structure the paragraph, explicitly listing the possible
> outcomes when the PATTERN does not match VALUE and stating that any
> other non-matching PATTERN will lead to undefined outcome.

Could you try to do that?
[ I've found back-and-forth modifications of docs give better results
  than single-sided writing.  ]

> Also, with the current behavior of `pcase-let', it appears to be
> impossible to distinguish between too short list (1 2 3) and
> (1 2 3 nil nil) when assigning destructuring pattern.

Destructuring  by definition can't do "distinguish", so that's not a big
surprise 🙂

But of course, this isn't really true, you can do:

    (pcase-let ((`(,x ,y ,z . ,tail) FOO))
      (if (equal tail '(nil nil))
          ...
        ...))

or you can get hairy and do things like:

    (pcase-let (((or `(,x ,y ,z ,a ,_)
                     (and `(,x ,y ,z) (let a 'shortorlonglist)))
                 FOO))
      (if (eq a 'shortorlonglist)
          ...
        ...))

but that kind if Pcase pattern, while possible, is rarely worth the trouble.

        Stefan