Skip to content
John Gietzen edited this page Dec 2, 2016 · 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 parser classes during each build.

To mark a file as a 'PegGrammar' simply select the file in the solution explorer, hit F4 (to bring up the properties window), and choose 'PegGrammar' from the 'Build Action' drop-down. If the build action is not available, you may need to reload your project.

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