如何访问 antlr golang 目标中的语法组件 [英] how to access grammar components in antlr golang target

查看:22
本文介绍了如何访问 antlr golang 目标中的语法组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

访问通过语法规则传递的运算符值时出现编译错误.例如,我有以下语法文件:

I am getting a compile error when accessing the operator value passed through the grammar rules. For example, I have the following grammar file:

grammar Expr;

@parser::header {
import (
    "os"
)
}

@parser::members {

func eval(left int, op antlr.Token, right int) int {
    if   (op.GetText() == "*") {
        return left * right
    } else if (op.GetText() == "+") {
        return left + right
    } else if (op.GetText() == "-") {
        return left - right
    } else {
        return 0
    }
}
}

stat:   e NEWLINE
    |   NEWLINE                   
    ;

e returns [int v]
    : a=e op=('+'|'-') b=e  {
                $v = eval($a.v, $op, $b.v)
                fmt.Fprintf(os.Stdout, "got args=%d %d\n", $a.v, $b.v)
                }
    | INT                   {
                $v = $INT.int
                fmt.Fprintf(os.Stdout, "got number=%d\n", $v)
                }    
    ; 

MUL : '*' ;
DIV : '/' ;
ADD : '+' ;
SUB : '-' ;

ID  :   [a-zA-Z]+ ;      // match identifiers
INT :   [0-9]+ ;         // match integers
NEWLINE:'\r'? '\n' ;     // return newlines to parser (is end-statement signal)
WS  :   [ \t]+ -> skip ; // toss out whitespace

这是测试代码:

package main

import (
    "os"
    "./parser"
    "github.com/antlr/antlr4/runtime/Go/antlr"
)

func calc(inputfile string) {
        input, _ := antlr.NewFileStream(inputfile)// Setup the input
    lexer := parser.NewExprLexer(input)// Create the Lexer
    stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
    p := parser.NewExprParser(stream)// Create the Parser
        p.Stat()
}

func main() {
    calc(os.Args[1])
}

这些是我运行的命令:

java org.antlr.v4.Tool -Dlanguage=Go -o parser -no-listener Expr.g4
go build expr_t.go

以上 2 个程序运行正常.但是,如果我将 eval 函数的比较更改为如下所示的内容,则会出现编译错误(类型不匹配):

The above 2 programs work correctly. But I get a compile error (type mismatch) if I change the eval function's comparisons to something like this:

if   (op.tokenType == ExprParserMUL) {
    return left * right

如何获取 op 的值与 ExprParseMUL 进行比较?

How to get the op's value for comparison with ExprParseMUL?

推荐答案

if (op.tokenType == ExprParserMUL) {
    return left * right

如何获取 op 的值与 ExprParseMUL 进行比较?

How to get the op's value for comparison with ExprParseMUL?

没有 tokenType 字段.使用 GetTokenType().

There isn't a tokenType field. Use GetTokenType().

参见:https://github.com/antlr/antlr4/blob/master/runtime/Go/antlr/token.go

这篇关于如何访问 antlr golang 目标中的语法组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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