What are the differences between PEGs and CFGs?

前端 未结 2 587
耶瑟儿~
耶瑟儿~ 2021-01-30 13:30

From this wikipedia page:

The fundamental difference between context-free grammars and parsing expression grammars is that the PEG\'s choice operato

2条回答
  •  广开言路
    2021-01-30 14:11

    A CFG grammar is non-deterministic, meaning that some input could result in two or more possible parse-trees. Though most CFG-based parser-generators have restrictions on the determinability of the grammar. It will give a warning or error if it has two or more choices.

    A PEG grammar is deterministic, meaning that any input can only be parsed one way.

    To take a classic example; The grammar

    if_statement := "if" "(" expr ")" statement "else" statement
                  | "if" "(" expr ")" statement;
    

    applied to the input

    if (x1) if (x2) y1 else y2
    

    could either be parsed as

    if_statement(x1, if_statement(x2, y1, y2))
    

    or

    if_statement(x1, if_statement(x2, y1), y2)
    

    A CFG-parser would generate a Shift/Reduce-conflict, since it can't decide if it should shift (read another token), or reduce (complete the node), when reaching the "else" keyword. Of course, there are ways to get around this problem.

    A PEG-parser would always pick the first choice.

    Which one is better is for you to decide. My opinion is that often PEG-grammars is easier to write, and CFG grammars easier to analyze.

提交回复
热议问题