예제 #1
0
 internal static UnaryNode Unary( Kind k, ExprNode expr, Symbol s )
 {
     UnaryNode res = new UnaryNode();
     res.kind = k;
     res.start = s.pos;
     res.end = s.endpos;
     res.expr = expr;
     return res;
 }
예제 #2
0
파일: AST.cs 프로젝트: GHScan/DailyProjects
 public ExprNode_Call(int line, ExprNode funcExpr, List<ExprNode> paramExprs)
     : base(line)
 {
     FuncExpr = funcExpr; ParamExprs = paramExprs;
 }
예제 #3
0
파일: AST.cs 프로젝트: GHScan/DailyProjects
 public StmtNode_For(int line, StmtNode first, ExprNode second, StmtNode third, StmtNode body)
     : base(line)
 {
     First = first; Second = second; Third = third; Body = body;
 }
예제 #4
0
        private ICollection <EventBean> SnapshotAndApplyFilter(FilterSpecCompiled filter, Attribute[] annotations, ExprNode filterExpr, AgentInstanceContext agentInstanceContext)
        {
            var indexedResult = SnapshotNullWhenNoIndex(filter, annotations, null, null);

            if (indexedResult != null)
            {
                if (indexedResult.IsEmpty() || filterExpr == null)
                {
                    return(indexedResult);
                }
                var dequeX = new ArrayDeque <EventBean>(Math.Min(indexedResult.Count, 16));
                ExprNodeUtility.ApplyFilterExpressionIterable(indexedResult.GetEnumerator(), filterExpr.ExprEvaluator, agentInstanceContext, dequeX);
                return(dequeX);
            }

            // fall back to window operator if snapshot doesn't resolve successfully
            var sourceCollection = _instance.EventCollection;
            var it = sourceCollection.GetEnumerator();

            if (it.MoveNext() == false)
            {
                return(Collections.GetEmptyList <EventBean>());
            }
            var deque = new ArrayDeque <EventBean>(sourceCollection.Count);

            if (filterExpr != null)
            {
                ExprNodeUtility.ApplyFilterExpressionIterable(sourceCollection.GetEnumerator(), filterExpr.ExprEvaluator, agentInstanceContext, deque);
            }
            else
            {
                do
                {
                    deque.Add(it.Current);
                } while (it.MoveNext());
            }
            return(deque);
        }
예제 #5
0
 public MultiplicationNode(ExprNode l, ExprNode r)
 {
     Left = l;
     Right = r;
 }
예제 #6
0
 public override bool EqualsNode(ExprNode node, bool ignoreStreamPrefix)
 {
     return(node is ExprCoalesceNode);
 }
예제 #7
0
 public override bool EqualsNode(
     ExprNode node,
     bool ignoreStreamPrefix)
 {
     return node is ExprPropertyExistsNode;
 }
예제 #8
0
 internal static ExprNode Expr( Kind k, Symbol s )
 {
     ExprNode res = new ExprNode();
     res.kind = k;
     res.start = s.pos;
     res.end = s.endpos;
     return res;
 }
예제 #9
0
 internal static ExprAndListNode ExprAndList( Kind k, ExprNode expr, ListNode list, Symbol s )
 {
     ExprAndListNode res = new ExprAndListNode();
     res.kind = k;
     res.start = s.pos;
     res.end = s.endpos;
     res.expr = expr;
     res.list = list;
     return res;
 }
예제 #10
0
 internal static ConstantNode Constant( IdentNode name, ExprNode constant, Symbol s )
 {
     ConstantNode res = new ConstantNode();
     res.kind = Kind.Constant;
     res.start = s.pos;
     res.end = s.endpos;
     res.name = name;
     res.constant = constant;
     return res;
 }
예제 #11
0
 internal static EnumValueNode EnumValue( ListNode attributes, IdentNode name, ExprNode expr, Symbol s )
 {
     EnumValueNode res = new EnumValueNode();
     res.kind = Kind.EnumValue;
     res.start = s.pos;
     res.end = s.endpos;
     res.attributes = attributes;
     res.name = name;
     res.expr = expr;
     return res;
 }
예제 #12
0
 internal static BinaryNode Binary( Kind k, ExprNode left, ExprNode right, Symbol s )
 {
     BinaryNode res = new BinaryNode();
     res.kind = k;
     res.start = s.pos;
     res.end = s.endpos;
     res.left = left;
     res.right = right;
     return res;
 }
예제 #13
0
 internal static AssignNode Assign( Kind k, ExprNode dest, ExprNode source, Symbol s )
 {
     AssignNode res = new AssignNode();
     res.kind = k;
     res.start = s.pos;
     res.end = s.endpos;
     res.dest = dest;
     res.source = source;
     return res;
 }
예제 #14
0
        internal static TypeNode type_from_expr( ExprNode expr )
        {
            Symbol s = new Symbol();
            s.pos = expr.start;
            s.endpos = expr.end;

            switch( expr.kind ) {
                case Kind.Identifier:
                    return Make.TypeName( (IdentNode)expr, s );
                case Kind.Dot: case Kind.TypeDot:
                    string id = String.Empty;
                    while( expr.kind == Kind.Dot ) {
                        IdentNode idn = ((BinaryNode)expr).right as IdentNode;
                        id = "." + idn.identifier + id;
                        expr = ((BinaryNode)expr).left;
                    }
                    if( expr.kind == Kind.TypeDot ) {
                        // types like: int.A
                        ExprAndTypeNode etn = (ExprAndTypeNode)expr;
                        id = (etn.type as BaseType).typeid.ToString().Substring(1) + "." + (etn.expr as IdentNode).identifier + id;
                        return Make.TypeName( Make.Ident( id, s ), s );
                    } else if( expr.kind == Kind.Identifier ) {
                        // types like: a.b.c
                        ((IdentNode)expr).identifier += id;
                        return Make.TypeName( (IdentNode)expr, s );
                    }
                    return null;
                case Kind.DimmedExpr:
                    TypeExprNode ten = (TypeExprNode)expr;
                    return Make.OneArrayType( type_from_expr( ten.expr ), ten.spec, s );
            }
            return null;
        }
예제 #15
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="viewFactory"></param>
 /// <param name="agentInstanceContext">contains required view services</param>
 /// <param name="xFieldName">is the field name of the field providing X data points</param>
 /// <param name="yFieldName">is the field name of the field providing X data points</param>
 /// <param name="eventType">Type of the event.</param>
 /// <param name="additionalProps">The additional props.</param>
 public RegressionLinestView(ViewFactory viewFactory, AgentInstanceContext agentInstanceContext, ExprNode xFieldName, ExprNode yFieldName, EventType eventType, StatViewAdditionalProps additionalProps)
     : base(viewFactory, agentInstanceContext, xFieldName, yFieldName, eventType, additionalProps)
 {
 }
예제 #16
0
 internal static ExprAndTypeNode ExprAndType( Kind k, ExprNode expr, TypeNode type, Symbol s )
 {
     ExprAndTypeNode res = new ExprAndTypeNode();
     res.kind = k;
     res.start = s.pos;
     res.end = s.endpos;
     res.expr = expr;
     res.type = type;
     return res;
 }
