Example #1
0
 private CheckerInfo PredicateCheckerInfo(PredicateInfo predicate)
 {
     CheckerInfo result;
     if (checkerInfoTable.TryGetValue(predicate, out result))
         return result;
     return checkerInfoTable[predicate] = new CheckerInfo();
 }
Example #2
0
        private void MarkDefined(PredicateInfo predicate, KnowledgeBaseRule rule)
        {
            CheckerInfo predicateCheckerInfo = PredicateCheckerInfo(predicate);

            if (predicateCheckerInfo.DefiningRule == null)
            {
                predicateCheckerInfo.DefiningRule = rule;
            }
        }
Example #3
0
 internal PredicateInfo EntryForStoring(PredicateIndicator p)
 {
     PredicateInfo entry;
     if (!db.TryGetValue(p, out entry))
     {
         db[p] = entry = new PredicateInfo(p.Functor, p.Arity, this);
     }
     return entry;
 }
Example #4
0
 internal PredicateInfo CheckForPredicateInfo(PredicateIndicator p)
 {
     PredicateInfo info = CheckForPredicateInfoInThisKB(p);
     if (info != null)
         return info;
     foreach (KnowledgeBase import in imports)
         if ((info = import.CheckForPredicateInfo(p)) != null)
             return info;
     return null;
 }
Example #5
0
        private CheckerInfo PredicateCheckerInfo(PredicateInfo predicate)
        {
            CheckerInfo result;

            if (checkerInfoTable.TryGetValue(predicate, out result))
            {
                return(result);
            }
            return(checkerInfoTable[predicate] = new CheckerInfo());
        }
        internal ByteCompiledRule(PredicateInfo predicate, Structure head, Structure[] ruleBody, string source, int line)
            : base(head, ruleBody, false, source, line)
        {
            this.predicate = predicate;
            var c = new Compiler(head, ruleBody, KnowledgeBase);

            code      = c.Code;
            frameSize = c.FrameSize;
            Disassemble();
            Console.WriteLine();
        }
Example #7
0
 // ReSharper disable once InconsistentNaming
 IEnumerable<CutState> ProveFromDB(Symbol functor, object[] args, PrologContext context)
 {
     PredicateInfo info = GetPredicateInfo(this, new PredicateIndicator(functor, args.Length));
     if (info == null)
     {
         if (ErrorOnUndefined)
             throw new UndefinedPredicateException(functor, args.Length);
         return PrologPrimitives.FailImplementation;
     }
     return info.Prove(args, context);
 }
        private ushort StartCallInstruction(PrologContext context, int framePointer, ref ushort pc, out ushort succeedPC,
                                            out IEnumerator <CutState> iterator)
        {
            int    iteratorRegister = code[pc++];
            ushort failPC           = GetUShort(ref pc);

            succeedPC = GetUShort(ref pc);
            iterator  = null;
            // Make the iterator.  How we do this depends on the opcode, so re-fetch it.
            switch ((Opcode)code[pc - CallTargetOffset])
            {
            case Opcode.CallWokenGoals:
            {
                if (context.GoalsHaveWoken)
                {
                    iterator = context.ProveAllWokenGoals().GetEnumerator();
                }
            }
            break;

            case Opcode.Call:
            {
                // It's a user-defined predicate call
                PredicateInfo calledPredicate = GetPredicate(ref pc);
                PushCallArgs(context, framePointer, predicate.Arity, ref pc);
                iterator = calledPredicate.StackCall(context).GetEnumerator();
            }
            break;

            case Opcode.CallPrimitive:
            {
                // It's a primitive call
                PrologPrimitives.PrimitiveImplementation implementation = GetPrimitive(ref pc);
                int arity = code[pc++];
                PushCallArgs(context, framePointer, arity, ref pc);
                iterator =
                    PrologPrimitives.StackCall(implementation, arity, context).GetEnumerator();
            }
            break;

            default:
                Debug.Assert(false, "Bad call opcode");
                break;
            }
            context.SetStack(framePointer, iteratorRegister, iterator);
            return(failPC);
        }
