CSharp · Console
using System;
using System.Reflection;
using Sprache;
using System.Linq;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
var expr = QueryGrammar<StoreData>.ParseCondition(@"
OR(
AND(
EQUAL(title, ""Foo""),
AND(
GREATER_THAN(views, 50),
EQUAL(timestamp, 123456789)
)
),
EQUAL(id, ""123"")
)");
Console.WriteLine(expr);
var func = expr.Compile();
var result = func(new StoreData
{
id = "321",
title = "Foo",
views = 51,
timestamp = 123456789
});
Console.WriteLine(result);
}
}
public class StoreData
{
public string id { get; set; }
public string title { get; set; }
public string content { get; set; }
public int views { get; set; }
public int timestamp { set; get; }
}
public static class QueryGrammar<T>
{
// We're parsing the query and translating it into an expression in the form
// of a lambda function taking a parameter of type T as input
static readonly ParameterExpression Param = Expression.Parameter(typeof(T));
// The only public member
public static Expression<Func<T, bool>> ParseCondition(string input)
{
// Parse a Term (recursively) until the end of the input is reached.
// Convert the output expression body into a lambda function that can
// be applied to an object of type T returning a bool (predicate)
return Term.End()
.Select(body => Expression.Lambda<Func<T, bool>>(body, Param))
.Parse(input);
}
// For escaping a character (such as ")
static Parser<char> EscapingChar => Parse.Char('\\');
// Pick the character that was escaped
static Parser<char> EscapedChar =>
from _ in EscapingChar
from c in Parse.AnyChar
select c;
static Parser<char> QuoteChar => Parse.Char('"');
static Parser<char> NonQuoteChar =>
Parse.AnyChar.Except(QuoteChar);
// Pick text in-between double qoutes
static Parser<string> QuotedText =>
from open in QuoteChar
from content in EscapedChar.Or(NonQuoteChar).Many().Text()
from close in QuoteChar
select content;
// Create an expression that "calls the getter of a property on a object of type T"
private static Expression GetProperty(string propName)
{
var memInfo = typeof(T).GetMember(propName,
MemberTypes.Property,
BindingFlags.Instance | BindingFlags.Public)
.FirstOrDefault();
if (memInfo == null)
throw new ParseException($"Property with name '{propName}' not found on type '{typeof(T)}'");
return Expression.MakeMemberAccess(Param, memInfo);
}
// Match a word without quotes, in order to match a field/property name
static Parser<Expression> FieldToken =>
Parse.Letter.AtLeastOnce().Text().Token()
.Select(name => GetProperty(name));
// Match a value. Either an integer or a quoted string
static Parser<Expression> ValueToken =>
(from strNum in Parse.Number
select Expression.Constant(int.Parse(strNum)))
.Or(QuotedText.Select(t => Expression.Constant(t)))
.Token();
// Common parser for all terms
static Parser<Expression> Term =>
EqualTerm
.Or(GreaterThanTerm)
.Or(OrTerm)
.Or(AndTerm);
static Parser<Expression> EqualTerm =>
(from tuple in Comparer("EQUAL")
select Expression.Equal(tuple.Field, tuple.Value))
.Token();
static Parser<Expression> GreaterThanTerm =>
(from tuple in Comparer("GREATER_THAN")
select Expression.GreaterThan(tuple.Field, tuple.Value))
.Token();
// Generally the comparer terms consist of:
// COMPARER_NAME + ( + FIELD_NAME + , + VALUE + )
static Parser<(Expression Field, Expression Value)> Comparer(string comparison) =>
(from startsWith in Parse.String(comparison).Text().Token()
from openParen in Parse.Char('(')
from field in FieldToken
from comma in Parse.Char(',')
from value in ValueToken
from closeParen in Parse.Char(')')
select (field, value))
.Token();
static Parser<Expression> AndTerm =>
(from tuple in Combinator("AND")
select Expression.AndAlso(tuple.Left, tuple.Right))
.Token();
static Parser<Expression> OrTerm =>
(from tuple in Combinator("OR")
select Expression.OrElse(tuple.Left, tuple.Right))
.Token();
// Generally combinators consist of:
// COMBINATOR_NAME + ( + TERM + , + TERM + )
// A term can be either a comparer of another combinator as seem above
static Parser<(Expression Left, Expression Right)> Combinator(string combination) =>
(from startsWith in Parse.String(combination).Text().Token()
from openParen in Parse.Char('(')
from lTerm in Term
from comma in Parse.Char(',')
from rTerm in Term
from closeParen in Parse.Char(')')
select (lTerm, rTerm))
.Token();
}