[plt-scheme] Tricks with eval and namespaces

From: Arjun Guha (garjun at cs.brown.edu)
Date: Mon Aug 1 15:30:56 EDT 2005


We have a type inference algorithm for an ML-ish language written as a 
language in PLT Scheme.  So, when we execute:

(module test (lib "lang/r5rs-tinfer.ss" "dungeon")

   (define err (lambda () (+ 1 #t))))

we get a type error.  We'd like to test individual expressions to see if 
they are well-typed or not.  However, the language requires an entire 
module.  So, we tried to create a function that takes an expression as a 
syntax object, wraps it in a (module ...) and evaluates it in a new 

(module ill-typed-expressions mzscheme

   (require (only (lib "lang/r5rs-tinfer.ss" "dungeon")))

   (define (test/error stx)
     (parameterize ([current-namespace (make-namespace)])
            (module a (lib "lang/r5rs-tinfer.ss" "dungeon")
              #, at stx)
            (require a)))))

    #'((define foo
        (+ #t 43)))))

However, when test/error evaluates, we get:

define-types-cgen: bad syntax in: (define-types-cgen (define-values (foo) 
(+ #t 43)))

The custom language doesn't bind define to anything, so we are vaguely 
surprised that define is getting expanded to define-values.

Here's a simpler example:

(module a mzscheme

   (define-syntax (my-define stx)
     (syntax-case stx ()
       [(_ name expr) #'(printf "~a defined as ~a" 'name 'expr)]))

   (define-syntax (my-module-begin stx)
     (syntax-case stx ()
       [(_ defn ...) #'(begin
                         defn ...)]))

   (provide (rename my-define define) (rename my-module-begin 

(module b mzscheme

   (require (only "a.ss"))

   (define (strange-eval stx)
     (parameterize ([current-namespace (make-namespace)])
            (module dummy-name "a.ss"
            (require dummy-name)))))

   (define f (strange-eval #'(define f "g"))))

Which gives:

Welcome to DrScheme, version 299.106-svn16jun2005.
Language: (module ...).
. errortrace: unrecognized expression form at top-level: (module 
dummy-name "a.ss" (begin (define-values (f) (#%datum . "g"))))

Again, the define is being expanded to define-values, even though a.ss 
has a custom definition for it.

We've tried various random/creative variants of this technique.  Any help 
would be appreciated.


-Arjun and Co.

Posted on the users mailing list.