gerbil icon indicating copy to clipboard operation
gerbil copied to clipboard

User-defined printers for structures

Open fare opened this issue 5 years ago • 5 comments

For debugging purposes, I would like to be able to see inside some of the structures I define, with a printing function that I define that will do the right thing for the structure at hand, skipping the ancillary data and showing the useful data in a way meaningful to the user.

Where are the hooks in Gerbil and/or Gambit that I will need to use to make this happen?

fare avatar Jan 06 '21 21:01 fare

You can define the :wr method and it will get invoked by the printer hook. Completely undocumented, you need to follow the gambit writer protocol which is also completely undocumented, you'll have to read the gambit sources.

But the hook is there, if we could have some documentation it could be great!

vyzo avatar Jan 06 '21 23:01 vyzo

@feeley on gitter notes:

@fare you need to use ##wr… the first parameter is the “write environment” which is a structure indicating what style of writing is happening (display, write, pretty-print, mark, etc) and the second parameter is the object to write. The mark style is used during the marking phase to detect cycles, so no actual writing happens in that “style”. Here’s for example how boxes are handled:

(define (##wr-box we obj)
  (case (macro-writeenv-style we)
    ((mark)
     (if (##wr-mark-begin we obj)
         (begin
           (##wr we (##unbox obj))
           (##wr-mark-end we obj))))
    (else
     (if (case (macro-writeenv-style we)
           ((print) #t)
           (else    (##wr-stamp we obj)))
         (begin
           (##wr-str we "#&")
           (##wr we (##unbox obj)))))))

fare avatar Jan 07 '21 01:01 fare

Here is a small gerbil example: https://gist.github.com/belmarca/d225ac1cca13f46d01528fead40200c3.

belmarca avatar Jan 07 '21 01:01 belmarca

Looks like the place macro-writeenv-style is used is in gambit/lib/_io.scm and I should pattern my definitions of wr methods after that.

fare avatar Jan 07 '21 04:01 fare

Nothing great, but there is now an working example in "production" in https://github.com/fare/gerbil-poo/blob/master/io.ss

fare avatar Jan 13 '21 17:01 fare