Dear Racket list,<br><br>Once again, I need a little help on a macro definition.<br><br>I want to define the following (simplified[1]) macro:<br>(define-syntax-rule/id [<i>id id-gen</i>] <i>body</i>)<br><br>where id is replaced with the result of id-gen inside body.<br>
For example:<br>(define-syntax-rule/id <br> [x #'foo]<br> (begin (define x 5)<br> (displayln x)))<br><br>is supposed to bind foo to 5 in the top-level at run-time.<br>(You can replace #'foo by some complex identifier-making expression using format-id.)<br>
Here is what I have right now, after much trial&error:<br><br>#lang racket<br><br>(require (for-syntax unstable/syntax)<br> (for-syntax errortrace/errortrace-key)<br> racket/splicing<br> )<br>
<br>
(provide (all-defined-out))<br><br>;; Like define-syntax-rule,<br>;; but id is replaced with the result of id-gen in body.<br>;; id-gen is eval'ed at macro-time.<br>(define-syntax (define-syntax-rule/id stx)<br> (syntax-case stx ()<br>
[(_ [id id-gen] body)<br> (with-syntax ([id-def (syntax-local-eval #'id-gen)])<br> #'(splicing-let-syntax ([tmp-form (syntax-rules ()<br> [(_ id) (begin (displayln 'body)<br>
body)])])<br> (tmp-form id-def))<br> )]<br> ))<br><br>;;; TESTS<br><br>(define-syntax-rule/id <br> [x #'foo]<br> (begin (define x 5)<br> (displayln x)<br>
(displayln 'x)<br> ))<br><br><br>It works (foo is bound to 5), except that foo is unknown (undefined identifier) after the (begin ...).<br>I suspect this is because of syntax-local-eval, but I don't know what to use instead.<br>
<br>There is another intriguing thing:<br>if just after (define x 5) we add (provide x), and in another file we require the first file, then foo is actually defined and can be used normally!<br>Why is that and why does this not work when there is no (provide x) ? [note that there is a (provide (all-defined out)).]<br>
<br>Can someone give me a hint as to what is going on?<br><br>I also suspect that using splicing-let-syntax is not the way to go, but again I don't know what to use otherwise, that would let me replace id with id-def.<br>
<br>Thank you very much,<br>Laurent<br><br><br>[1] To explain the name: once finished, this macro will be supposed to behave like an augmented version of define-syntax-rule but with explicit hygiene breaking:<br><br>(define-syntax-rule/id (make-getter id)<br>
[id2 (format-id #'here "get-~a" id)]<br> (define (id2) id))<br><br>which, when called on (make-getter foo) would create the get-foo function.<br>