Ejemplo n.º 1
0
        private static CreateTableColumn GetColumn(
            EsperEPL2GrammarParser.CreateTableColumnContext ctx,
            IDictionary<ITree, ExprNode> astExprNodeMap,
            StatementSpecMapEnv mapEnv)
        {
            var columnName = ctx.n.Text;

            ExprNode optExpression = null;
            if (ctx.builtinFunc() != null || ctx.chainable() != null)
            {
                optExpression = ASTExprHelper.ExprCollectSubNodes(ctx, 0, astExprNodeMap)[0];
            }

            var optType = ASTClassIdentifierHelper.Walk(ctx.classIdentifierWithDimensions());

            var primaryKey = false;
            if (ctx.p != null)
            {
                if (!string.Equals(ctx.p.Text, "primary", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw ASTWalkException.From("Invalid keyword '" + ctx.p.Text + "' encountered, expected 'primary key'");
                }

                if (!string.Equals(ctx.k.Text, "key", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw ASTWalkException.From("Invalid keyword '" + ctx.k.Text + "' encountered, expected 'primary key'");
                }

                primaryKey = true;
            }

            IList<AnnotationDesc> annots = new EmptyList<AnnotationDesc>();
            if (ctx.annotationEnum() != null)
            {
                annots = new List<AnnotationDesc>(ctx.annotationEnum().Length);
                foreach (EsperEPL2GrammarParser.AnnotationEnumContext anctx in ctx.annotationEnum())
                {
                    annots.Add(ASTAnnotationHelper.Walk(anctx, mapEnv.ImportService));
                }
            }

            if (ctx.typeExpressionAnnotation() != null)
            {
                if (annots.IsEmpty())
                {
                    annots = new List<AnnotationDesc>();
                }

                foreach (EsperEPL2GrammarParser.TypeExpressionAnnotationContext anno in ctx.typeExpressionAnnotation())
                {
                    annots.Add(new AnnotationDesc(anno.n.Text, anno.v.Text));
                }
            }

            return new CreateTableColumn(columnName, optExpression, optType, annots, primaryKey);
        }
Ejemplo n.º 2
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;
        }
Ejemplo n.º 3
0
 public static string ExpectMayTypeAnno(EsperEPL2GrammarParser.TypeExpressionAnnotationContext ctx, CommonTokenStream tokenStream)
 {
     if (ctx == null)
     {
         return null;
     }
     string annoName = ctx.n.Text;
     if (!string.Equals(annoName, "type", StringComparison.InvariantCultureIgnoreCase))
     {
         throw ASTWalkException.From("Invalid annotation for property selection, expected 'type' but found '" + annoName + "'", tokenStream, ctx);
     }
     return ctx.v.Text;
 }
Ejemplo n.º 4
0
 private static string ExtractUnicode (StringBuilder sb, int slashIndex) {
     string result;
     string code = sb.Substring (slashIndex + 2, slashIndex + 6);
     int charNum = Int32.Parse (code, 16); // hex to integer
     try {
         ByteArrayOutputStream baos = new ByteArrayOutputStream ();
         OutputStreamWriter osw = new OutputStreamWriter (baos, "UTF-8");
         osw.Write (charNum);
         osw.Flush ();
         result = baos.ToString ("UTF-8");
     } catch (Exception e) {
         throw ASTWalkException.From ("Failed to obtain for unicode '" + charNum + "'", e);
     }
     return result;
 }
Ejemplo n.º 5
0
        internal static bool ValidateIsPrimitiveArray(IToken p)
        {
            if (p != null)
            {
                if (!p.Text.ToLowerInvariant().Equals(ClassIdentifierWArray.PRIMITIVE_KEYWORD))
                {
                    throw ASTWalkException.From(
                        "Column type keyword '" + p.Text + "' not recognized, expecting '[" + ClassIdentifierWArray.PRIMITIVE_KEYWORD + "]'");
                }

                return true;
            }

            return false;
        }
Ejemplo n.º 6
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;
        }
