Exemple #1
0
        private static CreateIndexItem Walk(EsperEPL2GrammarParser.CreateIndexColumnContext col, IDictionary <ITree, ExprNode> astExprNodeMap)
        {
            var expressions = Collections.GetEmptyList <ExprNode>();

            if (col.i != null)
            {
                expressions = ASTExprHelper.ExprCollectSubNodes(col.i, 0, astExprNodeMap);
            }
            else if (col.expression() != null)
            {
                expressions = ASTExprHelper.ExprCollectSubNodes(col.expression(), 0, astExprNodeMap);
            }

            var type = CreateIndexType.HASH.GetNameInvariant();

            if (col.t != null)
            {
                type = col.t.Text;
            }

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

            if (col.p != null)
            {
                parameters = ASTExprHelper.ExprCollectSubNodes(col.p, 0, astExprNodeMap);
            }
            return(new CreateIndexItem(expressions, type, parameters));
        }
Exemple #2
0
        /// <summary>
        /// Returns the list of set-variable assignments under the given node.
        /// </summary>
        /// <param name="astExprNodeMap">map of AST to expression</param>
        /// <returns>list of assignments</returns>
        internal static IList <OnTriggerSetAssignment> GetOnTriggerSetAssignments(EsperEPL2GrammarParser.OnSetAssignmentListContext ctx, IDictionary <ITree, ExprNode> astExprNodeMap)
        {
            if (ctx == null || ctx.onSetAssignment().IsEmpty())
            {
                return(Collections.GetEmptyList <OnTriggerSetAssignment>());
            }
            IList <EsperEPL2GrammarParser.OnSetAssignmentContext> ctxs = ctx.onSetAssignment();
            IList <OnTriggerSetAssignment> assignments = new List <OnTriggerSetAssignment>(ctx.onSetAssignment().Length);

            foreach (var assign in ctxs)
            {
                ExprNode childEvalNode;
                if (assign.eventProperty() != null)
                {
                    var            prop   = ASTExprHelper.ExprCollectSubNodes(assign.eventProperty(), 0, astExprNodeMap)[0];
                    var            value  = ASTExprHelper.ExprCollectSubNodes(assign.expression(), 0, astExprNodeMap)[0];
                    ExprEqualsNode equals = new ExprEqualsNodeImpl(false, false);
                    equals.AddChildNode(prop);
                    equals.AddChildNode(value);
                    childEvalNode = equals;
                }
                else
                {
                    childEvalNode = ASTExprHelper.ExprCollectSubNodes(assign, 0, astExprNodeMap)[0];
                }
                assignments.Add(new OnTriggerSetAssignment(childEvalNode));
            }
            return(assignments);
        }
Exemple #3
0
        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);
        }
Exemple #4
0
        public static IList <ExprNode> GetExprNodesLibFunc(EsperEPL2GrammarParser.LibFunctionArgsContext ctx, IDictionary <ITree, ExprNode> astExprNodeMap)
        {
            if (ctx == null)
            {
                return(Collections.GetEmptyList <ExprNode>());
            }
            IList <EsperEPL2GrammarParser.LibFunctionArgItemContext> args = ctx.libFunctionArgItem();

            if (args == null || args.IsEmpty())
            {
                return(Collections.GetEmptyList <ExprNode>());
            }
            IList <ExprNode> parameters = new List <ExprNode>(args.Count);

            foreach (var arg in args)
            {
                if (arg.expressionLambdaDecl() != null)
                {
                    var lambdaparams = GetLambdaGoesParams(arg.expressionLambdaDecl());
                    var goes         = new ExprLambdaGoesNode(lambdaparams);
                    var lambdaExpr   = ASTExprHelper.ExprCollectSubNodes(arg.expressionWithNamed(), 0, astExprNodeMap)[0];
                    goes.AddChildNode(lambdaExpr);
                    parameters.Add(goes);
                }
                else
                {
                    var parameter = ASTExprHelper.ExprCollectSubNodes(arg.expressionWithNamed(), 0, astExprNodeMap)[0];
                    parameters.Add(parameter);
                }
            }
            return(parameters);
        }
