Esempio n. 1
0
        public static CreateIndexDesc Walk(EsperEPL2GrammarParser.CreateIndexExprContext ctx, IDictionary <ITree, ExprNode> astExprNodeMap)
        {
            var indexName  = ctx.n.Text;
            var windowName = ctx.w.Text;

            var unique = false;

            if (ctx.u != null)
            {
                string ident = ctx.u.Text;
                if (ident.ToLowerInvariant().Trim() == "unique")
                {
                    unique = true;
                }
                else
                {
                    throw ASTWalkException.From("Invalid keyword '" + ident + "' in create-index encountered, expected 'unique'");
                }
            }

            var columns = new List <CreateIndexItem>();
            var cols    = ctx.createIndexColumnList().createIndexColumn();

            foreach (var col in cols)
            {
                CreateIndexItem item = Walk(col, astExprNodeMap);
                columns.Add(item);
            }
            return(new CreateIndexDesc(unique, indexName, windowName, columns));
        }
        public static MatchRecognizeSkipEnum ParseSkip(CommonTokenStream tokenStream, EsperEPL2GrammarParser.MatchRecogMatchesAfterSkipContext ctx)
        {
            if ((!ctx.i1.GetText().ToUpper().Equals("MATCH")) ||
                (!ctx.i2.GetText().ToUpper().Equals("SKIP")) ||
                (!ctx.i5.GetText().ToUpper().Equals("ROW"))
                )
            {
                throw ASTWalkException.From(Message, tokenStream, ctx);
            }

            if ((!ctx.i3.GetText().ToUpper().Equals("TO")) &&
                (!ctx.i3.GetText().ToUpper().Equals("PAST"))
                )
            {
                throw ASTWalkException.From(Message, tokenStream, ctx);
            }

            if (ctx.i4.GetText().ToUpper().Equals("LAST"))
            {
                return(MatchRecognizeSkipEnum.PAST_LAST_ROW);
            }
            else if (ctx.i4.GetText().ToUpper().Equals("NEXT"))
            {
                return(MatchRecognizeSkipEnum.TO_NEXT_ROW);
            }
            else if (ctx.i4.GetText().ToUpper().Equals("CURRENT"))
            {
                return(MatchRecognizeSkipEnum.TO_CURRENT_ROW);
            }
            throw ASTWalkException.From(Message);
        }
Esempio n. 3
0
        private static Object ParseNumber(IRuleNode number, int factor)
        {
            var tokenType = GetSingleChildTokenType(number);

            if (tokenType == EsperEPL2GrammarLexer.IntegerLiteral)
            {
                return(ParseIntLongByte(number.GetText(), factor));
            }

            else if (tokenType == EsperEPL2GrammarLexer.FloatingPointLiteral)
            {
                var numberText = number.GetText();
                if (numberText.EndsWith("m"))
                {
                    return(DecimalValue.ParseString(number.GetText()) * factor);
                }
                else if (numberText.EndsWith("f") || numberText.EndsWith("F"))
                {
                    return(FloatValue.ParseString(number.GetText()) * factor);
                }
                else
                {
                    return(DoubleValue.ParseString(number.GetText()) * factor);
                }
            }
            throw ASTWalkException.From("Encountered unrecognized constant", number.GetText());
        }
Esempio n. 4
0
        private static Object WalkClassIdent(
            EsperEPL2GrammarParser.ClassIdentifierContext ctx,
            EngineImportService engineImportService)
        {
            string enumValueText = ctx.GetText();
            Object enumValue;

            try
            {
                enumValue = TypeHelper.ResolveIdentAsEnumConst(enumValueText, engineImportService, true);
            }
            catch (ExprValidationException)
            {
                throw ASTWalkException.From(
                          "Annotation value '" + enumValueText +
                          "' is not recognized as an enumeration value, please check imports or use a primitive or string type");
            }
            if (enumValue != null)
            {
                return(enumValue);
            }
            throw ASTWalkException.From(
                      "Annotation enumeration value '" + enumValueText +
                      "' not recognized as an enumeration class, please check imports or type used");
        }