Ejemplo n.º 7
0
        private static object WalkClassIdent(
            EsperEPL2GrammarParser.ClassIdentifierContext ctx,
            ImportServiceCompileTime importService)
        {
            var enumValueText = ctx.GetText();
            ValueAndFieldDesc enumValueAndField;
            try
            {
                enumValueAndField = ImportCompileTimeUtil.ResolveIdentAsEnumConst(enumValueText, importService, ExtensionClassEmpty.INSTANCE, 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 (enumValueAndField != null)
            {
                return enumValueAndField.Value;
            }

            // resolve as class
            object enumValue = null;
            if (enumValueText.EndsWith(".class") && enumValueText.Length > 6)
            {
                try
                {
                    var name = enumValueText.Substring(0, enumValueText.Length - 6);
                    enumValue = importService.ResolveClass(name, true, ExtensionClassEmpty.INSTANCE);
                }
                catch (ImportException)
                {
                    // expected
                }
            }

            if (enumValue != null)
            {
                return enumValue;
            }

            throw ASTWalkException.From(
                "Annotation enumeration value '" + enumValueText + "' not recognized as an enumeration class, please check imports or type used");
        }
Ejemplo n.º 8
0
        public static void RegExCollectAddSubNodes(
            RowRecogExprNode regexNode,
            ITree node,
            IDictionary<ITree, RowRecogExprNode> astRegExNodeMap)
        {
            if (regexNode == null)
            {
                throw ASTWalkException.From("Invalid null expression node for '" + ASTUtil.PrintNode(node) + "'");
            }

            RegExAction action = (exprNode, astExprNodeMapX, nodeX) => {
                astExprNodeMapX.Remove(nodeX);
                regexNode.AddChildNode(exprNode);
            };
            for (int i = 0; i < node.ChildCount; i++)
            {
                ITree childNode = node.GetChild(i);
                RegExApplyActionRecursive(childNode, astRegExNodeMap, action);
            }
        }
Ejemplo n.º 9
0
        public static ExprNode ResolvePropertyOrVariableIdentifier(
            string identifier,
            VariableCompileTimeResolver variableCompileTimeResolver,
            StatementSpecRaw spec)
        {
            VariableMetaData metaData = variableCompileTimeResolver.Resolve(identifier);
            if (metaData != null)
            {
                ExprVariableNodeImpl exprNode = new ExprVariableNodeImpl(metaData, null);
                spec.ReferencedVariables.Add(metaData.VariableName);
                string message = VariableUtil.CheckVariableContextName(spec.OptionalContextName, metaData);
                if (message != null)
                {
                    throw ASTWalkException.From(message);
                }

                return exprNode;
            }

            return new ExprIdentNodeImpl(identifier);
        }
Ejemplo n.º 10
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 = (exprNode, astExprNodeMapX, nodeX) => {
                astExprNodeMapX.Remove(nodeX);
                parentNode.AddChildNode(exprNode);
            };
            RecursiveFindRemoveChildExprNode(node, astExprNodeMap, action);
        }
Ejemplo n.º 11
0
        public static void PatternCollectAddSubnodesAddParentNode(
            EvalForgeNode evalNode,
            ITree node,
            IDictionary<ITree, EvalForgeNode> astPatternNodeMap)
        {
            if (evalNode == null)
            {
                throw ASTWalkException.From("Invalid null expression node for '" + ASTUtil.PrintNode(node) + "'");
            }

            for (int i = 0; i < node.ChildCount; i++)
            {
                var childNode = node.GetChild(i);
                EvalForgeNode childEvalNode = PatternGetRemoveTopNode(childNode, astPatternNodeMap);
                if (childEvalNode != null)
                {
                    evalNode.AddChildNode(childEvalNode);
                }
            }

            astPatternNodeMap.Put(node, evalNode);
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
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);
            }
        }
Ejemplo n.º 14
0
        public static MatchRecognizeSkipEnum ParseSkip(
            CommonTokenStream tokenStream,
            EsperEPL2GrammarParser.MatchRecogMatchesAfterSkipContext ctx)
        {
            if (!string.Equals(ctx.i1.GetText(), "MATCH", StringComparison.InvariantCultureIgnoreCase) ||
                !string.Equals(ctx.i2.GetText(), "SKIP", StringComparison.InvariantCultureIgnoreCase) ||
                !string.Equals(ctx.i5.GetText(), "ROW", StringComparison.InvariantCultureIgnoreCase)
            )
            {
                throw ASTWalkException.From(MESSAGE, tokenStream, ctx);
            }

            var i3 = ctx.i3.GetText();
            if (!string.Equals(i3, "TO", StringComparison.InvariantCultureIgnoreCase) &&
                !string.Equals(i3, "PAST", StringComparison.InvariantCultureIgnoreCase))
            {
                throw ASTWalkException.From(MESSAGE, tokenStream, ctx);
            }

            var i4 = ctx.i4.GetText();
            if (string.Equals(i4, "LAST", StringComparison.InvariantCultureIgnoreCase))
            {
                return MatchRecognizeSkipEnum.PAST_LAST_ROW;
            }

            if (string.Equals(i4, "NEXT", StringComparison.InvariantCultureIgnoreCase))
            {
                return MatchRecognizeSkipEnum.TO_NEXT_ROW;
            }

            if (string.Equals(i4, "CURRENT", StringComparison.InvariantCultureIgnoreCase))
            {
                return MatchRecognizeSkipEnum.TO_CURRENT_ROW;
            }

            throw ASTWalkException.From(MESSAGE);
        }
