[racket] Managing communication between two macro invocations at the top-level

From: Robby Findler (robby at eecs.northwestern.edu)
Date: Mon Jul 21 10:08:05 EDT 2014

I think you want to use the trick Matthew pointed out on the list a
while back where you expand into begin-for-syntax to do the set! so
the expander has a chance to see the identifier. This seems to make it
work. Eg, with tmp2.rkt containing this:

(require (for-syntax syntax/parse))
(define-for-syntax the-id #f)
(define-syntax (def-and-use-of-x stx)
  (syntax-parse stx
    [(def-and-use-of-x val)
     (with-syntax ([gen-id (car (generate-temporaries '(x)))])
       #'(begin
           (begin-for-syntax
             (set! the-id #'gen-id))
           (define gen-id val)
           gen-id))]))
(define-syntax (produce-id stx) the-id)
(def-and-use-of-x 3)
(produce-id)

then this works:

$  cat ~/tmp2.rkt | racket
Welcome to Racket v6.1.0.3.
> > > > > 3
> 3
>

Robby


On Mon, Jul 21, 2014 at 8:50 AM, Asumu Takikawa <asumu at ccs.neu.edu> wrote:
> On 2014-07-21 09:18:05 -0400, Matthias Felleisen wrote:
>> I have used this on one occasion. Does it work for you?
>
> I don't think it will work because in my situation at the top-level, the
> definition `(define a 10)` comes in a separate `begin` block (IOW, in another
> interaction) which breaks the connection.
>
> Here's an example showing the error you'd get:
>
>   -> (define-for-syntax id #f)
>   -> (define-syntax (def-and-use-of-x stx)
>        (syntax-parse stx
>          [(def-and-use-of-x val)
>           (with-syntax ([gen-id (generate-temporary)])
>             (set! id #'gen-id)
>             #'(begin (define gen-id val) gen-id))]))
>   -> (define-syntax (produce-id stx) id)
>   -> (def-and-use-of-x 3)
>   3
>   -> (produce-id)
>   ; g1: unbound identifier;
>   ;  also, no #%top syntax transformer is bound
>   ;   in: g1
>   ; [,bt for context]
>
> Cheers,
> Asumu
> ____________________
>   Racket Users list:
>   http://lists.racket-lang.org/users

Posted on the users mailing list.