使用JavaCC解析自定义语法的问题

时间:2018-05-26 00:12:53

标签: java parsing compiler-construction javacc

我正在用JavaCC编写解析器。这是我目前的进展:

PARSER_BEGIN(Compiler)

public class Compiler {
    public static void main(String[] args) {
        try {
            (new Compiler(new java.io.BufferedReader(new java.io.FileReader(args[0])))).S();
            System.out.println("Syntax is correct");
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

PARSER_END(Compiler)

<DEFAULT, INBODY> SKIP:  { " " | "\t" | "\r" }
<DEFAULT> TOKEN: { "(" | ")" |  <ID: (["a"-"z","A"-"Z","0"-"9","-","_"])+ > | "\n" : INBODY }
<DEFAULT> TOKEN: { <#RAND: (" " | "\t" | "\r")* > | <END: <RAND> "\n" <RAND> ("\n" <RAND>)+ > }
<INBODY>  TOKEN: { <STRING: (~["\n", "\r"])*> : DEFAULT }

void S(): {}
{
    (Signature() "\n" Body() (["\n"] <EOF> | <END> [<EOF>]) )+
}

void Signature(): {}
{
    "(" <ID> <ID> ")"
}

void Body(): {}
{
    <STRING> ("\n" <STRING> )*
}

我的目标是解析一个看起来像这样的语言:

(test1 pic1)
This line is a <STRING> token
After the last <STRING> one empty line is necessary

(test2 pic1)
String1
It is also allowed to have an arbitrary number (>=1) of empty lines




(test3 pic1)
String1
String2

(test4 pic1)
String1
String2
An arbitrary number (also zero) of empty lines follow till <EOF>

它几乎正常,但我现在面临的问题如下:

在解析文本的末尾(如上例中所述)允许有任意数字(包括零)的空行直到<EOF>。如果我在<EOF>之前没有空行,它按预期工作(它打印&#34;语法正确&#34;)。如果我在<EOF>之前至少有两个空行,它也会按预期工作(它打印&#34;语法正确&#34;)。如果在<EOF>之前只有一个空行,那么它也应该打印&#34;语法是正确的&#34;。但我得到了异常堆栈跟踪:

ParseException: Encountered "<EOF>" at line 19, column 9.
Was expecting:
    <STRING> ...

        at Compiler.generateParseException(Compiler.java:284)
        at Compiler.jj_consume_token(Compiler.java:217)
        at Compiler.Body(Compiler.java:83)
        at Compiler.S(Compiler.java:18)
        at Compiler.main(Compiler.java:6)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at com.simontuffs.onejar.Boot.run(Boot.java:340)
        at com.simontuffs.onejar.Boot.main(Boot.java:166)

有人知道问题可能是什么吗?

更新

更改行

(Signature() "\n" Body() (["\n"] <EOF> | <END> [<EOF>]) )+

(Signature() "\n" Body() (<EOF> | <END> [<EOF>]) )+

产生相同的行为。似乎["\n"](由于某种原因)完全被忽略了。

1 个答案:

答案 0 :(得分:1)

我找到了问题的核心。改变行

<STRING> ("\n" <STRING> )*

<STRING> (LOOKAHEAD(2) "\n" <STRING> )*

解决了这个问题。

它只需要一个本地LOOKAHEAD(2)