Ejemplo n.º 15
0
        public static ClassIdentifierWArray Walk(EsperEPL2GrammarParser.ClassIdentifierWithDimensionsContext ctx)
        {
            if (ctx == null)
            {
                return null;
            }

            var name = ASTUtil.UnescapeClassIdent(ctx.classIdentifier());
            IList<EsperEPL2GrammarParser.DimensionsContext> dimensions = ctx.dimensions();

            if (dimensions.IsEmpty())
            {
                return new ClassIdentifierWArray(name);
            }

            var first = dimensions[0].IDENT();
            var keyword = first?.ToString().Trim().ToLowerInvariant();
            if (keyword != null && !keyword.Equals(ClassIdentifierWArray.PRIMITIVE_KEYWORD))
            {
                throw ASTWalkException.From("Invalid array keyword '" + keyword + "', expected '" + ClassIdentifierWArray.PRIMITIVE_KEYWORD + "'");
            }

            return new ClassIdentifierWArray(name, dimensions.Count, keyword != null);
        }
Ejemplo n.º 16
0
        public static RowRecogExprRepeatDesc WalkOptionalRepeat(
            EsperEPL2GrammarParser.MatchRecogPatternRepeatContext ctx,
            IDictionary<ITree, ExprNode> astExprNodeMap)
        {
            if (ctx == null)
            {
                return null;
            }

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

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

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

            return new RowRecogExprRepeatDesc(e1, e2, null);
        }
Ejemplo n.º 17
0
        private static ContextSpec WalkChoice(
            EsperEPL2GrammarParser.CreateContextChoiceContext ctx,
            IDictionary<ITree, ExprNode> astExprNodeMap,
            IDictionary<ITree, EvalForgeNode> astPatternNodeMap,
            PropertyEvalSpec propertyEvalSpec)
        {
            // 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 = ExprNodeUtilityQuery.EMPTY_EXPR_ARRAY;
                    }
                    else
                    {
                        distinctExpressions = ASTExprHelper.ExprCollectSubNodesPerNode(
                            ctx.createContextDistinct().expressionList().expression(), astExprNodeMap);
                    }
                }

                ContextSpecCondition startEndpoint;
                if (ctx.START() != null)
                {
                    var immediate = CheckNow(ctx.i);
                    if (immediate)
                    {
                        startEndpoint = ContextSpecConditionImmediate.INSTANCE;
                    }
                    else
                    {
                        startEndpoint = GetContextCondition(ctx.r1, astExprNodeMap, astPatternNodeMap, propertyEvalSpec, false);
                    }
                }
                else
                {
                    var immediate = CheckNow(ctx.i);
                    startEndpoint = GetContextCondition(ctx.r1, astExprNodeMap, astPatternNodeMap, propertyEvalSpec, immediate);
                }

                var overlapping = ctx.INITIATED() != null;
                var endEndpoint = GetContextCondition(ctx.r2, astExprNodeMap, astPatternNodeMap, propertyEvalSpec, false);
                return new ContextSpecInitiatedTerminated(startEndpoint, endEndpoint, overlapping, distinctExpressions);
            }

            // partitioned
            if (ctx.PARTITION() != null)
            {
                IList<EsperEPL2GrammarParser.CreateContextPartitionItemContext> partitions = ctx.createContextPartitionItem();
                IList<ContextSpecKeyedItem> rawSpecs = new List<ContextSpecKeyedItem>();
                foreach (var partition in partitions)
                {
                    var filterSpec = ASTFilterSpecHelper.WalkFilterSpec(partition.eventFilterExpression(), propertyEvalSpec, astExprNodeMap);
                    propertyEvalSpec = null;

                    IList<string> propertyNames = new List<string>();
                    IList<EsperEPL2GrammarParser.ChainableContext> properties = partition.chainable();
                    foreach (var property in properties)
                    {
                        var propertyName = ASTUtil.GetPropertyName(property, 0);
                        propertyNames.Add(propertyName);
                    }

                    ASTExprHelper.ExprCollectSubNodes(partition, 0, astExprNodeMap); // remove expressions

                    rawSpecs.Add(
                        new ContextSpecKeyedItem(
                            filterSpec, propertyNames, partition.keywordAllowedIdent() == null ? null : partition.keywordAllowedIdent().GetText()));
                }

                IList<ContextSpecConditionFilter> optionalInit = null;
                if (ctx.createContextPartitionInit() != null)
                {
                    optionalInit = GetContextPartitionInit(ctx.createContextPartitionInit().createContextFilter(), astExprNodeMap);
                }

                ContextSpecCondition optionalTermination = null;
                if (ctx.createContextPartitionTerm() != null)
                {
                    optionalTermination = GetContextCondition(
                        ctx.createContextPartitionTerm().createContextRangePoint(), astExprNodeMap, astPatternNodeMap, propertyEvalSpec, false);
                }

                return new ContextSpecKeyed(rawSpecs, optionalInit, optionalTermination);
            }

            if (ctx.COALESCE() != null)
            {
                // hash
                IList<EsperEPL2GrammarParser.CreateContextCoalesceItemContext> coalesces = ctx.createContextCoalesceItem();
                IList<ContextSpecHashItem> rawSpecs = new List<ContextSpecHashItem>(coalesces.Count);
                foreach (var coalesce in coalesces)
                {
                    var chain = ASTChainSpecHelper.GetChainables(coalesce.chainable(), astExprNodeMap);
                    var func = chain[0];
                    var filterSpec = ASTFilterSpecHelper.WalkFilterSpec(coalesce.eventFilterExpression(), propertyEvalSpec, astExprNodeMap);
                    propertyEvalSpec = null;
                    rawSpecs.Add(new ContextSpecHashItem(func, filterSpec));
                }

                var granularity = ctx.g.Text;
                if (!granularity.ToLowerInvariant().Equals("granularity"))
                {
                    throw ASTWalkException.From("Expected 'granularity' keyword after list of coalesce items, found '" + granularity + "' instead");
                }

                var num = ASTConstantHelper.Parse(ctx.number());
                var preallocateStr = ctx.p?.Text;
                if (preallocateStr != null && !preallocateStr.ToLowerInvariant().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 ContextSpecHash(rawSpecs, num.AsInt32(), preallocateStr != null);
            }

            // categorized
            if (ctx.createContextGroupItem() != null)
            {
                IList<EsperEPL2GrammarParser.CreateContextGroupItemContext> grps = ctx.createContextGroupItem();
                IList<ContextSpecCategoryItem> items = new List<ContextSpecCategoryItem>();
                foreach (var grp in grps)
                {
                    var exprNode = ASTExprHelper.ExprCollectSubNodes(grp, 0, astExprNodeMap)[0];
                    var name = grp.i.Text;
                    items.Add(new ContextSpecCategoryItem(exprNode, name));
                }

                var filterSpec = ASTFilterSpecHelper.WalkFilterSpec(ctx.eventFilterExpression(), propertyEvalSpec, astExprNodeMap);
                return new ContextSpecCategory(items, filterSpec);
            }

            throw new IllegalStateException("Unrecognized context detail type");
        }
