Greg Young [MVP]

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Irony!!


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


Posted Tue, Feb 5 2008 4:16 PM by Greg

[Advertisement]

Comments

Erik wrote re: Irony!!
on Wed, Feb 6 2008 12:10 AM

Oh that's weird. I *just started* building something like this myself.

Jason Haley wrote Interesting Finds: February 6, 2008
on Wed, Feb 6 2008 12:26 PM
Matthew Podwysocki's Blog wrote DSLs, Compilers and the Irony of it All
on Wed, Feb 6 2008 7:14 PM

In a previous post, I posted about the Lang.NET symposium and rolling your own compiler. I cited an MSDN

Add a Comment

(required)  
(optional)
(required)  
Remember Me?