Esempio n. 5
0
        private static ContextDetailCondition GetContextCondition(
            EsperEPL2GrammarParser.CreateContextRangePointContext ctx,
            IDictionary <ITree, ExprNode> astExprNodeMap,
            IDictionary <ITree, EvalFactoryNode> astPatternNodeMap,
            PropertyEvalSpec propertyEvalSpec,
            bool immediate)
        {
            if (ctx == null)
            {
                return(ContextDetailConditionNever.INSTANCE);
            }
            if (ctx.crontabLimitParameterSet() != null)
            {
                var crontab = ASTExprHelper.ExprCollectSubNodes(
                    ctx.crontabLimitParameterSet(), 0, astExprNodeMap);
                return(new ContextDetailConditionCrontab(crontab, immediate));
            }
            else if (ctx.patternInclusionExpression() != null)
            {
                var evalNode = ASTExprHelper.PatternGetRemoveTopNode(
                    ctx.patternInclusionExpression(), astPatternNodeMap);
                var inclusive = false;
                if (ctx.i != null)
                {
                    var ident = ctx.i.Text;
                    if (ident != null && !ident.ToLowerInvariant().Equals("inclusive"))
                    {
                        throw ASTWalkException.From(
                                  "Expected 'inclusive' keyword after '@', found '" + ident + "' instead");
                    }
                    inclusive = true;
                }
                return(new ContextDetailConditionPattern(evalNode, inclusive, immediate));
            }
            else if (ctx.createContextFilter() != null)
            {
                var filterSpecRaw =
                    ASTFilterSpecHelper.WalkFilterSpec(
                        ctx.createContextFilter().eventFilterExpression(), propertyEvalSpec, astExprNodeMap);
                var asName = ctx.createContextFilter().i != null?ctx.createContextFilter().i.Text : null;

                if (immediate)
                {
                    throw ASTWalkException.From(
                              "Invalid use of 'now' with initiated-by stream, this combination is not supported");
                }
                return(new ContextDetailConditionFilter(filterSpecRaw, asName));
            }
            else if (ctx.AFTER() != null)
            {
                var timePeriod =
                    (ExprTimePeriod)ASTExprHelper.ExprCollectSubNodes(ctx.timePeriod(), 0, astExprNodeMap)[0];
                return(new ContextDetailConditionTimePeriod(timePeriod, immediate));
            }
            else
            {
                throw new IllegalStateException("Unrecognized child type");
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Validate.
        /// </summary>
        /// <param name="lowerBounds">is the lower bounds, or null if none supplied</param>
        /// <param name="upperBounds">is the upper bounds, or null if none supplied</param>
        /// <param name="isAllowLowerZero">true to allow zero value for lower range</param>
        /// <returns>
        /// true if closed range of constants and the constants are the same value
        /// </returns>
        /// <throws>ASTWalkException if the AST is incorrect</throws>
        public static bool Validate(ExprNode lowerBounds, ExprNode upperBounds, bool isAllowLowerZero)
        {
            var isConstants = true;

            Object constantLower = null;

            if (ExprNodeUtility.IsConstantValueExpr(lowerBounds))
            {
                constantLower = lowerBounds.ExprEvaluator.Evaluate(new EvaluateParams(null, true, null));
                if (constantLower == null || !(constantLower.IsNumber()))
                {
                    throw ASTWalkException.From(NumericMessage);
                }
            }
            else
            {
                isConstants = lowerBounds == null;
            }

            Object constantUpper = null;

            if (ExprNodeUtility.IsConstantValueExpr(upperBounds))
            {
                constantUpper = upperBounds.ExprEvaluator.Evaluate(new EvaluateParams(null, true, null));
                if (constantUpper == null || !(constantUpper.IsNumber()))
                {
                    throw ASTWalkException.From(NumericMessage);
                }
            }
            else
            {
                isConstants = isConstants && upperBounds == null;
            }

            if (!isConstants)
            {
                return(true);
            }

            if (constantLower != null && constantUpper != null)
            {
                int lower = constantLower.AsInt();
                int upper = constantUpper.AsInt();
                if (lower > upper)
                {
                    throw ASTWalkException.From(
                              "Incorrect range specification, lower bounds value '" + lower +
                              "' is higher then higher bounds '" + upper + "'");
                }
            }

            VerifyConstant(constantLower, isAllowLowerZero);
            VerifyConstant(constantUpper, false);

            return(constantLower != null && constantUpper != null && constantLower.Equals(constantUpper));
        }
Esempio n. 7
0
        public static int GetAssertTerminatedTokenType(IParseTree child)
        {
            if (!(child is ITerminalNode))
            {
                throw ASTWalkException.From("Unexpected exception walking AST, expected terminal node", child.GetText());
            }
            var term = (ITerminalNode)child;

            return(term.Symbol.Type);
        }
Esempio n. 8
0
        // Min/Max nodes can be either an aggregate or a per-row function depending on the number or arguments
        private static void HandleMinMax(
            string ident,
            EsperEPL2GrammarParser.LibFunctionArgsContext ctxArgs,
            IDictionary <ITree, ExprNode> astExprNodeMap)
        {
            // Determine min or max
            var            childNodeText = ident;
            MinMaxTypeEnum minMaxTypeEnum;
            var            filtered = childNodeText.StartsWith("f");

            if (childNodeText.ToLowerInvariant().Equals("min") || childNodeText.ToLowerInvariant().Equals("fmin"))
            {
                minMaxTypeEnum = MinMaxTypeEnum.MIN;
            }
            else if (childNodeText.ToLowerInvariant().Equals("max") || childNodeText.ToLowerInvariant().Equals("fmax"))
            {
                minMaxTypeEnum = MinMaxTypeEnum.MAX;
            }
            else
            {
                throw ASTWalkException.From("Uncountered unrecognized min or max node '" + ident + "'");
            }

            var args = Collections.GetEmptyList <ExprNode>();

            if (ctxArgs != null && ctxArgs.libFunctionArgItem() != null)
            {
                args = ASTExprHelper.ExprCollectSubNodes(ctxArgs, 0, astExprNodeMap);
            }
            var numArgsPositional = ExprAggregateNodeUtil.CountPositionalArgs(args);

            var isDistinct = ctxArgs != null && ctxArgs.DISTINCT() != null;

            if (numArgsPositional > 1 && isDistinct && !filtered)
            {
                throw ASTWalkException.From(
                          "The distinct keyword is not valid in per-row min and max " +
                          "functions with multiple sub-expressions");
            }

            ExprNode minMaxNode;

            if (!isDistinct && numArgsPositional > 1 && !filtered)
            {
                // use the row function
                minMaxNode = new ExprMinMaxRowNode(minMaxTypeEnum);
            }
            else
            {
                // use the aggregation function
                minMaxNode = new ExprMinMaxAggrNode(isDistinct, minMaxTypeEnum, filtered, false);
            }
            minMaxNode.AddChildNodes(args);
            astExprNodeMap.Put(ctxArgs, minMaxNode);
        }
Esempio n. 9
0
 public static bool ValidateIsPrimitiveArray(IToken p)
 {
     if (p != null)
     {
         if (!p.Text.ToLower().Equals("primitive"))
         {
             throw ASTWalkException.From("Column type keyword '" + p.Text + "' not recognized, expecting '[primitive]'");
         }
         return(true);
     }
     return(false);
 }
Esempio n. 10
0
        /// <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());
            }
        }