Ejemplo n.º 18
0
        public static MyPair 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.ToLowerInvariant().Trim().Equals("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 node = ASTExprHelper.ExprCollectSubNodes(ctx, 0, astExprNodeMap)[0];
                var alias = ctx.name.Text;
                var expressionUnmap = StatementSpecMapper.Unmap(node);
                var decl = new ExpressionDeclItem(alias, new string[0], true);
                decl.OptionalSoda = expressionUnmap;
                return new MyPair(decl, null);
            }

            if (ctx.expressionDef().stringconstant() != null)
            {
                var expressionText = scriptBodies.DeleteAt(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 optionalEventTypeName = ASTTypeExpressionAnnoHelper.ExpectMayTypeAnno(ctx.typeExpressionAnnotation(), tokenStream);
                var script = new ExpressionScriptProvided(
                    name, expressionText, parameters.ToArray(),
                    optionalReturnType, optionalReturnTypeArray, optionalEventTypeName, optionalDialect);
                return new MyPair(null, script);
            }

            var ctxexpr = ctx.expressionDef();
            var inner = ASTExprHelper.ExprCollectSubNodes(ctxexpr.expression(), 0, astExprNodeMap)[0];

            IList<string> parametersNames = new EmptyList<string>();
            var lambdactx = ctxexpr.expressionLambdaDecl();
            if (ctxexpr.expressionLambdaDecl() != null)
            {
                parametersNames = ASTLambdaHelper.GetLambdaGoesParams(lambdactx);
            }

            var expression = StatementSpecMapper.Unmap(inner);
            var expr = new ExpressionDeclItem(name, parametersNames.ToArray(), false);
            expr.OptionalSoda = expression;
            return new MyPair(expr, null);
        }
Ejemplo n.º 19
0
        public static OutputLimitSpec BuildOutputLimitSpec(
            CommonTokenStream tokenStream,
            EsperEPL2GrammarParser.OutputLimitContext ctx,
            IDictionary<ITree, ExprNode> astExprNodeMap)
        {
            var 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 = ctx.number().GetText().AsDouble();
                    }
                }
                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
                {
                    var constant = ASTConstantHelper.Parse(ctx.outputLimitAfter().number());
                    afterNumberOfEvents = constant.AsInt32();
                }
            }

            var 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);
        }