Subject: Re: bug#40693: 28.0.50; json-encode-alist changes alist

From: Michael Heerdegen <[email-masked]>
Date: Sun, 19 Apr 2020 01:13:04 +0200

Dmitry Gutov <[email-masked]> writes:

> diff --git a/lisp/json.el b/lisp/json.el
> index 18d7fda882..b65884f913 100644
> --- a/lisp/json.el
> +++ b/lisp/json.el
> @@ -564,9 +564,10 @@ json-encode-alist
>    "Return a JSON representation of ALIST."
>    (when json-encoding-object-sort-predicate
>      (setq alist
> -          (sort alist (lambda (a b)
> -                        (funcall json-encoding-object-sort-predicate
> -                                 (car a) (car b))))))
> +          (sort (copy-sequence alist)
> +                (lambda (a b)
> +                  (funcall json-encoding-object-sort-predicate
> +                           (car a) (car b))))))
>    (format "{%s%s}"
>            (json-join
>             (json--with-indentation

Why?  Isn't this a classical example of modifiable code?  After some
iterations

(symbol-function 'fun-withdraw)

=>

(closure
 (t)
 (amount)
 (json-encode-alist
  (cons
   (cons 'tamount amount)
   '((const . some-constant)
     (tamount . 12)
     (tamount . 12)
     (tamount . 12)))))

So the problem is in the implementation of `fun-withdraw', not in that
of `json-encode-alist' or `sort'.

I mean, it's really an example of an ugly trap, but how is
`json-encode-alist' different from other functions working with lists
that would exploit the same problem?

Michael.