예제 #17
0
        /// <summary>
        /// Method that recursively generates TAC for a given complex expression
        /// </summary>
        /// <param name="expression">Expression to be decomposed</param>
        /// <returns>Last tmp identifier left from TAC decomposition</returns>
        private string GenerateThreeAddressLine(ExprNode expression)
        {
            // This is used to merge the label from previous if/while/for node parsing
            // From an empty node to current parsed
            string label = null;

            if (TACodeContainer.Last != null && TACodeContainer.Last.Value.IsUtility)
            {
                label = TACodeContainer.Last.Value.Label;
                TACodeContainer.RemoveNode(TACodeContainer.Last.Value);
            }
            // Main switcher
            switch (expression)
            {
            // Trivial cases. Each switch branch generate simple corresponding node
            case IdNode idNode:
            {
                return(TACodeContainer.CreateAndPushIdNode(idNode, label));
            }

            case IntNumNode intNumNode:
            {
                return(TACodeContainer.CreateAndPushIntNumNode(intNumNode, label));
            }

            case BoolNode boolNode:
            {
                return(TACodeContainer.CreateAndPushBoolNode(boolNode, label));
            }

            case UnOpNode unOpNode:
            {
                var unaryExp = ManageTrivialCases(unOpNode.Unary);

                var tmpName = TmpNameManager.Instance.GenerateTmpVariableName();
                TACodeContainer.PushNode(new TacAssignmentNode()
                    {
                        Label = label,
                        LeftPartIdentifier = tmpName,
                        FirstOperand       = null,
                        Operation          = unOpNode.Op,
                        SecondOperand      = unaryExp
                    });
                return(tmpName);
            }

            // Complex case, when a part of an expr is a binary operation
            case BinOpNode binOpNode:
            {
                var leftPart  = ManageTrivialCases(binOpNode.Left);
                var rightPart = ManageTrivialCases(binOpNode.Right);

                // Creating and pushing the resulting binOp between
                // already generated above TAC variables
                var tmpName = TmpNameManager.Instance.GenerateTmpVariableName();
                TACodeContainer.PushNode(new TacAssignmentNode()
                    {
                        Label = label,
                        LeftPartIdentifier = tmpName,
                        FirstOperand       = leftPart,
                        Operation          = binOpNode.Op,
                        SecondOperand      = rightPart
                    });
                return(tmpName);
            }

            case LogicOpNode logicOpNode:
            {
                var leftPart  = ManageTrivialCases(logicOpNode.Left);
                var rightPart = ManageTrivialCases(logicOpNode.Right);

                // Creating and pushing the resulting LogicOp between
                // already generated above TAC variables
                var tmpName = TmpNameManager.Instance.GenerateTmpVariableName();
                TACodeContainer.PushNode(new TacAssignmentNode()
                    {
                        Label = label,
                        LeftPartIdentifier = tmpName,
                        FirstOperand       = leftPart,
                        Operation          = logicOpNode.Operation,
                        SecondOperand      = rightPart
                    });
                return(tmpName);
            }

            case LogicNotNode logicNotNode:
            {
                var unaryExp = ManageTrivialCases(logicNotNode.LogExpr);

                var tmpName = TmpNameManager.Instance.GenerateTmpVariableName();
                TACodeContainer.PushNode(new TacAssignmentNode()
                    {
                        Label = label,
                        LeftPartIdentifier = tmpName,
                        FirstOperand       = null,
                        Operation          = "!",
                        SecondOperand      = unaryExp
                    });
                return(tmpName);
            }
            }
            // Defaulting return. If no known code constructions are encountered
            return(default(string));
        }
예제 #18
0
 internal static InitializerNode Initializer( Kind k, ExprNode expr, ListNode subinits, Symbol s )
 {
     InitializerNode res = new InitializerNode();
     res.kind = k;
     res.start = s.pos;
     res.end = s.endpos;
     res.expr = expr;
     res.subinits = subinits;
     return res;
 }
        private AggregationLinearFactoryDesc HandleNonIntoTable(
            ExprNode[] childNodes,
            AggregationAccessorLinearType?stateType,
            ExprValidationContext validationContext)
        {
            var       streamTypeService = validationContext.StreamTypeService;
            int       streamNum;
            Type      resultType;
            ExprForge forge;
            ExprNode  evaluatorIndex = null;
            bool      istreamOnly;
            EventType containedType;
            Type      scalarCollectionComponentType = null;

            // validate wildcard use
            var isWildcard = childNodes.Length == 0 || childNodes.Length > 0 && childNodes[0] is ExprWildcard;

            if (isWildcard)
            {
                ExprAggMultiFunctionUtil.ValidateWildcardStreamNumbers(validationContext.StreamTypeService, stateType?.GetNameInvariant());
                streamNum     = 0;
                containedType = streamTypeService.EventTypes[0];
                resultType    = containedType.UnderlyingType;
                var tableMetadataX = validationContext.TableCompileTimeResolver.ResolveTableFromEventType(containedType);
                forge       = ExprNodeUtilityMake.MakeUnderlyingForge(0, resultType, tableMetadataX);
                istreamOnly = GetIstreamOnly(streamTypeService, 0);
                if ((stateType == AggregationAccessorLinearType.WINDOW) && istreamOnly && !streamTypeService.IsOnDemandStreams)
                {
                    throw MakeUnboundValidationEx(stateType);
                }
            }
            else if (childNodes.Length > 0 && childNodes[0] is ExprStreamUnderlyingNode)
            {
                // validate "stream.*"
                streamNum   = ExprAggMultiFunctionUtil.ValidateStreamWildcardGetStreamNum(childNodes[0]);
                istreamOnly = GetIstreamOnly(streamTypeService, streamNum);
                if ((stateType == AggregationAccessorLinearType.WINDOW) && istreamOnly && !streamTypeService.IsOnDemandStreams)
                {
                    throw MakeUnboundValidationEx(stateType);
                }

                var type = streamTypeService.EventTypes[streamNum];
                containedType = type;
                resultType    = type.UnderlyingType;
                var tableMetadataX = validationContext.TableCompileTimeResolver.ResolveTableFromEventType(type);
                forge = ExprNodeUtilityMake.MakeUnderlyingForge(streamNum, resultType, tableMetadataX);
            }
            else
            {
                // validate when neither wildcard nor "stream.*"
                var child   = childNodes[0];
                var streams = ExprNodeUtilityQuery.GetIdentStreamNumbers(child);
                if (streams.IsEmpty() || (streams.Count > 1))
                {
                    throw new ExprValidationException(
                              GetErrorPrefix(stateType) +
                              " requires that any child expressions evaluate properties of the same stream; Use 'firstever' or 'lastever' or 'nth' instead");
                }

                streamNum   = streams.First();
                istreamOnly = GetIstreamOnly(streamTypeService, streamNum);
                if ((stateType == AggregationAccessorLinearType.WINDOW) && istreamOnly && !streamTypeService.IsOnDemandStreams)
                {
                    throw MakeUnboundValidationEx(stateType);
                }

                resultType = childNodes[0].Forge.EvaluationType;
                forge      = childNodes[0].Forge;
                if (streamNum >= streamTypeService.EventTypes.Length)
                {
                    containedType = streamTypeService.EventTypes[0];
                }
                else
                {
                    containedType = streamTypeService.EventTypes[streamNum];
                }

                scalarCollectionComponentType = resultType;
            }

            if (childNodes.Length > 1)
            {
                if (stateType == AggregationAccessorLinearType.WINDOW)
                {
                    throw new ExprValidationException(GetErrorPrefix(stateType) + " does not accept an index expression; Use 'first' or 'last' instead");
                }

                evaluatorIndex = childNodes[1];
                var indexResultType = evaluatorIndex.Forge.EvaluationType;
                if (indexResultType != typeof(int?) && indexResultType != typeof(int))
                {
                    throw new ExprValidationException(GetErrorPrefix(stateType) + " requires an index expression that returns an integer value");
                }
            }

            // determine accessor
            AggregationAccessorForge accessor;

            if (evaluatorIndex != null)
            {
                var       isFirst  = stateType == AggregationAccessorLinearType.FIRST;
                var       constant = -1;
                ExprForge forgeIndex;
                if (evaluatorIndex.Forge.ForgeConstantType.IsCompileTimeConstant)
                {
                    constant   = evaluatorIndex.Forge.ExprEvaluator.Evaluate(null, true, null).AsInt32();
                    forgeIndex = null;
                }
                else
                {
                    forgeIndex = evaluatorIndex.Forge;
                }

                accessor = new AggregationAccessorFirstLastIndexWEvalForge(streamNum, forge, forgeIndex, constant, isFirst);
            }
            else
            {
                if (stateType == AggregationAccessorLinearType.FIRST)
                {
                    accessor = new AggregationAccessorFirstWEvalForge(streamNum, forge);
                }
                else if (stateType == AggregationAccessorLinearType.LAST)
                {
                    accessor = new AggregationAccessorLastWEvalForge(streamNum, forge);
                }
                else if (stateType == AggregationAccessorLinearType.WINDOW)
                {
                    accessor = new AggregationAccessorWindowWEvalForge(streamNum, forge, resultType);
                }
                else
                {
                    throw new IllegalStateException("Access type is undefined or not known as code '" + stateType + "'");
                }
            }

            var accessorResultType = resultType;

            if (stateType == AggregationAccessorLinearType.WINDOW)
            {
                accessorResultType = TypeHelper.GetArrayType(resultType);
            }

            var isFafWindow   = streamTypeService.IsOnDemandStreams && stateType == AggregationAccessorLinearType.WINDOW;
            var tableMetadata = validationContext.TableCompileTimeResolver.ResolveTableFromEventType(containedType);

            if (tableMetadata == null && !isFafWindow && (istreamOnly || streamTypeService.IsOnDemandStreams))
            {
                if (optionalFilter != null)
                {
                    positionalParams = ExprNodeUtilityMake.AddExpression(positionalParams, optionalFilter);
                }

                var serde = validationContext.SerdeResolver.SerdeForAggregation(accessorResultType, validationContext.StatementRawInfo);
                AggregationForgeFactory factoryX = new AggregationForgeFactoryFirstLastUnbound(this, accessorResultType, optionalFilter != null, serde);
                return(new AggregationLinearFactoryDesc(factoryX, containedType, scalarCollectionComponentType, streamNum));
            }

            var stateKey = new AggregationStateKeyWStream(
                streamNum,
                containedType,
                AggregationStateTypeWStream.DATAWINDOWACCESS_LINEAR,
                ExprNodeUtilityQuery.EMPTY_EXPR_ARRAY,
                optionalFilter);

            var optionalFilterForge = optionalFilter == null ? null : optionalFilter.Forge;
            AggregationStateFactoryForge stateFactory = new AggregationStateLinearForge(this, streamNum, optionalFilterForge);

            var factory = new AggregationForgeFactoryAccessLinear(
                this,
                accessor,
                accessorResultType,
                stateKey,
                stateFactory,
                AggregationAgentDefault.INSTANCE,
                containedType);
            var enumerationType = scalarCollectionComponentType == null ? containedType : null;

            var serdeForgables = SerdeEventTypeUtility.Plan(
                containedType,
                validationContext.StatementRawInfo,
                validationContext.SerdeEventTypeRegistry,
                validationContext.SerdeResolver);

            validationContext.AdditionalForgeables.AddAll(serdeForgables);

            return(new AggregationLinearFactoryDesc(factory, enumerationType, scalarCollectionComponentType, streamNum));
        }
