需要Antlr多余谓词吗? [英] Antlr superfluous Predicate required?

查看:63
本文介绍了需要Antlr多余谓词吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要忽略其中一部分的文件.在Lexer中,我使用门控语义谓词来避免为文件的不感兴趣部分创建令牌.我的规则类似于以下内容.

I have a file where I want to ignore parts of it. In the Lexer I use gated semantic predicates to avoid creating tokens for the uninteresting part of the file. My rules are similar to the following.

A 
: {!ignore}?=> 'A' 
;
START_IGNORE
: 'foo' {ignore = true; skip();}
;
END_IGNORE
: 'oof' {ignore = false; skip();}
;
IGNORE
: {ignore}?=> . {skip();}
;    

但是,除非我将START和END更改为也使用语义谓词(如下所示),否则它将不起作用.

However unless I change START and END to also use semantic predicates (as below) it does not work..

A 
: {!ignore}?=> 'A' 
;
START_IGNORE
: {true}?=> 'foo' {ignore = true; skip();}
;
END_IGNORE
: {true}?=> 'oof' {ignore = false; skip();}
;    
IGNORE
: {ignore}?=> . {skip();}
;  

为什么必须添加谓词?

我正在使用antlr-3.4

I am using antlr-3.4

推荐答案

为什么必须添加谓词?

Why do I have to add the predicates?

你不知道.至少不使用ANTLR v3.3.我不知道您正在测试的方法是什么,但是请不要使用ANTLRWorks的解释器或Eclipse ANTLR IDE插件.始终从命令行进行一些测试.

You don't. At least, not using ANTLR v3.3. I don't know how exactly you're testing, but don't use ANTLRWorks' interpreter or the Eclipse ANTLR IDE plugin. Always do a little test from the command line.

grammar T;

@parser::members {
  public static void main(String[] args) throws Exception {
    TLexer lexer = new TLexer(new ANTLRStringStream("A foo A B C oof A"));
    TParser parser = new TParser(new CommonTokenStream(lexer));
    parser.parse();
  }
}

@lexer::members {
  private boolean ignore = false;
}

parse
 : (t=. 
     {System.out.printf("[\%02d] type=\%s text='\%s'\n", $t.getCharPositionInLine(), tokenNames[$t.type], $t.text);}
   )* EOF
 ;

A 
 : {!ignore}?=> 'A' 
 ;

START_IGNORE
 : 'foo' {ignore = true; skip();}
 ;

END_IGNORE
 : 'oof' {ignore = false; skip();}
 ;

IGNORE
 : {ignore}?=> . {skip();}
 ;    

SPACE
 : ' ' {skip();}
 ;

像这样运行它:

java -cp antlr-3.3.jar org.antlr.Tool T.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar TParser

将打印以下内容:

[00] type=A text='A'
[16] type=A text='A'

即:从输入"A foo A B C oof A"中输入以下内容:"foo A B C oof"被踩skip.

I.e.: from the input "A foo A B C oof A" the following: "foo A B C oof" is skipped.

这篇关于需要Antlr多余谓词吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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