Beispiel #1
0
 public static IRuleSymbol CreateEntry(
     ISymbol containingSymbol,
     RuleNode item,
     DiagnosticBag diagnostics)
 {
     return(new RuleSymbol(containingSymbol, item, diagnostics));
 }
Beispiel #2
0
        private static bool ExecuteOnError(Grammar grammar, RuleNode ruleRef, Exception e)
        {
            ScriptRef[] scripts = grammar._scripts;
            bool        result  = false;

            foreach (ScriptRef scriptRef in scripts)
            {
                if (!(ruleRef._rule == scriptRef._rule) || scriptRef._method != RuleMethodScript.onError)
                {
                    continue;
                }
                object[] parameters = new object[1]
                {
                    e
                };
                if (grammar._proxy != null)
                {
                    Exception exceptionThrown;
                    grammar._proxy.OnError(scriptRef._rule, scriptRef._sMethod, parameters, out exceptionThrown);
                    if (exceptionThrown != null)
                    {
                        throw exceptionThrown;
                    }
                }
                else
                {
                    MethodInfo onParse;
                    Grammar    ruleInstance;
                    GetRuleInstance(grammar, scriptRef._rule, scriptRef._sMethod, out onParse, out ruleInstance);
                    onParse.Invoke(ruleInstance, parameters);
                }
                result = true;
            }
            return(result);
        }
Beispiel #3
0
        private static RuleNode ExtractRules(Grammar grammar, SPSERIALIZEDPHRASERULE rule, IntPtr phraseBuffer)
        {
            IntPtr  ptr      = new IntPtr((long)phraseBuffer + (int)rule.pszNameOffset);
            string  text     = Marshal.PtrToStringUni(ptr);
            Grammar grammar2 = grammar?.Find(text);

            if (grammar2 != null)
            {
                grammar = grammar2;
            }
            RuleNode ruleNode = new RuleNode(grammar, text, rule.SREngineConfidence, rule.ulFirstElement, rule.ulCountOfElements);

            if (rule.NextSiblingOffset != 0)
            {
                IntPtr ptr2 = new IntPtr((long)phraseBuffer + rule.NextSiblingOffset);
                SPSERIALIZEDPHRASERULE rule2 = (SPSERIALIZEDPHRASERULE)Marshal.PtrToStructure(ptr2, typeof(SPSERIALIZEDPHRASERULE));
                ruleNode._next = ExtractRules(grammar, rule2, phraseBuffer);
            }
            if (rule.FirstChildOffset != 0)
            {
                IntPtr ptr3 = new IntPtr((long)phraseBuffer + rule.FirstChildOffset);
                SPSERIALIZEDPHRASERULE rule3 = (SPSERIALIZEDPHRASERULE)Marshal.PtrToStructure(ptr3, typeof(SPSERIALIZEDPHRASERULE));
                ruleNode._child = ExtractRules(grammar, rule3, phraseBuffer);
            }
            return(ruleNode);
        }
