From 8388c9416a2a99e667d80c546901a4d930ed1d69 Mon Sep 17 00:00:00 2001
From: Peter Bex <peter@more-magic.net>
Date: Sun, 11 Apr 2021 12:52:20 +0200
Subject: [PATCH] Resolve variable in set! using "lookup" when variable is not
 global

This allows dropping the lookup in ##sys#current-environment
from ##sys#alias-global-hook because lookups when setting variables
now match lookups when dereferencing variables.

This currently only works inside the compiler; there is still a
problem in the interpreter causing the test to fail.
---
 core.scm               |  5 +++--
 modules.scm            |  2 +-
 tests/module-tests.scm | 22 ++++++++++++++++++++++
 3 files changed, 26 insertions(+), 3 deletions(-)

diff --git a/core.scm b/core.scm
index 492a23a7..e3e173a4 100644
--- a/core.scm
+++ b/core.scm
@@ -1174,8 +1174,9 @@
 					 ((assq var0 (##sys#current-environment))
 					  (warning
 					   (sprintf "~aassignment to imported value binding `~S'"
-					    (if ln (sprintf "(~a) - " ln) "") var0)))))
-				 `(set! ,var ,(walk val e var0 (memq var e) h ln #f))))))
+					     (if ln (sprintf "(~a) - " ln) "") var0)))))
+				 (let ((var (lookup var)))
+				   `(set! ,var ,(walk val e var0 (memq var e) h ln #f)))))))
 
 			((##core#debug-event)
 			 `(##core#debug-event
diff --git a/modules.scm b/modules.scm
index 29fb92e5..8393654f 100644
--- a/modules.scm
+++ b/modules.scm
@@ -804,7 +804,7 @@
 	  (else sym)))
   (cond ((keyword? sym) sym)
 	((namespaced-symbol? sym) sym)
-	((assq sym (##sys#current-environment)) =>
+	#;((assq sym (##sys#current-environment)) =>
 	 (lambda (a)
 	   (let ((sym2 (cdr a)))
 	     (dm "(ALIAS) in current environment " sym " -> " sym2)
diff --git a/tests/module-tests.scm b/tests/module-tests.scm
index ec447e45..5054ee8a 100644
--- a/tests/module-tests.scm
+++ b/tests/module-tests.scm
@@ -380,6 +380,28 @@
    (import (scheme) (chicken module))
    (eq? (current-module) 'm33)))
 
+;; #1131 Undefined variables for macros from other modules should not
+;; be looked up in the current environment
+(module undef (undefined)
+  (import scheme)
+  (define undefined 1))
+
+(module expando (do-it)
+  (import scheme)
+  (define-syntax do-it
+    (syntax-rules ()
+      ((_)
+       (let-syntax ((final
+                     (syntax-rules ()
+                       ((_ ?x) ?x))))
+         (final undefined))))))
+
+(import undef expando)
+;; Should fail, not return 1, because the let-syntax expansion should
+;; rename introduced identifiers from its SE (but input should be
+;; looked up here)
+(assert-error "Undefined variable should be undefined" (do-it))
+
 (test-end "modules")
 
 (test-exit)
-- 
2.20.1