Exemple #5
0
        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));
        }
Exemple #6
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");
            }
        }
Exemple #7
0
        public static void AddOptionalSimpleProperty(ExprNode exprNode, IToken token, VariableService variableService, StatementSpecRaw spec)
        {
            if (token == null)
            {
                return;
            }
            var node = ASTExprHelper.ResolvePropertyOrVariableIdentifier(token.Text, variableService, spec);

            exprNode.AddChildNode(node);
        }
Exemple #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);
        }
Exemple #9
0
        private static GroupByClauseElement WalkCombinable(
            EsperEPL2GrammarParser.GroupByCombinableExprContext ctx,
            IDictionary <ITree, ExprNode> astExprNodeMap)
        {
            if (ctx.e1 != null && ctx.LPAREN() == null)
            {
                ExprNode expr = ASTExprHelper.ExprCollectSubNodes(ctx.e1, 0, astExprNodeMap)[0];
                return(new GroupByClauseElementExpr(expr));
            }
            IList <ExprNode> combined = ASTExprHelper.ExprCollectSubNodes(ctx, 0, astExprNodeMap);

            return(new GroupByClauseElementCombinedExpr(combined));
        }
Exemple #10
0
 private static GroupByClauseElement WalkChoice(
     EsperEPL2GrammarParser.GroupByListChoiceContext choice,
     IDictionary <ITree, ExprNode> astExprNodeMap)
 {
     if (choice.e1 != null)
     {
         ExprNode expr = ASTExprHelper.ExprCollectSubNodes(choice.e1, 0, astExprNodeMap)[0];
         return(new GroupByClauseElementExpr(expr));
     }
     if (choice.groupByCubeOrRollup() != null)
     {
         return(WalkCubeOrRollup(choice.groupByCubeOrRollup(), astExprNodeMap));
     }
     return(WalkGroupingSets(choice.groupByGroupingSets().groupBySetsChoice(), astExprNodeMap));
 }
        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));
        }
Exemple #12
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));
        }
Exemple #13
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");
        }
Exemple #14
0
        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);
        }
Exemple #15
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));
        }
