我正在尝试编写一个简单的Recursive Descent Parser。 目标是为每个节点创建类的语法树。 我的小语言的BNF语法是:
<program> ::= <program> <statement>
| <statement>
<statement> ::= if <value> then <program> end
| msg <value>
<value> ::= '0'
| '1'
和我的测试程序:
if 1 then msg 0 end
当解析器完成解析 IF 和 END 之间的语句列表(代码块)时会出现问题,它会在结束之前查找下一个语句if语句 END
这通常是怎么做的? 我试图谷歌一个例子来做这个“如果那么结束”类型的事情,但未能找到一个好的例子。
我的代码是用VB编写的,但对于使用其他语言的程序员来说应该是可读的。这种情况的任何伪代码或示例都会有所帮助。
要测试我的代码,只需将此脚本复制粘贴到桌面上的* .vbs文件中,然后双击它:
class program_statement
public stmt
public stmts
sub execute
stmt.execute
if not(stmts is nothing) then stmts.execute
end sub
end class
class IF_value_THEN_program_END
public value
public program
sub execute
if value = "1" then program.execute
end sub
end class
class MSG_value
public value
sub execute
msgbox value.value
end sub
end class
class value
public value
end class
'----------------------------------------------
function P
set P = new program_statement
set P.stmt = S
if token = "" then
set P.stms = nothing
else
set P.stms = P()
end if
end function
function S
if token = "if" then
advance
set S = new IF_value_THEN_program_END
set S.value = V
expect("then")
set S.program = P
expect("end")
elseif token = "msg" then
advance
set S = new MSG_value
set S.value = V
else
warning "expected: if, msg"
end if
end function
function V
if token = "0" or token = "1" then
Set V = new value
V.value = token
advance
else
warning "expected: 0, 1"
end if
end function
'----------------------------------------------
sub warning(message)
msgbox message, vbexclamation, pionter & "=" & token
wscript.quit
end sub
sub advance
pionter = pionter + 1
end sub
function token
if pionter-1 < ubound(TEST) then token = TEST(pionter)
end function
sub expect(input)
if token = input then
advance
else
warning "expected: " & input
end if
end sub
'----------------------------------------------
TEST = split("if 1 then msg 0 end")
pionter = lbound(TEST)
Set My_Program = P
My_Program.execute