【问题标题】:Where in this BNF grammar do match ; after 'end'在这个 BNF 语法中的哪里匹配;在“结束”之后
【发布时间】:2014-06-22 22:57:59
【问题描述】:

阅读this Pascal BNF 语法我不明白为什么在函数定义中; 必须出现在end 之后。看到函数标题后,可能会出现function-block,即block

 function-declaration =
    function-heading ";" function-body |
    function-heading ";" directive |
    function-identification ";" function-body . 
function-body =
    block . 

当出现begin 时,那是statement-par 的一部分,那是块的一部分,它由statement-part 处理,对吧?

 block =
    declaration-part statement-part . 
 statement-part =
    begin statement-sequence end .

注意statement-part。在end 关键字之后没有;,这不是statement-sequence 的一部分。所以,我不明白编译器如何声称在 end 关键字之后缺少 ;,就像在这个例子中一样:

function myabs(i : integer) : integer;
begin
     if i < 0 then begin i := -i; end; < -- it's process by statement-sequence, so, ';' may appear
     myabs := i;
end; <-- it is the semicolon what about I'm speaking

我错过了什么?我读错语法了吗?如果我忽略它,我尝试过的所有 Pascal 编译器都会报错。​​

【问题讨论】:

  • 在同一个链接中,它具有将function-declarationfunction-body 组合在一起的部分,即:procedure-and-function-declaration-part = { (procedure-declaration | function-declaration) ";" } . 这就是分号所在的位置。
  • 为什么是-1?请不要投票者解释一下?

标签: pascal bnf


【解决方案1】:

ANTLRWorks 是您这里最好的朋友。

如果您使用 antlrworks (http://www.antlr3.org/works/) 尝试一些帕斯卡语法,例如 http://www.monperrus.net/martin/pascal-antlr3,您会看到类似

的程序
program first;
function myabs(i : integer) : integer;
begin
end;
begin
end.

会这样解析

这样您就可以确切地看到正在发生的事情。

ps。我提供给你的帕斯卡语法链接有一个特定标记的问题,但我敢打赌你可以解决这个问题;-)

ps2。更新 - antlrworks 截图来帮助@Jack

【讨论】:

  • 你是如何从整个语法中创建这个图表的?我只能从选定的语法(鼠标打开的地方)创建。
  • @Jack,这样做:打开 antlrworks 1.5.2,打开语法(ctrl+O),将 pascal sn-p 粘贴到左侧文本区域(选项卡“解释器”)。在左侧文本区域上方的选择框中默认选择“程序”,然后单击“播放”图标。我在答案中添加了屏幕截图以提供帮助。
【解决方案2】:

结束后不必有分号。就这么简单。

分号用于分隔语句。因此,如果它不是最后一个语句,则只需要在 end 后加一个分号。如果它是最后一个语句,则应改为句号。

现在,BNF 中也可能存在一些错误,这意味着根据 BNF,您不必在实际需要分号的地方使用分号,但解决这个问题的唯一方法是分析整个BFN的详细信息,我觉得这不是建设性的。 :-)

但在这种情况下,我认为您错过的是procedure or function declaration must end with a semi-colon

【讨论】:

  • 但是为什么任何 Pascal 编译器(我都尝试过)会说“预期的”;但发现了其他东西?
  • @TheMask 因为它期望在那个位置有一个分号,但它没有找到。别搞错了,你要问的位置应该有一个分号。
  • 我以前没见过你编辑过。非常感谢。 :) 真的,我以前读过所有这些程序员,但没有注意到。
【解决方案3】:

过程和函数不需要以分号结束,但必须用一个分隔:

来自the Pascal BNF

proc-and-func-declaration:  
   proc-or-func  
   proc-and-func-declaration ; proc-or-func 

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 2010-10-09
    • 2013-10-26
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多