예제 #1
0
        private LinkedList <StandardRule <T> > GetRuleList(object[] args)
        {
            LinkedList <StandardRule <T> > ruleList;

            lock (_ruleTable) {
                RuleTable curTable = _ruleTable;
                foreach (object o in args)
                {
                    Type objType = CompilerHelpers.GetType(o);

                    if (curTable.NextTable == null)
                    {
                        curTable.NextTable = new Dictionary <Type, RuleTable>(1);
                    }

                    RuleTable nextTable;
                    if (!curTable.NextTable.TryGetValue(objType, out nextTable))
                    {
                        curTable.NextTable[objType] = nextTable = new RuleTable();
                    }

                    curTable = nextTable;
                }

                if (curTable.Rules == null)
                {
                    curTable.Rules = new LinkedList <StandardRule <T> >();
                }

                ruleList = curTable.Rules;
            }
            return(ruleList);
        }
예제 #2
0
        private LinkedList <CallSiteRule <T> > GetRuleList(object[] args)
        {
            LinkedList <CallSiteRule <T> > ruleList;

            lock (_ruleTable) {
                RuleTable curTable = _ruleTable;
                foreach (object arg in args)
                {
                    Type objType = TypeUtils.GetTypeForBinding(arg);
                    if (curTable.NextTable == null)
                    {
                        curTable.NextTable = new Dictionary <Type, RuleTable>(1);
                    }

                    RuleTable nextTable;
                    if (!curTable.NextTable.TryGetValue(objType, out nextTable))
                    {
                        curTable.NextTable[objType] = nextTable = new RuleTable();
                    }

                    curTable = nextTable;
                }

                if (curTable.Rules == null)
                {
                    curTable.Rules = new LinkedList <CallSiteRule <T> >();
                }

                ruleList = curTable.Rules;
            }
            return(ruleList);
        }
예제 #3
0
        public void RuleTable_Extend()
        {
            var tbl = new RuleTable <int, string, object>(d => Expression.Constant(1), (d, s) => d);

            tbl.Add <int>("foo", x => x);

            var ext = tbl.Extend();

            ext.Add <int>("bar", x => x);

            var e1 = ext.GetEnumerator();
            var e2 = ((IEnumerable)ext).GetEnumerator();

            Assert.IsTrue(e1.MoveNext());
            Assert.IsTrue(e2.MoveNext());

            var c1 = e1.Current;
            var c2 = (Rule <int, string, object>)e2.Current;

            Assert.AreEqual("foo", c1.Name);
            Assert.AreEqual("foo", c2.Name);

            Assert.IsTrue(e1.MoveNext());
            Assert.IsTrue(e2.MoveNext());

            var c3 = e1.Current;
            var c4 = (Rule <int, string, object>)e2.Current;

            Assert.AreEqual("bar", c3.Name);
            Assert.AreEqual("bar", c4.Name);

            Assert.IsFalse(e1.MoveNext());
            Assert.IsFalse(e2.MoveNext());
        }
예제 #4
0
        public void RuleTable_AsReadOnly()
        {
            var tbl = new RuleTable <int, string, object>(d => Expression.Constant(1), (d, s) => d);

            tbl.Add <int>("foo", x => x);

            var rdo = tbl.AsReadOnly();

            Assert.ThrowsException <NotSupportedException>(() => rdo.Add <int>("qux", x => x));

            var e1 = rdo.GetEnumerator();
            var e2 = ((IEnumerable)rdo).GetEnumerator();

            Assert.IsTrue(e1.MoveNext());
            Assert.IsTrue(e2.MoveNext());

            var c1 = e1.Current;
            var c2 = (Rule <int, string, object>)e2.Current;

            Assert.AreEqual("foo", c1.Name);
            Assert.AreEqual("foo", c2.Name);

            Assert.IsFalse(e1.MoveNext());
            Assert.IsFalse(e2.MoveNext());
        }