Beispiel #4
0
        private async Task <bool> VisitNode(RuleNode rule, CancellationToken cancellationToken)
        {
            //If no leaf go recursive through rules collection
            if (rule.rules != null && rule.rules.Any() && rule.condition != null)
            {
                var ruleCondition = rule.condition.ParseEnum <RuleCondition>();
                var ruleResults   = new List <bool>();
                foreach (var ruleRule in rule.rules)
                {
                    ruleResults.Add(await VisitNode(ruleRule, cancellationToken));
                }

                return(ruleResults
                       .Aggregate(_ruleConditionMapping[ruleCondition]));
            }

            //If leaf execute condition calculation logic
            if (rule.id == null)
            {
                throw new Exception("Invalid rule definition. Rule id can't be empty");
            }

            var ruleId       = rule.id.ParseEnum <RuleId>();
            var ruleExecutor = _rulesExecutors.Single(x => x.RuleId == ruleId);

            return(await ruleExecutor.Execute(rule, cancellationToken));
        }
        public override void MarkupNotFulfilled(RuleNode ruleNode)
        {
            base.MarkupNotFulfilled(ruleNode);
            var rule = (QCumulativeTableRule)ruleNode;

            InCaseOfYesCheckAndNoVotesMarkAllVotesAsErrors(rule);
        }
        public void CreateExpression_DateOutsideOfWindowAndIsMonday_ReverseExpression_BuildsExpression(int year, int month, int day, bool validates, int numberOfErrorMsg)
        {
            // Test: (DateTime d) => d.DayOfWeek == DayOfWeek.Monday & (d < floorDate | d > ceilingDate)
            var floorDate   = new DateTime(2010, 2, 1);
            var ceilingDate = new DateTime(2010, 3, 1);
            var testDate    = new DateTime(year, month, day);

            // build rules / rule nodes for "d < floorDate | d > ceilingDate" and put in a group
            var rangeRuleNode = new RuleNode(new LessThan <CalendarEvent, DateTime>(floorDate));

            rangeRuleNode.OrChild(new RuleNode(new GreaterThan <CalendarEvent, DateTime>(ceilingDate)));
            var groupNode = new GroupNode(rangeRuleNode);

            // build rule / rule node for "d.DayOfWeek == DayOfWeek.Monday
            var dateOneMondayRule = new CustomRule <CalendarEvent, DateTime>((c, d) => d.DayOfWeek == DayOfWeek.Monday);

            dateOneMondayRule.Message = "Date does not fall on a Monday.";
            var dateOneMondayRuleNode = new RuleNode(dateOneMondayRule);

            // add the rangeRuleNode as an And child of dateOneMondayRuleNode
            dateOneMondayRuleNode.AndChild(groupNode);

            var tree = new RuleTree <CalendarEvent, DateTime>(dateOneMondayRuleNode);

            Assert.That(tree.LambdaExpression, Is.Not.Null);

            var context      = BuildContextForCalendarEventStartDate(testDate);
            var notification = new ValidationNotification();
            var isValid      = tree.LambdaExpression(context, null, notification);

            Assert.That(isValid, Is.EqualTo(validates));
        }
        public void TestLoadRuleWithLoop()
        {
            IProjectNode p = ProjectSerializer.LoadString("rule root {\r\n\tloop 1 2 {\r\n\t\tliteral a\r\n\t}\r\n}\r\n", null, null);

            Assert.AreEqual(1, p.Children.Count, "Didn't find the rule.");

            IProjectNode rule = p.Children[0];

            Assert.AreEqual(ProjectNodeType.RuleDeclaration, rule.NodeType);

            RuleNode rn = rule as RuleNode;

            Assert.IsNotNull(rn);
            Assert.AreEqual(1, rn.Children.Count, "Didn't find the command block.");
            Assert.AreEqual("root", rn.Name);

            CommandBlockNode cbn = rn.Children[0] as CommandBlockNode;

            Assert.IsNotNull(cbn);

            Assert.AreEqual(1, cbn.Children.Count);

            Whee.WordBuilder.Model.Commands.CommandBase cb = cbn.Children[0] as Whee.WordBuilder.Model.Commands.CommandBase;

            Assert.IsInstanceOfType(typeof(Whee.WordBuilder.Model.Commands.LoopCommand), cb);

            Assert.AreEqual(1, cb.Children.Count);
        }
Beispiel #8
0
        private static void RecursivelyExtractSemanticProperties(List <ResultPropertiesRef> propertyList, int semanticsOffset, IntPtr phraseBuffer, RuleNode ruleTree, IList <RecognizedWordUnit> words, bool isSapi53Header)
        {
            IntPtr ptr = new IntPtr((long)phraseBuffer + semanticsOffset);
            SPSERIALIZEDPHRASEPROPERTY sPSERIALIZEDPHRASEPROPERTY = (SPSERIALIZEDPHRASEPROPERTY)Marshal.PtrToStructure(ptr, typeof(SPSERIALIZEDPHRASEPROPERTY));
            string        propertyName;
            SemanticValue semanticValue = ExtractSemanticValueInformation(semanticsOffset, sPSERIALIZEDPHRASEPROPERTY, phraseBuffer, isSapi53Header, out propertyName);
            RuleNode      ruleNode      = ruleTree.Find(sPSERIALIZEDPHRASEPROPERTY.ulFirstElement, sPSERIALIZEDPHRASEPROPERTY.ulCountOfElements);

            if (propertyName == "SemanticKey")
            {
                ruleNode._name    = (string)semanticValue.Value;
                ruleNode._hasName = true;
            }
            else
            {
                propertyList.Add(new ResultPropertiesRef(propertyName, semanticValue, ruleNode));
            }
            if (sPSERIALIZEDPHRASEPROPERTY.pFirstChildOffset != 0)
            {
                RecursivelyExtractSemanticProperties(propertyList, (int)sPSERIALIZEDPHRASEPROPERTY.pFirstChildOffset, phraseBuffer, ruleTree, words, isSapi53Header);
            }
            if (sPSERIALIZEDPHRASEPROPERTY.pNextSiblingOffset != 0)
            {
                RecursivelyExtractSemanticProperties(propertyList, (int)sPSERIALIZEDPHRASEPROPERTY.pNextSiblingOffset, phraseBuffer, ruleTree, words, isSapi53Header);
            }
        }
Beispiel #9
0
            internal RuleNode Find(uint firstElement, uint count)
            {
                float num;

                if (count == 0)
                {
                    num = (float)firstElement - 0.5f;
                }
                else
                {
                    float num2 = firstElement;
                    num = num2 + (float)(count - 1);
                }
                for (RuleNode ruleNode = _child; ruleNode != null; ruleNode = ruleNode._next)
                {
                    float num4;
                    float num3;
                    if (ruleNode._count == 0)
                    {
                        num4 = (num3 = (float)ruleNode._firstElement - 0.5f);
                    }
                    else
                    {
                        num4 = ruleNode._firstElement;
                        num3 = num4 + (float)(ruleNode._count - 1);
                    }
                    if (num4 <= (float)firstElement && num3 >= num)
                    {
                        return(ruleNode.Find(firstElement, count));
                    }
                }
                return(this);
            }
Beispiel #10
0
        public RuleSelection(RuleNode node)
        {
            Node = node;
            var root = (CatalogueBaseNode)node.Ancestors().Last();

            SourceName = $"{root.Name} (v{root.Revision})";
        }
Beispiel #11
0
 private void BuildRuleNode(ICompiledRule rule, IEnumerable<ITerminalNode> terminalNodes)
 {
     var ruleNode = new RuleNode(rule);
     foreach (var terminalNode in terminalNodes)
     {
         terminalNode.Attach(ruleNode);
     }
 }
Beispiel #12
0
        internal static ReteNode Create(RuleNode node)
        {
            var expressions = node.CompiledRule.Definition.FilterGroup.Filters.Select(e =>
                                                                                      new KeyValuePair <string, LambdaExpression>($"Filter{e.FilterType}", e.Expression));

            return(new ReteNode(node.Id, NodeType.Rule, expressions: expressions,
                                rules: node.NodeInfo.Rules));
        }
Beispiel #13
0
 public void Rewriter_that_changes_node_returns_new_tree()
 {
     var subject = InfoGroup().AddRules(Rule("rule1"), Rule("rule2"));
     var result  = LambdaRewriter.Visit(subject, node => node switch
     {
         RuleNode r => r.WithName(r.Name + r.Name),
         _ => node
     });
Beispiel #14
0
        public RuleBuilder AddParallelRule(params RuleNode[] rules)
        {
            var parallelRule = new ParallelRule(rules.ToList());

            _lastRule.DependantRule = parallelRule;
            _lastRule = parallelRule;
            return(this);
        }
Beispiel #15
0
        public RuleBuilder InsertRuleChain(RuleNode rootRuleOfRuleChain)
        {
            var lastRuleOfChain = FindLastRuleInChain(rootRuleOfRuleChain);

            _lastRule.DependantRule = rootRuleOfRuleChain;
            _lastRule = lastRuleOfChain;
            return(this);
        }
        public bool ToCheck(LoanRequestModel loanRequestModel)
        {
            Customer customer = _context.Customers.FirstOrDefault(c => c.CustomerId == loanRequestModel.LoanSupplied);
            var      listRule = _context.Rules.Where(item => item.CustomerId2.CustomerId == loanRequestModel.LoanSupplied && item.IsManager == null).ToList();
            RuleNode treeRule = BuidlTree(listRule);

            return(Eval(loanRequestModel.DictionaryData, treeRule));
        }
Beispiel #17
0
        public RuleBuilder AddParallelRule <T>(IEnumerable <T> ruleArguments, Func <T, RuleNode> ruleCreationFunc)
        {
            var parallelRule = new ParallelRule(ruleArguments.Select(ruleCreationFunc).ToList());

            _lastRule.DependantRule = parallelRule;
            _lastRule = parallelRule;
            return(this);
        }
        public bool CheckCondition(RuleNode rule, double value)
        {
            var    ruleOperator = rule.@operator !.ParseEnum <RuleOperator>();
            object?ruleValue    = ruleOperator == RuleOperator.Between || ruleOperator == RuleOperator.NotBetween
                ? JsonSerializerHelpers.DeserializeFromObject <IEnumerable <double> >(rule.value !)
                : (object)JsonSerializerHelpers.DeserializeFromObject <double>(rule.value !);

            return(_operatorMappings[ruleOperator](ruleValue, value));
        }
Beispiel #19
0
 protected internal override void VisitRuleNode(SchemaBuilder builder, RuleNode node)
 {
     if (builder.IsVisited(node))
     {
         return;
     }
     builder.AddNode(node, ReteNode.Create);
     base.VisitRuleNode(builder, node);
 }
Beispiel #20
0
 protected internal override void VisitRuleNode(SnapshotBuilder builder, RuleNode node)
 {
     if (builder.IsVisited(node))
     {
         return;
     }
     builder.AddNode(node, NodeInfo.Create);
     base.VisitRuleNode(builder, node);
 }
Beispiel #21
0
        public async Task <bool> Execute(RuleNode rule, CancellationToken cancellationToken)
        {
            double currentTemperatureInGreenhouse = await _dbContext.GreenhouseAirParameters
                                                    .OrderByDescending(x => x.Timestamp)
                                                    .Select(x => x.Temperature)
                                                    .FirstOrDefaultAsync(cancellationToken);

            return(_operatorParser.CheckCondition(rule, currentTemperatureInGreenhouse));
        }
Beispiel #22
0
        private void BuildRuleNode(ICompiledRule compiledRule, IEnumerable <ITerminalNode> terminalNodes)
        {
            var ruleNode = new RuleNode(compiledRule);

            foreach (var terminalNode in terminalNodes)
            {
                terminalNode.Attach(ruleNode);
            }
        }
        public async Task <bool> Execute(RuleNode rule, CancellationToken cancellationToken)
        {
            double averageMaxWindSpeed = await _dbContext.WeatherStationWindParameters
                                         .OrderByDescending(x => x.MeasurementStartTime)
                                         .Select(x => x.MaxWindSpeed)
                                         .Take(3)
                                         .AverageAsync(cancellationToken);

            return(_operatorParser.CheckCondition(rule, averageMaxWindSpeed));
        }
        protected override IList <RuleNode> NextVisitedRuleNodes(RuleNode ruleNode)
        {
            var result = new List <RuleNode>();

            if (ruleNode.DependantRule != null)
            {
                result.Add(ruleNode.DependantRule);
            }
            return(result);
        }
Beispiel #25
0
        public void WalkThrough(RuleNode rootNode, BulletinScreenModelBase bulletin)
        {
            var visitor = new GeneralErrorMarkerVisitor();

            rootNode.Accept(visitor);

            SetWasntChecked(visitor);

            _votesFieldsWasntCheckedSetter.SetVoteFieldsThatDontHaveCorrespondingChecksSetAsWasntChecked(bulletin);
        }
Beispiel #26
0
        private Func <User, Resource, bool> Build(RuleNode root)
        {
            var expressionString = ParseRuleNode(root);
            var user             = Expression.Parameter(typeof(User), "u");
            var resource         = Expression.Parameter(typeof(Resource), "r");

            var expression = DynamicExpressionParser.ParseLambda(new[] { user, resource }, typeof(bool), expressionString);

            return((Func <User, Resource, bool>)expression.Compile());
        }
Beispiel #27
0
 private static bool RuleAndItsDependantsAreFulfilled(RuleNode node)
 {
     if (node.DependantRule == null)
     {
         return(node.IsFulfiled);
     }
     else
     {
         return(node.IsFulfiled && RuleAndItsDependantsAreFulfilled(node.DependantRule));
     }
 }
Beispiel #28
0
 private static RuleNode FindLastRuleInChain(RuleNode rule)
 {
     if (rule.DependantRule == null)
     {
         return(rule);
     }
     else
     {
         return(FindLastRuleInChain(rule.DependantRule));
     }
 }
Beispiel #29
0
        public override void MarkupFulfilled(RuleNode ruleNode)
        {
            var rule = (QCumulativeWarningRule)ruleNode;

            rule.Question.AdditionalMarks.YesCheckBoxField.ErrorLevel       = ErrorLevel.Valid;
            rule.Question.AdditionalMarks.NoCheckBoxField.ErrorLevel        = ErrorLevel.Valid;
            rule.Question.AdditionalMarks.AbstainedCheckBoxField.ErrorLevel = ErrorLevel.Valid;

            rule.Question.CandidatePoints.ForEach(c => c.VotesDocField.ErrorLevel = ErrorLevel.Valid);
            rule.Question.AdditionalMarks.NoVotesField.ErrorLevel        = ErrorLevel.Valid;
            rule.Question.AdditionalMarks.AbstainedVotesField.ErrorLevel = ErrorLevel.Valid;
        }
        public override void MarkupFulfilled(RuleNode ruleNode)
        {
            var rule = (QSimpleQSepAndHierSubQWarningRule)ruleNode;

            rule.Point.YesCheckBoxField.ErrorLevel       = ErrorLevel.Valid;
            rule.Point.NoCheckBoxField.ErrorLevel        = ErrorLevel.Valid;
            rule.Point.AbstainedCheckBoxField.ErrorLevel = ErrorLevel.Valid;

            rule.Point.YesVotesField.ErrorLevel       = ErrorLevel.Valid;
            rule.Point.NoVotesField.ErrorLevel        = ErrorLevel.Valid;
            rule.Point.AbstainedVotesField.ErrorLevel = ErrorLevel.Valid;
        }
Beispiel #31
0
        public RuleNodeMarkuperBase GetRuleMarkuperFor(RuleNode ruleNode)
        {
            foreach (var markuper in _markupers)
            {
                if (markuper.CanMarkupRuleNodeOfType(ruleNode))
                {
                    return(markuper);
                }
            }

            throw new NotSupportedException("��� ������������� ������ ��� ������� ���� " + ruleNode.GetType());
        }
Beispiel #32
0
 internal static NodeInfo Create(RuleNode node)
 {
     return new NodeInfo(NodeType.Rule, node.Rule.Definition.Name);
 }