Esempio n. 11
0
        private static bool CheckNow(IToken i)
        {
            if (i == null)
            {
                return(false);
            }
            var ident = i.Text;

            if (!ident.ToLowerInvariant().Equals("now"))
            {
                throw ASTWalkException.From("Expected 'now' keyword after '@', found '" + ident + "' instead");
            }
            return(true);
        }
Esempio n. 12
0
        private static bool CheckNow(IToken i)
        {
            if (i == null)
            {
                return(false);
            }
            String ident = i.Text;

            if (ident.ToLower() != "now")
            {
                throw ASTWalkException.From("Expected 'now' keyword after '@', found '" + ident + "' instead");
            }
            return(true);
        }
Esempio n. 13
0
        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);
            }
        }
Esempio n. 14
0
        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);
        }
Esempio n. 15
0
 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);
 }
Esempio n. 16
0
        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));
        }
Esempio n. 17
0
        public static string ExpectMayTypeAnno(
            EsperEPL2GrammarParser.TypeExpressionAnnotationContext ctx,
            CommonTokenStream tokenStream)
        {
            if (ctx == null)
            {
                return(null);
            }
            string annoName = ctx.n.Text;

            if (!annoName.ToLowerInvariant().Equals("type"))
            {
                throw ASTWalkException.From(
                          "Invalid annotation for property selection, expected 'type' but found '" + annoName + "'",
                          tokenStream, ctx);
            }
            return(ctx.v.Text);
        }
