Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change the result of a syntax-class?

Tags:

racket

I currently have a bunch of splicing syntax classes I use to generate code.
They look like this:

(define-splicing-syntax-class vec-exp
  (pattern (~seq x y)
    #:with result #'(vec x y)))

The goal is to be able to match a sequence x y anywhere and replace it with (vec x y).

The only way I see for now is by creating an attribute called result and use it:

> (syntax-parse #'(position 4.2 5.7)
    [(<name> <pos>:vec-exp)
     (attribute <pos>.result)])
#'(vec 4.2 5.7)

Is there a way to change my code so that I can get the same result by writing the following?

> (syntax-parse #'(position 4.2 5.7)
    [(<name> <pos>:vec-exp)
     (attribute <pos>)])
#'(4.2 5.7) ;; not what I want
like image 544
Zoé Martin Avatar asked Sep 13 '25 08:09

Zoé Martin


1 Answers

FWIW, you can do this. Not sure if it's acceptable for you or not.

(require syntax/parse
         (for-syntax syntax/parse))

(define-splicing-syntax-class vec-exp
  (pattern (~seq x y) #:with result #'(vec x y)))

(define-syntax ~res
  (pattern-expander
   (syntax-parser
     [(_ pat cls)
      #'(~and (~var PAT cls) (~bind [pat (attribute PAT.result)]))])))

And then:

> (syntax-parse #'(position 4.2 5.7)
    [(<name> (~res <pos> vec-exp))
     (attribute <pos>)])
#'(vec 4.2 5.7)
like image 84
Sorawee Porncharoenwase Avatar answered Sep 16 '25 07:09

Sorawee Porncharoenwase