使用FParsec解析方法参数 [英] Parsing method arguments with FParsec

查看:66
本文介绍了使用FParsec解析方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用FParsec实现方法参数解析器.

I am trying to implement a method arguments parser with FParsec.

我想知道FParsec本身是否已有一些已实现的功能来帮助我实现这一目标?我之所以这么问,是因为FParsec在处理运算符优先级时提供了工具,因此也可能对此有所帮助.

I was wondering if there is some already implemented feature in FParsec itself that'd aid me on this purpose? I ask this as FParsec provides tooling when dealing with operator precedence, so there might be something for this too.

解析左括号和右括号非常简单.令人头疼的是要处理可能发生的以下3种情况:

Parsing the opening and closing braces is pretty straight-forward. The headache lies in dealing with the following 3 cases that can happen:

方法参数可以包括:

  • 没有参数,
  • 一个论点
  • 多个参数(所有逗号分隔).请记住,最后一个参数不能以逗号开头!

在没有任何内置功能(即使用< |>运算符和流复制)的情况下,我已经掌握了如何自己实现此功能的一些线索,但是我想避免这种情况低水平的东西.

I already have some clues on how to implement this by myself in case there is not any built-in feature, namely with the <|> operator and stream copying, but I'd like to stay away from that kind of low level stuff if possible.

推荐答案

我相信您想使用sepBy.

type AST =
| Arguments of AST list
| Argument of string * string

let parseArguments =
    spaces 
    >>. pchar '(' 
    >>. spaces 
    >>. sepBy parseArgument (pchar ',') 
    .>> spaces 
    .>> pchar ')' 
    |>> Arguments

由devoured_elysium

上面的代码虽然没有编译,但却是正确的.我将在此处发布我的编译版本,以便任何人只要不花力气就能尝试代码,就可以这样做.

Edited by devoured_elysium:

The above code is correct although it doesn't compile. I'll post here my compiling version, so that if anyone just wants to try out the code without further ado, they can do it.

type AST =
| Arguments of AST list
| Argument of string

let parseArguments =
    spaces 
    >>. pchar '(' 
    >>. spaces 
    >>. sepBy (many1Satisfy isLetter |>> Argument) (pchar ',')
    .>> spaces 
    .>> pchar ')'
    |>> Arguments

test parseArguments "(a,b,c)" //succeed
test parseArguments "(a,b,c,)" //fail

这篇关于使用FParsec解析方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