예제 #20
0
 internal static StatementNode Statement( Kind k, ExprNode expr, IdentNode label, StatementNode stmt1, StatementNode stmt2, ListNode stmts, Symbol s )
 {
     StatementNode res = new StatementNode();
     res.kind = k;
     res.start = s.pos;
     res.end = s.endpos;
     res.expr = expr;
     res.label = label;
     res.stmt1 = stmt1;
     res.stmt2 = stmt2;
     res.stmts = stmts;
     return res;
 }
예제 #21
0
 public override bool EqualsNode(ExprNode node)
 {
     return(node is ExprCurrentEvaluationContextNode);
 }
예제 #22
0
 internal static TriplexNode Triplex( ExprNode cond, ExprNode Then, ExprNode Else, Symbol s )
 {
     TriplexNode res = new TriplexNode();
     res.kind = Kind.Triplex;
     res.start = s.pos;
     res.end = s.endpos;
     res.cond = cond;
     res.Then = Then;
     res.Else = Else;
     return res;
 }
예제 #23
0
 public PowerNode(ExprNode l, ExprNode r)
 {
     Left = l;
     Right = r;
 }
예제 #24
0
 internal static TypedStatementNode TypedStatement( Kind k, ExprNode expr, IdentNode label, StatementNode stmt1, StatementNode stmt2, ListNode stmts, TypeNode type, Symbol s )
 {
     TypedStatementNode res = new TypedStatementNode();
     res.kind = k;
     res.start = s.pos;
     res.end = s.endpos;
     res.expr = expr;
     res.label = label;
     res.stmt1 = stmt1;
     res.stmt2 = stmt2;
     res.stmts = stmts;
     res.type = type;
     return res;
 }
예제 #25
0
 public AdditionNode(ExprNode l, ExprNode r)
 {
     Left = l;
     Right = r;
 }
예제 #26
0
 internal static TypeExprNode TypeExpr( ExprNode expr, DimSpecNode spec, Symbol s )
 {
     TypeExprNode res = new TypeExprNode();
     res.kind = Kind.DimmedExpr;
     res.start = s.pos;
     res.end = s.endpos;
     res.expr = expr;
     res.spec = spec;
     return res;
 }
예제 #27
0
파일: AST.cs 프로젝트: GHScan/DailyProjects
 public ExprNode_UnaryOp(int line, string op, ExprNode expr)
     : base(line)
 {
     Op = op; Expr = expr;
 }
예제 #28
0
 public void AddInSetMultiIndex(int testStreamNum, ExprNode testPropExpr, int setStreamNum, ExprNode[] setPropExpr)
 {
     Check(testStreamNum, setStreamNum);
     InternalAddInKeywordMultiIndex(testStreamNum, setStreamNum, testPropExpr, setPropExpr);
 }
예제 #29
0
파일: AST.cs 프로젝트: GHScan/DailyProjects
 public StmtNode_Return(int line, ExprNode expr)
     : base(line)
 {
     Expr = expr;
 }
예제 #30
0
        private void InternalAddRange(int streamKey, int streamValue, QueryGraphRangeEnum rangeOp, ExprNode propertyStartExpr, ExprNode propertyEndExpr, ExprIdentNode propertyValueExpr)
        {
            if (_nToZeroAnalysis && streamValue != 0)
            {
                return;
            }
            if (_optionalHint != null && _optionalHint.Filter(streamKey, streamValue, ExcludePlanFilterOperatorType.RELOP))
            {
                return;
            }
            var valueLeft = GetCreateValue(streamKey, streamValue);

            valueLeft.AddRange(rangeOp, propertyStartExpr, propertyEndExpr, propertyValueExpr);
        }
예제 #31
0
        private static BindingMatchResult MatchBindingsAssignColumnNumbers(
            IntoTableSpec bindings,
            TableMetadata metadata,
            IList <AggregationServiceAggExpressionDesc> aggregations,
            IDictionary <ExprNode, string> selectClauseNamedNodes,
            IList <ExprEvaluator> methodAggEvaluatorsList,
            IList <ExprDeclaredNode> declaredExpressions)
        {
            IDictionary <AggregationServiceAggExpressionDesc, TableMetadataColumnAggregation> methodAggs = new LinkedHashMap <AggregationServiceAggExpressionDesc, TableMetadataColumnAggregation>();
            IDictionary <AggregationServiceAggExpressionDesc, TableMetadataColumnAggregation> accessAggs = new LinkedHashMap <AggregationServiceAggExpressionDesc, TableMetadataColumnAggregation>();

            foreach (var aggDesc in aggregations)
            {
                // determine assigned name
                var columnName = FindColumnNameForAggregation(selectClauseNamedNodes, declaredExpressions, aggDesc.AggregationNode);
                if (columnName == null)
                {
                    throw new ExprValidationException("Failed to find an expression among the select-clause expressions for expression '" + aggDesc.AggregationNode.ToExpressionStringMinPrecedenceSafe() + "'");
                }

                // determine binding metadata
                var columnMetadata = (TableMetadataColumnAggregation)metadata.TableColumns.Get(columnName);
                if (columnMetadata == null)
                {
                    throw new ExprValidationException("Failed to find name '" + columnName + "' among the columns for table '" + bindings.Name + "'");
                }

                // validate compatible
                ValidateIntoTableCompatible(bindings.Name, columnName, columnMetadata, aggDesc);

                if (!columnMetadata.Factory.IsAccessAggregation)
                {
                    methodAggs.Put(aggDesc, columnMetadata);
                }
                else
                {
                    accessAggs.Put(aggDesc, columnMetadata);
                }
            }

            // handle method-aggs
            var methodPairs = new TableColumnMethodPair[methodAggEvaluatorsList.Count];
            var methodIndex = -1;

            foreach (var methodEntry in methodAggs)
            {
                methodIndex++;
                var targetIndex = methodEntry.Value.MethodOffset;
                methodPairs[methodIndex]  = new TableColumnMethodPair(methodAggEvaluatorsList[methodIndex], targetIndex, methodEntry.Key.AggregationNode);
                methodEntry.Key.ColumnNum = targetIndex;
            }

            // handle access-aggs
            var accessSlots     = new LinkedHashMap <int, ExprNode>();
            var accessReadPairs = new List <AggregationAccessorSlotPair>();
            var accessIndex     = -1;
            var agents          = new List <AggregationAgent>();

            foreach (var accessEntry in accessAggs)
            {
                accessIndex++;
                var slot = accessEntry.Value.AccessAccessorSlotPair.Slot;
                var aggregationMethodFactory = accessEntry.Key.Factory;
                var accessor = aggregationMethodFactory.Accessor;
                accessSlots.Put(slot, accessEntry.Key.AggregationNode);
                accessReadPairs.Add(new AggregationAccessorSlotPair(slot, accessor));
                accessEntry.Key.ColumnNum = metadata.NumberMethodAggregations + accessIndex;
                agents.Add(aggregationMethodFactory.AggregationStateAgent);
            }
            AggregationAgent[]            agentArr    = agents.ToArray();
            AggregationAccessorSlotPair[] accessReads = accessReadPairs.ToArray();

            var targetStates    = new int[accessSlots.Count];
            var accessStateExpr = new ExprNode[accessSlots.Count];
            var count           = 0;

            foreach (var entry in accessSlots)
            {
                targetStates[count]    = entry.Key;
                accessStateExpr[count] = entry.Value;
                count++;
            }

            return(new BindingMatchResult(methodPairs, accessReads, targetStates, accessStateExpr, agentArr));
        }
