[plt-scheme] scope of module exports

From: Danny Yoo (dyoo at hkn.eecs.berkeley.edu)
Date: Tue Dec 12 18:23:25 EST 2006

(CCing johnnyb at eskimo.com, since I'm taking some of his code as an example 
and apply corrections.)


Hi Jon,

By the way, I did a quick read through:

     http://www-128.ibm.com/developerworks/linux/library/l-metaprog2.html

One of the macros there is really much more complicated than it needs to 
be.  Let me copy-and-paste it:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(module broken mzscheme
   (provide with-math-defines)
   (define-syntax with-math-defines
     (lambda (x)
       (syntax-case x ()
         ((with-math-defines expression)
          (with-syntax
              ((expr
                (datum->syntax-object
                 (syntax k)
                 `(let ((pi 3.14) (e 2.72))
                    ,(syntax-object->datum (syntax expression))))))
            (syntax expr)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


This is a bit broken because it erases lexical information through the use 
of syntax-object->datum.  Here's a concrete example of the problems we can 
see:

;;;;;;;;;;;;;;;;;;;;;;;;
(module golden mzscheme
   (provide golden)
   (define golden 1.618))

(module test-1 mzscheme
   (require broken
            golden)
   (with-math-defines
    (* golden pi)))
;;;;;;;;;;;;;;;;;;;;;;;;

If we try to compile TEST-1, things fail because because the GOLDEN 
binding from our GOLDEN module gets munged by SYNTAX-OBJECT->DATUM.


We can avoid this problem and simplify the macro at the same time:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(module fixed mzscheme
   ;; Correction to:
   ;; http://www-128.ibm.com/developerworks/linux/library/l-metaprog2.html
   (provide (all-defined))
   (define-syntax with-math-defines
     (lambda (stx)
       (syntax-case stx ()
         ((_ expression)
          (with-syntax ((pi (datum->syntax-object stx 'pi))
                        (e (datum->syntax-object stx 'e)))
            (syntax
             (let ((pi 3.14) (e 2.72))
               expression))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


And here, 'pi' 'e', and 'expression' are in the syntactic environment in 
the context of the (SYNTAX/LOC STX ...) subexpression.  'expression' was 
introduced by SYNTAX-CASE, and the other two from the WITH-SYNTAX.


Anyway, just wanted to give you another concrete example of WITH-SYNTAX in 
action.  Hope this helps!


Posted on the users mailing list.