[antlr-interest] AST.getType() Question

Arnar Birgisson arnarb at oddi.is
Sat Oct 18 05:57:50 PDT 2003


Hello

> I know, but I want to know the token name from the AST, outside
parsing. I want to do it after it.
> Any suggestions?

I keep a reference to my parser alive and use it to get the name of the
token. I have a function to pretty-print AST in the Scheme style with
indenting and both lexemes (getText()) and token names:

void printTree(antlr::RefAST tree, std::ostream& out,
	antlr::Parser& p, int indent) {
  int j = indent;
  std::string i = ""; while (j-- > 0) i += "  ";
  if (tree->getFirstChild()) {
    out << i << "( " << tree->toString() << " <" <<
      p.getTokenName(tree->getType()) << ">" << std::endl;
    printTree(tree->getFirstChild(), out, p, indent+1);
    out << i << ")" << std::endl;
  } else {
    out << i << tree->toString() << " <" << 
      p.getTokenName(tree->getType()) << ">" << std::endl;
  }
  if (tree->getNextSibling()) {
    printTree(tree->getNextSibling(), out, p, indent);
  }
}

I use it like this:

ASTFactory my_factory;
MyParser parser(selector);

parser.initializeASTFactory(my_factory);
parser.setASTFactory(&my_factory);

parser.forrit();
RefAST ast = RefAST(parser.getAST());

if (ast) {
  printTree(ast, cout, parser);
} else {
  cout << "null AST" << endl;
}


Arnar


 

Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/ 




More information about the antlr-interest mailing list