Pretty Printing for ASTs represented as structs

85 views
Skip to first unread message

Jeremy Siek

unread,
Aug 16, 2020, 4:48:50 PM8/16/20
to Racket Users

Hi All,

I'm looking into using Racket structs to represent abstract syntax trees.
I've gotten as far as defining gen:custom-write properties, but have not
yet figured out how to control indenting. Also, I'm not sure I'm just calling
write-string, write, and newline in my gen:custom-write methods, which I
suspect is not exactly correct.

Are there some good up-to-date examples of this that I could look at?

Thanks,
Jeremy

jackh...@gmail.com

unread,
Aug 16, 2020, 5:10:20 PM8/16/20
to Racket Users
I recommend using make-constructor-style-printer, which automates a lot of the fiddly indentation-handling you'd have to do otherwise.

Jay McCarthy

unread,
Aug 16, 2020, 6:05:04 PM8/16/20
to Jeremy Siek, Racket Users
I recommend defining the structs with `#:transparent` and just using `pretty-write` or `pretty-print`.

Jay

--
Jay McCarthy
Associate Professor @ CS @ UMass Lowell
http://jeapostrophe.github.io
Vincit qui se vincit.


--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/racket-users/550ad1e1-90af-4f6d-8f31-57fccfe2d25an%40googlegroups.com.

Jeremy Siek

unread,
Aug 17, 2020, 8:37:53 AM8/17/20
to Racket Users
Thanks for the tip!

I found the following to work pretty well :)

#lang racket
(require racket/match)
(require racket/struct)

(struct Var (name)
   #:methods gen:custom-write
  [(define (write-proc ast port mode)
     (match ast
       [(Var x)
        (write x port)]))])

(struct Num (value)
   #:methods gen:custom-write
  [(define (write-proc ast port mode)
     (match ast
       [(Num n)
        (write n port)]))])

(struct Let (var rhs body)
  #:methods gen:custom-write
  [(define write-proc
     (make-constructor-style-printer
      (lambda (obj) 'let)
      (lambda (obj) (list (unquoted-printing-string "([")
                          (Let-var obj)
                          (Let-rhs obj)
                          (unquoted-printing-string "])\n")
                          (Let-body obj)))))])
                         
(define x (Var 'x))
(define y (Var 'y))
(define n (Num 42))
(define l (Let x n (Let y n x)))
(pretty-print l)

Produced the output:

(let ([ x 42 ])
 (let ([ y 42 ])
 x))
Reply all
Reply to author
Forward
0 new messages