字符串递归 Antlr 词法分析器标记

发布于 2024-08-28 00:38:42 字数 112 浏览 14 评论 0原文

如何在词法分析器中构建一个可以处理内部递归的令牌,如下字符串:

${*anything*${*anything*}*anything*}

How do I build a token in lexer that can handle recursion inside as this string:

${*anything*${*anything*}*anything*}

?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

森罗 2024-09-04 00:38:42

是的,您可以在词法分析器规则中使用递归。

以下面的例子为例:

${a ${b} ${c ${ddd} c} a}

它将被以下语法正确解析:

parse
  : DollarVar
  ;

DollarVar
  : '${' (DollarVar | EscapeSequence | ~Special)+ '}'
  ;

fragment 
Special
  :  '\\' | '

如 ANTLRWorks 内部的解释器所示:

替代文本http://img185.imageshack.us/img185/5471/recq.png

| '{' | '}' ; fragment EscapeSequence : '\\' Special ;

如 ANTLRWorks 内部的解释器所示:

替代文本http://img185.imageshack.us/img185/5471/recq.png

Yes, you can use recursion inside lexer rules.

Take the following example:

${a ${b} ${c ${ddd} c} a}

which will be parsed correctly by the following grammar:

parse
  : DollarVar
  ;

DollarVar
  : '${' (DollarVar | EscapeSequence | ~Special)+ '}'
  ;

fragment 
Special
  :  '\\' | '

as the interpreter inside ANTLRWorks shows:

alt text http://img185.imageshack.us/img185/5471/recq.png

| '{' | '}' ; fragment EscapeSequence : '\\' Special ;

as the interpreter inside ANTLRWorks shows:

alt text http://img185.imageshack.us/img185/5471/recq.png

数理化全能战士 2024-09-04 00:38:42

正如 @BartK 在他的文章中巧妙指出的那样,ANTLR 的词法分析器确实支持递归,但您只会在解析器中看到一个标记。如果您需要解释该令牌中的各个部分,您可能希望在解析器中处理它。

IMO,你最好在解析器中做一些事情:

variable: DOLLAR LBRACE id variable id RBRACE;

通过做类似上面的事情,你将看到所有必要的部分,并且可以构建 AST 或以其他方式进行相应的处理。

ANTLR's lexers do support recursion, as @BartK adeptly points out in his post, but you will only see a single token within the parser. If you need to interpret the various pieces within that token, you'll probably want to handle it within the parser.

IMO, you'd be better off doing something in the parser:

variable: DOLLAR LBRACE id variable id RBRACE;

By doing something like the above, you'll see all the necessary pieces and can build an AST or otherwise handle accordingly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文