Reputation: 2063
I know there are tutorials for such but none of them have been helpful so far, googled for the past like 5 hours but still no success. Am trying to build a simple arithmetics calculator and I found a perfect language for online, I have built using the jar file to generate project files for c# but am stuck there. Here is the grammer
grammar testGrammer;
/*
* Parser Rules
*/
compileUnit
: expression + EOF
;
expression
: multiplyingExpression ((PLUS | MINUS) multiplyingExpression)*
;
multiplyingExpression
: powExpression ((TIMES | DIV) powExpression)*
;
powExpression
: atom (POW atom)*
;
atom
: scientific
| variable
| LPAREN expression RPAREN
| func
;
scientific
: number (E number)?
;
func
: funcname LPAREN expression RPAREN
;
funcname
: COS
| TAN
| SIN
| ACOS
| ATAN
| ASIN
| LOG
| LN
;
number
: MINUS? DIGIT + (POINT DIGIT +)?
;
variable
: MINUS? LETTER (LETTER | DIGIT)*
;
COS
: 'cos'
;
SIN
: 'sin'
;
TAN
: 'tan'
;
ACOS
: 'acos'
;
ASIN
: 'asin'
;
ATAN
: 'atan'
;
LN
: 'ln'
;
LOG
: 'log'
;
LPAREN
: '('
;
RPAREN
: ')'
;
PLUS
: '+'
;
MINUS
: '-'
;
TIMES
: '*'
;
DIV
: '/'
;
POINT
: '.'
;
E
: 'e' | 'E'
;
POW
: '^'
;
LETTER
: ('a' .. 'z') | ('A' .. 'Z')
;
DIGIT
: ('0' .. '9')
;
/*
* Lexer Rules
*/
WS
:[ \r\n\t] + -> channel(HIDDEN)
;
and here is its properties
The following are the project files
I know there should be some visitor class but am seriously stuck. I don't know how to proceed from here and to be honest it is my first time working with ANTLR or any other language parsers. Here is what I have so far and as you can see it's giving me a bunch of errors.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Antlr4.Runtime;
using Antlr4.Runtime.Tree;
namespace ExpressionParser
{
class Program
{
static void Main(string[] args)
{
String input = "3625";
ICharStream stream = CharStreams.fromString(input);
ITokenSource lexer = new testGrammerLexer(stream);
ITokenStream tokens = new CommonTokenStream(lexer);
testGrammerParser parser = new testGrammerParser(tokens);
parser.buildParseTrees = true;
IParseTree tree = parser.StartRule();
}
}
}
Any help please, thanks in advance.
Upvotes: 0
Views: 2100
Reputation: 1389
You dont have to use CharStream. Use this:
AntlrInputStream input = new AntlrInputStream("3625");
ITokenSource lexer = new testGrammerLexer(input);
ITokenStream tokens = new CommonTokenStream(lexer);
testGrammerParser parser = new testGrammerParser (tokens);
IParseTree tree = parser.compileUnit();
If you want to implement a Listener use this:
YourListener expressionWalker = new YourListener();
ParseTreeWalker walker = new ParseTreeWalker(); //get the walker
walker.Walk(tablesWalker, tree);
You have to create YourListener:
public class TablesWalker : testGrammerBaseListener
{
//override methods to evaluate expression
}
Upvotes: 1