问题描述
有没有一种方法可以在语法中指定我要跳过不符合任何规则的所有输入(否则将引发识别错误)?
Is there a way to specify in a grammar that I want to skip all input that doesnt match any of the rules (that would otherwise throw a recognition error)?
推荐答案
是.实施方式取决于您需要/想要进行跳过的地方.
Yes. Implementation depends on where you need/want to do the skipping.
在词法分析器中,最后一条规则如下:
In the lexer, a last rule like:
Unknown : . -> skip ; // or -> channel(HIDDEN) ;
将消耗任何其他不匹配的输入字符,但不会使它们被标记器和解析器所考虑.您确实想一次匹配一个字符,以便在每个输入文本索引处,所有其他词法分析器规则都有机会首先匹配.
will consume any otherwise unmatched input characters yet keep them from being tokenized and considered by the parser. You do want to match a single character at a time so that at every input text index all other lexer rules have a chance to match first.
类似地,在解析器中,最后一条规则如下:
Similarly, in the parser, a last rule like:
ignored : . ;
将使用不匹配的令牌,创建解析树节点,每个节点都作为包含单个忽略"令牌的上下文.然后,可以忽略它们在分析树中的存在.
will consume unmatched tokens, creating parse tree nodes, each as a context containing a single 'ignored' token. Their presence in the parse-tree can then be, well, ignored.
同样,被忽略的规则匹配应仅针对单个令牌,以确保所有其他较长的匹配规则都具有优先级,最后是规则的顺序,以确保首先考虑所有其他单个令牌匹配规则.
Again, the ignored rule match should be for just a single token, ensuring that all other longer match rules have priority, and last in the ordering of the rules, ensuring that all other single token match rules are considered first.
这篇关于跳过Antlr中不匹配的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!