예제 #5
0
    public void UpdateSuspendedRules(float dt, List <int> toRemove, RuleTable ActiveRules)
    {
        if (ActiveRules.ActiveIndices.Top > 0)
        {
            for (int i = 0; i < ActiveRules.ActiveIndices.Top; i++)
            {
                switch (ActiveRules.ActiveIndices.Elements[i])
                {
                case 0:
                    if (this.Rule0(dt) == RuleResult.Done)
                    {
                        ActiveRules.ActiveSlots[i] = false;
                    }
                    else
                    {
                        ActiveRules.SupportStack.Push(i);
                    }
                    break;

                default:
                    break;
                }
            }
            ActiveRules.ActiveIndices.Clear();
            var tmp = ActiveRules.SupportStack;
            ActiveRules.SupportStack  = ActiveRules.ActiveIndices;
            ActiveRules.ActiveIndices = tmp;
            if (ActiveRules.ActiveIndices.Top == 0)
            {
                toRemove.Add(ID);
            }
        }
    }
예제 #6
0
        public void RuleTable_DuplicateEntry()
        {
            var tbl = new RuleTable <int, string, object>(d => Expression.Constant(1), (d, s) => d);

            tbl.Add <int>("foo", x => x);

            Assert.ThrowsException <InvalidOperationException>(() => tbl.Add <int>("foo", x => x));
        }
예제 #7
0
            public static PluralCategory GetPluralCategory(CultureInfo info, RuleType ruleType, FluentNumber number)
            {
                var specialCase = IsSpecialCase(info.Name, ruleType);
                var langStr     = GetPluralRuleLang(info, specialCase);
                var func        = RuleTable.GetPluralFunc(langStr, ruleType);

                if (number.TryPluralOperands(out var op))
                {
                    return(func(op));
                }

                return(PluralCategory.Other);
            }
예제 #8
0
        /// <summary>
        /// Initializes the data files from the disk
        /// </summary>
        public void InitializeDataFiles()
        {
            // Load the lookup files
            EventPoints    = new EventPointTable();
            Settings       = new SettingsTable();
            Statistics     = new StatisticsTable();
            CustomCommands = new CustomCommandsTable();
            Rules          = new RuleTable();
            Mutes          = new MuteTable();
            Bans           = new BanTable();

            UnityDocs = new UnityDocs("manualReference.json", "scriptReference.json");
            Cooldowns = CooldownData.FromPath("cooldowns.json");
        }
예제 #9
0
        public void RuleTable_ArgumentChecking()
        {
            var tbl = new RuleTable <int, string, object>(d => Expression.Constant(1), (d, s) => d);

#pragma warning disable IDE0034 // Simplify 'default' expression (documents the signature)
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add(default(Rule <int, string, object>)));

            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(default(Expression <Func <int, int> >)));

            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(default(string), x => x));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", default(Expression <Func <int, int> >)));

            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(42, default(Expression <Func <int, int> >)));

            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(default(string), 42, x => x));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", 42, default(Expression <Func <int, int> >)));

            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(default(Func <int, bool>), x => x));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(x => true, default(Expression <Func <int, int> >)));

            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(42, default(Func <int, bool>), x => x));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(42, x => true, default(Expression <Func <int, int> >)));

            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(default(string), 42, x => true, x => x));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", 42, default(Func <int, bool>), x => x));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", 42, x => true, default(Expression <Func <int, int> >)));

            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(default(string), (x, rec, o) => "", (s, rec, o) => 42));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", default(Func <int, Func <int, object, string>, object, string>), (s, rec, o) => 42));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", (x, rec, o) => "", default(Func <string, Func <string, object, int>, object, int>)));

            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(default(string), 42, (x, rec, o) => "", (s, rec, o) => 42));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", 42, default(Func <int, Func <int, object, string>, object, string>), (s, rec, o) => 42));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", 42, (x, rec, o) => "", default(Func <string, Func <string, object, int>, object, int>)));

            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(default(string), x => true, (x, rec, o) => "", (s, rec, o) => 42));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", default(Func <int, bool>), (x, rec, o) => "", (s, rec, o) => 42));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", x => true, default(Func <int, Func <int, object, string>, object, string>), (s, rec, o) => 42));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", x => true, (x, rec, o) => "", default(Func <string, Func <string, object, int>, object, int>)));

            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>(default(string), 42, x => true, (x, rec, o) => "", (s, rec, o) => 42));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", 42, default(Func <int, bool>), (x, rec, o) => "", (s, rec, o) => 42));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", 42, x => true, default(Func <int, Func <int, object, string>, object, string>), (s, rec, o) => 42));
            Assert.ThrowsException <ArgumentNullException>(() => tbl.Add <int>("foo", 42, x => true, (x, rec, o) => "", default(Func <string, Func <string, object, int>, object, int>)));
#pragma warning restore IDE0034 // Simplify 'default' expression
        }
예제 #10
0
        /// <summary>
        /// Adds a new rule to the set of dashboard rules
        /// </summary>
        /// <param name="rule">The rule to add</param>
        /// <returns>Boolean; whether the addition was successful</returns>
        public bool AddRule(IDashboardRule rule)
        {
            #region Input Validation
            if (rule == null || string.IsNullOrEmpty(rule.FriendlyRule))
            {
                throw new ArgumentNullException("rule");
            }
            #endregion // Input Validation

            // check for duplicate rules
            foreach (DataRow row in RuleTable.Rows)
            {
                IDashboardRule rRule = (IDashboardRule)row[COLUMN_RULE];

                if (rRule.FriendlyRule.Equals(rule.FriendlyRule))
                {
                    // cannot add a duplicate rule, so return false
                    return(false);
                }
            }

            // find the highest run order value of all the rules presently in the table
            int maxInt = int.MinValue;

            foreach (DataRow row in RuleTable.Rows)
            {
                int value = row.Field <int>(COLUMN_RUN_ORDER);
                maxInt = Math.Max(maxInt, value);
            }

            RuleTable.Rows.Add(maxInt + 1, rule);

            // sort by run order
            this.ruleTable = RuleTable.Select("", COLUMN_RUN_ORDER).CopyToDataTable().DefaultView.ToTable("RuleTable");

            if (rule is DataAssignmentRule)
            {
                DataAssignmentRule assignRule = rule as DataAssignmentRule;
                if (!dashboardHelper.TableColumnNames.ContainsKey(assignRule.DestinationColumnName))
                {
                    dashboardHelper.TableColumnNames.Add(assignRule.DestinationColumnName, assignRule.DestinationColumnType);
                }
            }

            return(true);
        }
예제 #11
0
파일: Action.cs 프로젝트: thisiscam/formula
        /// <summary>
        /// Compile the action into rules. Should not be called unless successfully validated.
        /// </summary>
        public bool Compile(RuleTable rules, List <Flag> flags, CancellationToken cancel)
        {
            FindData[] parts;
            if (!Body.Compile(rules, out parts, flags, cancel))
            {
                return(false);
            }

            if (myComprData == null)
            {
                rules.CompileRule(HeadTerm, HeadType, parts, Head, Body, configurationContext);
            }
            else
            {
                rules.CompileRule(rules.MkComprHead(myComprData, HeadTerm), Index.FalseValue, parts, Head, Body, configurationContext);
            }

            return(true);
        }
예제 #12
0
        public void RuleTable_Concat()
        {
            var tbl1 = new RuleTable <int, string, object>(d => Expression.Constant(1), (d, s) => d);

            tbl1.Add <int>("foo", x => x);

            var tbl2 = new RuleTable <int, string, object>(d => Expression.Constant(1), (d, s) => d);

            tbl2.Add <int>("bar", x => x);

            var res = tbl1.Concat(tbl2);

            var e1 = res.GetEnumerator();
            var e2 = ((IEnumerable)res).GetEnumerator();

            Assert.IsTrue(e1.MoveNext());
            Assert.IsTrue(e2.MoveNext());

            var c1 = e1.Current;
            var c2 = (Rule <int, string, object>)e2.Current;

            Assert.AreEqual("foo", c1.Name);
            Assert.AreEqual("foo", c2.Name);

            Assert.IsTrue(e1.MoveNext());
            Assert.IsTrue(e2.MoveNext());

            var c3 = e1.Current;
            var c4 = (Rule <int, string, object>)e2.Current;

            Assert.AreEqual("bar", c3.Name);
            Assert.AreEqual("bar", c4.Name);

            Assert.IsFalse(e1.MoveNext());
            Assert.IsFalse(e2.MoveNext());

            Assert.ThrowsException <NotSupportedException>(() => res.Add <int>(x => x));
        }
예제 #13
0
        private void SetMaxLocationsPerProof(RuleTable rules)
        {
            var source = rules.ModuleData == null ? null : rules.ModuleData.Source.AST;

            if (source == null)
            {
                return;
            }

            Configuration config = null;

            switch (source.Node.NodeKind)
            {
            case NodeKind.Model:
                config = (Configuration)((Model)source.Node).Config.CompilerData;
                break;

            case NodeKind.Domain:
                config = (Configuration)((Domain)source.Node).Config.CompilerData;
                break;

            case NodeKind.Transform:
                config = (Configuration)((Transform)source.Node).Config.CompilerData;
                break;

            default:
                return;
            }

            Contract.Assert(config != null);
            Cnst maxLocs;

            if (config.TryGetSetting(Configuration.Proofs_MaxLocationsSetting, out maxLocs))
            {
                maxLocationsPerProof = (int)maxLocs.GetNumericValue().Numerator;
            }
        }
예제 #14
0
 public RuleCommand(RuleTable ruleTable, SettingsTable settings)
 {
     _ruleTable = ruleTable;
     _settings  = settings;
 }
예제 #15
0
        public FindData[] Optimize(RuleTable rules, ConstraintSystem environment, CancellationToken cancel)
        {
            //// Step 1. Try to split the items into connected components.
            var itemDats = new Map <Term, ItemData>(Term.Compare);
            var useLists = new Map <Term, Set <ItemData> >(Term.Compare);

            foreach (var kv in findPatterns)
            {
                itemDats.Add(kv.Key, RegisterUses(new ItemData(kv.Key, kv.Value.Item1), useLists));
            }

            foreach (var con in constraints)
            {
                itemDats.Add(con, RegisterUses(new ItemData(con), useLists));
            }

            FindData f1, f2;
            Tuple <ItemData, LinkedList <ItemData> > partialRule;
            var components = ComputeComponents(itemDats, useLists);

            if (components.Length == 0)
            {
                return(new FindData[] { rules.CompilePartialRule(default(FindData), default(FindData), new Set <Term>(Term.Compare), environment) });
            }

            var outputs = new FindData[components.Length];

            for (int i = 0; i < components.Length; ++i)
            {
                var ordering = OrderComponents(i, components[i], useLists);
                Contract.Assert(ordering != null && ordering.Count > 0);

                //// Debug_PrintOrderData(i, ordering);
                //// Console.WriteLine();

                using (var it = ordering.GetEnumerator())
                {
                    it.MoveNext();
                    partialRule = it.Current;
                    if (partialRule.Item1 != null)
                    {
                        f1 = new FindData(partialRule.Item1.Item, findPatterns[partialRule.Item1.Item].Item1, findPatterns[partialRule.Item1.Item].Item2);
                    }
                    else
                    {
                        f1 = default(FindData);
                    }

                    var constrs = new Set <Term>(Term.Compare);
                    foreach (var c in partialRule.Item2)
                    {
                        constrs.Add(c.Item);
                    }

                    if (ordering.Count == 1)
                    {
                        outputs[i] = rules.CompilePartialRule(f1, default(FindData), constrs, environment);
                        continue;
                    }

                    while (it.MoveNext())
                    {
                        partialRule = it.Current;
                        if (constrs == null)
                        {
                            constrs = new Set <Term>(Term.Compare);
                        }

                        if (partialRule.Item1 != null)
                        {
                            f2 = new FindData(partialRule.Item1.Item, findPatterns[partialRule.Item1.Item].Item1, findPatterns[partialRule.Item1.Item].Item2);
                        }
                        else
                        {
                            f2 = default(FindData);
                        }

                        foreach (var c in partialRule.Item2)
                        {
                            constrs.Add(c.Item);
                        }

                        f1         = rules.CompilePartialRule(f1, f2, constrs, environment);
                        outputs[i] = f1;
                        constrs    = null;
                    }
                }
            }

            return(outputs);
        }
예제 #16
0
        /// <summary>
        /// Compiles the action set into a set of rules. Should not be called if validation failed.
        /// </summary>
        public bool Compile(RuleTable rules, List <Flag> flags, CancellationToken cancel)
        {
            bool result = true;

            if (IsCompiled != LiftedBool.Unknown)
            {
                return((bool)IsCompiled);
            }
            else if (myComprData == null)
            {
                foreach (var a in actions)
                {
                    result = a.Compile(rules, flags, cancel) && result;
                }

                return((bool)(IsCompiled = result));
            }

            //// For a comprehension need to compile the bodies of the actions
            //// before compiling the actions, so a representation for the comprehension is known.
            FindData[] parts;
            var        bodies = new LinkedList <Term>();

            foreach (var a in actions)
            {
                result = a.Body.Compile(rules, out parts, flags, cancel) && result;
                if (result)
                {
                    bodies.AddLast(rules.MkBodyTerm(parts));
                }
            }

            if (!result)
            {
                return((bool)(IsCompiled = result));
            }

            bool wasAdded;
            Term reads       = Index.TrueValue;
            var  comprSymbol = Index.SymbolTable.GetOpSymbol(ReservedOpKind.Compr);
            var  conjSymbol  = Index.SymbolTable.GetOpSymbol(ReservedOpKind.Conj);

            foreach (var kv in myComprData.ReadVars.Reverse)
            {
                reads = Index.MkApply(conjSymbol, new Term[] { kv.Key, reads }, out wasAdded);
            }

            var headSet = new Set <Term>(Term.Compare);

            foreach (var a in actions)
            {
                headSet.Add(a.HeadTerm);
            }

            Term heads = Index.TrueValue;

            foreach (var h in headSet.Reverse)
            {
                heads = Index.MkApply(conjSymbol, new Term[] { h, heads }, out wasAdded);
            }

            myComprData.Representation = Index.MkApply(comprSymbol, new Term[] { heads, reads, rules.MkBodiesTerm(bodies) }, out wasAdded);
            foreach (var a in actions)
            {
                result = a.Compile(rules, flags, cancel) && result;
            }

            return((bool)(IsCompiled = result));
        }
예제 #17
0
        internal ProofTree(Term conclusion, CoreRule coreRule, Map <string, FactSet> factSets, RuleTable rules)
        {
            Contract.Requires(conclusion != null && factSets != null);
            this.factSets = factSets;
            Conclusion    = conclusion;
            CoreRule      = coreRule;
            Rule          = coreRule == null?Factory.Instance.MkId("fact", new Span(0, 0, 0, 0, new ProgramName("fact"))).Node : coreRule.Node;

            SetMaxLocationsPerProof(rules);
        }
예제 #18
0
 public bool Compile(RuleTable rules, List <Flag> flags, CancellationToken cancel)
 {
     return(actionSet.Compile(rules, flags, cancel));
 }
예제 #19
0
        private bool BuildModules(DependencyCollection <Location, Location> modDeps)
        {
            int nDeps;
            var deps   = modDeps.GetTopologicalSort(out nDeps, cancel);
            var flags  = new List <Flag>();
            var result = true;

            foreach (var d in deps)
            {
                Contract.Assert(d.Kind == DependencyNodeKind.Normal);
                if (d.Resource.AST.Node.NodeKind != NodeKind.Domain &&
                    d.Resource.AST.Node.NodeKind != NodeKind.Transform &&
                    d.Resource.AST.Node.NodeKind != NodeKind.TSystem &&
                    d.Resource.AST.Node.NodeKind != NodeKind.Model)
                {
                    continue; //// Others not implemented yet.
                }

                var ast     = d.Resource.AST;
                var modData = d.Resource.AST.Node.CompilerData as ModuleData;
                Contract.Assert(modData != null);

                //// In this case, the module was already compiled on an earlier interaction.
                if (modData.Phase != ModuleData.PhaseKind.Reduced)
                {
                    continue;
                }

                string name;
                modData.Reduced.Node.TryGetStringAttribute(AttributeKind.Name, out name);
                //// Console.WriteLine("Building symbol table for {0}", name);

                var symbTable = new SymbolTable(modData);

                flags.Clear();
                result = symbTable.Compile(flags, cancel) & result;
                Result.AddFlags((AST <Program>)Factory.Instance.ToAST(ast.Root), flags);
                flags.Clear();

                if (cancel.IsCancellationRequested)
                {
                    return(false);
                }

                if (!symbTable.IsValid)
                {
                    continue;
                }

                modData.PassedPhase(ModuleData.PhaseKind.TypesDefined, symbTable);

                if (modData.Source.AST.Node.NodeKind == NodeKind.Model)
                {
                    //// Console.WriteLine("Building fact table for {0}", name);
                    var facts = new FactSet(modData);
                    if (facts.Validate(flags, cancel))
                    {
                        modData.PassedPhase(ModuleData.PhaseKind.Compiled, facts);
                    }
                    else
                    {
                        result = false;
                    }
                }
                else if (modData.Source.AST.Node.NodeKind == NodeKind.TSystem)
                {
                    var tsys = new Common.Composites.CoreTSystem(modData);
                    if (tsys.Compile(flags, cancel))
                    {
                        modData.PassedPhase(ModuleData.PhaseKind.Compiled, tsys);
                    }
                    else
                    {
                        result = false;
                    }
                }
                else
                {
                    //// Console.WriteLine("Building rule table for {0}", name);
                    var ruleTable = new RuleTable(modData);
                    if (ruleTable.Compile(flags, cancel))
                    {
                        modData.PassedPhase(ModuleData.PhaseKind.Compiled, ruleTable);
                        Configuration conf = null;
                        switch (modData.Source.AST.Node.NodeKind)
                        {
                        case NodeKind.Domain:
                            conf = (Configuration)((Domain)modData.Source.AST.Node).Config.CompilerData;
                            break;

                        case NodeKind.Transform:
                            conf = (Configuration)((Transform)modData.Source.AST.Node).Config.CompilerData;
                            break;

                        default:
                            throw new NotImplementedException();
                        }

                        Cnst prodCheckSetting;
                        if (conf.TryGetSetting(Configuration.Compiler_ProductivityCheckSetting, out prodCheckSetting))
                        {
                            ruleTable.ProductivityCheck(prodCheckSetting, flags);
                        }
                    }
                    else
                    {
                        result = false;
                    }
                }

                Result.AddFlags((AST <Program>)Factory.Instance.ToAST(ast.Root), flags);

                if (cancel.IsCancellationRequested)
                {
                    return(false);
                }
            }

            return(result);
        }
예제 #20
0
	public void UpdateSuspendedRules(float dt, World world, List<int> toRemove, RuleTable ActiveRules) { if (ActiveRules.ActiveIndices.Top > 0 && frame == World.frame)
{
  for (int i = 0; i < ActiveRules.ActiveIndices.Top; i++)
  {
    var x = ActiveRules.ActiveIndices.Elements[i];
    switch (x)
    {case 0:
        if (this.Rule0(dt, world) == RuleResult.Done)
        {
          ActiveRules.ActiveSlots[i] = false;
          ActiveRules.ActiveIndices.Top--;
        }
        else{          
          ActiveRules.SupportSlots[0] = true;
          ActiveRules.SupportStack.Push(x);
        }
        break;
case 3:
        if (this.Rule3(dt, world) == RuleResult.Done)
        {
          ActiveRules.ActiveSlots[i] = false;
          ActiveRules.ActiveIndices.Top--;
        }
        else{          
          ActiveRules.SupportSlots[3] = true;
          ActiveRules.SupportStack.Push(x);
        }
        break;

      default:
        break;
    }
  }
  ActiveRules.ActiveIndices.Clear();
  ActiveRules.Clear();

  var tmp = ActiveRules.SupportStack;
  var tmp1 = ActiveRules.SupportSlots;

  ActiveRules.SupportStack = ActiveRules.ActiveIndices;
  ActiveRules.SupportSlots = ActiveRules.ActiveSlots;


  ActiveRules.ActiveIndices = tmp;
  ActiveRules.ActiveSlots = tmp1;

  if (ActiveRules.ActiveIndices.Top == 0)
    toRemove.Add(ID);
}else
{
  if (this.frame != World.frame)
    toRemove.Add(ID);
} }
예제 #21
0
 public void UpdateSuspendedRules(float dt, List<int> toRemove, RuleTable ActiveRules)
 {
     if (ActiveRules.ActiveIndices.Top > 0)
     {
       for (int i = 0; i < ActiveRules.ActiveIndices.Top; i++)
       {
     switch (ActiveRules.ActiveIndices.Elements[i])
     {
       case 0:
         if (this.Rule0(dt) == RuleResult.Done)
           ActiveRules.ActiveSlots[i] = false;
         else
           ActiveRules.SupportStack.Push(i);
         break;
       default:
         break;
     }
       }
       ActiveRules.ActiveIndices.Clear();
       var tmp = ActiveRules.SupportStack;
       ActiveRules.SupportStack = ActiveRules.ActiveIndices;
       ActiveRules.ActiveIndices = tmp;
       if (ActiveRules.ActiveIndices.Top == 0)
     toRemove.Add(ID);
     }
 }
예제 #22
0
        // function prototype and some of the methode is like https://github.com/opennars/opennars/blob/4515f1d8e191a1f097859decc65153287d5979c5/nars_core/nars/inference/RuleTables.java#L73
        internal static void reason(
            ClassicalTaskLink taskLink,
            ClassicalTermLink beliefLink,
            DerivationContext ctx
            )
        {
            { // debugging
                int taskId   = taskLink.targetTask.name.term.getAtomicOrTerm;
                int beliefId = beliefLink.target.getAtomicOrTerm;

                if (taskId == 300002 && beliefId == 300004)
                {
                    int breakpointHere2 = 1;
                }
                else if (taskId == 300004 && beliefId == 300002)
                {
                    int breakpointHere2 = 1;
                }

                int breakpointHere1 = 1;
            }

            Memory memory = ctx.memory;

            memory.emotion.manageBusy(ctx);

            ClassicalTask     task         = ctx.currentTask;
            ClassicalSentence taskSentence = task.sentence;

            TermOrCompoundTermOrVariableReferer taskTerm   = taskSentence.term;
            TermOrCompoundTermOrVariableReferer beliefTerm = beliefLink.target;

            // commented because not jet translated
            //if (equalSubTermsInRespectToImageAndProduct(taskTerm, beliefTerm))
            //    return;

            ClassicalConcept beliefConcept = memory.translateTermToConcept(beliefTerm);

            ClassicalSentence belief = (beliefConcept != null) ? beliefConcept.getBelief(ctx, task) : null;

            ctx.currentBelief = belief;

            if (belief != null)
            {
                beliefTerm = belief.term; //because interval handling that differs on conceptual level


                // too restrictive, its checked for non-deductive inference rules in derivedTask (also for single prem)
                if (Stamp.checkBaseOverlap(task.sentence.stamp, belief.stamp))
                {
                    ctx.evidentalOverlap = true;
                    if (!task.sentence.stamp.isEternal || !belief.stamp.isEternal)
                    {
                        return; // only allow for eternal reasoning for now to prevent derived event floods
                    }
                    //return; // preparisons are made now to support this nicely
                }
                // comment out for recursive examples, this is for the future, it generates a lot of potentially useless tasks

                //ctx.emit(Events.BeliefReason.class, belief, beliefTerm, taskTerm, nal);

                if (LocalRules.match(task, belief, ctx))    // new tasks resulted from the match, so return
                {
                    return;
                }
            }

            // current belief and task may have changed, so set again:
            ctx.currentBelief = belief;
            ctx.currentTask   = task;

            // HACK< derivation must be made by combining compounds >
            if (!TermUtilities.isTermCompoundTerm(taskTerm) || !TermUtilities.isTermCompoundTerm(beliefTerm))
            {
                return;
            }

            // derive and create new tasks for the results
            {
                IList <TemporaryDerivedCompoundWithDecorationAndTruth> derivedCompoundTermsWithDecorationAndTruth = new List <TemporaryDerivedCompoundWithDecorationAndTruth>();
                bool insert = true;

                DeriverCaller.deriverCaller(
                    ctx.compoundAndTermContext,
                    ctx.compoundAndTermContext.translateToCompoundChecked(taskTerm),
                    ctx.compoundAndTermContext.translateToCompoundChecked(beliefTerm),
                    out derivedCompoundTermsWithDecorationAndTruth, insert);

                // translate derivedCompoundTermsWithDecorationAndTruth to tasks and add them
                // for this we have to call DerivationContext.doublePremiseTask() to generate the tasks
                foreach (var iDerivedWithDecorationAndTruth in derivedCompoundTermsWithDecorationAndTruth)
                {
                    TermOrCompoundTermOrVariableReferer content = iDerivedWithDecorationAndTruth.derivedCompoundWithDecoration.termReferer;

                    bool temporalInduction = false; // TODO< decide by rule? from the deriver? >
                    bool overlapAllowed    = false; // TODO< decide by rule? from the deriver? >

                    TruthValue truth = null;
                    truth = RuleTable.calcTruthDoublePremise(task.sentence.truth, belief.truth, iDerivedWithDecorationAndTruth.truthfunction);

                    ClassicalBudgetValue budget = new ClassicalBudgetValue(0.5f, 0.5f, 0.5f); // TODO< calculate budget by table >

                    ctx.doublePremiseTask(content,
                                          truth,
                                          budget,
                                          temporalInduction,
                                          overlapAllowed
                                          );
                }
            }
        }