public GrammarResult Grammar() { GrammarResult result = new GrammarResult(); foreach (Production production in Compiler.Parser.Grammar.Instance) { ProductionModel productionModel = new ProductionModel { Head = production.Identifier }; production.ForEach(x => { productionModel.SubProductions.Add(new SubProductionModel { Expressions = x.Select(y => new ExpressionModel { Name = y.ToString(), IsNonTerminalExpression = y is NonTerminalExpressionDefinition }).ToList() }); }); result.Productions.Add(productionModel); } return(result); }
public static SearchResult <T> FilterUsingAntlr <T>( this IQueryable <T> query, string queryString, params Expression <Func <T, string> >[] properties) { if (query == null) { throw new ArgumentNullException("query"); } if (properties == null) { throw new ArgumentNullException("properties"); } if (properties.Length == 0) { throw new ArgumentException("At least one property is expected", "properties"); } if (string.IsNullOrWhiteSpace(queryString)) { return(new SearchResult <T>(query, Enumerable.Empty <string>())); } AntlrInputStream input = new AntlrInputStream(queryString); SearchGrammarLexer lexer = new SearchGrammarLexer(input); CommonTokenStream tokens = new CommonTokenStream(lexer); SearchGrammarParser parser = new SearchGrammarParser(tokens); IParseTree parseTree = parser.prog(); var arg = Expression.Parameter(typeof(T), "p"); MemberExpression[] memberExpressions = new MemberExpression[properties.Length]; for (int i = 0; i < properties.Length; i++) { var propertyMemberExpression = properties[i].Body as MemberExpression; if (propertyMemberExpression == null) { throw new ArgumentException( "The " + i + "th property is invalid. Please provide property member expression like 'o => o.Name'", "properties"); } string propertyString = propertyMemberExpression.ToString(); string name = propertyString.Substring(propertyString.IndexOf('.') + 1); memberExpressions[i] = Expression.Property(arg, name); } #if DEBUG string treeText = new StringBuilderVisitor().Visit(parseTree); System.Diagnostics.Trace.WriteLine(treeText); #endif GrammarResult searchResult = null; try { ExpressionBuilderVisitor visitor = new ExpressionBuilderVisitor(memberExpressions); searchResult = visitor.Visit(parseTree); } catch (InvalidSearchException) { string failedTreeText = new StringBuilderVisitor().Visit(parseTree); System.Diagnostics.Trace.WriteLine("Failed to parse search grammar '" + queryString + "': \r\n" + failedTreeText); throw; } var searchPredicate = Expression.Lambda <Func <T, bool> >(searchResult.Expression, arg); return(new SearchResult <T>(query.Where(searchPredicate), searchResult.Terms)); }