File: Main3.cpp

package info (click to toggle)
antlr 2.7.7%2Bdfsg-14
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 10,016 kB
  • sloc: java: 54,649; cs: 12,537; makefile: 8,854; cpp: 7,359; pascal: 5,273; sh: 4,333; python: 4,297; lisp: 1,969; xml: 220; lex: 192; ansic: 127
file content (66 lines) | stat: -rw-r--r-- 1,463 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
 * Different version of the calculator which parses the 
 * first command line argument. E.g. pass your expression as ./calc3 "1+1;"
 * argv[1] is mapped to a CharInputBuffer and then fed to the lexer
 */

#include <iostream>
#include <antlr/AST.hpp>
#include <antlr/CharInputBuffer.hpp>
#include "CalcLexer.hpp"
#include "CalcParser.hpp"
#include "CalcTreeWalker.hpp"

int main( int argc, char*argv[] )
{
	ANTLR_USING_NAMESPACE(std);
	ANTLR_USING_NAMESPACE(antlr);

	if( argc != 2 )
	{
		cerr << argv[0] << ": \"<expression>\"" << endl;
		return 1;
	}

	CharInputBuffer input( reinterpret_cast<unsigned char*>(argv[1]), strlen(argv[1]) );

	try
	{
		CalcLexer lexer(input);
		lexer.setFilename("<arguments>");

		CalcParser parser(lexer);
		parser.setFilename("<arguments>");

		ASTFactory ast_factory;
		parser.initializeASTFactory(ast_factory);
		parser.setASTFactory(&ast_factory);

		// Parse the input expression
		parser.expr();
		RefAST t = parser.getAST();
		if( t )
		{
			// Print the resulting tree out in LISP notation
			cout << t->toStringTree() << endl;
			CalcTreeWalker walker;

			// Traverse the tree created by the parser
			float r = walker.expr(t);
			cout << "value is " << r << endl;
		}
		else
			cout << "No tree produced" << endl;
	}
	catch(ANTLRException& e)
	{
		cerr << "Parse exception: " << e.toString() << endl;
		return -1;
	}
	catch(exception& e)
	{
		cerr << "exception: " << e.what() << endl;
		return -1;
	}
	return 0;
}