Пример #1
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 (int i = 0; i < node.ChildCount; i++)
            {
                ITree childNode = node.GetChild(i);
                RecursiveFindRemoveChildExprNode(childNode, astExprNodeMap, action);
            }
        }
Пример #2
0
        public static ExprNode MathGetExpr(
            IParseTree ctx,
            IDictionary<ITree, ExprNode> astExprNodeMap,
            Configuration configurationInformation)
        {
            int count = 1;
            ExprNode @base = ASTExprHelper.ExprCollectSubNodes(ctx.GetChild(0), 0, astExprNodeMap)[0];

            while (true)
            {
                int token = ASTUtil.GetAssertTerminatedTokenType(ctx.GetChild(count));
                MathArithTypeEnum mathArithTypeEnum = TokenToMathEnum(token);

                ExprNode right = ASTExprHelper.ExprCollectSubNodes(ctx.GetChild(count + 1), 0, astExprNodeMap)[0];

                ExprMathNode math = new ExprMathNode(
                    mathArithTypeEnum,
                    configurationInformation.Compiler.Expression.IsIntegerDivision,
                    configurationInformation.Compiler.Expression.IsDivisionByZeroReturnsNull);
                math.AddChildNode(@base);
                math.AddChildNode(right);
                @base = math;

                count += 2;
                if (count >= ctx.ChildCount)
                {
                    break;
                }
            }

            return @base;
        }
Пример #3
0
 public static void DisplayAST(ITree ast)
 {
     Log.Debug(".displayAST...");
     if (Log.IsDebugEnabled)
     {
         ASTUtil.DumpAST(ast);
     }
 }
Пример #4
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);
                }
            }

            var ruleNode = (IRuleNode) node;
            var ruleIndex = ruleNode.RuleContext.RuleIndex;
            if (ruleIndex == EsperEPL2GrammarParser.RULE_number)
            {
                return ParseNumber(ruleNode, 1);
            }

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

                return ParseNumber(number, 1);
            }

            if (ruleIndex == EsperEPL2GrammarParser.RULE_stringconstant)
            {
                return StringValue.ParseString(node.GetText());
            }

            if (ruleIndex == EsperEPL2GrammarParser.RULE_constant)
            {
                return Parse(ruleNode.GetChild(0));
            }

            throw ASTWalkException.From("Encountered unrecognized constant", node.GetText());
        }
Пример #5
0
        private object ParseLoadJson(string expression)
        {
            var parsed = ParseJson(expression);
            var tree   = (EsperEPL2GrammarParser.StartJsonValueRuleContext)parsed.First;

            Assert.AreEqual(EsperEPL2GrammarParser.RULE_startJsonValueRule, ASTUtil.GetRuleIndexIfProvided(tree));
            ITree root = tree.GetChild(0);

            ASTUtil.DumpAST(root);
            return(ASTJsonHelper.Walk(parsed.Second, tree.jsonvalue()));
        }
Пример #6
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);
 }
Пример #7
0
        public static IList <string> GetLambdaGoesParams(EsperEPL2GrammarParser.ExpressionLambdaDeclContext ctx)
        {
            IList <string> parameters;

            if (ctx.i != null)
            {
                parameters = new List <string>(1);
                parameters.Add(ctx.i.GetText());
            }
            else
            {
                parameters = ASTUtil.GetIdentList(ctx.columnListKeywordAllowed());
            }

            return(parameters);
        }
Пример #8
0
        private static string[] ParseParamsStreamNames(EsperEPL2GrammarParser.GopParamsItemContext item)
        {
            IList<string> paramNames = new List<string>(1);
            if (item.gopParamsItemMany() != null)
            {
                foreach (EsperEPL2GrammarParser.ClassIdentifierContext ctx in item.gopParamsItemMany().classIdentifier())
                {
                    paramNames.Add(ctx.GetText());
                }
            }
            else
            {
                paramNames.Add(ASTUtil.UnescapeClassIdent(item.classIdentifier()));
            }

            return paramNames.ToArray();
        }
Пример #9
0
        public static IList<ColumnDesc> GetColTypeList(EsperEPL2GrammarParser.CreateColumnListContext ctx)
        {
            if (ctx == null)
            {
                return new EmptyList<ColumnDesc>();
            }

            IList<ColumnDesc> result = new List<ColumnDesc>(ctx.createColumnListElement().Length);
            foreach (var colctx in ctx.createColumnListElement())
            {
                var colname = colctx.classIdentifier();
                var name = ASTUtil.UnescapeClassIdent(colname);
                var classIdent = ASTClassIdentifierHelper.Walk(colctx.classIdentifierWithDimensions());
                result.Add(new ColumnDesc(name, classIdent?.ToEPL()));
            }

            return result;
        }
