[antlr-interest] Re: Getting Column and Line in CPP AST's

jenlhunt2003 steam at tapisinc.com
Fri Feb 13 08:00:51 PST 2004


Ric Klaren sent me the following custom AST for 2.7.2/3 based on Peter
Morlings getLine() program (found at
http://www.imada.sdu.dk/~morling/issue4.htm.  I have succesfully used
this with VC++6.  Thanks Ric!

my_ast.h
//////////////////////////////////////
#ifndef __MY_AST_H__
#define __MY_AST_H__

#include <string>
#include <antlr/CommonAST.hpp>

class MyAST;

typedef ANTLR_USE_NAMESPACE(antlr)ASTRefCount<MyAST> RefMyAST;

class MyAST : public ANTLR_USE_NAMESPACE(antlr)CommonAST {
public:
	MyAST( const MyAST& other )
	: CommonAST(other)
	, line(other.line)
	{
	}
	MyAST( void ) : CommonAST(), line(0) {}
	virtual ~MyAST( void ) {}
	virtual int getLine( void ) const
	{
		// most of the time the line number is not set if the node is a
		// imaginary one. Usually this means it has a child. Refer to the
		// child line number. Of course this could be extended a bit.

		if ( line != 0 )
			return line;
		if( getFirstChild() )
			return ( RefMyAST(getFirstChild())->getLine() );
		return 0;
	}
	virtual void setLine( int l )
	{
		line = l;
	}
	virtual void initialize(int t, const ANTLR_USE_NAMESPACE(std)string&
txt)
	{
		CommonAST::initialize(t,txt);
		line = 0;
	}
	virtual void initialize( ANTLR_USE_NAMESPACE(antlr)RefToken t )
	{
		CommonAST::initialize(t);
		line = t->getLine();
	}
	virtual void initialize( RefMyAST ast )
	{
		CommonAST::initialize(ANTLR_USE_NAMESPACE(antlr)RefAST(ast));
		line = ast->getLine();
	}
	// for convenience will also work without
	void addChild( RefMyAST c )
	{
		BaseAST::addChild( ANTLR_USE_NAMESPACE(antlr)RefAST(c) );
	}
	// for convenience will also work without
	void setNextSibling( RefMyAST c )
	{
		BaseAST::setNextSibling( ANTLR_USE_NAMESPACE(antlr)RefAST(c) );
	}

	virtual ANTLR_USE_NAMESPACE(antlr)RefAST clone( void )
	{
		return ANTLR_USE_NAMESPACE(antlr)RefAST(new MyAST(*this));
	}
	static ANTLR_USE_NAMESPACE(antlr)RefAST factory( void )
	{
		return ANTLR_USE_NAMESPACE(antlr)RefAST(RefMyAST(new MyAST()));
	}
private:
	int line;
};

#endif

//////////////////////////////////////
Usage:

#include "my_ast.h"

ASTLabelType = "RefMyAST";

RefMyAST t = parser.getAST();

ASTFactory ast_factory("MyAST",MyAST::factory);
parser.initializeASTFactory(ast_factory);
parser.setASTFactory(&ast_factory);

walker.TopRule(t);



 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
     http://groups.yahoo.com/group/antlr-interest/

<*> To unsubscribe from this group, send an email to:
     antlr-interest-unsubscribe at yahoogroups.com

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



More information about the antlr-interest mailing list