[antlr-interest] Small snippet to print TreeView

Subhobroto Sinha subhobrotosinha at rediffmail.com
Tue Jul 5 12:24:17 PDT 2005


  
Hi mates

I modified Barry Kelly's code to print out an AST to show a clear child-sibling relationship in a view consistent with those given in the official docs.

Be very careful, in that I wrote AND tested the code in about 10 minutes. I do expect bug reports from you - I will be very disappointed to the contrary.

Enjoy, and please share any comments and changes you make to the snippet. It's in C++.

////////
static void RecurseIntoMyAST(const RefAST& root, const string& strSpacing = "")
{
	if(root == NULL) return; /* You may leave this out */
	
	//Print this node
	cout << strSpacing << root->getText();
	
	//Print all children
	
	for(RefAST child = root->getNextSibling(); child != NULL; child = child->getNextSibling())
	{
		cout << " - " << child->getText();
		
		if(child->getFirstChild() != NULL)
		{
			string strTemp = strSpacing + "    ";
			cout << "\n" << strTemp << "|\n";
			RecurseIntoMyAST(child->getFirstChild(), strTemp);
		}
	}

	if(root->getFirstChild() != NULL)
	{
		cout << "\n" << strSpacing << "|\n";
		RecurseIntoMyAST(root->getFirstChild(), strSpacing);
	}
}
////////

Simply call this on 'parser.getAST()' - it's your call..

I would like if somebody fixed the alignment however (it now is aligned well only for single characters)

Regards

Subhobroto Sinha

http://www.geocities.com/subhobrotosinha
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20050705/e35274e2/attachment.html


More information about the antlr-interest mailing list