[antlr-interest] added org.antlr.runtime.tree.DOTTreeGenerator class

Terence Parr parrt at cs.usfca.edu
Wed Dec 13 17:07:43 PST 2006


Hi,

Needed for book, but formalized.

/** A utility class to generate DOT diagrams (graphviz) from
*  arbitrary trees.  You can pass in your own templates and
*  can pass in any kind of tree or use Tree interface method.
*  I wanted this separator so that you don't have to include
*  ST just to use the org.antlr.runtime.tree.* package.
*  This is a set of non-static methods so you can subclass
*  to override.  For example, here is an invocation:
*
*      CharStream input = new ANTLRInputStream(System.in);
*      TLexer lex = new TLexer(input);
*      CommonTokenStream tokens = new CommonTokenStream(lex);
*      TParser parser = new TParser(tokens);
*      TParser.e_return r = parser.e();
*      Tree t = (Tree)r.tree;
*      System.out.println(t.toStringTree());
*      DOTTreeGenerator gen = new DOTTreeGenerator();
*      StringTemplate st = gen.toDOT(t);
*      System.out.println(st);
*/

Assume grammar:

grammar T;
options {output=AST;}
e : m ('+'^^ m)* ;

m : a ('*'^^ a)* ;

a : INT
   | ID
   ;

INT : '0'..'9'+ ;

ID  : 'a'..'z'+ ;

WS : (' '|'\n')+ {$channel=HIDDEN;}
    ;

and test rig:

public class Test {
     public static void main(String[] args) throws Exception {
         CharStream input = new ANTLRInputStream(System.in);
         TLexer lex = new TLexer(input);
         CommonTokenStream tokens = new CommonTokenStream(lex);
         TParser parser = new TParser(tokens);
         TParser.e_return r = parser.e();
         Tree t = (Tree)r.tree;
         System.out.println(t.toStringTree());
         DOTTreeGenerator gen = new DOTTreeGenerator();
         StringTemplate st = gen.toDOT(t);
         System.out.println(st);
     }
}

Sample run:

$ java Test
3+4*5
(+ 3 (* 4 5))
digraph {
   node [shape=plaintext, fixedsize=true, fontsize=11,  
fontname="Courier",
         width=.4, height=.2];
   edge [arrowsize=.7]
   "+" -> "3"
   "+" -> "*"
   "*" -> "4"
   "*" -> "5"
}

looks like:

-------------- next part --------------
A non-text attachment was scrubbed...
Name: 345.png
Type: image/png
Size: 4262 bytes
Desc: not available
Url : http://www.antlr.org/pipermail/antlr-interest/attachments/20061213/e0536ede/attachment.png 
-------------- next part --------------

Oh, and antlr-dev folks: updated tree adaptor to impl getChild and  
getChildCount

edit //depot/code/antlr/main/README.txt#129
edit //depot/code/antlr/main/src/org/antlr/runtime/tree/BaseTree.java#13
edit //depot/code/antlr/main/src/org/antlr/runtime/tree/ 
CommonTreeAdaptor.java#14
add //depot/code/antlr/main/src/org/antlr/runtime/tree/ 
DOTTreeGenerator.java#1
Change 3331 submitted.

Ter


More information about the antlr-interest mailing list