将EBNF语法转换为PEG

时间:2018-10-29 21:12:02

标签: php parsing bnf ebnf

我有一个EBNF语法,想将其转换为PEG(https://github.com/anatoo/PHPPEG):

query = { word | wildcard }
word = ( [apostrophe] ( letter { alpha } ) ) | ” , ”
letter = ” a ” | ... | ” z ” | ” A ” | ... | ” Z ”
alpha = letter | ” 0 ” | ... | ” 9 ”
apostrophe = ” ’ ”
wildcard = ” ? ” | ” * ” | synonyms | multiset | optionset
synonyms = ” ~ ” word
multiset = ” { ” word { word } ” } ”
optionset = ” [ ” word { word } ” ] ”

任何人都可以解释如何从一种转换为另一种,或者是否有我可以阅读的地方?

谢谢!

• the question mark (?), which matches exactly one word;
• the asterisk (*), which matches any sequence of words;
• the tilde sign in front of a word (∼<word>), which matches any of the word’s synonyms;
• the multiset operator ({<words>}), which matches any ordering of the enumerated words; and,
• the optionset operator ([<words>]), which matches any one word from a list of options.

1 个答案:

答案 0 :(得分:1)

有几种Peg实现,然后将它们全部添加到Peg选择的通用约定中,这些约定是:

  • 运算符“ *”,“ +”和“?”具有与常规相同的含义 表情;
  • 替代品实际上是优先选择,它们使用 “ /”运算符,以指示该差异;
  • 运算符“&”和“!”指定正负零长度预读(即,它们不前进“当前”指针);

在EBNF中,重复由“ {}”表示,在Peg中由“ *”运算符表示,表示对象的零次或多次重复。例如,您的第一个语法规则可以在假设的Peg实现中表示如下:

query = (word / wildcard)* 

EBNF“ []”运算符与Peg的“?”含义相同运算符,表示主题是可选的。这是您的第二条规则,因为它可以转换为Peg:

word = (apostrophe?  letter alpha*) / ","

最后,一些Peg实现允许直接在其语法中使用正则表达式。看看您的第三个规则如何用这种钉表示:

letter = [a-zA-Z]

取决于您使用的语言和特定的Peg实现,可能会发生一些变化,但是我希望这些指南可以为您指明正确的方向。