简体   繁体   English

有没有办法强制 JavaCC 接受模棱两可的非 LL(1) 语法?

[英]Is there a way to force JavaCC to accept ambiguous non-LL(1) grammar?

I'm trying to create a didactic parser in JavaCC to explain the use of lookahead for my homework.我正在尝试在 JavaCC 中创建一个教学解析器来解释我的家庭作业中前瞻的使用。 I was thinking about creating a ambiguous grammar on porpose to show the behavior of the parser in such situation.我正在考虑在 porpose 上创建一个模棱两可的语法来显示解析器在这种情况下的行为。 My grammar is below:我的语法如下:

void s() : 
{}
{
    "a" ( bc() | bd() ) <EOF>   
}

void bc() :
{}
{
    "b" "c"
}

void bd() :
{}
{
    "b" "d"
}

Reading the JavaCC Tutorials about lookahead I understood that, in the parser creating, a warning about use of lookahead will be shown (Ok) and if ignored the parser will still work but choosing always the first option.阅读关于前瞻的JavaCC 教程我明白,在解析器创建时,将显示有关使用前瞻的警告(好的),如果忽略,解析器仍然可以工作,但始终选择第一个选项。 I supposed the last part because the tutorial says "The generated parser will still work using the default lookahead algorithm, but it may not do what you expect of it."我认为是最后一部分,因为教程说“生成的解析器仍将使用默认的前瞻算法工作,但它可能不会按照您的预期运行。”

However, when I try to create the parser this error is shown:但是,当我尝试创建解析器时,会显示此错误:

$ javac *.java
ExampleABCD.java:18: error: unreachable statement
        }{
         ^
1 error

And the cause is:原因是:

case 6:{
        bc();
        break;
        }{        //Here
        bd();
        break;
        }

I expected to the parser work but not properly.我希望解析器工作但不正常。 Shouldn't it be like that?不应该是这样吗? If this error is expected, is there a way to make it work even with this ambiguous grammar?如果预期会出现此错误,即使使用这种模棱两可的语法,有没有办法使其工作?

note: I don't want to use lookahead yet, my goal is to use it later when I will explain how it can solve the problem.注意:我还不想使用lookahead,我的目标是稍后在解释它如何解决问题时使用它。

Now JavaCC has no issue with this.现在 JavaCC 对此没有任何问题。 It produces warnings and .java code that correctly reflects the .jj file.它会生成正确反映 .jj 文件的警告和 .java 代码。 The problem is that your Java compiler does not like unreachable code.问题是您的 Java 编译器不喜欢无法访问的代码。

See Is there a way to ignore the 'Unreachable statement' error?请参阅有没有办法忽略“无法访问的语句”错误?

What you can do is this你能做的是这个

void s() : 
{}
{
    "a" ( LOOKAHEAD({true})  // TODO fix the lookahead
          bc()
        | 
          bd() )
    <EOF>   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM