gpt4 book ai didi

lua - 创建递归 LPeg 模式

转载 作者:行者123 更新时间:2023-12-03 14:30:14 28 4
gpt4 key购买 nike

在普通的 PEG(解析表达式语法)中,这是一个有效的语法:

values <- number (comma values)*
number <- [0-9]+
comma <- ','

但是,如果我尝试使用 LPeg 编写此规则,则该规则的递归性质将失败:
local lpeg   = require'lpeg'

local comma = lpeg.P(',')
local number = lpeg.R('09')^1
local values = number * (comma * values)^-1
--> bad argument #2 to '?' (lpeg-pattern expected, got nil)

虽然在这个简单的例子中我可以重写规则以不使用递归,但我有一些我不想重写的现有语法。

如何在 LPeg 中编写自引用规则?

最佳答案

使用 grammar .

With the use of Lua variables, it is possible to define patterns incrementally, with each new pattern using previously defined ones. However, this technique does not allow the definition of recursive patterns. For recursive patterns, we need real grammars.

LPeg represents grammars with tables, where each entry is a rule.

The call lpeg.V(v) creates a pattern that represents the nonterminal (or variable) with index v in a grammar. Because the grammar still does not exist when this function is evaluated, the result is an open reference to the respective rule.

A table is fixed when it is converted to a pattern (either by calling lpeg.P or by using it wherein a pattern is expected). Then every open reference created by lpeg.V(v) is corrected to refer to the rule indexed by v in the table.

When a table is fixed, the result is a pattern that matches its initial rule. The entry with index 1 in the table defines its initial rule. If that entry is a string, it is assumed to be the name of the initial rule. Otherwise, LPeg assumes that the entry 1 itself is the initial rule.

As an example, the following grammar matches strings of a's and b's that have the same number of a's and b's:

equalcount = lpeg.P{
"S"; -- initial rule name
S = "a" * lpeg.V"B" + "b" * lpeg.V"A" + "",
A = "a" * lpeg.V"S" + "b" * lpeg.V"A" * lpeg.V"A",
B = "b" * lpeg.V"S" + "a" * lpeg.V"B" * lpeg.V"B",
} * -1

It is equivalent to the following grammar in standard PEG notation:

  S <- 'a' B / 'b' A / ''
A <- 'a' S / 'b' A A
B <- 'b' S / 'a' B B

关于lua - 创建递归 LPeg 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26149826/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com