开发者

By grammar rules of recursive descent parser how can we validate the source string

If the following two input strings are inputed :

1)<id> + <id> * <id>
2) <id> * <id> <id>

E ::= T{+T}* 
T ::= V{*V}* 
V ::= <id>

Then by applying the above grammar rules of recursive descent parser how can we validate the above source string. What type of the error will be indicated by recursive开发者_JAVA技巧 descent parser ?

Thanks...


Your grammar rules look like arithmetic infix notation. Pyparsing (a Python parsing add-on module) has a built-in method for building parser expressions for this kind of notation, called operatorPrecedence. Here is how a pyparsing parser would parse your two examples:

from pyparsing import operatorPrecedence, opAssoc, ParseException

expr = operatorPrecedence("<id>",
    [
    ('*', 2, opAssoc.LEFT),
    ('+', 2, opAssoc.LEFT),
    ])

tests = """\
<id> + <id> * <id> 
<id> * <id> <id>""".splitlines()

for t in tests:
    print t
    try:
        print expr.parseString(t, parseAll=True).asList()
    except ParseException,pe:
        print "parsing failed"
    print

Prints:

<id> + <id> * <id> 
[['<id>', '+', ['<id>', '*', '<id>']]]

<id> * <id> <id>
parsing failed

Hope this helps you in your studies.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