From be8cb5d069e378c17edd456fd5040eea8b759aae Mon Sep 17 00:00:00 2001
From: "Tarn W. Burton" <twburton@gmail.com>
Date: Tue, 21 Feb 2023 07:48:12 -0500
Subject: [PATCH] Avoid inserting NIL into simple LOOP from FORMAT

---
 src/code/format.lisp |  3 ++-
 tests/printer.lisp   | 13 +++++++++++++
 2 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/src/code/format.lisp b/src/code/format.lisp
index 7a2de48c7..715047901 100644
--- a/src/code/format.lisp
+++ b/src/code/format.lisp
@@ -399,7 +399,8 @@
 	  (form new-directives)
 	  (expand-directive (car remaining-directives)
 			    (cdr remaining-directives))
-	(push form results)
+	(when form
+          (push form results))
 	(setf remaining-directives new-directives)))
     (reverse results)))
 
diff --git a/tests/printer.lisp b/tests/printer.lisp
index 5c958448a..8870c6b8f 100644
--- a/tests/printer.lisp
+++ b/tests/printer.lisp
@@ -113,3 +113,16 @@
 
 (define-test sub-output-integer.1
     (assert-prints "-536870912" (princ most-negative-fixnum)))
+
+;;; Simple LOOP requires only compound forms. Hence NIL is not
+;;; permitted. Some FORMAT directives (like newline) return NIL
+;;; as the form when they have nothing to add to the body.
+;;; Normally this is fine since BLOCK accepts NIL as a form. On
+;;; the other hand, when the newline directive is inside of an
+;;; iteration directive this will produce something like
+;;; (LOOP (fu) nil (bar)) which is not acceptable. To verify
+;;; that this is not happening we make sure we are not getting
+;;; (BLOCK NIL NIL) since this is easier to test for.
+(define-test format-no-nil-form.1
+    (assert-equal '(block nil) (third (second (macroexpand-1 '(formatter "~
+"))))))
-- 
GitLab