Пример #10
0
        /// <summary>
        ///     Walk an annotation root name or child node (nested annotations).
        /// </summary>
        /// <param name="ctx">annotation walk node</param>
        /// <param name="importService">for imports</param>
        /// <returns>annotation descriptor</returns>
        /// <throws>ASTWalkException if the walk failed</throws>
        public static AnnotationDesc Walk(
            EsperEPL2GrammarParser.AnnotationEnumContext ctx,
            ImportServiceCompileTime importService)
        {
            var name = ASTUtil.UnescapeClassIdent(ctx.classIdentifier());
            IList<Pair<string, object>> values = new List<Pair<string, object>>();
            if (ctx.elementValueEnum() != null)
            {
                var value = WalkValue(ctx.elementValueEnum(), importService);
                values.Add(new Pair<string, object>("Value", value));
            }
            else if (ctx.elementValuePairsEnum() != null)
            {
                WalkValuePairs(ctx.elementValuePairsEnum(), values, importService);
            }

            return new AnnotationDesc(name, values);
        }
Пример #11
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);
            }
        }
Пример #12
0
        private static GraphOperatorOutputItemType ParseType(EsperEPL2GrammarParser.GopOutTypeParamContext ctx)
        {
            if (ctx.q != null)
            {
                return new GraphOperatorOutputItemType(true, null, null);
            }

            var className = ASTUtil.UnescapeClassIdent(ctx.gopOutTypeItem().classIdentifier());
            IList<GraphOperatorOutputItemType> typeParams = new List<GraphOperatorOutputItemType>();
            if (ctx.gopOutTypeItem().gopOutTypeList() != null)
            {
                IList<EsperEPL2GrammarParser.GopOutTypeParamContext> pctxs = ctx.gopOutTypeItem().gopOutTypeList().gopOutTypeParam();
                foreach (var pctx in pctxs)
                {
                    var type = ParseType(pctx);
                    typeParams.Add(type);
                }
            }

            return new GraphOperatorOutputItemType(false, className, typeParams);
        }
Пример #13
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);
        }
Пример #14
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);
        }
Пример #15
0
 public static string PrintNode(ITree node)
 {
     var writer = new StringWriter();
     ASTUtil.DumpAST(writer, node, 0);
     return writer.ToString();
 }
