FParsec.CSharp 0.1.32

There is a newer version of this package available.
See the version list below for details.
dotnet add package FParsec.CSharp --version 0.1.32
NuGet\Install-Package FParsec.CSharp -Version 0.1.32
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="FParsec.CSharp" Version="0.1.32" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add FParsec.CSharp --version 0.1.32
#r "nuget: FParsec.CSharp, 0.1.32"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install FParsec.CSharp as a Cake Addin
#addin nuget:?package=FParsec.CSharp&version=0.1.32

// Install FParsec.CSharp as a Cake Tool
#tool nuget:?package=FParsec.CSharp&version=0.1.32

FParsec.CSharp

Build status NuGet

FParsec.CSharp is a C# wrapper for the F# package FParsec. FParsec is a parser combinator library with which you can implement parsers declaratively and efficiently.

Why FParsec.CSharp?

While using FParsec from C# is entirely possible in theory, it is very awkward in practice. Most of FParsec's elegance is lost in translation due to C#'s inferior type inference and its lack of custom operators.

FParsec.CSharp tries to alleviate that by wrapping FParsec's operators as extension functions.

FParsec.CSharp does not try to hide any types from FParsec or FSharp.Core--the wrapper is thin and also avoids name collisions. That way you can always fallback to FParsec anytime you need some functionality not (yet) implemented by FParsec.CSharp.

Based on the current implementation it should be easy to extend the wrapper yourself. Pull requests are always welcome!

Examples

You can find lots of examples in the test project. Below are some parser definitions from there.

Simple JSON

This is what a basic JSON parser looks like with FParsec.CSharp:

FSharpFunc<CharStream<Unit>, Reply<object>> jvalue = null;

var jnull = StringCI("null").Return((object)null);
var jnum = Int.Map(i => (object)i);
var jbool = StringCI("true").Or(StringCI("false"))
    .Map(b => (object)bool.Parse(b));
var quotedString = Between('"', Many(NoneOf("\"")), '"')
    .Map(string.Concat);
var jstring = quotedString.Map(s => (object)s);

var arrItems = Many(Rec(() => jvalue), sep: CharP(',').And(WS));
var jarray = Between(CharP('[').And(WS), arrItems, CharP(']'))
    .Map(elems => (object)new JArray(elems));

var jidentifier = quotedString;
var jprop = jidentifier.And(WS).And(Skip(':')).And(WS).And(Rec(() => jvalue))
    .Map((name, value) => new JProperty(name, value));
var objProps = Many(jprop, sep: CharP(',').And(WS));
var jobject = Between(CharP('{').And(WS), objProps, CharP('}'))
    .Map(props => (object)new JObject(props));

jvalue = OneOf(jnum, jbool, jnull, jstring, jarray, jobject).And(WS);

var simpleJsonParser = WS.And(jobject).And(WS).And(EOF).Map(o => (JObject)o);

Run it like so:

[Fact] public void CanParseJson() => simpleJsonParser
    .ParseString(@"{
        ""prop1"" : ""val"",
        ""prop2"" : [false, 13, null],
        ""prop3"" : { }
    }")
    .Result
    .ShouldBe(new JObject(
        new JProperty("prop1", "val"),
        new JProperty("prop2", new JArray(false, 13, null)),
        new JProperty("prop3", new JObject())));

Simple XML

var nameStart = Letter.Or(CharP('_'));
var nameChar = Letter.Or(Digit).Or(AnyOf("-_."));
var name = nameStart.And(Many(nameChar))
    .Map((first, rest) => string.Concat(rest.Prepend(first)));

var quotedString = Between('"', Many(NoneOf("\"")), '"')
    .Map(string.Concat);
var attribute = WS1.And(name).And(WS).And(Skip('=')).And(WS).And(quotedString)
    .Map((attrName, attrVal) => new XAttribute(attrName, attrVal));
var attributes = Many(Try(attribute));

FSharpFunc<CharStream<Unit>, Reply<XElement>> element = null;

var emptyElement = Between("<", name.And(attributes).And(WS), "/>")
    .Map((elName, attrs) => new XElement(elName, attrs));

