[plt-scheme] Re: macros and eval

From: Jakub Piotr Cłapa (jpc-ml at zenburn.net)
Date: Sun Mar 16 19:49:32 EDT 2008

jomirez wrote:
> preferrably without any #lang header or any other "not strictly
> necessary" text (although if there is no way around this, i know i can
> simulate it in memory, or write it into another - temporary - file) ,
> so it won't confuse some of our half braindead admins ;-).

Put this code you showed in a separate module (let's name it 
backup-lang.ss) and then make something like this (see the end of the 
post for discussion):

#v+
(save-module this-module)

(eval-in-enriched-ns this-module ("backup-lang.scm")
   (load (vector-ref (current-command-line-arguments) 0)))
#v-

save-module and eval-in-enriched-ns are my helper functions:

#v+
(module avrp-common mzscheme
   (provide eval-in-enriched-ns
            module-path->symbol
            save-module)

   (define-syntax save-module
     (syntax-rules ()
       [(_ variable)
        (define variable
          (let loop ([m (syntax-source-module #'variable)])
            (if (symbol? m)
                m
                (let-values ([(name base) (module-path-index-split m)])
                  ((current-module-name-resolver)
                   name
                   (if base (loop base) #f)
                   #f)))))]))

   (define-syntax (eval-in-enriched-ns stx)
     (syntax-case stx ()
       [(eval-in-enriched-ns this-module (module-path ...)
          body ...)
        (with-syntax ([(module-symbol ...) (generate-temporaries 
#'(module-path ...))])
          #'(let ([new-ns (make-namespace)]
                  [module-symbol (module-path->symbol module-path 
this-module)] ...)
              (namespace-attach-module (current-namespace)
                                       module-symbol
                                       new-ns) ...
              (parameterize ([current-namespace new-ns])
                (namespace-require module-symbol) ...
                body ...)))]))


   (define (module-path->symbol module-path this-module)
     ((current-module-name-resolver) module-path this-module #f))
   )
#v-

This work quite well even in binaries created with mzc. The problems 
remaining:

1. save-module doesn't work in nested expressions (must be done on the 
module level; no, not because of the define it expands to but because 
the syntax-source-module + the recursive resolver don't work otherwise)

2. The naming should be improved.

3. There should be a simpler way to do module resolving in 3.99 but OTOH 
the principle remains the same.

PS. Maybe the dynamic-require could be tweaked to deal with this whole 
mess for us? We would (read-syntax) the whole file, wrap it in a module 
declaration and pass this to the dynamic-require machinery.

-- 
regards,
Jakub Piotr Cłapa


Posted on the users mailing list.