Been looking for something like this ... This will be quite useful for things like DSL creation or for finally creating that logo.net implementation we have all been waiting for.
Or you could for instance start putting serialized versions of ASTs in attributes anyone? Think ...
private void MyMethod( [Requires("value>5 and value<10")] int i) {
}
I reckon you could implement that in a few hours with this little gem. ASTs in attributes are yummy.
http://www.codeplex.com/irony
using System;
using System.Collections.Generic;
using System.Text;
using Irony.Compiler;
namespace Irony.Samples {
//Sample expression grammar - recognizes arithmetic expressions with numbers and variables
//
// Expr -> n | v | Expr BinOp Expr | UnOp Expr | ( Expr )
// BinOp -> + | - | * | / | **
// UnOp -> -
// ExprLine -> Expr EOF
public class ExpressionGrammar : Irony.Compiler.Grammar {
public ExpressionGrammar() {
// 1. Terminals
Terminal n = new NumberTerminal("number");
Terminal v = new IdentifierTerminal("variable");
// 2. Non-terminals
NonTerminal Expr = new NonTerminal("Expr");
NonTerminal BinOp = new NonTerminal("BinOp");
NonTerminal UnOp = new NonTerminal("UnOp");
NonTerminal ExprLine = new NonTerminal("ExprLine");
// 3. BNF rules
Expr.Rule = n | v | Expr + BinOp + Expr | UnOp + Expr | "(" + Expr + ")";
BinOp.Rule = Symbol("+") | "-" | "*" | "/" | "**";
UnOp.Rule = "-";
ExprLine.Rule = Expr + Eof; //EOF it is optional
this.Root = ExprLine; // Set grammar root
// 4. Operators precedence
RegisterOperators(1, "+", "-");
RegisterOperators(2, "*", "/");
RegisterOperators(3, Associativity.Right, "**");
PunctuationSymbols.AddRange(new string[] { "(", ")" });
}
}
}
// Parsing expressions
ExpressionGrammar grammar = new ExpressionGrammar();
LanguageCompiler compiler = new LanguageCompiler(grammar);
string expr = "a + b * 3.14 / (2.0 * x + y**z**2)";
AstNode rootNode = compiler.Parse(expr);
//rootNode now contains an AST node that is the root of the syntax tree.
updated: nice little article here http://www.codeproject.com/KB/recipes/Irony.aspx
