RSS Feed for This PostCurrent Article

C# Parser Framework

Sprache is a small library for constructing parsers directly in C# code.

It isn’t an "industrial strength" framework – it fits somewhere in between regular expressions and a full-blown toolset like ANTLR.

Unlike most parser-building frameworks, you use Sprache directly from your program code, and don’t need to set up any build-time code generation tasks.

A simple parser might parse a sequence of characters:

   1: // Parse any number of capital 'A's in a row

   2: var parseA = Parse.Char('A').AtLeastOnce();

Sprache provides a number of built-in functions that can make bigger parsers from smaller ones, often callable via Linq query comprehensions:

   1: Parser<string> identifier =

   2:             from leading in Parse.Whitespace.Many()

   3:             from first in Parse.Letter.Once()

   4:             from rest in Parse.LetterOrDigit.Many()

   5:             from trailing in Parse.Whitespace.Many()

   6:             select new string(first.Concat(rest).ToArray());

   7:  

   8: var id = identifier.Parse(" abc123  ");

   9:  

  10: Assert.AreEqual("abc123", id);


Trackback URL


Sorry, comments for this entry are closed at this time.