Пример #16
0
        public static ExprTimePeriod TimePeriodGetExprAllParams(
            EsperEPL2GrammarParser.TimePeriodContext ctx,
            IDictionary<ITree, ExprNode> astExprNodeMap,
            VariableCompileTimeResolver variableCompileTimeResolver,
            StatementSpecRaw spec,
            Configuration config,
            TimeAbacus timeAbacus)
        {
            ExprNode[] nodes = new ExprNode[9];
            for (int i = 0; i < ctx.ChildCount; i++)
            {
                IParseTree unitRoot = ctx.GetChild(i);

                ExprNode valueExpr;
                if (ASTUtil.IsTerminatedOfType(unitRoot.GetChild(0), EsperEPL2GrammarLexer.IDENT))
                {
                    string ident = unitRoot.GetChild(0).GetText();
                    valueExpr = ASTExprHelper.ResolvePropertyOrVariableIdentifier(ident, variableCompileTimeResolver, spec);
                }
                else
                {
                    AtomicReference<ExprNode> @ref = new AtomicReference<ExprNode>();
                    ExprAction action = (exprNode, astExprNodeMapX, node) => {
                        astExprNodeMapX.Remove(node);
                        @ref.Set(exprNode);
                    };
                    ASTExprHelper.RecursiveFindRemoveChildExprNode(unitRoot.GetChild(0), astExprNodeMap, action);
                    valueExpr = @ref.Get();
                }

                if (ASTUtil.GetRuleIndexIfProvided(unitRoot) == EsperEPL2GrammarParser.RULE_microsecondPart)
                {
                    nodes[8] = valueExpr;
                }

                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(
                nodes[0] != null, nodes[1] != null,
                nodes[2] != null, nodes[3] != null,
                nodes[4] != null, nodes[5] != null,
                nodes[6] != null, nodes[7] != null,
                nodes[8] != null, timeAbacus);

            foreach (ExprNode node in nodes)
            {
                if (node != null)
                {
                    timeNode.AddChildNode(node);
                }
            }

            return timeNode;
        }
Пример #17
0
        /// <summary>
        /// Parse expression using the rule the ParseRuleSelector instance supplies.
        /// </summary>
        /// <param name="expression">text to parse</param>
        /// <param name="parseRuleSelector">parse rule to select</param>
        /// <param name="addPleaseCheck">true to include depth paraphrase</param>
        /// <param name="eplStatementErrorMsg">text for error</param>
        /// <param name="rewriteScript">whether to rewrite script expressions</param>
        /// <returns>AST - syntax tree</returns>
        /// <throws>EPException                         when the AST could not be parsed</throws>
        /// <throws>StatementSpecCompileSyntaxException syntax exceptions</throws>
        public static ParseResult Parse(
            string expression,
            string eplStatementErrorMsg,
            bool addPleaseCheck,
            ParseRuleSelector parseRuleSelector,
            bool rewriteScript)
        {
            if (Log.IsDebugEnabled)
            {
                Log.Debug(".parse Parsing expr=" + expression);
            }

            var input = new CaseInsensitiveInputStream(expression);
            var lex = NewLexer(input);

            var tokens = new CommonTokenStream(lex);
            var parser = ParseHelper.NewParser(tokens);

            ITree tree;
            try
            {
                tree = parseRuleSelector.InvokeParseRule(parser);
            }
            catch (RecognitionException ex)
            {
                tokens.Fill();
                if (rewriteScript)
                {
                    if (IsContainsScriptOrClassExpression(tokens))
                    {
                        return HandleScriptAndClassRewrite(tokens, eplStatementErrorMsg, addPleaseCheck, parseRuleSelector);
                    }
                }

                Log.Debug("Error parsing statement [" + expression + "]", ex);
                throw ExceptionConvertor.ConvertStatement(ex, eplStatementErrorMsg, addPleaseCheck, parser);
            }
            catch (Exception e)
            {
                try
                {
                    tokens.Fill();
                }
                catch (Exception)
                {
                    Log.Debug("Token-fill produced exception: " + e.Message, e);
                }

                if (Log.IsDebugEnabled)
                {
                    Log.Debug("Error parsing statement [" + eplStatementErrorMsg + "]", e);
                }

                if (e.InnerException is RecognitionException recognitionException)
                {
                    if (rewriteScript)
                    {
                        if (IsContainsScriptOrClassExpression(tokens))
                        {
                            return HandleScriptAndClassRewrite(tokens, eplStatementErrorMsg, addPleaseCheck, parseRuleSelector);
                        }
                    }

                    throw ExceptionConvertor.ConvertStatement(recognitionException, eplStatementErrorMsg, addPleaseCheck, parser);
                }

                throw;
            }

            // if we are re-writing scripts and contain a script, then rewrite
            if (rewriteScript && IsContainsScriptOrClassExpression(tokens))
            {
                return HandleScriptAndClassRewrite(tokens, eplStatementErrorMsg, addPleaseCheck, parseRuleSelector);
            }

            if (Log.IsDebugEnabled)
            {
                Log.Debug(".parse Dumping AST...");
                ASTUtil.DumpAST(tree);
            }

            var expressionWithoutAnnotation = expression;
            if (tree is EsperEPL2GrammarParser.StartEPLExpressionRuleContext)
            {
                var epl = (EsperEPL2GrammarParser.StartEPLExpressionRuleContext) tree;
                expressionWithoutAnnotation = GetNoAnnotation(expression, epl.annotationEnum(), tokens);
            }

            return new ParseResult(
                tree,
                expressionWithoutAnnotation,
                tokens,
                EmptyList<string>.Instance,
                EmptyList<string>.Instance);

        }
Пример #18
0
        private static CreateSchemaDesc GetSchemaDesc(
            EsperEPL2GrammarParser.CreateSchemaDefContext ctx,
            AssignedType assignedType)
        {
            var schemaName = ctx.name.Text;
            var columnTypes = GetColTypeList(ctx.createColumnList());

            // get model-after types (could be multiple for variants)
            ISet<string> typeNames = new LinkedHashSet<string>();
            if (ctx.variantList() != null)
            {
                IList<EsperEPL2GrammarParser.VariantListElementContext> variantCtxs = ctx.variantList().variantListElement();
                foreach (var variantCtx in variantCtxs)
                {
                    typeNames.Add(variantCtx.GetText());
                }
            }

            // get inherited and start timestamp and end timestamps
            string startTimestamp = null;
            string endTimestamp = null;
            ISet<string> inherited = new LinkedHashSet<string>();
            ISet<string> copyFrom = new LinkedHashSet<string>();
            if (ctx.createSchemaQual() != null)
            {
                IList<EsperEPL2GrammarParser.CreateSchemaQualContext> qualCtxs = ctx.createSchemaQual();
                foreach (var qualCtx in qualCtxs)
                {
                    var qualName = qualCtx.i.Text.ToLowerInvariant();
                    var cols = ASTUtil.GetIdentList(qualCtx.columnList());
                    if (string.Equals(qualName, "inherits", StringComparison.InvariantCultureIgnoreCase))
                    {
                        inherited.AddAll(cols);
                        continue;
                    }

                    if (string.Equals(qualName, "starttimestamp", StringComparison.InvariantCultureIgnoreCase))
                    {
                        startTimestamp = cols[0];
                        continue;
                    }

                    if (string.Equals(qualName, "endtimestamp", StringComparison.InvariantCultureIgnoreCase))
                    {
                        endTimestamp = cols[0];
                        continue;
                    }

                    if (string.Equals(qualName, "copyfrom", StringComparison.InvariantCultureIgnoreCase))
                    {
                        copyFrom.AddAll(cols);
                        continue;
                    }

                    throw new EPException(
                        "Expected 'inherits', 'starttimestamp', 'endtimestamp' or 'copyfrom' keyword after create-schema clause but encountered '" +
                        qualName + "'");
                }
            }

            return new CreateSchemaDesc(schemaName, typeNames, columnTypes, inherited, assignedType, startTimestamp, endTimestamp, copyFrom);
        }
Пример #19
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);
        }
