JavaCC - 解析 XPATH 表达式的一个步骤 [英] JavaCC - parse a step of an XPATH expression

查看:24
本文介绍了JavaCC - 解析 XPATH 表达式的一个步骤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为(简单的)XPath 解析器编写 JavaCC 脚本,但在解析各个步骤时遇到了问题.

I'm trying to write a JavaCC script for a (simple) XPath parser and I'm having problems with the part to parse individual steps.

我对语法的想法是这样的:

My idea of the grammar is this:

Step ::= ( AxisName "::" )? NodeTest ( "[" Predicate "]" )*

我已将其转换为以下脚本片段:

I have transformed it into the following script snippet:

Step Step() :
{
    Token t;

    Step step;

    Axis axis;
    NodeTest nodeTest;
    Expression predicate;
}
{
    { axis = Axis.child; }

    (
        t = <IDENTIFIER>
        { axis = Axis.valueOf(t.image); }

        <COLON>
        <COLON>
    )?

    t = <IDENTIFIER>
    { nodeTest = new NodeNameTest(t.image); }

    { step = new Step(axis, nodeTest); }

    (       
        <OPEN_PAR>

        predicate = Expression()

        { step.addPredicate(predicate); }

        <CLOSE_PAR>
    )*

    { return step; }
}

然而,这不起作用.给定以下表达式:

This, however, doesn't work. Given the following expression:

p

它抛出以下错误:

Exception in thread "main" java.lang.IllegalArgumentException: No enum constant cz.dusanrychnovsky.generator.expression.Axis.p
    at java.lang.Enum.valueOf(Unknown Source)
    at cz.dusanrychnovsky.generator.expression.Axis.valueOf(Axis.java:3)
    at cz.dusanrychnovsky.generator.parser.XPathParser.Step(XPathParser.java:123)
    at cz.dusanrychnovsky.generator.parser.XPathParser.RelativeLocationPath(XPathParser.java:83)
    at cz.dusanrychnovsky.generator.parser.XPathParser.AbsoluteLocationPath(XPathParser.java:66)
    at cz.dusanrychnovsky.generator.parser.XPathParser.Start(XPathParser.java:23)
    at cz.dusanrychnovsky.generator.parser.XPathParser.parse(XPathParser.java:16)
    at cz.dusanrychnovsky.generator.Main.main(Main.java:24)

我相信会发生什么是解析器在输入中看到一个标识符,因此它采用轴分支,即使后面没有冒号,解析器当时无法知道.

I believe that what happens is that the parser sees an identifier on the input so it takes the axis branch even though no colons will follow, which the parser cannot know at that time.

解决此问题的最佳方法是什么?我是否应该以某种方式增加 Step 规则的前瞻值,如果是这种情况,那么我将如何做到这一点?还是我需要以某种方式重写规则?

What is the best way to fix this? Should I somehow increase the lookahead value for the Step rule, and if that's the case, then how exactly would I do that? Or do I need to rewrite the rule somehow?

推荐答案

两种选择:

(   LOOKAHEAD(3)
    t = <IDENTIFIER>
    { axis = Axis.valueOf(t.image); }

    <COLON>
    <COLON>
)?

(   LOOKAHEAD( <IDENTIFIER> <COLON> <COLON> )
    t = <IDENTIFIER>
    { axis = Axis.valueOf(t.image); }

    <COLON>
    <COLON>
)?

这篇关于JavaCC - 解析 XPATH 表达式的一个步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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