Example #9
0
        internal PredicateInfo CheckForPredicateInfo(PredicateIndicator p)
        {
            PredicateInfo info = CheckForPredicateInfoInThisKB(p);

            if (info != null)
            {
                return(info);
            }
            foreach (KnowledgeBase import in imports)
            {
                if ((info = import.CheckForPredicateInfo(p)) != null)
                {
                    return(info);
                }
            }
            return(null);
        }
Example #10
0
 private static void SourceFromPredicateInfo(PredicateIndicator p, PredicateInfo predicateInfo, ISOPrologWriter writer)
 {
     foreach (var knowledgeBaseEntry in predicateInfo.Entries)
     {
         var       rule = (KnowledgeBaseRule)knowledgeBaseEntry;
         var       head = new Structure(p.Functor, rule.HeadArgs);
         Structure structure;
         if (rule.BodyGoals == null || rule.BodyGoals.Length == 0)
         {
             structure = head;
         }
         else
         {
             structure = new Structure(Symbol.Implication, head, Commafy(rule.BodyGoals));
         }
         writer.Write(structure);
         writer.WriteString(".\n");
     }
 }
Example #11
0
 void ReallyCheck()
 {
     WalkKB(KnowledgeBase.Global);
     foreach (var component in UnityEngine.Object.FindObjectsOfType <KB>())
     {
         WalkKB(component.KnowledgeBase);
     }
     foreach (var pair in checkerInfoTable)
     {
         var checkerInfo = pair.Value;
         if (!checkerInfo.Referenced)
         {
             KnowledgeBaseRule rule   = checkerInfo.DefiningRule;
             PredicateInfo     global = KnowledgeBase.Global.CheckForPredicateInfo(new PredicateIndicator(rule.HeadFunctor, rule.HeadArity));
             if (global == null || !global.External)
             {
                 rule.PrintWarning("{0}/{1} is never used.", rule.HeadFunctor, rule.HeadArity);
             }
         }
     }
 }
Example #12
0
 private static void SourceFromPredicateInfo(PredicateIndicator p, PredicateInfo predicateInfo, ISOPrologWriter writer)
 {
     foreach (var knowledgeBaseEntry in predicateInfo.Entries)
     {
         var rule = (KnowledgeBaseRule)knowledgeBaseEntry;
         var head = new Structure(p.Functor, rule.HeadArgs);
         Structure structure;
         if (rule.BodyGoals == null || rule.BodyGoals.Length == 0)
         {
             structure = head;
         }
         else
         {
             structure = new Structure(Symbol.Implication, head, Commafy(rule.BodyGoals));
         }
         writer.Write(structure);
         writer.WriteString(".\n");
     }
 }
Example #13
0
 internal PredicateInfo EntryForStoring(PredicateIndicator p)
 {
     PredicateInfo entry;
     if (!db.TryGetValue(p, out entry))
     {
         db[p] = entry = new PredicateInfo(p.Functor, p.Arity, this);
     }
     return entry;
 }
Example #14
0
 private void MarkReferenced(PredicateInfo predicate)
 {
     PredicateCheckerInfo(predicate).Referenced = true;
 }
Example #15
0
 private void MarkDefined(PredicateInfo predicate, KnowledgeBaseRule rule)
 {
     CheckerInfo predicateCheckerInfo = PredicateCheckerInfo(predicate);
     if (predicateCheckerInfo.DefiningRule == null)
         predicateCheckerInfo.DefiningRule = rule;
 }
Example #16
0
 private void MarkReferenced(PredicateInfo predicate)
 {
     PredicateCheckerInfo(predicate).Referenced = true;
 }
