public static ExprNode MathGetExpr(IParseTree ctx, IDictionary <ITree, ExprNode> astExprNodeMap, ConfigurationInformation configurationInformation) { var count = 1; var @base = ASTExprHelper.ExprCollectSubNodes(ctx.GetChild(0), 0, astExprNodeMap)[0]; while (true) { int token = ASTUtil.GetAssertTerminatedTokenType(ctx.GetChild(count)); var mathArithTypeEnum = TokenToMathEnum(token); var right = ASTExprHelper.ExprCollectSubNodes(ctx.GetChild(count + 1), 0, astExprNodeMap)[0]; var math = new ExprMathNode(mathArithTypeEnum, configurationInformation.EngineDefaults.ExpressionConfig.IsIntegerDivision, configurationInformation.EngineDefaults.ExpressionConfig.IsDivisionByZeroReturnsNull); math.AddChildNode(@base); math.AddChildNode(right); @base = math; count += 2; if (count >= ctx.ChildCount) { break; } } return(@base); }
public static IList <ColumnDesc> GetColTypeList(EsperEPL2GrammarParser.CreateColumnListContext ctx) { if (ctx == null) { return(Collections.GetEmptyList <ColumnDesc>()); } IList <ColumnDesc> result = new List <ColumnDesc>(ctx.createColumnListElement().Length); foreach (var colctx in ctx.createColumnListElement()) { IList <EsperEPL2GrammarParser.ClassIdentifierContext> idents = colctx.classIdentifier(); var name = ASTUtil.UnescapeClassIdent(idents[0]); string type; if (colctx.VALUE_NULL() != null) { type = null; } else { type = ASTUtil.UnescapeClassIdent(idents[1]); } var array = colctx.b != null; var primitiveArray = ValidateIsPrimitiveArray(colctx.p); result.Add(new ColumnDesc(name, type, array, primitiveArray)); } return(result); }
public static String PrintNode(ITree node) { var writer = new StringWriter(); ASTUtil.DumpAST(writer, node, 0); return(writer.ToString()); }
/// <summary> /// Resolve "table" and "table.property" when nested-property, not chainable /// </summary> public static ExprTableAccessNode CheckTableNameGetExprForProperty(TableService tableService, string propertyName) { // handle "var_name" alone, without chained, like an simple event property var index = ASTUtil.UnescapedIndexOfDot(propertyName); if (index == -1) { if (tableService.GetTableMetadata(propertyName) != null) { return(new ExprTableAccessNodeTopLevel(propertyName)); } return(null); } // handle "var_name.column", without chained, like a nested event property var tableName = ASTUtil.UnescapeDot(propertyName.Substring(0, index)); if (tableService.GetTableMetadata(tableName) == null) { return(null); } // it is a tables's subproperty var sub = propertyName.Substring(index + 1); return(new ExprTableAccessNodeSubprop(tableName, sub)); }
/// <summary> /// Resolve "table.property", not chainable /// </summary> public static Pair <ExprTableAccessNode, ExprDotNode> CheckTableNameGetExprForSubproperty(TableService tableService, string tableName, string subproperty) { var metadata = tableService.GetTableMetadata(tableName); if (metadata == null) { return(null); } var index = ASTUtil.UnescapedIndexOfDot(subproperty); if (index == -1) { if (metadata.KeyTypes.Length > 0) { return(null); } var tableNodeX = new ExprTableAccessNodeSubprop(tableName, subproperty); return(new Pair <ExprTableAccessNode, ExprDotNode>(tableNodeX, null)); } // we have a nested subproperty such as "tablename.subproperty.abc" IList <ExprChainedSpec> chainedSpecs = new List <ExprChainedSpec>(1); chainedSpecs.Add(new ExprChainedSpec(subproperty.Substring(index + 1), Collections.GetEmptyList <ExprNode>(), true)); var tableNode = new ExprTableAccessNodeSubprop(tableName, subproperty.Substring(0, index)); var dotNode = new ExprDotNode(chainedSpecs, false, false); dotNode.AddChildNode(tableNode); return(new Pair <ExprTableAccessNode, ExprDotNode>(tableNode, dotNode)); }
public static FilterSpecRaw WalkFilterSpec(EsperEPL2GrammarParser.EventFilterExpressionContext ctx, PropertyEvalSpec propertyEvalSpec, IDictionary <ITree, ExprNode> astExprNodeMap) { var eventName = ASTUtil.UnescapeClassIdent(ctx.classIdentifier()); var exprNodes = ctx.expressionList() != null?ASTExprHelper.ExprCollectSubNodes(ctx.expressionList(), 0, astExprNodeMap) : new List <ExprNode>(1); return(new FilterSpecRaw(eventName, exprNodes, propertyEvalSpec)); }
public void TestParse() { Object result; Assert.AreEqual("abc", ParseLoadJson("\"abc\"")); Assert.AreEqual("http://www.uri.com", ParseLoadJson("\"http://www.uri.com\"")); Assert.AreEqual("new\nline", ParseLoadJson("\"new\\nline\"")); Assert.AreEqual(" ~ ", ParseLoadJson("\" \\u007E \"")); Assert.AreEqual("/", ParseLoadJson("\"\\/\"")); Assert.AreEqual(true, ParseLoadJson("true")); Assert.AreEqual(false, ParseLoadJson("false")); Assert.AreEqual(null, ParseLoadJson("null")); Assert.AreEqual(10, ParseLoadJson("10")); Assert.AreEqual(-10, ParseLoadJson("-10")); Assert.AreEqual(20L, ParseLoadJson("20L")); Assert.AreEqual(5.5d, ParseLoadJson("5.5")); result = ParseLoadJson("{\"name\":\"myname\",\"value\":5}"); EPAssertionUtil.AssertPropsMap((Map)result, "name,value".Split(','), "myname", 5); result = ParseLoadJson("{name:\"myname\",value:5}"); EPAssertionUtil.AssertPropsMap((Map)result, "name,value".Split(','), "myname", 5); result = ParseLoadJson("[\"one\",2]"); EPAssertionUtil.AssertEqualsExactOrder(new Object[] { "one", 2 }, (IList <object>)result); result = ParseLoadJson("{\"one\": { 'a' : 2 } }"); Map inner = (Map)((Map)result).Get("one"); Assert.AreEqual(1, inner.Count); String json = "{\n" + " \"glossary\": {\n" + " \"title\": \"example glossary\",\n" + "\t\t\"GlossDiv\": {\n" + " \"title\": \"S\",\n" + "\t\t\t\"GlossList\": {\n" + " \"GlossEntry\": {\n" + " \"ID\": \"SGML\",\n" + "\t\t\t\t\t\"SortAs\": \"SGML\",\n" + "\t\t\t\t\t\"GlossTerm\": \"Standard Generalized Markup Language\",\n" + "\t\t\t\t\t\"Acronym\": \"SGML\",\n" + "\t\t\t\t\t\"Abbrev\": \"ISO 8879:1986\",\n" + "\t\t\t\t\t\"GlossDef\": {\n" + " \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\n" + "\t\t\t\t\t\t\"GlossSeeAlso\": [\"GML\", \"XML\"]\n" + " },\n" + "\t\t\t\t\t\"GlossSee\": \"markup\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}"; ITree tree = ParseJson(json).First; ASTUtil.DumpAST(tree); Object loaded = ParseLoadJson(json); Assert.AreEqual("{glossary={title=example glossary, GlossDiv={title=S, GlossList={GlossEntry={ID=SGML, SortAs=SGML, GlossTerm=Standard Generalized Markup Language, Acronym=SGML, Abbrev=ISO 8879:1986, GlossDef={para=A meta-markup language, used to create markup languages such as DocBook., GlossSeeAlso=[GML, XML]}, GlossSee=markup}}}}}", loaded.Render()); }
public void TestEscapeDot() { String [][] inout = new String[][] { new [] { "a", "a" }, new [] { "", "" }, new [] { " ", " " }, new [] { ".", "\\." }, new [] { ". .", "\\. \\." }, new [] { "a.", "a\\." }, new [] { ".a", "\\.a" }, new [] { "a.b", "a\\.b" }, new [] { "a..b", "a\\.\\.b" }, new [] { "a\\.b", "a\\.b" }, new [] { "a\\..b", "a\\.\\.b" }, new [] { "a.\\..b", "a\\.\\.\\.b" }, new [] { "a.b.c", "a\\.b\\.c" } }; for (int i = 0; i < inout.Length; i++) { String @in = inout[i][0]; String expected = inout[i][1]; Assert.AreEqual(expected, ASTUtil.EscapeDot(@in), "for input " + @in); } }
public void TestUnescapeIndexOf() { Object [][] inout = new Object[][] { new Object[] { "a", -1 }, new Object[] { "", -1 }, new Object[] { " ", -1 }, new Object[] { ".", 0 }, new Object[] { " . .", 1 }, new Object[] { "a.", 1 }, new Object[] { ".a", 0 }, new Object[] { "a.b", 1 }, new Object[] { "a..b", 1 }, new Object[] { "a\\.b", -1 }, new Object[] { "a.\\..b", 1 }, new Object[] { "a\\..b", 3 }, new Object[] { "a.b.c", 1 }, new Object[] { "abc.", 3 } }; for (int i = 0; i < inout.Length; i++) { var @in = (String)inout[i][0]; var expected = (int?)inout[i][1]; Assert.AreEqual(expected, ASTUtil.UnescapedIndexOfDot(@in), "for input " + @in); } }
private static CreateSchemaDesc GetSchemaDesc(EsperEPL2GrammarParser.CreateSchemaDefContext ctx, AssignedType assignedType) { var schemaName = ctx.name.Text; var columnTypes = GetColTypeList(ctx.createColumnList()); // get model-after types (could be multiple for variants) ISet <string> typeNames = new LinkedHashSet <string>(); if (ctx.variantList() != null) { IList <EsperEPL2GrammarParser.VariantListElementContext> variantCtxs = ctx.variantList().variantListElement(); foreach (var variantCtx in variantCtxs) { typeNames.Add(variantCtx.GetText().UnmaskTypeName()); } } // get inherited and start timestamp and end timestamps string startTimestamp = null; string endTimestamp = null; ISet <string> inherited = new LinkedHashSet <string>(); ISet <string> copyFrom = new LinkedHashSet <string>(); if (ctx.createSchemaQual() != null) { IList <EsperEPL2GrammarParser.CreateSchemaQualContext> qualCtxs = ctx.createSchemaQual(); foreach (var qualCtx in qualCtxs) { var qualName = qualCtx.i.Text.ToLower(); var cols = ASTUtil.GetIdentList(qualCtx.columnList()); var qualNameLower = qualName.ToLower(); switch (qualNameLower) { case "inherits": inherited.AddAll(cols); continue; case "starttimestamp": startTimestamp = cols[0]; continue; case "endtimestamp": endTimestamp = cols[0]; continue; case "copyfrom": copyFrom.AddAll(cols); continue; } throw new EPException("Expected 'inherits', 'starttimestamp', 'endtimestamp' or 'copyfrom' keyword after create-schema clause but encountered '" + qualName + "'"); } } return(new CreateSchemaDesc(schemaName, typeNames, columnTypes, inherited, assignedType, startTimestamp, endTimestamp, copyFrom)); }
public void TestGetPropertyNameEscaped() { String PROPERTY = "a\\.b\\.c"; Pair <ITree, CommonTokenStream> parsed = SupportParserHelper.ParseEventProperty(PROPERTY); ITree propertyNameExprNode = parsed.First.GetChild(0); ASTUtil.DumpAST(propertyNameExprNode); String propertyName = ((IRuleNode)propertyNameExprNode).GetText(); Assert.AreEqual(PROPERTY, propertyName); }
private Object ParseLoadJson(String expression) { Pair <ITree, CommonTokenStream> parsed = ParseJson(expression); EsperEPL2GrammarParser.StartJsonValueRuleContext tree = (EsperEPL2GrammarParser.StartJsonValueRuleContext)parsed.First; Assert.AreEqual(EsperEPL2GrammarParser.RULE_startJsonValueRule, ASTUtil.GetRuleIndexIfProvided(tree)); ITree root = tree.GetChild(0); ASTUtil.DumpAST(root); return(ASTJsonHelper.Walk(parsed.Second, tree.jsonvalue())); }
/// <summary> /// Parse the AST constant node and return Object value. /// </summary> /// <param name="node">parse node for which to parse the string value</param> /// <returns>value matching AST node type</returns> public static Object Parse(IParseTree node) { if (node is ITerminalNode) { var terminal = (ITerminalNode)node; switch (terminal.Symbol.Type) { case EsperEPL2GrammarParser.BOOLEAN_TRUE: return(BoolValue.ParseString(terminal.GetText())); case EsperEPL2GrammarParser.BOOLEAN_FALSE: return(BoolValue.ParseString(terminal.GetText())); case EsperEPL2GrammarParser.VALUE_NULL: return(null); default: throw ASTWalkException.From("Encountered unexpected constant type " + terminal.Symbol.Type, terminal.Symbol); } } else { var ruleNode = (IRuleNode)node; var ruleIndex = ruleNode.RuleContext.RuleIndex; if (ruleIndex == EsperEPL2GrammarParser.RULE_number) { return(ParseNumber(ruleNode, 1)); } else if (ruleIndex == EsperEPL2GrammarParser.RULE_numberconstant) { var number = FindChildRuleByType(ruleNode, EsperEPL2GrammarParser.RULE_number); if (ruleNode.ChildCount > 1) { if (ASTUtil.IsTerminatedOfType(ruleNode.GetChild(0), EsperEPL2GrammarLexer.MINUS)) { return(ParseNumber(number, -1)); } return(ParseNumber(number, 1)); } else { return(ParseNumber(number, 1)); } } else if (ruleIndex == EsperEPL2GrammarParser.RULE_stringconstant) { bool requireUnescape = !IsRegexpNode(node); return(StringValue.ParseString(node.GetText(), requireUnescape)); } else if (ruleIndex == EsperEPL2GrammarParser.RULE_constant) { return(Parse(ruleNode.GetChild(0))); } throw ASTWalkException.From("Encountered unrecognized constant", node.GetText()); } }
internal static IList <string> GetLambdaGoesParams(EsperEPL2GrammarParser.ExpressionLambdaDeclContext ctx) { IList <string> parameters; if (ctx.i != null) { parameters = new List <string>(1); parameters.Add(ctx.i.Text); } else { parameters = ASTUtil.GetIdentList(ctx.columnList()); } return(parameters); }
private static String[] ParseParamsStreamNames(EsperEPL2GrammarParser.GopParamsItemContext item) { IList <String> paramNames = new List <String>(1); if (item.gopParamsItemMany() != null) { foreach (var ctx in item.gopParamsItemMany().classIdentifier()) { paramNames.Add(ctx.GetText()); } } else { paramNames.Add(ASTUtil.UnescapeClassIdent(item.classIdentifier())); } return(paramNames.ToArray()); }
public static void ExprCollectAddSingle(ExprNode parentNode, ITree node, IDictionary <ITree, ExprNode> astExprNodeMap) { if (parentNode == null) { throw ASTWalkException.From("Invalid null expression node for '" + ASTUtil.PrintNode(node) + "'"); } if (node == null) { return; } ExprAction action = (exprNodeX, astExprNodeMapX, nodeX) => { astExprNodeMapX.Remove(nodeX); parentNode.AddChildNode(exprNodeX); }; RecursiveFindRemoveChildExprNode(node, astExprNodeMap, action); }
public static void RegExCollectAddSubNodes(RowRegexExprNode regexNode, ITree node, IDictionary <ITree, RowRegexExprNode> astRegExNodeMap) { if (regexNode == null) { throw ASTWalkException.From("Invalid null expression node for '" + ASTUtil.PrintNode(node) + "'"); } RegExAction action = (exprNode, astRegExNodeMapX, nodeX) => { astRegExNodeMapX.Remove(nodeX); regexNode.AddChildNode(exprNode); }; for (var i = 0; i < node.ChildCount; i++) { var childNode = node.GetChild(i); RegExApplyActionRecursive(childNode, astRegExNodeMap, action); } }
public static void PatternCollectAddSubnodesAddParentNode(EvalFactoryNode evalNode, ITree node, IDictionary <ITree, EvalFactoryNode> astPatternNodeMap) { if (evalNode == null) { throw ASTWalkException.From("Invalid null expression node for '" + ASTUtil.PrintNode(node) + "'"); } for (var i = 0; i < node.ChildCount; i++) { var childNode = node.GetChild(i); var childEvalNode = PatternGetRemoveTopNode(childNode, astPatternNodeMap); if (childEvalNode != null) { evalNode.AddChildNode(childEvalNode); } } astPatternNodeMap.Put(node, evalNode); }
/// <summary> /// Walk an annotation root name or child node (nested annotations). /// </summary> /// <param name="ctx">annotation walk node</param> /// <param name="engineImportService">for engine imports</param> /// <returns>annotation descriptor</returns> /// <throws>ASTWalkException if the walk failed</throws> public static AnnotationDesc Walk(EsperEPL2GrammarParser.AnnotationEnumContext ctx, EngineImportService engineImportService) { var name = ASTUtil.UnescapeClassIdent(ctx.classIdentifier()); IList <Pair <String, Object> > values = new List <Pair <String, Object> >(); if (ctx.elementValueEnum() != null) { var value = WalkValue(ctx.elementValueEnum(), engineImportService); values.Add(new Pair <String, Object>("Value", value)); } else if (ctx.elementValuePairsEnum() != null) { WalkValuePairs(ctx.elementValuePairsEnum(), values, engineImportService); } return(new AnnotationDesc(name, values)); }
public static Pair <ExprTableAccessNode, IList <ExprChainedSpec> > CheckTableNameGetLibFunc( TableService tableService, EngineImportService engineImportService, LazyAllocatedMap <ConfigurationPlugInAggregationMultiFunction, PlugInAggregationMultiFunctionFactory> plugInAggregations, string engineURI, string classIdent, IList <ExprChainedSpec> chain) { var index = ASTUtil.UnescapedIndexOfDot(classIdent); // handle special case "table.Keys()" function if (index == -1) { if (tableService.GetTableMetadata(classIdent) == null) { return(null); // not a table } var funcName = chain[1].Name; if (funcName.ToLowerInvariant().Equals("keys")) { var subchain = chain.SubList(2, chain.Count); var node = new ExprTableAccessNodeKeys(classIdent); return(new Pair <ExprTableAccessNode, IList <ExprChainedSpec> >(node, subchain)); } else { throw ASTWalkException.From( "Invalid use of variable '" + classIdent + "', unrecognized use of function '" + funcName + "', expected 'keys()'"); } } // Handle "table.property" (without the variable[...] syntax since this is ungrouped use) var tableName = ASTUtil.UnescapeDot(classIdent.Substring(0, index)); if (tableService.GetTableMetadata(tableName) == null) { return(null); } // this is a table access expression var sub = classIdent.Substring(index + 1); return(HandleTable(engineImportService, plugInAggregations, engineURI, tableName, sub, chain)); }
public void TestGetPropertyName() { String PROPERTY = "a('aa').b[1].c"; // Should parse and result in the exact same property name Pair <ITree, CommonTokenStream> parsed = SupportParserHelper.ParseEventProperty(PROPERTY); ITree propertyNameExprNode = parsed.First.GetChild(0); ASTUtil.DumpAST(propertyNameExprNode); String propertyName = ((IRuleNode)propertyNameExprNode).GetText(); Assert.AreEqual(PROPERTY, propertyName); // Try AST with tokens separated, same property name parsed = SupportParserHelper.ParseEventProperty("a( 'aa' ). b [ 1 ] . c"); propertyNameExprNode = parsed.First.GetChild(0); propertyName = ((IRuleNode)propertyNameExprNode).GetText(); Assert.AreEqual(PROPERTY, propertyName); }
public static void ExprCollectAddSubNodes(ExprNode parentNode, ITree node, IDictionary <ITree, ExprNode> astExprNodeMap) { if (parentNode == null) { throw ASTWalkException.From("Invalid null expression node for '" + ASTUtil.PrintNode(node) + "'"); } if (node == null) { return; } ExprAction action = (exprNode, astExprNodeMapX, nodeX) => { astExprNodeMapX.Remove(nodeX); parentNode.AddChildNode(exprNode); }; for (var i = 0; i < node.ChildCount; i++) { var childNode = node.GetChild(i); RecursiveFindRemoveChildExprNode(childNode, astExprNodeMap, action); } }
private static GraphOperatorOutputItemType ParseType(EsperEPL2GrammarParser.GopOutTypeParamContext ctx) { if (ctx.q != null) { return(new GraphOperatorOutputItemType(true, null, null)); } var className = ASTUtil.UnescapeClassIdent(ctx.gopOutTypeItem().classIdentifier()); IList <GraphOperatorOutputItemType> typeParams = new List <GraphOperatorOutputItemType>(); if (ctx.gopOutTypeItem().gopOutTypeList() != null) { IList <EsperEPL2GrammarParser.GopOutTypeParamContext> pctxs = ctx.gopOutTypeItem().gopOutTypeList().gopOutTypeParam(); foreach (var pctx in pctxs) { var type = ParseType(pctx); typeParams.Add(type); } } return(new GraphOperatorOutputItemType(false, className, typeParams)); }
private static CreateTableColumn GetColumn(EsperEPL2GrammarParser.CreateTableColumnContext ctx, IDictionary <ITree, ExprNode> astExprNodeMap, EngineImportService engineImportService) { string columnName = ctx.n.Text; ExprNode optExpression = null; if (ctx.builtinFunc() != null || ctx.libFunction() != null) { optExpression = ASTExprHelper.ExprCollectSubNodes(ctx, 0, astExprNodeMap)[0]; } string optTypeName = null; bool? optTypeIsArray = null; bool? optTypeIsPrimitiveArray = null; if (ctx.createTableColumnPlain() != null) { EsperEPL2GrammarParser.CreateTableColumnPlainContext sub = ctx.createTableColumnPlain(); optTypeName = ASTUtil.UnescapeClassIdent(sub.classIdentifier()); optTypeIsArray = sub.b != null; optTypeIsPrimitiveArray = ASTCreateSchemaHelper.ValidateIsPrimitiveArray(sub.p); } bool primaryKey = false; if (ctx.p != null) { if (ctx.p.Text.ToLower() != "primary") { throw ASTWalkException.From("Invalid keyword '" + ctx.p.Text + "' encountered, expected 'primary key'"); } if (ctx.k.Text.ToLower() != "key") { throw ASTWalkException.From("Invalid keyword '" + ctx.k.Text + "' encountered, expected 'primary key'"); } primaryKey = true; } IList <AnnotationDesc> annots = Collections.GetEmptyList <AnnotationDesc>(); if (ctx.annotationEnum() != null) { annots = new List <AnnotationDesc>(ctx.annotationEnum().Length); foreach (EsperEPL2GrammarParser.AnnotationEnumContext anctx in ctx.annotationEnum()) { annots.Add(ASTAnnotationHelper.Walk(anctx, engineImportService)); } } if (ctx.propertyExpressionAnnotation() != null) { if (annots.IsEmpty()) { annots = new List <AnnotationDesc>(); } foreach (EsperEPL2GrammarParser.PropertyExpressionAnnotationContext anno in ctx.propertyExpressionAnnotation()) { annots.Add(new AnnotationDesc(anno.n.Text, anno.v.Text)); } } return(new CreateTableColumn(columnName, optExpression, optTypeName, optTypeIsArray, optTypeIsPrimitiveArray, annots, primaryKey)); }
private static ContextDetail WalkChoice(EsperEPL2GrammarParser.CreateContextChoiceContext ctx, IDictionary <ITree, ExprNode> astExprNodeMap, IDictionary <ITree, EvalFactoryNode> astPatternNodeMap, PropertyEvalSpec propertyEvalSpec, FilterSpecRaw filterSpec) { // temporal fixed (start+end) and overlapping (initiated/terminated) if (ctx.START() != null || ctx.INITIATED() != null) { ExprNode[] distinctExpressions = null; if (ctx.createContextDistinct() != null) { if (ctx.createContextDistinct().expressionList() == null) { distinctExpressions = new ExprNode[0]; } else { distinctExpressions = ASTExprHelper.ExprCollectSubNodesPerNode(ctx.createContextDistinct().expressionList().expression(), astExprNodeMap); } } ContextDetailCondition startEndpoint; if (ctx.START() != null) { bool immediate = CheckNow(ctx.i); if (immediate) { startEndpoint = new ContextDetailConditionImmediate(); } else { startEndpoint = GetContextCondition(ctx.r1, astExprNodeMap, astPatternNodeMap, propertyEvalSpec, false); } } else { bool immediate = CheckNow(ctx.i); startEndpoint = GetContextCondition(ctx.r1, astExprNodeMap, astPatternNodeMap, propertyEvalSpec, immediate); } bool overlapping = ctx.INITIATED() != null; ContextDetailCondition endEndpoint = GetContextCondition(ctx.r2, astExprNodeMap, astPatternNodeMap, propertyEvalSpec, false); return(new ContextDetailInitiatedTerminated(startEndpoint, endEndpoint, overlapping, distinctExpressions)); } // partitioned if (ctx.PARTITION() != null) { IList <EsperEPL2GrammarParser.CreateContextPartitionItemContext> partitions = ctx.createContextPartitionItem(); IList <ContextDetailPartitionItem> rawSpecs = new List <ContextDetailPartitionItem>(); foreach (EsperEPL2GrammarParser.CreateContextPartitionItemContext partition in partitions) { filterSpec = ASTFilterSpecHelper.WalkFilterSpec(partition.eventFilterExpression(), propertyEvalSpec, astExprNodeMap); propertyEvalSpec = null; IList <String> propertyNames = new List <String>(); IList <EsperEPL2GrammarParser.EventPropertyContext> properties = partition.eventProperty(); foreach (EsperEPL2GrammarParser.EventPropertyContext property in properties) { String propertyName = ASTUtil.GetPropertyName(property, 0); propertyNames.Add(propertyName); } ASTExprHelper.ExprCollectSubNodes(partition, 0, astExprNodeMap); // remove expressions rawSpecs.Add(new ContextDetailPartitionItem(filterSpec, propertyNames)); } return(new ContextDetailPartitioned(rawSpecs)); } // hash else if (ctx.COALESCE() != null) { IList <EsperEPL2GrammarParser.CreateContextCoalesceItemContext> coalesces = ctx.createContextCoalesceItem(); IList <ContextDetailHashItem> rawSpecs = new List <ContextDetailHashItem>(coalesces.Count); foreach (EsperEPL2GrammarParser.CreateContextCoalesceItemContext coalesce in coalesces) { ExprChainedSpec func = ASTLibFunctionHelper.GetLibFunctionChainSpec(coalesce.libFunctionNoClass(), astExprNodeMap); filterSpec = ASTFilterSpecHelper.WalkFilterSpec(coalesce.eventFilterExpression(), propertyEvalSpec, astExprNodeMap); propertyEvalSpec = null; rawSpecs.Add(new ContextDetailHashItem(func, filterSpec)); } String granularity = ctx.g.Text; if (!granularity.ToLower().Equals("granularity")) { throw ASTWalkException.From("Expected 'granularity' keyword after list of coalesce items, found '" + granularity + "' instead"); } var num = ASTConstantHelper.Parse(ctx.number()); String preallocateStr = ctx.p != null ? ctx.p.Text : null; if (preallocateStr != null && !preallocateStr.ToLower().Equals("preallocate")) { throw ASTWalkException.From("Expected 'preallocate' keyword after list of coalesce items, found '" + preallocateStr + "' instead"); } if (!num.GetType().IsNumericNonFP() || num.GetType().GetBoxedType() == typeof(long?)) { throw ASTWalkException.From("Granularity provided must be an int-type number, received " + num.GetType() + " instead"); } return(new ContextDetailHash(rawSpecs, num.AsInt(), preallocateStr != null)); } // categorized if (ctx.createContextGroupItem() != null) { IList <EsperEPL2GrammarParser.CreateContextGroupItemContext> grps = ctx.createContextGroupItem(); IList <ContextDetailCategoryItem> items = new List <ContextDetailCategoryItem>(); foreach (EsperEPL2GrammarParser.CreateContextGroupItemContext grp in grps) { ExprNode exprNode = ASTExprHelper.ExprCollectSubNodes(grp, 0, astExprNodeMap)[0]; String name = grp.i.Text; items.Add(new ContextDetailCategoryItem(exprNode, name)); } filterSpec = ASTFilterSpecHelper.WalkFilterSpec(ctx.eventFilterExpression(), propertyEvalSpec, astExprNodeMap); return(new ContextDetailCategory(items, filterSpec)); } throw new IllegalStateException("Unrecognized context detail type"); }
public static Pair <ExpressionDeclItem, ExpressionScriptProvided> WalkExpressionDecl( EsperEPL2GrammarParser.ExpressionDeclContext ctx, IList <String> scriptBodies, IDictionary <ITree, ExprNode> astExprNodeMap, CommonTokenStream tokenStream) { var name = ctx.name.Text; if (ctx.alias != null) { if (ctx.alias.Text.ToLower().Trim() != "alias") { throw ASTWalkException.From("For expression alias '" + name + "' expecting 'alias' keyword but received '" + ctx.alias.Text + "'"); } if (ctx.columnList() != null) { throw ASTWalkException.From("For expression alias '" + name + "' expecting no parameters but received '" + tokenStream.GetText(ctx.columnList()) + "'"); } if (ctx.expressionDef() != null && ctx.expressionDef().expressionLambdaDecl() != null) { throw ASTWalkException.From("For expression alias '" + name + "' expecting an expression without parameters but received '" + tokenStream.GetText(ctx.expressionDef().expressionLambdaDecl()) + "'"); } if (ctx.expressionDef().stringconstant() != null) { throw ASTWalkException.From("For expression alias '" + name + "' expecting an expression but received a script"); } var exprNode = ASTExprHelper.ExprCollectSubNodes(ctx, 0, astExprNodeMap)[0]; var alias = ctx.name.Text; var decl = new ExpressionDeclItem(alias, Collections.GetEmptyList <String>(), exprNode, true); return(new Pair <ExpressionDeclItem, ExpressionScriptProvided>(decl, null)); } if (ctx.expressionDef().stringconstant() != null) { var expressionText = scriptBodies[0]; scriptBodies.RemoveAt(0); var parameters = ASTUtil.GetIdentList(ctx.columnList()); var optionalReturnType = ctx.classIdentifier() == null ? null : ASTUtil.UnescapeClassIdent(ctx.classIdentifier()); var optionalReturnTypeArray = ctx.array != null; var optionalDialect = ctx.expressionDialect() == null ? null : ctx.expressionDialect().d.Text; var script = new ExpressionScriptProvided( name, expressionText, parameters, optionalReturnType, optionalReturnTypeArray, optionalDialect); return(new Pair <ExpressionDeclItem, ExpressionScriptProvided>(null, script)); } var ctxexpr = ctx.expressionDef(); var inner = ASTExprHelper.ExprCollectSubNodes(ctxexpr.expression(), 0, astExprNodeMap)[0]; var parametersNames = Collections.GetEmptyList <string>(); var lambdactx = ctxexpr.expressionLambdaDecl(); if (ctxexpr.expressionLambdaDecl() != null) { parametersNames = ASTLibFunctionHelper.GetLambdaGoesParams(lambdactx); } var expr = new ExpressionDeclItem(name, parametersNames, inner, false); return(new Pair <ExpressionDeclItem, ExpressionScriptProvided>(expr, null)); }
private static ASTLibModel GetModel(EsperEPL2GrammarParser.LibFunctionContext ctx, CommonTokenStream tokenStream) { var root = ctx.libFunctionWithClass(); IList <EsperEPL2GrammarParser.LibFunctionNoClassContext> ctxElements = ctx.libFunctionNoClass(); // there are no additional methods if (ctxElements == null || ctxElements.IsEmpty()) { var classIdent = root.classIdentifier() == null ? null : ASTUtil.UnescapeClassIdent(root.classIdentifier()); var ele = FromRoot(root); return(new ASTLibModel(classIdent, Collections.SingletonList(ele))); } // add root and chain to just a list of elements IList <ASTLibModelChainElement> chainElements = new List <ASTLibModelChainElement>(ctxElements.Count + 1); var rootElement = FromRoot(root); chainElements.Add(rootElement); foreach (var chainedCtx in ctxElements) { var chainedElement = new ASTLibModelChainElement(chainedCtx.funcIdentChained().GetText(), chainedCtx.libFunctionArgs(), chainedCtx.l != null); chainElements.Add(chainedElement); } // determine/remove the list of chain elements, from the start and uninterrupted, that don't have parameters (no parenthesis 'l') IList <ASTLibModelChainElement> chainElementsNoArgs = new List <ASTLibModelChainElement>(chainElements.Count); for (int ii = 0; ii < chainElements.Count; ii++) { var element = chainElements[ii]; if (!element.HasLeftParen) { // has no parenthesis, therefore part of class identifier chainElementsNoArgs.Add(element); chainElements.RemoveAt(ii--); } else { // else stop here break; } } // write the class identifier including the no-arg chain elements var classIdentBuf = new StringBuilder(); var delimiter = ""; if (root.classIdentifier() != null) { classIdentBuf.Append(ASTUtil.UnescapeClassIdent(root.classIdentifier())); delimiter = "."; } foreach (var noarg in chainElementsNoArgs) { classIdentBuf.Append(delimiter); classIdentBuf.Append(noarg.FuncName); delimiter = "."; } if (chainElements.IsEmpty()) { // would this be an event property, but then that is handled greedily by parser throw ASTWalkException.From("Encountered unrecognized lib function call", tokenStream, ctx); } // class ident can be null if empty var classIdentifierString = classIdentBuf.ToString(); var classIdentifier = classIdentifierString.Length > 0 ? classIdentifierString : null; return(new ASTLibModel(classIdentifier, chainElements)); }
public static ExprTimePeriod TimePeriodGetExprAllParams(EsperEPL2GrammarParser.TimePeriodContext ctx, IDictionary <ITree, ExprNode> astExprNodeMap, VariableService variableService, StatementSpecRaw spec, ConfigurationInformation config) { var nodes = new ExprNode[8]; for (var i = 0; i < ctx.ChildCount; i++) { var unitRoot = ctx.GetChild(i); ExprNode valueExpr; if (ASTUtil.IsTerminatedOfType(unitRoot.GetChild(0), EsperEPL2GrammarLexer.IDENT)) { var ident = unitRoot.GetChild(0).GetText(); valueExpr = ASTExprHelper.ResolvePropertyOrVariableIdentifier(ident, variableService, spec); } else { var @ref = new Atomic <ExprNode>(); ExprAction action = (exprNode, astExprNodeMapX, nodeX) => { astExprNodeMapX.Remove(nodeX); @ref.Set(exprNode); }; ASTExprHelper.RecursiveFindRemoveChildExprNode(unitRoot.GetChild(0), astExprNodeMap, action); valueExpr = @ref.Get(); } if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_millisecondPart) { nodes[7] = valueExpr; } if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_secondPart) { nodes[6] = valueExpr; } if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_minutePart) { nodes[5] = valueExpr; } if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_hourPart) { nodes[4] = valueExpr; } if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_dayPart) { nodes[3] = valueExpr; } if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_weekPart) { nodes[2] = valueExpr; } if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_monthPart) { nodes[1] = valueExpr; } if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_yearPart) { nodes[0] = valueExpr; } } ExprTimePeriod timeNode = new ExprTimePeriodImpl(config.EngineDefaults.ExpressionConfig.TimeZone, nodes[0] != null, nodes[1] != null, nodes[2] != null, nodes[3] != null, nodes[4] != null, nodes[5] != null, nodes[6] != null, nodes[7] != null); if (nodes[0] != null) { timeNode.AddChildNode(nodes[0]); } if (nodes[1] != null) { timeNode.AddChildNode(nodes[1]); } if (nodes[2] != null) { timeNode.AddChildNode(nodes[2]); } if (nodes[3] != null) { timeNode.AddChildNode(nodes[3]); } if (nodes[4] != null) { timeNode.AddChildNode(nodes[4]); } if (nodes[5] != null) { timeNode.AddChildNode(nodes[5]); } if (nodes[6] != null) { timeNode.AddChildNode(nodes[6]); } if (nodes[7] != null) { timeNode.AddChildNode(nodes[7]); } return(timeNode); }
/// <summary> /// Parse expression using the rule the ParseRuleSelector instance supplies. /// </summary> /// <param name="expression">text to parse</param> /// <param name="eplStatementErrorMsg">text for error</param> /// <param name="addPleaseCheck">true to include depth paraphrase</param> /// <param name="parseRuleSelector">parse rule to select</param> /// <param name="rewriteScript">if set to <c>true</c> [rewrite script].</param> /// <returns> /// AST - syntax tree /// </returns> /// <exception cref="EPException">IOException parsing expression ' + expression + '\''</exception> /// <throws>EPException when the AST could not be parsed</throws> public static ParseResult Parse(String expression, String eplStatementErrorMsg, bool addPleaseCheck, ParseRuleSelector parseRuleSelector, bool rewriteScript) { if (Log.IsDebugEnabled) { Log.Debug(".parse Parsing expr=" + expression); } ICharStream input; try { input = new NoCaseSensitiveStream(expression); } catch (IOException ex) { throw new EPException("IOException parsing expression '" + expression + '\'', ex); } var lex = NewLexer(input); var tokens = new CommonTokenStream(lex); var parser = ParseHelper.NewParser(tokens); ITree tree; try { tree = parseRuleSelector.Invoke(parser); } catch (RecognitionException ex) { tokens.Fill(); if (rewriteScript && IsContainsScriptExpression(tokens)) { return(HandleScriptRewrite(tokens, eplStatementErrorMsg, addPleaseCheck, parseRuleSelector)); } Log.Debug("Error parsing statement [" + expression + "]", ex); throw ExceptionConvertor.ConvertStatement(ex, eplStatementErrorMsg, addPleaseCheck, parser); } catch (Exception e) { try { tokens.Fill(); } catch (Exception ex) { Log.Debug("Token-fill produced exception: " + ex.Message, ex); } if (Log.IsDebugEnabled) { Log.Debug("Error parsing statement [" + eplStatementErrorMsg + "]", e); } if (e.InnerException is RecognitionException) { if (rewriteScript && IsContainsScriptExpression(tokens)) { return(HandleScriptRewrite(tokens, eplStatementErrorMsg, addPleaseCheck, parseRuleSelector)); } throw ExceptionConvertor.ConvertStatement((RecognitionException)e.InnerException, eplStatementErrorMsg, addPleaseCheck, parser); } else { throw; } } // if we are re-writing scripts and contain a script, then rewrite if (rewriteScript && IsContainsScriptExpression(tokens)) { return(HandleScriptRewrite(tokens, eplStatementErrorMsg, addPleaseCheck, parseRuleSelector)); } if (Log.IsDebugEnabled) { Log.Debug(".parse Dumping AST..."); ASTUtil.DumpAST(tree); } var expressionWithoutAnnotation = expression; if (tree is EsperEPL2GrammarParser.StartEPLExpressionRuleContext) { var epl = (EsperEPL2GrammarParser.StartEPLExpressionRuleContext)tree; expressionWithoutAnnotation = GetNoAnnotation(expression, epl.annotationEnum(), tokens); } else if (tree is EsperEPL2GrammarParser.StartPatternExpressionRuleContext) { var pattern = (EsperEPL2GrammarParser.StartPatternExpressionRuleContext)tree; expressionWithoutAnnotation = GetNoAnnotation(expression, pattern.annotationEnum(), tokens); } return(new ParseResult(tree, expressionWithoutAnnotation, tokens, Collections.GetEmptyList <String>())); }