[antlr-interest] Export Parse Tree Graph

Le Hyaric Bruno bruno.le-hyaric at fr.thalesgroup.com
Fri Apr 16 05:38:33 PDT 2010


Hi, I made something like that in Python for my personal use :


import os

import antlr3.tree


# Path d'installation de graphviz
DOT = r' PATH TO DOT.EXE '



def __scan(node):
    """
        Simple top-down recursive scan of the tree
        to build the DOT graph definition
    """
    graph = str()
    if node.parent:
        node_id = str(hash(node))
        parent_id = str(hash(node.parent))
        node_label = str(node.getText()).replace('"','\\"') + ':' + str(node.getType())
        parent_label = str(node.parent.getText()).replace('"','\\"') + ':' + str(node.parent.getType())
        graph += '\t"' + parent_id + '" [label="' + parent_label + '"];\n'
        graph += '\t"' + node_id + '" [label="' + node_label + '"];\n'
        graph += '\t"' + parent_id + '" -> "' + node_id + '";\n'
    for child in node.children:
        graph += __scan(child)
    return graph

def __ast_to_dot(node, graph_name):
    """
        Build the DOT graph definition
    """
    body_graph = __scan(node)
    
    dot_graph = str()
    dot_graph += 'digraph "' + graph_name + '" {\n'
    dot_graph += body_graph
    dot_graph += '}\n'
    
    return dot_graph

def ast_graph(node,filename):
    """
        Build the DOT graph definition, save it in a DOT file
        then call graphviz/dot.exe to build the SVG file
        
        DON'T USE THIS ON BIG ADA SOURCE FILE
        
        (SVG file can be viewed with Firefox)
    """
    if not(isinstance(node,antlr3.tree.CommonTree)):
        raise 'node must be a antlr3.tree.CommonTree'
    dot_graph = __ast_to_dot(node, os.path.basename(filename).replace('.','_'))
    
    dot_path = filename.replace('.','_') + '.dot'
    dot_file = open(dot_path,'w')
    dot_file.write(dot_graph)
    dot_file.close()
    
    svg_path = os.path.splitext(filename)[0] + '.svg'
    cmd = DOT + ' -Tsvg -o "' + svg_path + '" "' + dot_path + '"'
    print cmd
    os.system(cmd)




> Hi,
> I'm currently using ANTLR v3 with the language = Python option.
> Is there a way to export the interpreted parse tree graph(as seen in the
> interpreter section of ANTLRWorks) to a dot file or a bitmap image without
> using ANTLRWorks?
> With thanks.



More information about the antlr-interest mailing list