ANTLR:省略'*'符号的乘法 [英] ANTLR: multiplication omiting '*' symbol

查看:97
本文介绍了ANTLR:省略'*'符号的乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一种用于对数字进行乘法和除法的语法,其中不需要包含'*'符号.我需要它来输出AST.所以对于这样的输入:

I'm trying to create a grammar for multiplying and dividing numbers in which the '*' symbol does not need to be included. I need it to output an AST. So for input like this:

1 2/3 4

我希望AST成为

(*(/(* 1 2)3)4)

(* (/ (* 1 2) 3) 4)

我遇到了以下内容,该内容使用Java代码创建了适当的节点:

I've hit upon the following, which uses java code to create the appropriate nodes:

grammar TestProd;

options {
  output = AST;
}

tokens {
  PROD;
}

DIV :   '/';

multExpr: (INTEGER -> INTEGER)
          ( {div = null;}
            div=DIV? b=INTEGER
                ->
                ^({$div == null ? (Object)adaptor.create(PROD, "*") : (Object)adaptor.create(DIV, "/")}
              $multExpr $b))*
    ;

INTEGER: ('0' | '1'..'9' '0'..'9'*);

WHITESPACE: (' ' | '\t')+ { $channel = HIDDEN; };

这有效.但是,有没有更好/更简单的方法呢?

This works. But is there a better/simpler way?

推荐答案

这里是一种方法:

grammar Test;

options {
  backtrack=true;
  output=AST;
}

tokens {
  MUL;
  DIV;
}

parse
  : expr* EOF
  ;

expr
  :  (atom -> atom) 
     ( '/' a=atom -> ^(DIV $expr $a)
     | a=atom     -> ^(MUL $expr $a)
     )*
  ;

atom
  :  Number
  |  '(' expr ')' -> expr
  ;

Number
  :  '0'..'9'+
  ;

Space
  :  (' ' | '\t' | '\r' | '\n') {skip();}
  ;

经过测试:

import org.antlr.runtime.*;
import org.antlr.runtime.tree.Tree;

public class Main {
    public static void main(String[] args) throws Exception {
        String source = "1 2 / 3 4";
        ANTLRStringStream in = new ANTLRStringStream(source);
        TestLexer lexer = new TestLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        TestParser parser = new TestParser(tokens);
        TestParser.parse_return result = parser.parse();
        Tree tree = (Tree)result.getTree();
        System.out.println(tree.toStringTree());
    }
}

制作:

(MUL (DIV (MUL 1 2) 3) 4)

这篇关于ANTLR:省略'*'符号的乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