Scala 解析器标记分隔符问题

发布于 2024-08-12 15:07:19 字数 1701 浏览 7 评论 0原文

我正在尝试为下面的命令定义语法。

object ParserWorkshop {
    def main(args: Array[String]) = {
        ChoiceParser("todo link todo to database")
        ChoiceParser("todo link todo to database deadline: next tuesday context: app.model")
    }
}

第二个命令应标记为:

action = todo
message = link todo to database
properties = [deadline: next tuesday, context: app.model]

当我在下面定义的语法上运行此输入时,我收到以下错误消息:

[1.27] parsed: Command(todo,link todo to database,List())
[1.36] failure: string matching regex `\z' expected but `:' found

todo link todo to database deadline: next tuesday context: app.model
                                   ^

据我所知,它失败了,因为匹配消息单词的模式与模式几乎相同对于属性键:值对的键,因此解析器无法分辨消息在哪里结束以及属性在哪里开始。我可以通过坚持为每个属性使用开始令牌来解决这个问题,如下所示:

todo link todo to database :deadline: next tuesday :context: app.model

但我更愿意使命令尽可能接近自然语言。 我有两个问题:

错误消息的实际含义是什么? 我将如何修改现有语法以适用于给定的输入字符串?

import scala.util.parsing.combinator._

case class Command(action: String, message: String, properties: List[Property])
case class Property(name: String, value: String)

object ChoiceParser extends JavaTokenParsers {
    def apply(input: String) = println(parseAll(command, input))

    def command = action~message~properties ^^ {case a~m~p => new Command(a, m, p)}

    def action = ident

    def message = """[\w\d\s\.]+""".r

    def properties = rep(property)

    def property = propertyName~":"~propertyValue ^^ {
        case n~":"~v => new Property(n, v)
    }

    def propertyName: Parser[String] = ident

    def propertyValue: Parser[String] = """[\w\d\s\.]+""".r
}

I'm trying to define a grammar for the commands below.

object ParserWorkshop {
    def main(args: Array[String]) = {
        ChoiceParser("todo link todo to database")
        ChoiceParser("todo link todo to database deadline: next tuesday context: app.model")
    }
}

The second command should be tokenized as:

action = todo
message = link todo to database
properties = [deadline: next tuesday, context: app.model]

When I run this input on the grammar defined below, I receive the following error message:

[1.27] parsed: Command(todo,link todo to database,List())
[1.36] failure: string matching regex `\z' expected but `:' found

todo link todo to database deadline: next tuesday context: app.model
                                   ^

As far as I can see it fails because the pattern for matching the words of the message is nearly identical to the pattern for the key of the property key:value pair, so the parser cannot tell where the message ends and the property starts. I can solve this by insisting that start token be used for each property like so:

todo link todo to database :deadline: next tuesday :context: app.model

But i would prefer to keep the command as close natural language as possible.
I have two questions:

What does the error message actually mean?
And how would I modify the existing grammar to work for the given input strings?

import scala.util.parsing.combinator._

case class Command(action: String, message: String, properties: List[Property])
case class Property(name: String, value: String)

object ChoiceParser extends JavaTokenParsers {
    def apply(input: String) = println(parseAll(command, input))

    def command = action~message~properties ^^ {case a~m~p => new Command(a, m, p)}

    def action = ident

    def message = """[\w\d\s\.]+""".r

    def properties = rep(property)

    def property = propertyName~":"~propertyValue ^^ {
        case n~":"~v => new Property(n, v)
    }

    def propertyName: Parser[String] = ident

    def propertyValue: Parser[String] = """[\w\d\s\.]+""".r
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩人痒 2024-08-19 15:07:19

这真的很简单。当您使用 ~ 时,您必须了解已成功完成的各个解析器不会回溯。

因此,例如,message 得到了冒号之前的所有内容,因为所有这些都是可接受的模式。接下来,propertiespropertyrep,它需要 propertyName,但它只找到冒号(第一个char 没有被消息吞噬)。因此 propertyName 失败,property 失败。现在,如前所述,properties 是一个 rep,因此它以 0 次重复成功完成,这使得 command 成功完成。

那么,回到parseAllcommand 解析器成功返回,消耗了冒号之前的所有内容。然后它会问一个问题:我们是否处于输入的末尾(\z)?不,因为旁边有一个冒号。因此,它期望输入结束,但得到了一个冒号。

您必须更改正则表达式,以便它不会消耗冒号之前的最后一个标识符。例如:

def message = """[\w\d\s\.]+(?![:\w])""".r

顺便说一句,当您使用 def 时,您会强制重新计算表达式。换句话说,每次调用这些定义时,每个定义都会创建一个解析器。每次处理它们所属的解析器时都会实例化正则表达式。如果将所有内容更改为 val,您将获得更好的性能。

请记住,这些东西定义解析器,但它们不运行它。它是运行解析器的parseAll

It is really simple. When you use ~, you have to understand that there's no backtracking on individual parsers which have completed succesfully.

So, for instance, message got everything up to before the colon, as all of that is an acceptable pattern. Next, properties is a rep of property, which requires propertyName, but it only finds the colon (the first char not gobbled by message). So propertyName fails, and property fails. Now, properties, as mentioned, is a rep, so it finishes succesfully with 0 repetitions, which then makes command finish succesfully.

So, back to parseAll. The command parser returned succesfully, having consumed everything before the colon. It then asks the question: are we at the end of the input (\z)? No, because there is a colon right next. So, it expected end-of-input, but got a colon.

You'll have to change the regex so it won't consume the last identifier before a colon. For example:

def message = """[\w\d\s\.]+(?![:\w])""".r

By the way, when you use def you force the expression to be reevaluated. In other words, each of these defs create a parser every time each one is called. The regular expressions are instantiated every time the parsers they belong to are processed. If you change everything to val, you'll get much better performance.

Remember, these things define the parser, they do not run it. It is parseAll which runs a parser.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文