/// <summary>
 /// Add a term (fact or rule) to the KB.
 /// </summary>
 public void AssertA(Structure structure)
 {
     Assert(structure, false, false);
 }
        /// <summary>
        /// Add a term (fact or rule) to the KB.
        /// </summary>
        public void Assert(Structure structure, bool atEnd, bool checkSingletons)
        {
            if (structure == null)
            {
                throw new ArgumentNullException("structure", "Term to add to KB may not be null.");
            }
            //structure = structure.Expand();

            if (structure == null)
            {
                throw new ArgumentNullException("structure");
            }

            Structure head = structure.IsFunctor(Symbol.Implication, 2)
                                 ? Term.Structurify(structure.Argument(0),
                                                    "Head of :- must be a valid proposition or predicate.")
                                 : structure;

            if (head.IsFunctor(Symbol.ColonColon, 2))
            {
                var argument = head.Argument(0);
                var kb       = argument as KnowledgeBase;
                if (kb == null)
                {
                    var o = argument as GameObject;
                    if (o != null)
                    {
                        kb = o.KnowledgeBase();
                    }
                    else
                    {
                        var c = argument as Component;
                        if (c != null)
                        {
                            kb = c.KnowledgeBase();
                        }
                        else
                        {
                            throw new ArgumentTypeException(
                                      "assert",
                                      "knowledgebase",
                                      argument,
                                      typeof(KnowledgeBase));
                        }
                    }
                }
                if (structure.IsFunctor(Symbol.Implication, 2))
                {
                    kb.Assert(
                        new Structure(Symbol.Implication, head.Argument(1), structure.Argument(1)),
                        atEnd,
                        checkSingletons);
                }
                else
                {
                    kb.Assert(structure.Argument(1), atEnd, checkSingletons);
                }
            }
            else
            {
                if (PrologPrimitives.Implementations.ContainsKey(head.Functor))
                {
                    throw new PrologException(
                              new Structure(
                                  "error",
                                  new Structure(
                                      "permission_error",
                                      Symbol.Intern("modify"),
                                      Symbol.Intern("static_procedure"),
                                      Term.PredicateIndicatorExpression(head))));
                }

                KnowledgeBaseRule assertion = KnowledgeBaseRule.FromTerm(
                    structure,
                    checkSingletons,
                    Prolog.CurrentSourceFile,
                    Prolog.CurrentSourceLineNumber);
                PredicateInfo info = EntryForStoring(head.PredicateIndicator);
                PredicateInfo parentInfo;
                if (!info.Shadow && this.Parent != null &&
                    (parentInfo = this.Parent.CheckForPredicateInfoInThisKB(head.PredicateIndicator)) != null &&
                    !parentInfo.External)
                {
                    throw new PrologException(
                              new Structure(
                                  "error",
                                  new Structure(
                                      "permission_error",
                                      Symbol.Intern("shadow"),
                                      Term.PredicateIndicatorExpression(head))));
                }

                info.Assert(assertion, atEnd);
            }
        }
 /// <summary>
 /// Add a term (fact or rule) to the KB.
 /// </summary>
 public void AssertZ(Structure structure)
 {
     Assert(structure, true, false);
 }
Example #4
0
 public Suspension(Structure delayedGoal, Structure frozenGoal, PrologContext prologContext)
 {
     DelayedGoal = delayedGoal;
     FrozenGoal  = frozenGoal;
     context     = prologContext;
 }
        internal IEnumerable <CutState> FindClauses(Structure head, object body)
        {
            PredicateInfo i = CheckForPredicateInfo(head.PredicateIndicator);

            return((i == null)?CutStateSequencer.Fail():i.FindClauses(head, body));
        }
Example #6
0
 /// <summary>
 /// Test whether GOAL is provable
 /// </summary>
 /// <param name="goal">Goal to prove</param>
 /// <returns>True if provable, else false.</returns>
 public bool IsTrue(Structure goal)
 {
     return(Prove(goal).GetEnumerator().MoveNext());
 }
Example #7
0
 internal override IEnumerable <bool> UnifyWithStructure(Structure value)
 {
     return(UnifyWithCanonicalValue(value));
 }
Example #8
0
 /// <summary>
 /// Adds ASSERTION to GAMEOBJECT's knowledgebase.
 /// </summary>
 /// <param name="gameObject">Object whose knowledge base it should be added to</param>
 /// <param name="assertion">Assertion to add</param>
 public static void Assert(this GameObject gameObject, Structure assertion)
 {
     gameObject.KnowledgeBase().AssertZ(assertion);
 }
Example #9
0
 /// <summary>
 /// Adds ASSERTION to COMPONENT's knowledgebase.
 /// </summary>
 /// <param name="component">Object whose knowledge base it should be added to</param>
 /// <param name="assertion">Assertion to add</param>
 public static void Assert(this Component component, Structure assertion)
 {
     component.KnowledgeBase().AssertZ(assertion);
 }
Example #10
0
 public void AddSuspendedGoalSavingToTrail(Structure goal, PrologContext context)
 {
     SaveAndUpdate(new Metastructure(goal, null, context, MetaBinding), context);
 }
Example #11
0
            private void CompileGoal(Structure goal, ref ushort failAddress, ref ushort backPatchAddress)
            {
                byte continuationRegister = env.GetRegister();
                // Allocate registers to goal arguments.
                var argRegisters = new byte[goal.Arity];

                for (int i = 0; i < goal.Arity; i++)
                {
                    object arg = goal.Argument(i);
                    if (arg is Structure)
                    {
                        argRegisters[i] = env.GetRegister();
                    }
                    else
                    {
                        var @var = arg as LogicVariable;
                        if (@var != null)
                        {
                            argRegisters[i] = this.env.InsureRegisterAndLock(@var);
                        }
                        else
                        {
                            // It's a literal.
                            argRegisters[i] = NoRegister;
                        }
                    }
                }

                // Build goal arguments into registers.
                for (int i = 0; i < goal.Arity; i++)
                {
                    if (argRegisters[i] != NoRegister)
                    {
                        CompileBuild(goal.Argument(i), NoRegister, argRegisters[i]);
                    }
                }

                // Emit call instruction
                ushort startOfCallInstruction = CurrentPC;

                BackPatch(backPatchAddress, startOfCallInstruction);
                PrologPrimitives.PrimitiveImplementation primitiveImplementation;
                bool isPrimitive = PrologPrimitives.Implementations.TryGetValue(goal.Functor,
                                                                                out primitiveImplementation);

                // Call header
                Emit(isPrimitive?Opcode.CallPrimitive : Opcode.Call, continuationRegister);
                EmitUShort(failAddress);
                backPatchAddress = CurrentPC;
                EmitUShort(0);      // This will get backpatched
                // Call target
                if (isPrimitive)
                {
                    EmitUShort(PrimitiveTable.IndexOf(primitiveImplementation));
                    EmitByte((byte)goal.Arity);
                }
                else
                {
                    EmitUShort(PredicateTable.IndexOf(this.knowledgeBase.EntryForStoring(goal.PredicateIndicator)));
                }
                // Call arguments
                for (int i = 0; i < goal.Arity; i++)
                {
                    byte reg = argRegisters[i];
                    if (reg == NoRegister)
                    {
                        EmitUShort((ushort)(0x8000 + GlobalLiteralTable.IndexOf(goal.Argument(i))));
                    }
                    else
                    {
                        EmitByte(reg);
                    }
                }
                failAddress = startOfCallInstruction;
            }
Example #12
0
 // ReSharper disable once InconsistentNaming
 void LoadCSVRow(int rowNumber, Structure row)
 {
     if (!this.IsTrue(new Structure("load_csv_row", rowNumber, row)))
         throw new Exception(string.Format("Failed to load CSV row number {0} : {1}", rowNumber, Term.ToStringInPrologFormat(row)));
 }
Example #13
0
        /// <summary>
        /// Proves the specified goal, throwing an exception with badGoalErrorMessage if the goal is ill-formed.
        /// </summary>
        internal IEnumerable <CutState> Prove(object goal, string badGoalErrorMessage)
        {
            Structure s = Term.Structurify(goal, badGoalErrorMessage);

            return(KnowledgeBase.Prove(s.Functor, s.Arguments, this, CurrentFrame));
        }
Example #14
0
 /// <summary>
 /// Proves the goal in the specified structure.
 /// </summary>
 internal IEnumerable <CutState> Prove(Structure goal)
 {
     return(KnowledgeBase.Prove(goal.Functor, goal.Arguments, this, CurrentFrame));
 }
 /// <summary>
 /// Remove all terms matching head
 /// </summary>
 public void RetractAll(Structure head)
 {
     EntryForStoring(head.PredicateIndicator).RetractAll(head);
 }
Example #16
0
 internal override bool UnifyWithStructure(Structure value, PrologContext context)
 {
     return(UnifyWithCanonicalValue(value, context));
 }
 internal IEnumerable <CutState> Retract(Structure head, object body)
 {
     return(EntryForStoring(head.PredicateIndicator).Retract(head, body));
 }
Example #18
0
        private void WalkGoal(KnowledgeBase kb, KnowledgeBaseRule rule, Structure goal)
        {
            var    predicateIndicator = goal.PredicateIndicator;
            Symbol functor            = goal.Functor;
            int    arity = goal.Arity;

            switch (functor.Name)
            {
            case "begin":
                foreach (var arg in goal.Arguments)
                {
                    WalkGoal(kb, rule, arg);
                }
                break;

            case "once":
            case "check":
            case "randomize":
            case "not":
            case "\\+":
                if (arity == 1)
                {
                    WalkGoal(kb, rule, goal.Argument(0));
                }
                else
                {
                    WarnUndefined(rule, functor, arity);
                }
                break;

            case ",":
            case ";":
            case "->":
                if (arity == 2)
                {
                    WalkGoal(kb, rule, goal.Argument(0));
                    WalkGoal(kb, rule, goal.Argument(1));
                }
                else
                {
                    WarnUndefined(rule, functor, arity);
                }
                break;

            case "call":
            case "maplist":
                if (arity < 1)
                {
                    WarnUndefined(rule, functor, arity);
                }
                else
                {
                    object goalToCall            = goal.Argument(0);
                    var    goalToCallAsStructure = goalToCall as Structure;
                    if (goalToCallAsStructure != null)
                    {
                        var newArgs = new object[arity - 1 + goalToCallAsStructure.Arity];
                        goalToCallAsStructure.Arguments.CopyTo(newArgs, 0);
                        WalkGoal(kb, rule, new Structure(goalToCallAsStructure.Functor, newArgs));
                    }
                    else
                    {
                        var call = goalToCall as Symbol;
                        if (call != null)
                        {
                            this.WalkGoal(kb, rule, new Structure(call, new object[arity - 1]));
                        }
                    }
                }
                break;

            case "arg_min":
            case "arg_max":
                if (arity == 3)
                {
                    WalkGoal(kb, rule, goal.Argument(2));
                }
                else
                {
                    WarnUndefined(rule, functor, arity);
                }
                break;

            case "find_all":
                if (arity == 3)
                {
                    WalkGoal(kb, rule, goal.Argument(1));
                }
                else
                {
                    WarnUndefined(rule, functor, arity);
                }
                break;

            default:
                if (PrologPrimitives.IsDefined(predicateIndicator))
                {
                    var arglist = PrologPrimitives.Arglist(predicateIndicator.Functor);
                    for (int i = 0; i < Math.Min(predicateIndicator.Arity, arglist.Count); i++)
                    {
                        var argSym = arglist[i] as Symbol;
                        if (argSym != null)
                        {
                            var arg = argSym.Name;
                            if (arg[0] == ':')
                            {
                                WalkGoal(kb, rule, goal.Argument(i));
                            }
                            else if (arg == "..." && arglist[i - 1] is string && ((string)arglist[i - 1])[0] == ':')
                            {
                                // Predicate accepts a rest arg of goals
                                for (int j = i; j < predicateIndicator.Arity; j++)
                                {
                                    WalkGoal(kb, rule, goal.Argument(j));
                                }
                            }
                        }
                    }
                }
                else
                {
                    var predicate = kb.CheckForPredicateInfo(predicateIndicator);
                    if (predicate == null)
                    {
                        WarnUndefined(rule, functor, arity);
                    }
                    else
                    {
                        MarkReferenced(predicate);
                        if (predicate.HigherOrderArguments != null)
                        {
                            foreach (int argIndex in predicate.HigherOrderArguments)
                            {
                                WalkGoal(kb, rule, goal.Argument(argIndex));
                            }
                        }
                    }
                }
                break;
            }
        }