Esempio n. 18
0
        public static ExprNode ResolvePropertyOrVariableIdentifier(String identifier, VariableService variableService, StatementSpecRaw spec)
        {
            var metaData = variableService.GetVariableMetaData(identifier);

            if (metaData != null)
            {
                var exprNode = new ExprVariableNodeImpl(metaData, null);
                spec.HasVariables = true;
                AddVariableReference(spec, metaData.VariableName);
                var message = VariableServiceUtil.CheckVariableContextName(spec.OptionalContextName, metaData);
                if (message != null)
                {
                    throw ASTWalkException.From(message);
                }
                return(exprNode);
            }
            else
            {
                return(new ExprIdentNodeImpl(identifier));
            }
        }
Esempio n. 19
0
        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);
            }
        }
Esempio n. 20
0
 private static void VerifyConstant(Object value, bool isAllowZero)
 {
     if (value != null)
     {
         int bound = value.AsInt();
         if (isAllowZero)
         {
             if (bound < 0)
             {
                 throw ASTWalkException.From("Incorrect range specification, a bounds value of negative value is not allowed");
             }
         }
         else
         {
             if (bound <= 0)
             {
                 throw ASTWalkException.From("Incorrect range specification, a bounds value of zero or negative value is not allowed");
             }
         }
     }
 }
        public static RowRegexExprRepeatDesc walkOptionalRepeat(EsperEPL2GrammarParser.MatchRecogPatternRepeatContext ctx, IDictionary <ITree, ExprNode> astExprNodeMap)
        {
            if (ctx == null)
            {
                return(null);
            }

            ExprNode e1 = ctx.e1 == null ? null : ASTExprHelper.ExprCollectSubNodes(ctx.e1, 0, astExprNodeMap)[0];
            ExprNode e2 = ctx.e2 == null ? null : ASTExprHelper.ExprCollectSubNodes(ctx.e2, 0, astExprNodeMap)[0];

            if (ctx.comma == null && ctx.e1 != null)
            {
                return(new RowRegexExprRepeatDesc(null, null, e1));
            }

            if (e1 == null && e2 == null)
            {
                throw ASTWalkException.From("Invalid match-recognize quantifier '" + ctx.GetText() + "', expecting an expression");
            }

            return(new RowRegexExprRepeatDesc(e1, e2, null));
        }
Esempio n. 22
0
        private static MathArithTypeEnum TokenToMathEnum(int token)
        {
            switch (token)
            {
            case EsperEPL2GrammarLexer.DIV:
                return(MathArithTypeEnum.DIVIDE);

            case EsperEPL2GrammarLexer.STAR:
                return(MathArithTypeEnum.MULTIPLY);

            case EsperEPL2GrammarLexer.PLUS:
                return(MathArithTypeEnum.ADD);

            case EsperEPL2GrammarLexer.MINUS:
                return(MathArithTypeEnum.SUBTRACT);

            case EsperEPL2GrammarLexer.MOD:
                return(MathArithTypeEnum.MODULO);

            default:
                throw ASTWalkException.From("Encountered unrecognized math token type " + token);
            }
        }