예제 #32
0
        private void InternalAddEqualsNoProp(int keyExprStream, int indexedStream, ExprIdentNode indexedProp, ExprNode exprNodeNoIdent)
        {
            if (_nToZeroAnalysis && indexedStream != 0)
            {
                return;
            }
            if (_optionalHint != null && _optionalHint.Filter(keyExprStream, indexedStream, ExcludePlanFilterOperatorType.EQUALS))
            {
                return;
            }
            var value = GetCreateValue(keyExprStream, indexedStream);

            value.AddKeyedExpr(indexedProp, exprNodeNoIdent);
        }
 public ExprDotNodeFilterAnalyzerDTBetweenDesc(EventType[] typesPerStream, int targetStreamNum, String targetPropertyName, ExprNode start, ExprNode end, bool includeLow, bool includeHigh)
 {
     this.typesPerStream     = typesPerStream;
     this.targetStreamNum    = targetStreamNum;
     this.targetPropertyName = targetPropertyName;
     this.start       = start;
     this.end         = end;
     this.includeLow  = includeLow;
     this.includeHigh = includeHigh;
 }
예제 #34
0
        private void InternalAddEqualsUnkeyed(int streamKey, int streamValue, ExprIdentNode indexedProp, ExprNode exprNodeNoIdent)
        {
            if (_nToZeroAnalysis && streamValue != 0)
            {
                return;
            }
            if (_optionalHint != null && _optionalHint.Filter(streamKey, streamValue, ExcludePlanFilterOperatorType.EQUALS))
            {
                return;
            }
            var value = GetCreateValue(streamKey, streamValue);

            value.AddUnkeyedExpr(indexedProp, exprNodeNoIdent);
        }
예제 #35
0
        public static Type GetCoercionTypeRangeIn(Type valuePropType, ExprNode exprStart, ExprNode exprEnd)
        {
            Type coercionType  = null;
            Type startPropType = exprStart.ExprEvaluator.ReturnType.GetBoxedType();
            Type endPropType   = exprEnd.ExprEvaluator.ReturnType.GetBoxedType();

            if (valuePropType != startPropType)
            {
                coercionType = valuePropType.GetCompareToCoercionType(startPropType);
            }
            if (valuePropType != endPropType)
            {
                coercionType = coercionType.GetCompareToCoercionType(endPropType);
            }
            return(coercionType);
        }
예제 #36
0
        public ICollection <EventBean> SnapshotNoLockWithFilter(FilterSpecCompiled filter, Attribute[] annotations, ExprNode filterExpr, ExprEvaluatorContext exprEvaluatorContext)
        {
            if (_tailView.RevisionProcessor != null)
            {
                return(_tailView.RevisionProcessor.GetSnapshot(_agentInstanceContext.EpStatementAgentInstanceHandle, Parent));
            }

            var indexedResult = _rootViewInstance.Snapshot(filter, annotations);

            if (indexedResult != null)
            {
                if (indexedResult.IsEmpty())
                {
                    return(indexedResult);
                }
                if (filterExpr == null)
                {
                    return(indexedResult);
                }
                var deque = new ArrayDeque <EventBean>(Math.Min(indexedResult.Count, 16));
                ExprNodeUtility.ApplyFilterExpressionIterable(indexedResult.GetEnumerator(), filterExpr.ExprEvaluator, exprEvaluatorContext, deque);
                return(deque);
            }

            // fall back to window operator if snapshot doesn't resolve successfully
            var en = Parent.GetEnumerator();

            if (!en.MoveNext())
            {
                return(Collections.GetEmptyList <EventBean>());
            }
            var list = new ArrayDeque <EventBean>();

            if (filterExpr != null)
            {
                en = Parent.GetEnumerator();
                ExprNodeUtility.ApplyFilterExpressionIterable(en, filterExpr.ExprEvaluator, _agentInstanceContext, list);
            }
            else
            {
                do
                {
                    list.Add(en.Current);
                } while (en.MoveNext());
            }
            return(list);
        }
예제 #37
0
 public override bool EqualsNode(
     ExprNode node,
     bool ignoreStreamPrefix)
 {
     throw new UnsupportedOperationException("Compare is not available");
 }
예제 #38
0
 public ExprNodeProxy(String engineURI, String statementName, ExprNode exprNode)
 {
     _engineURI     = engineURI;
     _statementName = statementName;
     _exprNode      = exprNode;
 }
예제 #39
0
        public ExprNodeAdapterBase Make(
            FilterSpecParamExprNode node,
            EventBean[] events,
            ExprEvaluatorContext exprEvaluatorContext,
            StatementContext statementContext,
            int agentInstanceId)
        {
            int filterSpecId = node.FilterSpecId;
            int filterSpecParamPathNum = node.FilterSpecParamPathNum;
            ExprNode exprNode = node.ExprNode;
            VariableService variableService = node.VariableService;

            // handle table evaluator context
            if (node.HasTableAccess)
            {
                exprEvaluatorContext = new ExprEvaluatorContextWTableAccess(exprEvaluatorContext, node.TableService);
            }

            // non-pattern case
            ExprNodeAdapterBase adapter;
            if (events == null)
            {
                // if a subquery is present in a filter stream acquire the agent instance lock
                if (node.HasFilterStreamSubquery)
                {
                    adapter = GetLockableSingle(
                        filterSpecId, filterSpecParamPathNum, exprNode, exprEvaluatorContext, variableService,
                        statementContext, agentInstanceId);
                }
                    // no-variable no-prior event evaluation
                else if (!node.HasVariable)
                {
                    adapter = new ExprNodeAdapterBase(
                        filterSpecId, filterSpecParamPathNum, exprNode, exprEvaluatorContext);
                }
                else
                {
                    // with-variable no-prior event evaluation
                    adapter = new ExprNodeAdapterBaseVariables(
                        filterSpecId, filterSpecParamPathNum, exprNode, exprEvaluatorContext, variableService);
                }
            }
            else
            {
                // pattern cases
                VariableService variableServiceToUse = node.HasVariable ? variableService : null;
                if (node.UseLargeThreadingProfile)
                {
                    // no-threadlocal evaluation
                    // if a subquery is present in a pattern filter acquire the agent instance lock
                    if (node.HasFilterStreamSubquery)
                    {
                        adapter = GetLockableMultiStreamNoTL(
                            filterSpecId, filterSpecParamPathNum, exprNode, exprEvaluatorContext, variableServiceToUse,
                            events);
                    }
                    else
                    {
                        adapter = new ExprNodeAdapterMultiStreamNoTL(
                            filterSpecId, filterSpecParamPathNum, exprNode, exprEvaluatorContext, variableServiceToUse,
                            events);
                    }
                }
                else
                {
                    if (node.HasFilterStreamSubquery)
                    {
                        adapter = GetLockableMultiStream(
                            filterSpecId, filterSpecParamPathNum, exprNode, exprEvaluatorContext, variableServiceToUse,
                            events);
                    }
                    else
                    {
                        // evaluation with threadlocal cache
                        adapter = new ExprNodeAdapterMultiStream(
                            filterSpecId, filterSpecParamPathNum, exprNode, exprEvaluatorContext, variableServiceToUse,
                            events);
                    }
                }
            }

            if (!node.HasTableAccess)
            {
                return adapter;
            }

            // handle table
            return new ExprNodeAdapterBaseWTableAccess(
                filterSpecId, filterSpecParamPathNum, exprNode, exprEvaluatorContext, adapter, node.TableService);
        }
예제 #40
0
파일: UpdateDesc.cs 프로젝트: ikvm/nesper
 /// <summary>Ctor. </summary>
 /// <param name="optionalStreamName">a stream name if provided for the Update</param>
 /// <param name="assignments">the individual assignments made</param>
 /// <param name="optionalWhereClause">the where-clause expression if provided</param>
 public UpdateDesc(String optionalStreamName, IList <OnTriggerSetAssignment> assignments, ExprNode optionalWhereClause)
 {
     OptionalStreamName  = optionalStreamName;
     Assignments         = assignments;
     OptionalWhereClause = optionalWhereClause;
 }
예제 #41
0
 /// <summary>Constructor requires the name of the field to use in the parent view to Compute a trend. </summary>
 /// <param name="expression">is the name of the field within the parent view to use to get numeric data points for this view</param>
 /// <param name="agentInstanceContext">contains required view services</param>
 public MyTrendSpotterView(AgentInstanceViewFactoryChainContext agentInstanceContext, ExprNode expression)
 {
     _agentInstanceContext = agentInstanceContext;
     _expression           = expression;
     _eventType            = CreateEventType(agentInstanceContext.StatementContext);
 }
예제 #42
0
 public override bool EqualsNode(
     ExprNode node,
     bool ignoreStreamPrefix)
 {
     return false;
 }
예제 #43
0
파일: ExprNotNode.cs 프로젝트: ikvm/nesper
 public override bool EqualsNode(ExprNode node)
 {
     return(node is ExprNotNode);
 }
예제 #44
0
 public TableColumnMethodPair(ExprEvaluator evaluator, int targetIndex, ExprNode aggregationNode)
 {
     Evaluator       = evaluator;
     TargetIndex     = targetIndex;
     AggregationNode = aggregationNode;
 }
예제 #45
0
 public ModuloNode(ExprNode l, ExprNode r)
 {
     Left = l;
     Right = r;
 }
예제 #46
0
        public static SubordinateQueryPlanDesc PlanSubquery(
            EventType[] outerStreams,
            SubordPropPlan joinDesc,
            bool isNWOnTrigger,
            bool forceTableScan,
            IndexHint optionalIndexHint,
            bool indexShare,
            int subqueryNumber,
            bool isVirtualDataWindow,
            EventTableIndexMetadata indexMetadata,
            ICollection <string> optionalUniqueKeyProps,
            bool onlyUseExistingIndexes,
            string statementName,
            int statementId,
            Attribute[] annotations)
        {
            if (isVirtualDataWindow)
            {
                var indexProps = GetIndexPropDesc(joinDesc.HashProps, joinDesc.RangeProps);
                var lookupStrategyFactoryVdw = new SubordTableLookupStrategyFactoryVDW(statementName, statementId, annotations,
                                                                                       outerStreams,
                                                                                       indexProps.HashJoinedProps,
                                                                                       new CoercionDesc(false, indexProps.HashIndexCoercionType),
                                                                                       indexProps.RangeJoinedProps,
                                                                                       new CoercionDesc(false, indexProps.RangeIndexCoercionType),
                                                                                       isNWOnTrigger,
                                                                                       joinDesc, forceTableScan, indexProps.ListPair);
                return(new SubordinateQueryPlanDesc(lookupStrategyFactoryVdw, null));
            }

            var          hashKeys              = Collections.GetEmptyList <SubordPropHashKey>();
            CoercionDesc hashKeyCoercionTypes  = null;
            var          rangeKeys             = Collections.GetEmptyList <SubordPropRangeKey>();
            CoercionDesc rangeKeyCoercionTypes = null;

            ExprNode[] inKeywordSingleIdxKeys = null;
            ExprNode   inKeywordMultiIdxKey   = null;

            SubordinateQueryIndexDesc[] indexDescs;
            if (joinDesc.InKeywordSingleIndex != null)
            {
                var single    = joinDesc.InKeywordSingleIndex;
                var keyInfo   = new SubordPropHashKey(new QueryGraphValueEntryHashKeyedExpr(single.Expressions[0], false), null, single.CoercionType);
                var indexDesc = FindOrSuggestIndex(
                    Collections.SingletonMap(single.IndexedProp, keyInfo),
                    Collections.GetEmptyMap <string, SubordPropRangeKey>(), optionalIndexHint, indexShare, subqueryNumber,
                    indexMetadata, optionalUniqueKeyProps, onlyUseExistingIndexes);
                if (indexDesc == null)
                {
                    return(null);
                }
                var desc = new SubordinateQueryIndexDesc(indexDesc.IndexKeyInfo, indexDesc.IndexName, indexDesc.IndexMultiKey, indexDesc.QueryPlanIndexItem);
                indexDescs             = new SubordinateQueryIndexDesc[] { desc };
                inKeywordSingleIdxKeys = single.Expressions;
            }
            else if (joinDesc.InKeywordMultiIndex != null)
            {
                var multi = joinDesc.InKeywordMultiIndex;

                indexDescs = new SubordinateQueryIndexDesc[multi.IndexedProp.Length];
                for (var i = 0; i < multi.IndexedProp.Length; i++)
                {
                    var keyInfo   = new SubordPropHashKey(new QueryGraphValueEntryHashKeyedExpr(multi.Expression, false), null, multi.CoercionType);
                    var indexDesc = FindOrSuggestIndex(
                        Collections.SingletonMap(multi.IndexedProp[i], keyInfo),
                        Collections.GetEmptyMap <string, SubordPropRangeKey>(), optionalIndexHint, indexShare, subqueryNumber,
                        indexMetadata, optionalUniqueKeyProps, onlyUseExistingIndexes);
                    if (indexDesc == null)
                    {
                        return(null);
                    }
                    indexDescs[i] = indexDesc;
                }
                inKeywordMultiIdxKey = multi.Expression;
            }
            else
            {
                var indexDesc = FindOrSuggestIndex(joinDesc.HashProps,
                                                   joinDesc.RangeProps, optionalIndexHint, false, subqueryNumber,
                                                   indexMetadata, optionalUniqueKeyProps, onlyUseExistingIndexes);
                if (indexDesc == null)
                {
                    return(null);
                }
                var indexKeyInfo = indexDesc.IndexKeyInfo;
                hashKeys              = indexKeyInfo.OrderedHashDesc;
                hashKeyCoercionTypes  = indexKeyInfo.OrderedKeyCoercionTypes;
                rangeKeys             = indexKeyInfo.OrderedRangeDesc;
                rangeKeyCoercionTypes = indexKeyInfo.OrderedRangeCoercionTypes;
                var desc = new SubordinateQueryIndexDesc(indexDesc.IndexKeyInfo, indexDesc.IndexName, indexDesc.IndexMultiKey, indexDesc.QueryPlanIndexItem);
                indexDescs = new SubordinateQueryIndexDesc[] { desc };
            }

            if (forceTableScan)
            {
                return(null);
            }

            var lookupStrategyFactory = SubordinateTableLookupStrategyUtil.GetLookupStrategy(outerStreams,
                                                                                             hashKeys, hashKeyCoercionTypes, rangeKeys, rangeKeyCoercionTypes, inKeywordSingleIdxKeys, inKeywordMultiIdxKey, isNWOnTrigger);

            return(new SubordinateQueryPlanDesc(lookupStrategyFactory, indexDescs));
        }
예제 #47
0
 public SubtractionNode(ExprNode l, ExprNode r)
 {
     Left = l;
     Right = r;
 }
예제 #48
0
 public override bool EqualsNode(ExprNode node)
 {
     return(false);      // 2 subselects are never equivalent
 }
예제 #49
0
 public DivisionNode(ExprNode l, ExprNode r)
 {
     Left = l;
     Right = r;
 }
예제 #50
0
        /// <summary>
        ///     Analye EQUALS (=) node.
        /// </summary>
        /// <param name="equalsNode">node to analyze</param>
        /// <param name="queryGraph">store relationships between stream properties</param>
        /// <param name="isOuterJoin">indicator for outer join</param>
        protected internal static void AnalyzeEqualsNode(
            ExprEqualsNode equalsNode,
            QueryGraphForge queryGraph,
            bool isOuterJoin)
        {
            if (equalsNode.ChildNodes[0] is ExprIdentNode &&
                equalsNode.ChildNodes[1] is ExprIdentNode) {
                var identNodeLeft = (ExprIdentNode) equalsNode.ChildNodes[0];
                var identNodeRight = (ExprIdentNode) equalsNode.ChildNodes[1];

                if (identNodeLeft.StreamId != identNodeRight.StreamId) {
                    queryGraph.AddStrictEquals(
                        identNodeLeft.StreamId,
                        identNodeLeft.ResolvedPropertyName,
                        identNodeLeft,
                        identNodeRight.StreamId,
                        identNodeRight.ResolvedPropertyName,
                        identNodeRight);
                }

                return;
            }

            if (isOuterJoin) {
                // outerjoins don't use constants or one-way expression-derived information to evaluate join
                return;
            }

            // handle constant-compare or transformation case
            var indexedStream = -1;
            ExprIdentNode indexedPropExpr = null;
            ExprNode exprNodeNoIdent = null;

            if (equalsNode.ChildNodes[0] is ExprIdentNode) {
                indexedPropExpr = (ExprIdentNode) equalsNode.ChildNodes[0];
                indexedStream = indexedPropExpr.StreamId;
                exprNodeNoIdent = equalsNode.ChildNodes[1];
            }
            else if (equalsNode.ChildNodes[1] is ExprIdentNode) {
                indexedPropExpr = (ExprIdentNode) equalsNode.ChildNodes[1];
                indexedStream = indexedPropExpr.StreamId;
                exprNodeNoIdent = equalsNode.ChildNodes[0];
            }

            if (indexedStream == -1) {
                return; // require property of right/left side of equals
            }

            var eligibility = EligibilityUtil.VerifyInputStream(exprNodeNoIdent, indexedStream);
            if (!eligibility.Eligibility.IsEligible()) {
                return;
            }

            if (eligibility.Eligibility == Eligibility.REQUIRE_NONE) {
                queryGraph.AddUnkeyedExpression(indexedStream, indexedPropExpr, exprNodeNoIdent);
            }
            else {
                queryGraph.AddKeyedExpression(
                    indexedStream,
                    indexedPropExpr,
                    eligibility.StreamNum.Value,
                    exprNodeNoIdent);
            }
        }
예제 #51
0
파일: AST.cs 프로젝트: GHScan/DailyProjects
 public ExprNode_BinaryOp(int line, string op, ExprNode lexpr, ExprNode rexpr)
     : base(line)
 {
     Op = op; Lexpr = lexpr; Rexpr = rexpr;
 }
예제 #52
0
 public ExprNodeAdapterMultiStream(int filterSpecId, int filterSpecParamPathNum, ExprNode exprNode, ExprEvaluatorContext evaluatorContext, VariableService variableService, EventBean[] prototype)
     : base(filterSpecId, filterSpecParamPathNum, exprNode, evaluatorContext, variableService)
 {
     _prototypeArray = prototype;
     _arrayPerThread = ThreadLocalManager.Create(
         () =>
     {
         var eventsPerStream = new EventBean[_prototypeArray.Length];
         Array.Copy(_prototypeArray, 0, eventsPerStream, 0, _prototypeArray.Length);
         return(eventsPerStream);
     });
 }
예제 #53
0
파일: AST.cs 프로젝트: GHScan/DailyProjects
 public ExprNode_IndexOf(int line, ExprNode arrayExpr, ExprNode indexExpr)
     : base(line)
 {
     ArrayExpr = arrayExpr; IndexExpr = indexExpr;
 }
예제 #54
0
 public RowRegexExprRepeatDesc(ExprNode lower, ExprNode upper, ExprNode single)
 {
     Lower  = lower;
     Upper  = upper;
     Single = single;
 }
예제 #55
0
파일: AST.cs 프로젝트: GHScan/DailyProjects
 public StmtNode_Assign(int line, ExprNode lexpr, ExprNode rexpr)
     : base(line)
 {
     Lexpr = lexpr; Rexpr = rexpr;
 }
예제 #56
0
        public static void ApplyExpressionToStatements(
            EPServiceProviderSPI engine,
            string filter,
            Action <EPServiceProvider, EPStatement> consumer)
        {
            // compile filter
            ExprNode filterExpr  = null;
            var      isUseFilter = false;

            if (!String.IsNullOrWhiteSpace(filter))
            {
                isUseFilter = true;
                var statementExprNode = CompileValidateStatementFilterExpr(engine, filter);
                if (statementExprNode.Second == null)
                {
                    filterExpr = statementExprNode.First;
                }
            }

            IList <string> statementNames = engine.EPAdministrator.StatementNames;

            foreach (var statementName in statementNames)
            {
                var epStmt = engine.EPAdministrator.GetStatement(statementName);
                if (epStmt == null)
                {
                    continue;
                }

                if (isUseFilter)
                {
                    if (filterExpr != null)
                    {
                        if (!EvaluateStatement(filterExpr, epStmt))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        var    match        = false;
                        string searchString = filter.ToLowerInvariant();
                        if ((epStmt.Name != null) && (epStmt.Name.ToLowerInvariant().Contains(searchString)))
                        {
                            match = true;
                        }
                        if (!match)
                        {
                            if ((epStmt.Text != null) && (epStmt.Text.ToLowerInvariant().Contains(searchString)))
                            {
                                match = true;
                            }
                            if ((epStmt.State != null) &&
                                (epStmt.State.ToString().ToLowerInvariant().Contains(searchString)))
                            {
                                match = true;
                            }
                        }
                        if (!match)
                        {
                            continue;
                        }
                    }
                }

                consumer.Invoke(engine, epStmt);
            }
        }
예제 #57
0
파일: AST.cs 프로젝트: GHScan/DailyProjects
 public StmtNode_IfElse(int line, ExprNode expr, StmtNode ifStmt, StmtNode elseStmt)
     : base(line)
 {
     Expr = expr; IfStmt = ifStmt; ElseStmt = elseStmt;
 }
예제 #58
0
        /// <summary>
        /// Returns an instance to handle the aggregation required by the aggregation expression nodes, depending on
        /// whether there are any group-by nodes.
        /// </summary>
        /// <param name="selectAggregateExprNodes">aggregation nodes extracted out of the select expression</param>
        /// <param name="selectClauseNamedNodes">The select clause named nodes.</param>
        /// <param name="declaredExpressions">The declared expressions.</param>
        /// <param name="groupByNodes">The group by nodes.</param>
        /// <param name="havingAggregateExprNodes">aggregation nodes extracted out of the select expression</param>
        /// <param name="orderByAggregateExprNodes">aggregation nodes extracted out of the select expression</param>
        /// <param name="groupKeyExpressions">The group key expressions.</param>
        /// <param name="hasGroupByClause">indicator on whethere there is group-by required, or group-all</param>
        /// <param name="annotations">statement annotations</param>
        /// <param name="variableService">variable</param>
        /// <param name="isJoin">true for joins</param>
        /// <param name="isDisallowNoReclaim">if set to <c>true</c> [is disallow no reclaim].</param>
        /// <param name="whereClause">the where-clause function if any</param>
        /// <param name="havingClause">the having-clause function if any</param>
        /// <param name="factoryService">The factory service.</param>
        /// <param name="typesPerStream">The types per stream.</param>
        /// <param name="groupByRollupDesc">The group by rollup desc.</param>
        /// <param name="optionalContextName">Name of the optional context.</param>
        /// <param name="intoTableSpec">The into table spec.</param>
        /// <param name="tableService">The table service.</param>
        /// <param name="isUnidirectional">if set to <c>true</c> [is unidirectional].</param>
        /// <param name="isFireAndForget">if set to <c>true</c> [is fire and forget].</param>
        /// <param name="isOnSelect">if set to <c>true</c> [is on select].</param>
        /// <returns>
        /// instance for aggregation handling
        /// </returns>
        /// <exception cref="ExprValidationException">
        /// Into-table requires at least one aggregation function
        /// or
        /// The ' + funcname + ' function may not occur in the where-clause or having-clause of a statement with aggregations as 'previous' does not provide remove stream data; Use the 'first','last','window' or 'count' aggregation functions instead
        /// or
        /// Invalid into-table clause: Failed to find table by name ' + intoTableSpec.Name + '
        /// </exception>
        /// <exception cref="EPException">Failed to obtain hook for  + HookType.INTERNAL_AGGLOCALLEVEL</exception>
        /// <throws>com.espertech.esper.epl.expression.core.ExprValidationException if validation fails</throws>
        public static AggregationServiceFactoryDesc GetService(IList <ExprAggregateNode> selectAggregateExprNodes, IDictionary <ExprNode, string> selectClauseNamedNodes, IList <ExprDeclaredNode> declaredExpressions, ExprNode[] groupByNodes, IList <ExprAggregateNode> havingAggregateExprNodes, IList <ExprAggregateNode> orderByAggregateExprNodes, IList <ExprAggregateNodeGroupKey> groupKeyExpressions, bool hasGroupByClause, Attribute[] annotations, VariableService variableService, bool isJoin, bool isDisallowNoReclaim, ExprNode whereClause, ExprNode havingClause, AggregationServiceFactoryService factoryService, EventType[] typesPerStream, AggregationGroupByRollupDesc groupByRollupDesc, string optionalContextName, IntoTableSpec intoTableSpec, TableService tableService, bool isUnidirectional, bool isFireAndForget, bool isOnSelect)
        {
            // No aggregates used, we do not need this service
            if ((selectAggregateExprNodes.IsEmpty()) && (havingAggregateExprNodes.IsEmpty()))
            {
                if (intoTableSpec != null)
                {
                    throw new ExprValidationException("Into-table requires at least one aggregation function");
                }

                return(new AggregationServiceFactoryDesc(
                           factoryService.GetNullAggregationService(),
                           Collections.GetEmptyList <AggregationServiceAggExpressionDesc>(),
                           Collections.GetEmptyList <ExprAggregateNodeGroupKey>()));
            }

            // Validate the absence of "prev" function in where-clause:
            // Since the "previous" function does not post remove stream results, disallow when used with aggregations.
            if ((whereClause != null) || (havingClause != null))
            {
                var visitor = new ExprNodePreviousVisitorWParent();
                if (whereClause != null)
                {
                    whereClause.Accept(visitor);
                }
                if (havingClause != null)
                {
                    havingClause.Accept(visitor);
                }
                if ((visitor.Previous != null) && (!visitor.Previous.IsEmpty()))
                {
                    string funcname = visitor.Previous[0].Second.PreviousType.ToString().ToLower();
                    throw new ExprValidationException("The '" + funcname + "' function may not occur in the where-clause or having-clause of a statement with aggregations as 'previous' does not provide remove stream data; Use the 'first','last','window' or 'count' aggregation functions instead");
                }
            }

            // Compile a map of aggregation nodes and equivalent-to aggregation nodes.
            // Equivalent-to functions are for example "select sum(a*b), 5*sum(a*b)".
            // Reducing the total number of aggregation functions.
            IList <AggregationServiceAggExpressionDesc> aggregations = new List <AggregationServiceAggExpressionDesc>();

            foreach (var selectAggNode in selectAggregateExprNodes)
            {
                AddEquivalent(selectAggNode, aggregations);
            }
            foreach (var havingAggNode in havingAggregateExprNodes)
            {
                AddEquivalent(havingAggNode, aggregations);
            }
            foreach (var orderByAggNode in orderByAggregateExprNodes)
            {
                AddEquivalent(orderByAggNode, aggregations);
            }

            // Construct a list of evaluation node for the aggregation functions (regular agg).
            // For example "sum(2 * 3)" would make the sum an evaluation node.
            IList <ExprEvaluator> methodAggEvaluatorsList = new List <ExprEvaluator>();

            foreach (var aggregation in aggregations)
            {
                var aggregateNode = aggregation.AggregationNode;
                if (!aggregateNode.Factory.IsAccessAggregation)
                {
                    var evaluator = aggregateNode.Factory.GetMethodAggregationEvaluator(
                        typesPerStream.Length > 1, typesPerStream);
                    methodAggEvaluatorsList.Add(evaluator);
                }
            }

            // determine local group-by, report when hook provided
            AggregationGroupByLocalGroupDesc localGroupDesc = AnalyzeLocalGroupBy(aggregations, groupByNodes, groupByRollupDesc, intoTableSpec);

            // determine binding
            if (intoTableSpec != null)
            {
                // obtain metadata
                var metadata = tableService.GetTableMetadata(intoTableSpec.Name);
                if (metadata == null)
                {
                    throw new ExprValidationException("Invalid into-table clause: Failed to find table by name '" + intoTableSpec.Name + "'");
                }

                EPLValidationUtil.ValidateContextName(true, intoTableSpec.Name, metadata.ContextName, optionalContextName, false);

                // validate group keys
                var groupByTypes = ExprNodeUtility.GetExprResultTypes(groupByNodes);
                ExprTableNodeUtil.ValidateExpressions(intoTableSpec.Name, groupByTypes, "group-by", groupByNodes,
                                                      metadata.KeyTypes, "group-by");

                // determine how this binds to existing aggregations, assign column numbers
                var bindingMatchResult = MatchBindingsAssignColumnNumbers(intoTableSpec, metadata, aggregations, selectClauseNamedNodes, methodAggEvaluatorsList, declaredExpressions);

                // return factory
                AggregationServiceFactory aggregationServiceFactory;
                if (!hasGroupByClause)
                {
                    aggregationServiceFactory = factoryService.GetNoGroupWBinding(bindingMatchResult.Accessors, isJoin, bindingMatchResult.MethodPairs, intoTableSpec.Name, bindingMatchResult.TargetStates, bindingMatchResult.AccessStateExpr, bindingMatchResult.Agents);
                }
                else
                {
                    aggregationServiceFactory = factoryService.GetGroupWBinding(metadata, bindingMatchResult.MethodPairs, bindingMatchResult.Accessors, isJoin, intoTableSpec, bindingMatchResult.TargetStates, bindingMatchResult.AccessStateExpr, bindingMatchResult.Agents, groupByRollupDesc);
                }
                return(new AggregationServiceFactoryDesc(aggregationServiceFactory, aggregations, groupKeyExpressions));
            }

            // Assign a column number to each aggregation node. The regular aggregation goes first followed by access-aggregation.
            var columnNumber = 0;

            foreach (var entry in aggregations)
            {
                if (!entry.Factory.IsAccessAggregation)
                {
                    entry.ColumnNum = columnNumber++;
                }
            }
            foreach (var entry in aggregations)
            {
                if (entry.Factory.IsAccessAggregation)
                {
                    entry.ColumnNum = columnNumber++;
                }
            }

            // determine method aggregation factories and evaluators(non-access)
            ExprEvaluator[] methodAggEvaluators = methodAggEvaluatorsList.ToArray();
            var             methodAggFactories  = new AggregationMethodFactory[methodAggEvaluators.Length];
            var             count = 0;

            foreach (var aggregation in aggregations)
            {
                var aggregateNode = aggregation.AggregationNode;
                if (!aggregateNode.Factory.IsAccessAggregation)
                {
                    methodAggFactories[count] = aggregateNode.Factory;
                    count++;
                }
            }

            // handle access aggregations
            var multiFunctionAggPlan = AggregationMultiFunctionAnalysisHelper.AnalyzeAccessAggregations(aggregations);
            var accessorPairs        = multiFunctionAggPlan.AccessorPairs;
            var accessAggregations   = multiFunctionAggPlan.StateFactories;

            AggregationServiceFactory serviceFactory;

            // analyze local group by
            AggregationLocalGroupByPlan localGroupByPlan = null;

            if (localGroupDesc != null)
            {
                localGroupByPlan = AggregationGroupByLocalGroupByAnalyzer.Analyze(methodAggEvaluators, methodAggFactories, accessAggregations, localGroupDesc, groupByNodes, accessorPairs);
                try {
                    AggregationLocalLevelHook hook = (AggregationLocalLevelHook)TypeHelper.GetAnnotationHook(annotations, HookType.INTERNAL_AGGLOCALLEVEL, typeof(AggregationLocalLevelHook), null);
                    if (hook != null)
                    {
                        hook.Planned(localGroupDesc, localGroupByPlan);
                    }
                }
                catch (ExprValidationException e) {
                    throw new EPException("Failed to obtain hook for " + HookType.INTERNAL_AGGLOCALLEVEL);
                }
            }

            // Handle without a group-by clause: we group all into the same pot
            if (!hasGroupByClause)
            {
                if (localGroupByPlan != null)
                {
                    serviceFactory = factoryService.GetNoGroupLocalGroupBy(isJoin, localGroupByPlan, isUnidirectional, isFireAndForget, isOnSelect);
                }
                else if ((methodAggEvaluators.Length > 0) && (accessorPairs.Length == 0))
                {
                    serviceFactory = factoryService.GetNoGroupNoAccess(methodAggEvaluators, methodAggFactories, isUnidirectional, isFireAndForget, isOnSelect);
                }
                else if ((methodAggEvaluators.Length == 0) && (accessorPairs.Length > 0))
                {
                    serviceFactory = factoryService.GetNoGroupAccessOnly(accessorPairs, accessAggregations, isJoin, isUnidirectional, isFireAndForget, isOnSelect);
                }
                else
                {
                    serviceFactory = factoryService.GetNoGroupAccessMixed(methodAggEvaluators, methodAggFactories, accessorPairs, accessAggregations, isJoin, isUnidirectional, isFireAndForget, isOnSelect);
                }
            }
            else
            {
                var hasNoReclaim          = HintEnum.DISABLE_RECLAIM_GROUP.GetHint(annotations) != null;
                var reclaimGroupAged      = HintEnum.RECLAIM_GROUP_AGED.GetHint(annotations);
                var reclaimGroupFrequency = HintEnum.RECLAIM_GROUP_AGED.GetHint(annotations);
                if (localGroupByPlan != null)
                {
                    serviceFactory = factoryService.GetGroupLocalGroupBy(isJoin, localGroupByPlan, isUnidirectional, isFireAndForget, isOnSelect);
                }
                else
                {
                    if (!isDisallowNoReclaim && hasNoReclaim)
                    {
                        if (groupByRollupDesc != null)
                        {
                            throw GetRollupReclaimEx();
                        }
                        if ((methodAggEvaluators.Length > 0) && (accessorPairs.Length == 0))
                        {
                            serviceFactory = factoryService.GetGroupedNoReclaimNoAccess(groupByNodes, methodAggEvaluators, methodAggFactories, isUnidirectional, isFireAndForget, isOnSelect);
                        }
                        else if ((methodAggEvaluators.Length == 0) && (accessorPairs.Length > 0))
                        {
                            serviceFactory = factoryService.GetGroupNoReclaimAccessOnly(groupByNodes, accessorPairs, accessAggregations, isJoin, isUnidirectional, isFireAndForget, isOnSelect);
                        }
                        else
                        {
                            serviceFactory = factoryService.GetGroupNoReclaimMixed(groupByNodes, methodAggEvaluators, methodAggFactories, accessorPairs, accessAggregations, isJoin, isUnidirectional, isFireAndForget, isOnSelect);
                        }
                    }
                    else if (!isDisallowNoReclaim && reclaimGroupAged != null)
                    {
                        if (groupByRollupDesc != null)
                        {
                            throw GetRollupReclaimEx();
                        }
                        serviceFactory = factoryService.GetGroupReclaimAged(groupByNodes, methodAggEvaluators, methodAggFactories, reclaimGroupAged, reclaimGroupFrequency, variableService, accessorPairs, accessAggregations, isJoin, optionalContextName, isUnidirectional, isFireAndForget, isOnSelect);
                    }
                    else if (groupByRollupDesc != null)
                    {
                        serviceFactory = factoryService.GetGroupReclaimMixableRollup(groupByNodes, groupByRollupDesc, methodAggEvaluators, methodAggFactories, accessorPairs, accessAggregations, isJoin, groupByRollupDesc, isUnidirectional, isFireAndForget, isOnSelect);
                    }
                    else
                    {
                        if ((methodAggEvaluators.Length > 0) && (accessorPairs.Length == 0))
                        {
                            serviceFactory = factoryService.GetGroupReclaimNoAccess(groupByNodes, methodAggEvaluators, methodAggFactories, accessorPairs, accessAggregations, isJoin, isUnidirectional, isFireAndForget, isOnSelect);
                        }
                        else
                        {
                            serviceFactory = factoryService.GetGroupReclaimMixable(groupByNodes, methodAggEvaluators, methodAggFactories, accessorPairs, accessAggregations, isJoin, isUnidirectional, isFireAndForget, isOnSelect);
                        }
                    }
                }
            }

            return(new AggregationServiceFactoryDesc(serviceFactory, aggregations, groupKeyExpressions));
        }
예제 #59
0
 public ExprNodeVisitor_CodeEmitor(StmtNodeVisitor_CodeEmitor stmt, Type targetType, ExprNode node)
 {
     Trace.Assert(targetType != null);
     m_stmt = stmt;
     m_targetType = targetType;
     node.acceptVisitor(this);
     toTargetType();
 }
예제 #60
0
        // 14.6.6 Cast expressions =======
        // To resolve cast-expression ambiguities, the following rule exists: A sequence of one or
        // more tokens (§9.4) enclosed in parentheses is considered the start of a cast-expression only
        // if at least one of the following are true:
        //    • The sequence of tokens is correct grammar for a type, but not for an expression.
        //  • The sequence of tokens is correct grammar for a type, and the token immediately following
        //      the closing parentheses is the token “~”, the token “!”, the token “(”, an identifier (§9.4.1),
        //      a literal (§9.4.4), or any keyword (§9.4.3) except as and is.
        private static bool CastExpr( ExprNode expr, lapg_symbol next )
        {
            // check if expression can be type
            if( !Util.CanBeType( expr ) )
            return false;

            // if expression is only type (contains dim_specifier)
            if( Util.ContainsDimSpec( expr ) )
            return true;

            // Type or Expr
            switch( (Tokens)next.lexem ) {
            case Tokens.TILDE:
            case Tokens.EXCL:
            case Tokens.LROUNDBRACKET:
            case Tokens.identifier:
            case Tokens.Licon:
            case Tokens.Lfcon:
            case Tokens.Lscon:
            case Tokens.Lccon:
            case Tokens.Lfalse:
            case Tokens.Ltrue:
            case Tokens.Lnull:
                return true;
            case Tokens.Lis:
            case Tokens.Las:
                return false;
            }

            // keyword
            if( next.lexem >= (int)Tokens.Labstract && next.lexem <= (int)Tokens.Lwhile )
            return true;

            return false;
        }