Skip to content
John Gietzen edited this page Aug 15, 2015 · 14 revisions

Installing

The easiest way to get a copy of Pegasus is to install the Pegasus NuGet package in Visual Studio.

PM> Install-Package Pegasus

Setting Up Your Project

Once you have the package installed, files in your project marked as 'PegGrammar' in the properties window will be compiled to their respective .peg.cs parser classes during each build. These parser classes will be automatically included in compilation, so there is no need to include the .peg.cs files yourself.

To mark a file as a 'PegGrammar' simple select the file in the solution explorer, hit F4 (to bring up the properties window), and choose 'PegGrammar' from the 'Build Action' drop-down.

Examples

Math.peg

A mathematical expression evaluator. Enhanced from the readme to ignore whitespace, report errors, and memoize where needed.

@namespace PegExamples
@classname MathExpressionParser

start <decimal>
  = _ value:additive _ EOF { value }

additive <decimal> -memoize
    = left:additive _ "+" _ right:multiplicative { left + right }
    / left:additive _ "-" _ right:multiplicative { left - right }
    / multiplicative

multiplicative <decimal> -memoize
    = left:multiplicative _ "*" _ right:primary { left * right }
    / left:multiplicative _ "/" _ right:primary { left / right }
    / primary

primary <decimal>
    = decimal
    / "(" _ additive:additive _ ")" { additive }

decimal <decimal>
    = value:([0-9]+ ("." [0-9]+)?) { decimal.Parse(value) }

_ = [ \t\r\n]*

EOF
  = !.
  / unexpected:. #ERROR{ "Unexpected character '" + unexpected + "'." }

AMEX.peg

American Express CSV parser, supporting strings containing newlines and double quotes.

file <IList<object>>
  = l:line<1,, eol> eol eof { l }

line<object>
  = date:        bare   ","
                 string ","
    description: string ","
    cardholder:  string ","
    account:     string ","
                 string ","
                 string ","
    amount:      bare   ","
                 string ","
                 string ","
    details:     string ","
    merchant:    string ","
    address1:    string ","
    address2:    string ","
                 string ","
                 string ","
                 string
  {
    new { date, description, cardholder, account, amount, details, merchant, address1, address2 }
  }

end
  = "," / eol

bare
  = '' (!end .)*

string
  = '"' c:char* '"' { string.Concat(c) }
  / &end            { null }

char
  = c:[^"\\] { c }
  / '\\' c:. { c }

eol
  = '\r\n' / '\n'

eof
  = !.
Clone this wiki locally