gpt4 book ai didi

antlr - 语句或退出语句的 ANTLR 文法

转载 作者:行者123 更新时间:2023-12-01 08:07:27 26 4
gpt4 key购买 nike

我在 ANTLR 语法中写下了以下语句:

loopStatement
: 'loop' (statement|exit)* 'end' 'loop' ';'
;

如果我没理解错的话,(statement|exit)*的意思是我可以有一个statement或者一个exit statement。那是即 statement_1 exit_1,或 statement_1,或 statement_1 statement_2,exit_1,对吗?
我的解析器可以工作,除了没有语句的时候。
例如:

这个有效:

loop
x:=x+1; <<< statement_1
exit when x=9; <<<<exit_1
end loop;

这也有效(没有 exit):

loop
x:=x+1; <<< statement_1
<<<<exit_1 (no exit)
end loop;

但是这个有效(没有声明):

loop
<<< statement_1
exit when x=9; <<<<exit_1
end loop;

我的语法有问题吗?

最佳答案

pantelis wrote:

If I understand correctly, (statement|exit)* means that I can have a statement or an exit statement.

准确地说,(statement|exit)* 匹配空字符串,或者零个或多个 statementexit 语句(在没有具体顺序!)。所以它会匹配:

  • 声明声明...
  • 退出退出退出...
  • exit exit语句语句exit ...
  • ...

但是,为什么不让您的 exit 语句只是一个常规语句呢?我的小演示:

loopStatement
: 'loop' statement* 'end' 'loop' ';'
;

statement
: 'exit' 'when' expression ';' // exit statement
| ID ':=' expression ';' // assignment
;

expression
: equalityExpression
;

equalityExpression
: addExpression ('=' addExpression)*
;

addExpression
: atom ('+' atom)*
;

atom
: ID
| Number
| '(' expression ')'
;

ID
: 'a'..'z'+
;

Number
: '0'..'9'+
;

正确解析所有 3 个示例:


1

loop
x:=x+1;
exit when x=9;
end loop;

enter image description here


2

loop
x:=x+1;

end loop;

enter image description here


3

loop

exit when x=9;
end loop;

enter image description here


4

或者什么都没有:

loop

end loop;

enter image description here

关于antlr - 语句或退出语句的 ANTLR 文法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5400483/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com