Пример #20
0
        public void TestParse()
        {
            object result;

            Assert.AreEqual("abc", ParseLoadJson("\"abc\""));
            Assert.AreEqual("http://www.uri.com", ParseLoadJson("\"http://www.uri.com\""));
            Assert.AreEqual("new\nline", ParseLoadJson("\"new\\nline\""));
            Assert.AreEqual(" ~ ", ParseLoadJson("\" \\u007E \""));
            Assert.AreEqual("/", ParseLoadJson("\"\\/\""));
            Assert.AreEqual(true, ParseLoadJson("true"));
            Assert.AreEqual(false, ParseLoadJson("false"));
            Assert.AreEqual(null, ParseLoadJson("null"));
            Assert.AreEqual(10, ParseLoadJson("10"));
            Assert.AreEqual(-10, ParseLoadJson("-10"));
            Assert.AreEqual(20L, ParseLoadJson("20L"));
            Assert.AreEqual(5.5d, ParseLoadJson("5.5"));

            result = ParseLoadJson("{\"name\":\"myname\",\"value\":5}");
            EPAssertionUtil.AssertPropsMap(result.AsStringDictionary(), "name,value".SplitCsv(), "myname", 5);

            result = ParseLoadJson("{name:\"myname\",value:5}");
            EPAssertionUtil.AssertPropsMap(result.AsStringDictionary(), "name,value".SplitCsv(), "myname", 5);

            result = ParseLoadJson("[\"one\",2]");
            EPAssertionUtil.AssertEqualsExactOrder(new object[] { "one", 2 }, (IList <object>)result);

            result = ParseLoadJson("{\"one\": { 'a' : 2 } }");
            var inner = result.AsStringDictionary().Get("one").AsStringDictionary();

            Assert.AreEqual(1, inner.Count);

            var json = "{\n" +
                       "    \"glossary\": {\n" +
                       "        \"title\": \"example glossary\",\n" +
                       "\t\t\"GlossDiv\": {\n" +
                       "            \"title\": \"S\",\n" +
                       "\t\t\t\"GlossList\": {\n" +
                       "                \"GlossEntry\": {\n" +
                       "                    \"ID\": \"SGML\",\n" +
                       "\t\t\t\t\t\"SortAs\": \"SGML\",\n" +
                       "\t\t\t\t\t\"GlossTerm\": \"Standard Generalized Markup Language\",\n" +
                       "\t\t\t\t\t\"Acronym\": \"SGML\",\n" +
                       "\t\t\t\t\t\"Abbrev\": \"ISO 8879:1986\",\n" +
                       "\t\t\t\t\t\"GlossDef\": {\n" +
                       "                        \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\n" +
                       "\t\t\t\t\t\t\"GlossSeeAlso\": [\"GML\", \"XML\"]\n" +
                       "                    },\n" +
                       "\t\t\t\t\t\"GlossSee\": \"markup\"\n" +
                       "                }\n" +
                       "            }\n" +
                       "        }\n" +
                       "    }\n" +
                       "}";
            var tree = ParseJson(json).First;

            ASTUtil.DumpAST(tree);
            var loaded = ParseLoadJson(json);

            Assert.AreEqual(
                "{\"glossary\"={\"title\"=\"example glossary\", \"GlossDiv\"={\"title\"=\"S\", \"GlossList\"={\"GlossEntry\"={\"ID\"=\"SGML\", \"SortAs\"=\"SGML\", \"GlossTerm\"=\"Standard Generalized Markup Language\", \"Acronym\"=\"SGML\", \"Abbrev\"=\"ISO 8879:1986\", \"GlossDef\"={\"para\"=\"A meta-markup language, used to create markup languages such as DocBook.\", \"GlossSeeAlso\"=[\"GML\", \"XML\"]}, \"GlossSee\"=\"markup\"}}}}}",
                loaded.ToString());
        }
Пример #21
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");
        }