Subject: bug#62317: 28.2; This byte-compiled file behaves wrongly.

From: Stefan Monnier <[email-masked]>
Date: Sat, 01 Apr 2023 12:27:35 -0400

> * How to reproduce:
> First, ~/.emacs.d/init.el:
> ------------------------------------------------------------------------
> (eval-and-compile
>   (push user-emacs-directory load-path)
>   (require 'a))
>
> ;; Hereafter is ignored when byte-compiled.
>
> (defvar foo-var 'baz)
> (message "Hello, world.")
> (pop-to-buffer "*Messages*")
> ------------------------------------------------------------------------
>
> ~/.emacs.d/a.el:
> ------------------------------------------------------------------------
> (set-buffer "*Messages*") ;; or (set-buffer (get-buffer-create "bar"))
> (provide 'a)
> ------------------------------------------------------------------------

I suspect you can simplify the above to:

    (eval-and-compile (set-buffer "*Messages*"))
    ;; Hereafter is ignored when byte-compiled.
    (message "Hello, world.")

> Stefan, any ideas?  I think switching to a different buffer inside
> `eval-and-compile` is a bad idea, but maybe I'm missing something.

I tend to agree.
[ Side note: (push user-emacs-directory load-path) is also a bad idea.  ]

We could guard against this to some extent, but there will always be
ways for the code executed at compile-time to mess up the state of
the compiler, so I'm not sure where we should draw the line.

FWIW, in my book `set-buffer` is a code smell (usually better replaced
by `with-current-buffer`).

Admittedly, the resulting behavior can be very puzzling&frustrating for
the user, which would tend to argue in favor of trying to at least
detect the problem.
But note that if the code switched to a buffer where point is not at
EOB, we'd probably get helpful error messages during compilation, so
I'm leaning towards considering it a "minor corner case" issue, but
I think the untested patch below would be enough to plug the hole.

        Stefan

diff --git a/lisp/emacs-lisp/bytecomp.el b/lisp/emacs-lisp/bytecomp.el
index 5df1205869c..e22ab94e378 100644
--- a/lisp/emacs-lisp/bytecomp.el
+++ b/lisp/emacs-lisp/bytecomp.el
@@ -2376,7 +2376,10 @@ byte-compile-from-buffer
                  (form (read-positioning-symbols inbuffer))
                  (warning (byte-run--unescaped-character-literals-warning)))
             (when warning (byte-compile-warn-x form "%s" warning))
-	    (byte-compile-toplevel-file-form form)))
+            ;; Defend against macros using `set-buffer' or `goto-char'
+            ;; bug#62317.
+            (save-excursion
+	      (byte-compile-toplevel-file-form form))))
 	;; Compile pending forms at end of file.
 	(byte-compile-flush-pending)
 	(byte-compile-warn-about-unresolved-functions)))