ANTLR4 Lexer听众

时间:2017-05-12 19:33:11

标签: java antlr antlr4

在Antlr4中,我如何拦截所有INT / NEWLINE令牌解析? 我想像听众一样痴迷。

鉴于语言:

 grammar Expr;      
    prog:   (expr NEWLINE)* ;
    expr:   expr ('*'|'/') expr
        |   expr ('+'|'-') expr
        |   INT
        |   '(' expr ')'
        ;
    NEWLINE : [\r\n]+ ;
    INT     : [0-9]+ ;


Css3Lexer lexer = new Css3Lexer(this.file.getStreamAntlr()); 
Css3Parser parser = new Css3Parser(new CommonTokenStream(lexer)); 
parser.addParseListener(..)// doesnt resolve.

1 个答案:

答案 0 :(得分:1)

首先,我会注释你的语法,使听众事件更具体:

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);
    }
}