Question

I try to parse C++ source files with antlr3 generated parser for the Python runtime. I need to make some changes in grammar, and i whant to draw syntax tree using generated parser in order to verify that my changes is correct, how can i do this?

Simple sample, syntax tree of which i need:

int main (){
  int a = 4;
  return a;
}

PS: sorry for my english.

Was it helpful?

Solution

As far as I know, there does not exist a way to draw an AST from the output of an ANTLR 3 parse using a Python library/app.

Here is a way to print a level order traversal of the AST on your console (assuming your grammar is called Cpp.g):

#!/usr/bin/env python

import antlr3
from antlr3 import *
from antlr3.tree import *
from CppLexer import *
from CppParser import *

def print_level_order(tree, indent):
  print '{0}{1}'.format('   '*indent, tree.text)
  for child in tree.getChildren():
    print_level_order(child, indent+1)

input = """
  int main (){
    int a = 4;
    return a;
  }
"""
char_stream = antlr3.ANTLRStringStream(input)
lexer = CppLexer(char_stream)
tokens = antlr3.CommonTokenStream(lexer)
parser = CppParser(tokens)
tree = parser.parse().tree 
print_level_order(tree, 0)

The snippet came from: ANTLR parsing MismatchedTokenException

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top