var openingTag = Between('<', name.And(attributes).And(WS), '>');
FSharpFunc<CharStream<Unit>, Reply<string>> closingTag(string tagName) => Between("</", StringP(tagName).And(WS), ">");
var childElements = Many1(Try(WS.And(Rec(() => element)).And(WS)))
    .Map(attrs => (object)attrs);
var text = Many(NoneOf("<"))
    .Map(t => (object)string.Concat(t));
var content = childElements.Or(text);
var parentElement = openingTag.And(content).Map(Flat).And(x => closingTag(x.Item1).Return(x))
    .Map((elName, elAttrs, elContent) => new XElement(elName, elAttrs, elContent));

element = Try(emptyElement).Or(parentElement);

var simpleXmlParser = element.And(WS).And(EOF);

Glob patterns

var globParser =
    Many(OneOf(
        Skip('?').Map(NFA.MakeAnyChar),
        Skip('*').Map(NFA.MakeAnyChar).Map(NFA.MakeZeroOrMore),
        Between('[', AnyChar.And(Skip('-')).And(AnyChar), ']').Map(NFA.MakeCharRange),
        Skip('\\').And(AnyOf(@"?*[]\")).Map(NFA.MakeChar),
        AnyChar.Map(NFA.MakeChar)))
    .And(EOF)
    .Map(NFA.Concat)
    .Map(proto => proto(new Final()));

This example contructs a non-deterministic finite automaton (NFA) during parsing and can be used for matching:

[Fact] public void CanParseAndMatchGlobPattern() => globParser
    .ParseString(@"The * syntax is easy?").Result
    .Matches("The glob syntax is easy!")
    .ShouldBe(true);

Arithmetic expressions

FParsec.CSharp also comes with a builder to construct FParsec.OperatorPrecedenceParsers:

var basicExprParser = new OPPBuilder<int, Unit>()
    .WithOperators(ops => ops
        .AddInfix("+", 1, Associativity.Left, (x, y) => x + y)
        .AddInfix("*", 2, Associativity.Left, (x, y) => x * y))
    .WithTerms(Integer)
    .Build()
    .ExpressionParser;

var recursiveExprParser = new OPPBuilder<int, Unit>()
    .WithOperators(ops => ops
        .AddInfix("+", 1, Associativity.Left, (x, y) => x + y)
        .AddInfix("*", 2, Associativity.Left, (x, y) => x * y))
    .WithTerms(term => OneOf(Integer, Between('(', term, ')')))
    .Build()
    .ExpressionParser;

var exprParser =
    WS.And(new OPPBuilder<int, Unit>()
        .WithOperators(ops => ops
            .AddInfix("+", 10, Associativity.Left, WS, (x, y) => x + y)
            .AddInfix("-", 10, Associativity.Left, WS, (x, y) => x - y)
            .AddInfix("*", 20, Associativity.Left, WS, (x, y) => x * y)
            .AddInfix("/", 20, Associativity.Left, WS, (x, y) => x / y)
            .AddPrefix("-", 20, x => -x)
            .AddInfix("^", 30, Associativity.Right, WS, (x, y) => (int)Math.Pow(x, y))
            .AddPostfix("!", 40, Factorial))
        .WithImplicitOperator(20, (x, y) => x * y)
        .WithTerms(term => OneOf(
            Integer.And(WS),
            Between(CharP('(').And(WS), term, CharP(')').And(WS))))
        .Build()
        .ExpressionParser);

Hints

In order to simplify the types shown in IntelliSense you can use type aliases:

using Chars = FParsec.CharStream<Microsoft.FSharp.Core.Unit>;

Unfortunately C# does not support type aliases with open generics. Hence if you want to simplify the type of parser you will have to do it for each of the possible Reply<T>s you are using:

using StringParser = Microsoft.FSharp.Core.FSharpFunc<FParsec.CharStream<Microsoft.FSharp.Core.Unit>, FParsec.Reply<string>>;
using JsonParser = Microsoft.FSharp.Core.FSharpFunc<FParsec.CharStream<Microsoft.FSharp.Core.Unit>, FParsec.Reply<JObject>>;
// ...

Alternatives

FParsec.CSharp does not wrap all of FParsec's features yet. If you need an all-in-one solution then have a look at the following alternatives:

  • Pidgin
    • Can also parse binary data.
    • Not as fast as FParsec.
  • Sprache
    • Is not as optimized as Pidgin.
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories (2)

Showing the top 2 popular GitHub repositories that depend on FParsec.CSharp:

Repository Stars
sdcb/OpenVINO.NET
High quality .NET wrapper for OpenVINO™ toolkit.
sdcb/Sdcb.FFmpeg
FFmpeg basic .NET API generated by CppSharp
Version Downloads Last updated
12.2.0 1,868 12/28/2021
12.1.0 1,575 1/1/2021
12.0.5 340 12/30/2020
12.0.4 481 11/14/2020
12.0.3 493 7/10/2020
12.0.2 542 3/6/2020
12.0.1 419 3/6/2020
12.0.0 524 11/12/2019
11.0.0 545 10/3/2019
8.3.2 520 9/1/2019
8.3.1 526 6/23/2019
8.3.0 518 6/23/2019
8.2.0 501 6/18/2019
8.1.3 558 6/12/2019
8.1.2 544 6/11/2019
8.1.1 539 6/11/2019
8.1.0 542 6/11/2019
8.0.0 535 6/11/2019
7.1.1 565 6/10/2019
7.1.0 552 6/10/2019
7.0.0 535 6/10/2019
6.4.0 578 6/6/2019
6.3.0 594 6/6/2019
6.2.0 535 6/4/2019
6.1.0 551 6/4/2019
6.0.0 552 6/4/2019
5.12.0 567 6/3/2019
5.11.0 554 6/2/2019
5.10.2 536 5/31/2019
5.10.1 550 5/31/2019
5.9.0 541 5/28/2019
5.8.0 535 5/28/2019
5.7.0 523 5/28/2019
5.6.0 534 5/27/2019
5.5.0 532 5/27/2019
5.4.0 552 5/26/2019
5.3.0 524 5/25/2019
5.2.0 536 5/25/2019
5.1.0 518 5/25/2019
5.0.0 546 5/25/2019
4.5.0 542 5/24/2019
4.4.0 535 5/24/2019
4.3.0 546 5/24/2019
4.2.0 561 5/24/2019
4.1.0 532 5/24/2019
4.0.1 546 5/23/2019
4.0.0 536 5/23/2019
3.6.0 558 5/23/2019
3.5.0 533 5/23/2019
3.4.0 550 5/22/2019
3.3.0 589 5/22/2019
3.2.0 571 5/21/2019
3.1.0 574 5/21/2019
3.0.0 579 5/21/2019
2.17.0 585 5/21/2019
2.16.0 571 5/19/2019
2.15.0 553 5/19/2019
2.11.0 567 5/19/2019
2.10.1 553 5/19/2019
2.10.0 561 5/18/2019
2.9.0 591 5/18/2019
2.8.0 561 5/18/2019
2.7.0 542 5/18/2019
2.6.0 547 5/17/2019
2.5.0 564 5/17/2019
2.4.0 538 5/17/2019
2.3.0 548 5/17/2019
2.2.0 559 5/17/2019
2.1.0 536 5/17/2019
2.0.0 535 5/16/2019
1.1.0 578 5/16/2019
1.0.0 550 5/15/2019
0.1.36 560 5/10/2019
0.1.32 541 5/5/2019
0.1.29 564 5/3/2019
0.1.28 558 5/3/2019
0.1.26 555 5/3/2019
0.1.25 662 5/2/2019
0.1.20 547 4/29/2019
0.1.19 560 4/29/2019
0.1.18 560 4/29/2019
0.1.17 581 4/29/2019
0.1.16 560 4/28/2019
0.1.15 533 4/28/2019
0.1.14 561 4/28/2019
0.1.12 567 4/28/2019
0.1.9 580 4/28/2019
0.1.6 607 4/27/2019

Add support for implicit operators to `OPPBuilder`.