简体   繁体   English

来自BNF的递归下降解析器伪代码

[英]Recursive Descent Parser Pseudo Code from BNF

Ok, I thought there would be enough CS majors on here to check my pseudo code for my recursive descent parser. 好吧,我认为这里有足够的CS专业来检查我的递归下降解析器的伪代码。 I developed it from this BNF 我是从这个BNF开发的

EXP ::= EXP + TERM | EXP - TERM | TERM
TERM ::= TERM * FACTOR | TERM/FACTOR | FACTOR
FACTOR ::= (EXP) | DIGIT
DIGIT ::= 0|1|2|3

Here's the pseudo code: 这是伪代码:

procedure exp()
    term()
    if token == ‘+’
        match(‘+’)
        term()
    elseif token == ‘-‘
        match(‘-‘)
        term()
    else
        break    

procedure term()
    factor()
    if token == ‘*’
        match(‘*’)
        factor()
    elseif token == ‘/’
        match(‘/’)
        factor()
    else
        break

procedure factor()
    if token == ‘(‘
        match(‘(‘)
        exp()
        match(‘)’)
    else
        digit()

procedure digit()
    if token == ‘0’
        match(‘0’)
    elseif token == ‘1’
        match(‘1’)
    elseif token == ‘2’
        match(‘2’)
    else
        match(‘3’)

match(t)
    if token == t
        advancetokenpointer
    else
        error

Is this correct? 这个对吗? I was thinking I may need to have a return in each procedure, and I'm not sure of my procedure correctness either. 我想我可能需要在每个程序中都有一个返回,我也不确定我的程序是否正确。 Maybe include end procedure too? 也许包括结束程序? Anyways, thanks a lot! 无论如何,非常感谢! :-) :-)

You are half way there. 你在中途。 Especifically, you are not accounting for the left-recursive parts of the grammar, as in "EXP ::= EXP...", or "TERM ::= TERM...". 特别是,您没有考虑语法的左递归部分,如“EXP :: = EXP ...”或“TERM :: = TERM ...”。

Recursive descent is not well suited for left-recursion anyway, but fortunatelly there are standard transformations you can perform in the grammar that will eliminate this kind of left recursion. 无论如何,递归下降并不适合左递归,但幸运的是,你可以在语法中执行标准转换来消除这种左递归。 As an example, the following grammar: 作为一个例子,以下语法:

A ::= A x B | B

could be coded like this: 可以像这样编码:

procedure A()
  B()
  repeat
    if token == 'x'
      match('x')
      B()
    else
      break

Moreover, the code for factor is not following the grammar correctly. 而且,因子的代码没有正确地遵循语法。 Notice that in the first alternative, EXP is called recursivelly (this is a kind of recursion that Recursive Descent has no problem with) and you are calling factor instead. 请注意,在第一个替代方案中,EXP被称为递归调用(这是递归下降没有问题的一种递归),而您正在调用因子。 Also, you are matching the right parenthesis as if it was optional, while it is actually required. 此外,您正在匹配右括号,就好像它是可选的,而实际上是必需的。 This same problem exists in the code for DIGIT. DIGIT的代码中存在同样的问题。 If neither 0, 1 or 2 match, 3 must match. 如果0,1或2都不匹配,则3必须匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM