On Fri, Nov 16, 2018 at 12:43 PM Andrew Wilcox <andrew.wil...@gmail.com> wrote:
>
> I'd like to be able to eval a custom language from inside a module... without 
> instantiating modules multiple times.
>
> With the help of Matthew Butterick, I've gotten this far:
>
> ; runtime.rkt
> #lang racket
>
>
> (printf "This is runtime.rkt~n")
>
>
>
> ; example.rkt
> #lang racket
>
> (require "runtime.rkt")
>
> (provide foo)
>
> (printf "This is example.rkt~n")
>
> (define-syntax foo
>   (syntax-rules ()
>     ((foo)
>      (printf "foo!~n"))))
>
>
>
> ; eval-example.rkt
> #lang racket
>
> (require racket/runtime-path)
>
> (require "runtime.rkt")
>
> (provide eval-example)
>
> (define-runtime-path example "example.rkt")
>
> (define example-namespace (make-base-empty-namespace))
>
> (parameterize ((current-namespace example-namespace))
>   (namespace-require example))
>
> (define (eval-example code)
>   (parameterize ((current-namespace example-namespace))
>     (eval code)))
>
>
> however this instantiates runtime.rkt twice:
>
> $ racket eval-example.rkt
> This is runtime.rkt
> This is runtime.rkt
> This is example.rkt
>
>
> which turns out to be bad (for example, if I define a struct in the runtime, 
> I end up having a different struct types).  I want there to be a single copy 
> of the runtime.rkt module (much like if I had said (require "runtime.rkt") 
> from two different modules).
>
> What I want to do is rather simple (I hope): define a custom language in a 
> module such as example.rkt, and then be able to eval that language.
>
> Is there a way to do this?
>

Because eval-example.rkt creates a new, independent namespace and runs
example.rkt in the new namespace, the modules eval-example.rkt and
example.rkt will have different instantiations of runtime.rkt. The
workaround, therefore, is to share the instantiation of runtime.rkt.
However, sharing also implies that eval-example.rkt could be affected
by example.rkt unexpectedly.

There are two ways to share the instantiation of runtime.rkt.

1. Keep the new namespace, but use namespace-attach-module to attach
runtime.rkt from eval-example.rkt to example-namespace before
(namespace-require example).

;; eval-example.rkt
> (define-runtime-module-path runtime "runtime.rkt")
> (define-namespace-anchor here)
> (define host (namespace-anchor->namespace here))
> (parameterize ((current-namespace example-namespace))
>   (namespace-attach-module host runtime)
>   (namespace-require example))

2. Just use the same namespace as eval-example.rkt

;; eval-example.rkt
> (define-namespace-anchor here)
> (define example-namespace (namespace-anchor->namespace here))

Both methods need to be used with care.

-- 
You received this message because you are subscribed to the Google Groups 
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to racket-users+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to