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

查看:33
本文介绍了antlr 全局规则范围声明 vs @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) 范围之外,您还可以拥有 本地 规则范围,如下所示:

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 全局规则范围声明 vs @members 声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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