antlr全局规则范围声明与@members声明 [英] antlr global rule scope declaration vs @members declaration

查看:245
本文介绍了antlr全局规则范围声明与@members声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,您更愿意声明一个变量,全局范围还是@members声明?在我看来,它们可以达到相同的目的?

Which one would you prefer to declare a variable in which case, global scope or @members declaration? It seems to me that they can serve for same purpose?

更新这是一种语法,解释我的意思.

UPDATE here is a grammar to explain what i mean.

grammar GlobalVsScope;

scope global{
  int i;
}
@lexer::header{package org.inanme.antlr;}
@parser::header{package org.inanme.antlr;}

@parser::members {
  int j;
}

start
scope global;
@init{
  System.out.println($global::i);
  System.out.println(j);
}:R EOF;

R:'which one';

推荐答案

请注意,除了全局(ANTLR)范围外,您还可以具有 local 规则范围,如下所示:

Note that besides global (ANTLR) scopes, you can also have local rule-scopes, like this:

grammar T;

options { backtrack=true; }

parse
scope { String x; }
parse
 : 'foo'? ID {$parse::x = "xyz";} rule*
 | 'foo' ID
 ;

rule
 : ID {System.out.println("x=" + $parse::x);}
 ;  

我唯一考虑使用 local 规则范围的条件是,当有很多谓词或启用全局回溯(导致 all 规则具有在它们前面的谓词).在那种情况下,您可以可以创建一个成员变量String x(或在全局范围内定义)并在parse规则中进行设置,但是您可能会在之后更改此实例/作用域变量解析器可以回溯的位置,而该回溯将导致将全局变量设置为其原始格式/状态!局部范围变量也将被设置",但是风险可能较小:它们在单个规则中是局部的.

The only time I'd consider using local rule-scopes is when there are a lot of predicates, or global backtracking is enabled (resulting in all rules to have predicates in front of them). In that case, you could create a member variable String x (or define it in a global scope) and set it in the parse rule, but you might be changing this instance/scope variable after which the parser could backtrack, and this backtracking will not cause the global variable to be set to it's original form/state! The local scoped variable will also not be "unset", but that will likely be less of a risk: them being local to a single rule.

总结:是的,您是对的,全局作用域和成员/实例变量非常相似.但是由于语法更友好,我会尽快选择成员变量.

To summarize: yes, you're right, global scopes and member/instance variables are much alike. But I'd sooner opt for members-variables because of the friendlier syntax.

这篇关于antlr全局规则范围声明与@members声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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