Esempio n. 23
0
 /// <summary>
 /// Walk an annotation root name or child node (nested annotations).
 /// </summary>
 /// <param name="node">annotation walk node</param>
 /// <returns>annotation descriptor</returns>
 /// <throws>com.espertech.esper.epl.parse.ASTWalkException if the walk failed</throws>
 public static Object Walk(CommonTokenStream tokenStream, EsperEPL2GrammarParser.JsonvalueContext node)
 {
     if (node.constant() != null)
     {
         EsperEPL2GrammarParser.ConstantContext constCtx = node.constant();
         if (constCtx.stringconstant() != null)
         {
             return(ExtractString(constCtx.stringconstant().GetText()));
         }
         else
         {
             return(ASTConstantHelper.Parse(constCtx.GetChild(0)));
         }
     }
     else if (node.jsonobject() != null)
     {
         return(WalkObject(tokenStream, node.jsonobject()));
     }
     else if (node.jsonarray() != null)
     {
         return(WalkArray(tokenStream, node.jsonarray()));
     }
     throw ASTWalkException.From("Encountered unexpected node type in json tree", tokenStream, node);
 }
Esempio n. 24
0
        /// <summary>
        /// Build an output limit spec from the AST node supplied.
        /// </summary>
        /// <param name="astExprNodeMap">is the map of current AST tree nodes to their respective expression root node</param>
        /// <param name="engineURI">the engine uri</param>
        /// <param name="timeProvider">provides time</param>
        /// <param name="variableService">provides variable resolution</param>
        /// <param name="exprEvaluatorContext">context for expression evaluatiom</param>
        /// <returns>output limit spec</returns>
        public static OutputLimitSpec BuildOutputLimitSpec(
            CommonTokenStream tokenStream,
            EsperEPL2GrammarParser.OutputLimitContext ctx,
            IDictionary <ITree, ExprNode> astExprNodeMap,
            VariableService variableService,
            String engineURI,
            TimeProvider timeProvider,
            ExprEvaluatorContext exprEvaluatorContext)
        {
            OutputLimitLimitType displayLimit = OutputLimitLimitType.DEFAULT;

            if (ctx.k != null)
            {
                switch (ctx.k.Type)
                {
                case EsperEPL2GrammarParser.FIRST: displayLimit = OutputLimitLimitType.FIRST; break;

                case EsperEPL2GrammarParser.LAST: displayLimit = OutputLimitLimitType.LAST; break;

                case EsperEPL2GrammarParser.SNAPSHOT: displayLimit = OutputLimitLimitType.SNAPSHOT; break;

                case EsperEPL2GrammarParser.ALL: displayLimit = OutputLimitLimitType.ALL; break;

                default: throw ASTWalkException.From("Encountered unrecognized token " + ctx.k.Text, tokenStream, ctx);
                }
            }

            // next is a variable, or time period, or number
            String           variableName                  = null;
            double?          rate                          = null;
            ExprNode         whenExpression                = null;
            IList <ExprNode> crontabScheduleSpec           = null;
            IList <OnTriggerSetAssignment> thenExpressions = null;
            ExprTimePeriod                 timePeriodExpr  = null;
            OutputLimitRateType            rateType;
            ExprNode                       andAfterTerminateExpr           = null;
            IList <OnTriggerSetAssignment> andAfterTerminateSetExpressions = null;

            if (ctx.t != null)
            {
                rateType = OutputLimitRateType.TERM;
                if (ctx.expression() != null)
                {
                    andAfterTerminateExpr = ASTExprHelper.ExprCollectSubNodes(ctx.expression(), 0, astExprNodeMap)[0];
                }
                if (ctx.onSetExpr() != null)
                {
                    andAfterTerminateSetExpressions = ASTExprHelper.GetOnTriggerSetAssignments(ctx.onSetExpr().onSetAssignmentList(), astExprNodeMap);
                }
            }
            else if (ctx.wh != null)
            {
                rateType       = OutputLimitRateType.WHEN_EXPRESSION;
                whenExpression = ASTExprHelper.ExprCollectSubNodes(ctx.expression(), 0, astExprNodeMap)[0];
                if (ctx.onSetExpr() != null)
                {
                    thenExpressions = ASTExprHelper.GetOnTriggerSetAssignments(ctx.onSetExpr().onSetAssignmentList(), astExprNodeMap);
                }
            }
            else if (ctx.at != null)
            {
                rateType            = OutputLimitRateType.CRONTAB;
                crontabScheduleSpec = ASTExprHelper.ExprCollectSubNodes(ctx.crontabLimitParameterSet(), 0, astExprNodeMap);
            }
            else
            {
                if (ctx.ev != null)
                {
                    rateType = ctx.e != null ? OutputLimitRateType.EVENTS : OutputLimitRateType.TIME_PERIOD;
                    if (ctx.i != null)
                    {
                        variableName = ctx.i.Text;
                    }
                    else if (ctx.timePeriod() != null)
                    {
                        timePeriodExpr = (ExprTimePeriod)ASTExprHelper.ExprCollectSubNodes(ctx.timePeriod(), 0, astExprNodeMap)[0];
                    }
                    else
                    {
                        ASTExprHelper.ExprCollectSubNodes(ctx.number(), 0, astExprNodeMap);  // remove
                        rate = Double.Parse(ctx.number().GetText());
                    }
                }
                else
                {
                    rateType = OutputLimitRateType.AFTER;
                }
            }

            // get the AFTER time period
            ExprTimePeriod afterTimePeriodExpr = null;
            int?           afterNumberOfEvents = null;

            if (ctx.outputLimitAfter() != null)
            {
                if (ctx.outputLimitAfter().timePeriod() != null)
                {
                    ExprNode expression = ASTExprHelper.ExprCollectSubNodes(ctx.outputLimitAfter(), 0, astExprNodeMap)[0];
                    afterTimePeriodExpr = (ExprTimePeriod)expression;
                }
                else
                {
                    Object constant = ASTConstantHelper.Parse(ctx.outputLimitAfter().number());
                    afterNumberOfEvents = constant.AsInt();
                }
            }

            bool andAfterTerminate = false;

            if (ctx.outputLimitAndTerm() != null)
            {
                andAfterTerminate = true;
                if (ctx.outputLimitAndTerm().expression() != null)
                {
                    andAfterTerminateExpr = ASTExprHelper.ExprCollectSubNodes(ctx.outputLimitAndTerm().expression(), 0, astExprNodeMap)[0];
                }
                if (ctx.outputLimitAndTerm().onSetExpr() != null)
                {
                    andAfterTerminateSetExpressions = ASTExprHelper.GetOnTriggerSetAssignments(ctx.outputLimitAndTerm().onSetExpr().onSetAssignmentList(), astExprNodeMap);
                }
            }

            return(new OutputLimitSpec(rate, variableName, rateType, displayLimit, whenExpression, thenExpressions, crontabScheduleSpec, timePeriodExpr, afterTimePeriodExpr, afterNumberOfEvents, andAfterTerminate, andAfterTerminateExpr, andAfterTerminateSetExpressions));
        }
Esempio n. 25
0
        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));
        }
Esempio n. 26
0
 private static ASTWalkException GetException()
 {
     return(ASTWalkException.From("Inconsistent use of substitution parameters, expecting all substitutions to either all provide a name or provide no name"));
 }
Esempio n. 27
0
        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));
        }
Esempio n. 28
0
        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));
        }
Esempio n. 29
0
        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");
        }