Pegasus PEG Parser Generator for C#

repository·develop·Indexed 42 days ago

https://github.com/otac0n/pegasus

A Parsing Expression Grammar (PEG) parser generator for C# that integrates with MSBuild and Visual Studio. It uses a custom PegGrammar build action to automatically generate parser classes from .peg grammar files during the build process.

Tokens
572
Snippets
2
Records
3
Agent score
3%

What's inside Pegasus

  1. Use PegGrammar build action to generate parsers

    develop

    Pegasus uses a custom MSBuild build action called PegGrammar.

    1. Create a grammar file (e.g., MyParser.peg).
    2. In the Visual Studio Properties window for that file, set the Build Action to PegGrammar.
    3. During every build, Pegasus will compile the grammar into a corresponding .peg.g.cs parser class.
    4. These generated classes are automatically included in your project's compilation, so you can instantiate them directly in your C# code.
  2. Install Pegasus via NuGet

    develop

    The easiest way to use Pegasus in a C# project is to install the Pegasus NuGet package. This integrates the parser generator with MSBuild and Visual Studio.

    In the Visual Studio Package Manager Console, run:

    Install-Package Pegasus

    Note for Visual Studio 2017 and earlier: You may need to reload your project for the PegGrammar build action to be correctly recognized after installation.

  3. Create a mathematical expression parser with Pegasus

    develop

    Pegasus uses a PEG-style syntax to define rules. You can use directives like @namespace, @classname, and @using to configure the generated C# class. Rules can also use the -memoize directive to improve performance for certain grammar structures.

    Example grammar file:

    @namespace PegExamples
    @classname ExpressionParser
    @using System.Globalization
    
    additive <double> -memoize
        = left:additive "+" right:multiplicative { left + right }
        / left:additive "-" right:multiplicative { left - right }
        / multiplicative
    
    multiplicative <double> -memoize
        = left:multiplicative "*" right:power { left * right }
        / left:multiplicative "/" right:power { left / right }
        / power
    
    power <double>
        = left:primary "^" right:power { Math.Pow(left, right) }
        / primary
    
    primary <double> -memoize
        = decimal
        / "-" primary:primary { -primary }
        / "(" additive:additive ")" { additive }
    
    decimal <double>
        = value:([0-9]+ ("." [0-9]+)?) { double.Parse(value, CultureInfo.InvariantCulture) }

    To use the generated parser in your C# code:

    var parser = new PegExamples.ExpressionParser();
    var result = parser.Parse("5.1+2*3");
    Console.WriteLine(result); // Outputs "11.1".