Introduction

Lingua.NET is a parser generator that uses code-based grammar definitions. Parser generators typically read a text-based grammar specification and emit source code that is subsequently compiled. Lingua.NET uses reflection to extract the grammar from an assembly and create the corresponding parser.

A grammar consits of three primary elements:

Specifying a Grammar

Terminals, nonterminals and rules are defined by class and static methods as illustrated below.

Terminals

[Terminal(@"\d+")]
public class Number : Terminal
{
}
A terminal is a class that:

Nonterminals

public class BooleanOperator : Nonterminal
{
}
A nonterminal is a class that:

Rules

public class BooleanOperator : Nonterminal
{
    public static void Rule(BooleanOperator result, OperatorAddition op)
    {
      // Code
    }
}
A rule is a static method that:

Using Lingua.NET

Once a grammar has been defined, use Lingua.NET to generate a terminal reader and parser.

Load Grammar

Construct a Grammar object and read in the grammar defined within the specified assembly.
Assembly assembly = Assembly.GetAssembly(typeof(App));

Grammar grammar = new Grammar();
grammar.Load(assembly);
grammar.LoadRules(assembly);
grammar.Resolve();

Generate Parser and Terminal Reader

The grammar is used to construct a terminal reader and parser.
ITerminalReaderGenerator terminalReaderGenerator = new TerminalReaderGenerator();
TerminalReaderGeneratorResult terminalReaderGeneratorResult = terminalReaderGenerator.GenerateTerminalReader(grammar);
ITerminalReader terminalReader = terminalReaderGeneratorResult.TerminalReader;

IParserGenerator parserGenerator = new ParserGenerator();
ParserGeneratorResult parserGeneratorResult = parserGenerator.GenerateParser(grammar);
IParser parser = parserGeneratorResult.Parser;

Open Terminal Reader and Parse Terminal Stream

The terminal reader and parser are used to process the desired text.
terminalReader.Open(txtExpression.Text);
Start result = parser.Parse(terminalReader);