Exemple #16
0
        public static void HandleLibFunc(
            CommonTokenStream tokenStream,
            EsperEPL2GrammarParser.LibFunctionContext ctx,
            ConfigurationInformation configurationInformation,
            EngineImportService engineImportService,
            IDictionary <ITree, ExprNode> astExprNodeMap,
            LazyAllocatedMap <ConfigurationPlugInAggregationMultiFunction, PlugInAggregationMultiFunctionFactory> plugInAggregations,
            string engineURI,
            ExpressionDeclDesc expressionDeclarations,
            ExprDeclaredService exprDeclaredService,
            IList <ExpressionScriptProvided> scriptExpressions,
            ContextDescriptor contextDescriptor,
            TableService tableService,
            StatementSpecRaw statementSpec,
            VariableService variableService)
        {
            var model    = GetModel(ctx, tokenStream);
            var duckType = configurationInformation.EngineDefaults.ExpressionConfig.IsDuckTyping;
            var udfCache = configurationInformation.EngineDefaults.ExpressionConfig.IsUdfCache;

            // handle "some.xyz(...)" or "some.other.xyz(...)"
            if (model.ChainElements.Count == 1 &&
                model.OptionalClassIdent != null &&
                ASTTableExprHelper.CheckTableNameGetExprForProperty(tableService, model.OptionalClassIdent) == null)
            {
                var chainSpec = GetLibFunctionChainSpec(model.ChainElements[0], astExprNodeMap);

                var declaredNodeX = ExprDeclaredHelper.GetExistsDeclaredExpr(model.OptionalClassIdent, Collections.GetEmptyList <ExprNode>(), expressionDeclarations.Expressions, exprDeclaredService, contextDescriptor);
                if (declaredNodeX != null)
                {
                    ExprNode exprNode = new ExprDotNode(Collections.SingletonList(chainSpec), duckType, udfCache);
                    exprNode.AddChildNode(declaredNodeX);
                    ASTExprHelper.ExprCollectAddSubNodesAddParentNode(exprNode, ctx, astExprNodeMap);
                    return;
                }

                IList <ExprChainedSpec> chainX = new List <ExprChainedSpec>(2);
                chainX.Add(new ExprChainedSpec(model.OptionalClassIdent, Collections.GetEmptyList <ExprNode>(), true));
                chainX.Add(chainSpec);
                var dotNodeX = new ExprDotNode(chainX, configurationInformation.EngineDefaults.ExpressionConfig.IsDuckTyping, configurationInformation.EngineDefaults.ExpressionConfig.IsUdfCache);
                if (dotNodeX.IsVariableOp(variableService))
                {
                    statementSpec.HasVariables = true;
                }
                ASTExprHelper.ExprCollectAddSubNodesAddParentNode(dotNodeX, ctx, astExprNodeMap);
                return;
            }

            // try additional built-in single-row function
            ExprNode singleRowExtNode = engineImportService.ResolveSingleRowExtendedBuiltin(model.ChainElements[0].FuncName);

            if (singleRowExtNode != null)
            {
                if (model.ChainElements.Count == 1)
                {
                    ASTExprHelper.ExprCollectAddSubNodesAddParentNode(singleRowExtNode, ctx, astExprNodeMap);
                    return;
                }
                var spec = new List <ExprChainedSpec>();
                EsperEPL2GrammarParser.LibFunctionArgsContext firstArgs = model.ChainElements[0].Args;
                var childExpressions = ASTLibFunctionHelper.GetExprNodesLibFunc(firstArgs, astExprNodeMap);
                singleRowExtNode.AddChildNodes(childExpressions);
                AddChainRemainderFromOffset(model.ChainElements, 1, spec, astExprNodeMap);
                var dotNodeX = new ExprDotNode(spec, configurationInformation.EngineDefaults.ExpressionConfig.IsDuckTyping, configurationInformation.EngineDefaults.ExpressionConfig.IsUdfCache);
                dotNodeX.AddChildNode(singleRowExtNode);
                ASTExprHelper.ExprCollectAddSubNodesAddParentNode(dotNodeX, ctx, astExprNodeMap);
                return;
            }

            // try plug-in single-row function
            try {
                var firstFunctionX           = model.ChainElements[0].FuncName;
                var firstFunctionIsProperty  = !model.ChainElements[0].HasLeftParen;
                var classMethodPair          = engineImportService.ResolveSingleRow(firstFunctionX);
                IList <ExprChainedSpec> spec = new List <ExprChainedSpec>();
                var firstArgs        = model.ChainElements[0].Args;
                var childExpressions = ASTLibFunctionHelper.GetExprNodesLibFunc(firstArgs, astExprNodeMap);
                spec.Add(new ExprChainedSpec(classMethodPair.Second.MethodName, childExpressions, firstFunctionIsProperty));
                AddChainRemainderFromOffset(model.ChainElements, 1, spec, astExprNodeMap);
                var plugin = new ExprPlugInSingleRowNode(firstFunctionX, classMethodPair.First, spec, classMethodPair.Second);
                ASTExprHelper.ExprCollectAddSubNodesAddParentNode(plugin, ctx, astExprNodeMap);
                return;
            }
            catch (EngineImportUndefinedException e) {
                // Not an single-row function
            }
            catch (EngineImportException e) {
                throw new IllegalStateException("Error resolving single-row function: " + e.Message, e);
            }

            // special case for min,max
            var firstFunction = model.ChainElements[0].FuncName;

            if ((firstFunction.ToLower().Equals("max")) || (firstFunction.ToLower().Equals("min")) ||
                (firstFunction.ToLower().Equals("fmax")) || (firstFunction.ToLower().Equals("fmin")))
            {
                var firstArgs = model.ChainElements[0].Args;
                HandleMinMax(firstFunction, firstArgs, astExprNodeMap);
                return;
            }

            // obtain chain with actual expressions
            IList <ExprChainedSpec> chain = new List <ExprChainedSpec>();

            AddChainRemainderFromOffset(model.ChainElements, 0, chain, astExprNodeMap);

            // add chain element for class info, if any
            var distinct = model.ChainElements[0].Args != null && model.ChainElements[0].Args.DISTINCT() != null;

            if (model.OptionalClassIdent != null)
            {
                chain.Insert(0, new ExprChainedSpec(model.OptionalClassIdent, Collections.GetEmptyList <ExprNode>(), true));
                distinct = false;
            }
            firstFunction = chain[0].Name;

            // try plug-in aggregation function
            var aggregationNode = ASTAggregationHelper.TryResolveAsAggregation(engineImportService, distinct, firstFunction, plugInAggregations, engineURI);

            if (aggregationNode != null)
            {
                var firstSpec = chain.Pluck(0);
                aggregationNode.AddChildNodes(firstSpec.Parameters);
                ExprNode exprNode;
                if (chain.IsEmpty())
                {
                    exprNode = aggregationNode;
                }
                else
                {
                    exprNode = new ExprDotNode(chain, duckType, udfCache);
                    exprNode.AddChildNode(aggregationNode);
                }
                ASTExprHelper.ExprCollectAddSubNodesAddParentNode(exprNode, ctx, astExprNodeMap);
                return;
            }

            // try declared or alias expression
            var declaredNode = ExprDeclaredHelper.GetExistsDeclaredExpr(firstFunction, chain[0].Parameters, expressionDeclarations.Expressions, exprDeclaredService, contextDescriptor);

            if (declaredNode != null)
            {
                chain.RemoveAt(0);
                ExprNode exprNode;
                if (chain.IsEmpty())
                {
                    exprNode = declaredNode;
                }
                else
                {
                    exprNode = new ExprDotNode(chain, duckType, udfCache);
                    exprNode.AddChildNode(declaredNode);
                }
                ASTExprHelper.ExprCollectAddSubNodesAddParentNode(exprNode, ctx, astExprNodeMap);
                return;
            }

            // try script
            var scriptNode = ExprDeclaredHelper.GetExistsScript(configurationInformation.EngineDefaults.ScriptsConfig.DefaultDialect, chain[0].Name, chain[0].Parameters, scriptExpressions, exprDeclaredService);

            if (scriptNode != null)
            {
                chain.RemoveAt(0);
                ExprNode exprNode;
                if (chain.IsEmpty())
                {
                    exprNode = scriptNode;
                }
                else
                {
                    exprNode = new ExprDotNode(chain, duckType, udfCache);
                    exprNode.AddChildNode(scriptNode);
                }
                ASTExprHelper.ExprCollectAddSubNodesAddParentNode(exprNode, ctx, astExprNodeMap);
                return;
            }

            // try table
            var tableInfo = ASTTableExprHelper.CheckTableNameGetLibFunc(tableService, engineImportService, plugInAggregations, engineURI, firstFunction, chain);

            if (tableInfo != null)
            {
                ASTTableExprHelper.AddTableExpressionReference(statementSpec, tableInfo.First);
                chain = tableInfo.Second;
                ExprNode exprNode;
                if (chain.IsEmpty())
                {
                    exprNode = tableInfo.First;
                }
                else
                {
                    exprNode = new ExprDotNode(chain, duckType, udfCache);
                    exprNode.AddChildNode(tableInfo.First);
                }
                ASTExprHelper.ExprCollectAddSubNodesAddParentNode(exprNode, ctx, astExprNodeMap);
                return;
            }

            // Could be a mapped property with an expression-parameter "mapped(expr)" or array property with an expression-parameter "array(expr)".
            ExprDotNode dotNode;

            if (chain.Count == 1)
            {
                dotNode = new ExprDotNode(chain, false, false);
            }
            else
            {
                dotNode = new ExprDotNode(chain, duckType, udfCache);
            }
            ASTExprHelper.ExprCollectAddSubNodesAddParentNode(dotNode, ctx, astExprNodeMap);
        }
Exemple #17
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));
        }