简体   繁体   English

在中使用变量

[英]Using variables in parboiled

I'm attempting to create a simple XML parser using the parboiled Java library . 我正在尝试使用已煮过的Java库创建一个简单的XML解析器。

The following code attempts to use a variable to verify that the closing tag contains the same identifier as the opening tag. 以下代码尝试使用变量来验证结束标记包含与开始标记相同的标识符。

class SimpleXmlParser2 extends BaseParser<Object> {
    Rule Expression() {
        StringVar id = new StringVar();
        return Sequence(OpenElement(id), ElementContent(), CloseElement(id));
    }

    Rule OpenElement(StringVar id) {        
        return Sequence('<', Identifier(), ACTION(id.set(match())), '>');
    }

    Rule CloseElement(StringVar id) {    
        return Sequence("</", id.get(), '>');                               
    }

    Rule ElementContent() {
        return ZeroOrMore(NoneOf("<>"));
    }

    Rule Identifier() {
        return OneOrMore(CharRange('A', 'z'));
    }    
}

The above, however, fails with the error message org.parboiled.errors.GrammarException: 'null' cannot be automatically converted to a parser Rule , when I create the ParseRunner. 但是,以上操作失败,并显示错误消息org.parboiled.errors.GrammarException: 'null' cannot be automatically converted to a parser Rule创建ParseRunner时, org.parboiled.errors.GrammarException: 'null' cannot be automatically converted to a parser Rule

It would appear that I have a basic misunderstanding of how variables should be used in parboiled. 看来我对应该如何使用变量进行基本的理解有一个基本的误解。 Can anyone help me resolve this? 谁能帮我解决这个问题?

Came up with an answer. 想出了一个答案。 Including it here for any other parboiled newbie who may struggle with the same issue. 对于可能遇到相同问题的任何其他熟食新手,请在此处包括此内容。

The problem was that any access to the variable's content must happen in a parser action to ensure that it takes place in the parse-phase, rather than in the rule construction phase. 问题在于,对变量内容的任何访问都必须在解析器操作中进行,以确保它在解析阶段而不是在规则构造阶段进行。

The following changes to the program above, ensures that parsing fails if an element identifier is unmatched. 对上面程序的以下更改可确保在元素标识符不匹配时解析失败。

Rule CloseElement(StringVar id) {    
    return Sequence("</", Identifier(), matchStringVar(id), '>');                               
}

Action matchStringVar(final StringVar var) {
    return new Action() {
        public boolean run(Context ctx) {
            String match = ctx.getMatch();
            return match.equals(var.get());
        }
    };
}

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

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