Example #17
0
        /// <summary>
        /// Prints the byte code for the rule to System.Console.
        /// </summary>
        public void Disassemble()
        {
            ushort pc = 0;

            while (pc < code.Length)
            {
                var opcode = (Opcode)code[pc++];
                Console.Write("L{0}: {1} ", pc - 1, opcode.ToString());
                switch (opcode)
                {
                case Opcode.MatchStructure:
                {
                    Symbol functor    = GetSymbol(ref pc);
                    int    arity      = code[pc++];
                    int    endofMatch = GetUShort(ref pc);
                    Console.Write("{0}/{1}, L{2}, ", functor.Name, arity, endofMatch);
                    DisassembleOperand(ref pc);
                }
                break;

                case Opcode.MatchVar:
                case Opcode.MatchVarFirst:
                {
                    if (opcode == Opcode.MatchVarFirst)
                    {
                        Console.Write("{0}, ", GetSymbol(ref pc));
                    }
                    byte register = code[pc++];
                    Console.Write("{0}, ", FormatRegister(register));
                    DisassembleOperand(ref pc);
                }
                break;

                case Opcode.MatchLiteral:
                {
                    Console.Write(GetLiteral(ref pc));
                    Console.Write(", ");
                    DisassembleOperand(ref pc);
                }
                break;

                case Opcode.BuildStructure:
                {
                    Console.Write(GetSymbol(ref pc));
                    Console.Write("/{0}, ", code[pc++]);
                    DisassembleOperand(ref pc);
                }
                break;

                case Opcode.BuildVar:
                {
                    Console.Write(GetSymbol(ref pc));
                    Console.Write(", ");
                    DisassembleOperand(ref pc);
                }
                break;

                case Opcode.BuildReg:
                {
                    byte reg = code[pc++];
                    Console.Write("{0}, ", FormatRegister(reg));
                    DisassembleOperand(ref pc);
                }
                break;

                case Opcode.BuildLiteral:
                {
                    Console.Write(GetLiteral(ref pc));
                    DisassembleOperand(ref pc);
                }
                break;

                case Opcode.Call:
                case Opcode.CallPrimitive:
                case Opcode.CallWokenGoals:
                {
                    Console.Write("{0}", FormatRegister(code[pc++]));
                    Console.Write(", {0}", FormatLabel(GetUShort(ref pc)));
                    Console.Write(", {0}", FormatLabel(GetUShort(ref pc)));
                    if (opcode != Opcode.CallWokenGoals)
                    {
                        int arity;
                        if (opcode == Opcode.Call)
                        {
                            PredicateInfo p = GetPredicate(ref pc);
                            Console.Write(", {0}/{1}", p.Name, p.Arity);
                            arity = p.Arity;
                        }
                        else
                        {
                            PrologPrimitives.PrimitiveImplementation impl = GetPrimitive(ref pc);
                            arity = code[pc++];
                            Console.Write(", {0}/{1}", PrologPrimitives.PrimitiveName(impl), arity);
                        }
                        while (arity-- > 0)
                        {
                            Console.Write(", ");
                            int arg = code[pc++];
                            if (arg < 0x80)
                            {
                                Console.Write("{0}", FormatRegister(arg));         // It's a register
                            }
                            else
                            {
                                // It's a literal
                                arg = ((arg & 0x7f) << 8) + code[pc++];
                                Console.Write(GlobalLiteralTable[arg]);
                            }
                        }
                    }
                }
                break;

                default:
                    throw new Exception("Unknown opcode " + opcode);
                }
                Console.WriteLine();
            }
        }
Example #18
0
        internal IEnumerable <CutState> FindClauses(Structure head, object body)
        {
            PredicateInfo i = CheckForPredicateInfo(head.PredicateIndicator);

            return((i == null)?CutStateSequencer.Fail():i.FindClauses(head, body));
        }
Example #19
0
        private PredicateInfo GetPredicate(ref ushort pc)
        {
            PredicateInfo pred = PredicateTable[GetUShort(ref pc)];

            return(pred);
        }
Example #20
0
        /// <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);
            }
        }