How to print an AST without formatting?

85 views
Skip to first unread message

ju...@sqreen.io

unread,
Jan 9, 2020, 10:22:56 AM1/9/20
to golang-nuts
Hello,

I am looking for a way to keep to original token positioning but I cannot find how to avoid it when using `go/printer` or `go/format`.
Basically, how to make this example print the same string that was parsed: https://play.golang.org/p/dI7WcevQJAZ

Thanks for your help!
Julio

Julio Guerra

unread,
Jan 9, 2020, 10:39:41 AM1/9/20
to golang-nuts
I saw `go tool cover` does it, but I don't see anything else but a simple call to printer.Fprint(w, f.fset, f.astFile) at https://github.com/golang/tools/blob/master/cmd/cover/cover.go#L384

David Finkel

unread,
Jan 10, 2020, 12:35:58 PM1/10/20
to ju...@sqreen.io, golang-nuts
In the general case, this is not possible because the `go/ast` package types drop the positions of some tokens. (e.g. the `range` token in a `for := range` loop)
I'm reasonably certain code is only likely to round-trip (via `go/format.Node`) if it was previously formatted with the same version's `gofmt` (or `go/format.Source`).

Based on the documentation on `go/printer`'s `Fprint` function, it doesn't seem to make any guarantees about matching the parsed format. From that doc:
Fprint "pretty-prints" an AST node to output. It calls Config.Fprint with default settings. Note that gofmt uses tabs for indentation but spaces for alignment; use format.Node (package go/format) for output that matches gofmt.

I wish I had more helpful advice.

Thanks for your help!
Julio

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/fbf8e5b6-f237-470c-9267-246132a2e0bc%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages