Subject: Re: bug#55414: 29.0.50; Byte compilation error for the modus-themes

From: Stefan Monnier <[email-masked]>
Date: Thu, 26 May 2022 11:20:14 -0400

Lars Ingebrigtsen [2022-05-26 13:57:09] wrote:

> Eli Zaretskii <[email-masked]> writes:
>
>> Lars, is it just me, or are you also concerned by a large increase in
>> the default values of these variables?
>
> I'm not really that concerned in general, but in this case, the entire
> problem is apparently due to one function --
> byte-compile--first-symbol-with-pos -- that's very recursive.  It could
> be rewritten to not be recursive, and these problems would go away
> (which we've seen in many contexts now), if I understand correctly.

The patch below should significantly reduce the recursion depth (and
hopefully make it faster, to boot) because the (loop (cdr form)) call is
in tail position (and named-let should hence apply TCO to it).

Does it help for modus-themes?

        Stefan

diff --git a/lisp/emacs-lisp/bytecomp.el b/lisp/emacs-lisp/bytecomp.el
index 87798288fb5..6e9ad39c6a7 100644
--- a/lisp/emacs-lisp/bytecomp.el
+++ b/lisp/emacs-lisp/bytecomp.el
@@ -1183,28 +1183,23 @@ byte-compile-abbreviate-file
 (defun byte-compile--first-symbol-with-pos (form)
   "Return the \"first\" symbol with position found in form, or 0 if none.
 Here, \"first\" is by a depth first search."
-  (let (sym)
-    (cond
-     ((symbol-with-pos-p form) form)
-     ((consp form)
-      (or (and (symbol-with-pos-p (setq sym (byte-compile--first-symbol-with-pos (car form))))
-               sym)
-          (and (symbolp (setq sym (byte-compile--first-symbol-with-pos (cdr form))))
-               sym)
-          0))
-     ((and (or (vectorp form) (recordp form))
-           (> (length form) 0))
-      (let ((i 0)
-            (len (length form))
-            elt)
-        (catch 'sym
-          (while (< i len)
-            (when (symbol-with-pos-p
-                   (setq elt (byte-compile--first-symbol-with-pos (aref form i))))
-              (throw 'sym elt))
-            (setq i (1+ i)))
-          0)))
-     (t 0))))
+  (or (named-let loop ((form form))
+        (cond
+         ((symbol-with-pos-p form) form)
+         ((consp form)
+          (or (loop (car form))
+              (loop (cdr form))))
+         ((and (or (vectorp form) (recordp form))
+               (> (length form) 0))
+          (let ((i 0)
+                (len (length form))
+                elt)
+            (catch 'sym
+              (while (< i len)
+                (when (setq elt (loop (aref form i)))
+                  (throw 'sym elt))
+                (setq i (1+ i))))))))
+      0))
 
 (defun byte-compile--warning-source-offset ()
   "Return a source offset from `byte-compile-form-stack'.