A little sooner than expected, I decided to publish the source code for LazyParser.NET on CodePlex.

LazyParser.NET is a lightweight C# expression parser that allows you to add late-bound expression parsing to your .NET applications. It will allow you to use (user supplied?) C# expressions to be used in a variety of situations:

  • Validation expressions
  • Blog engines
  • Content management systems
  • Calculators

The following features are supported in this release:

  • Full C# 2.0 expression syntax (exceptions listed below)
    • All numeric and boolean operators
    • Method calls (isolated and member/static methods)
    • Constructor calls
    • typeof() expression
    • All literals (numeric, character, string), including character and string escaping
  • C# 2.0 compliant (operator precedence, implicit conversions, nullable type lifting, type promotion, etc…)
  • Late binding
  • Field access interceptors at runtime
  • Support for member fields, properties and methods
  • Support for static fields, properties and methods
  • Function injection using delegates

Not supported in this release:

  • Indexing operator ( “[]” )
  • Conditional operator ( a ? b : c)
  • Unary operators (except “!”, which is supported)
  • “is” and “as” operators

An example of how you can use this library:

ParserContext context = new ParserContext();

context.Add("Math", new ClassName(typeof(Math)));
context.Add("SomeString", "Hi there!");
context.Add("SomeNumber", 20);
context.Add("fmt",  new StaticMethod(typeof(String), "Format"));

CSharpParser parser = new CSharpParser();

string stringValue = parser.Evaluate<string>("fmt(\"I said: {0}\", SomeString)", context);  // returns "I said: Hi there!"

int intValue = parser.Evaluate<int>("Math.Max(10, SomeNumber)" , context); // returns 20

double doubleValue = parser.Evaluate<double>("SomeNumber * 2.0", context); // returns 40.0

 

This is just the first pre-1.0 release of this library, so there may be some small problems. Any suggestions for improvement or bug reports are more than welcome. Please use the CodePlex discussion area and the issue tracker for this purpose

UPDATE: LazyParser.NET v0.9.1 has been published on CodePlex, with support for indexing operators.




This weblog is sponsored by The Vici Project.
Share this article:
  • Digg
  • StumbleUpon
  • del.icio.us
  • Twitter
  • DotNetKicks
  • DZone
  • LinkedIn
  • Reddit
  • Tumblr