첫째, 리스너 이벤트가 더 구체적으로 확인하기 위해 문법을 주석 것 :
:이 같은 특정 청취자를 만들 수 있습니다
grammar Expr;
prog: stmt+ EOF;
stmt: expr NEWLINE+;
expr:
expr ('*'|'/') expr # Mult
| expr ('+'|'-') expr # Add
| INT # Int
| '(' expr ')' # Paren
;
NEWLINE : '\r\n';
INT : [0-9]+ ;
public class ExprListener : ExprBaseListener
{
private Stack <int> stack = new Stack <int>();
public override void ExitInt(ExprParser.IntContext context)
{
int i = Convert.ToInt32(context.INT().GetText());
stack.Push(i);
}
public override void ExitStmt(ExprParser.StmtContext context)
{
int result = stack.Pop();
Console.WriteLine("result " + result);
}
public override void ExitMult(ExprParser.MultContext context)
{
int r = stack.Pop();
int l = stack.Pop();
string op = context.GetChild(1).GetText();
int result;
if (op == "*")
result = l * r;
else
result = l/r;
stack.Push(result);
}
public override void ExitAdd(ExprParser.AddContext context)
{
int r = stack.Pop();
int l = stack.Pop();
string op = context.GetChild(1).GetText();
int result;
if (op == "+")
result = l + r;
else
result = l - r;
stack.Push(result);
}
}