[antlr-interest] Formatter Implementation

Alex Sedow alexsedow at mail.ru
Tue Jan 4 02:50:56 PST 2005


I try to write formatter which generates the program using a AST-tree. How
it is better for making? It is necessary to use AST-visitor or to write
corresponding function in each AST-node?

The basic problem with AST-visitor consists that AST-node can contain a
number of tokens and children. Each child can generate any number of tokens.
For example for-statement generates the following sequence of tokens:

"for" "(" initializer-tokens ";" condition-tokens ";" iterator-tokens ")"
statement-tokens

The task of the formatter will consist in pasting tokens of the parent and
children and adding additional tokens like whitespace, newline, etc. The
variant with classical AST-visitor does not approach because each AST-node
is visited only once. Therefore I while have stopped on a variant with
expanded AST-visitor which in addition visits AST-node after each child. For
for-statement it will look so:

<-visitForStatementBefore
visit initializer
<-visitForStatementInner1AfterInitializer
visit condition
<-visitForStatementInner2AfterCondition
visit iterator
<-visitForStatementInner3AfterIterator
visit statement
<-visitForStatamentAfter

For full C# grammar it is rather bulky. About 500 functions in expanded
AST-visitor.

If somebody has experience in a writting formaters then please suggest idea.

Alex.



More information about the antlr-interest mailing list