Esempio n. 1
0
 /// <summary>
 /// Creates a blank DB entry for the specified functor
 /// </summary>
 public PredicateInfo(Symbol functorName, int arity, KnowledgeBase kb)
 {
     Name = functorName;
     Arity = arity;
     Entries = new List<KnowledgeBaseEntry>();
     KnowledgeBase = kb;
 }
Esempio n. 2
0
 public static void DeclareOperator(int pri, Symbol type, Symbol op)
 {
     DeclareOperator(pri, Specifier(type.Name), op.Name);
 }
 /// <summary>
 /// Thrown to signal that a predicate used as a goal does not appear in the database.
 /// </summary>
 public UndefinedPredicateException(Symbol functor, int arity) 
     : this(new PredicateIndicator(functor, arity))
 { }
Esempio n. 4
0
 public static IList<object> Arglist(Symbol functor)
 {
     return Implementations[functor].Arglist();
 }
Esempio n. 5
0
 /// <summary>
 /// Creates a new logic variable
 /// </summary>
 public LogicVariable(Symbol name)
 {
     Name = name;
     UID = ++UIDCounter;
     mValue = this;
 }
Esempio n. 6
0
 PredicateInfo CheckForPredicateInfoInThisKB(Symbol functor, int arity)
 {
     return CheckForPredicateInfoInThisKB(new PredicateIndicator(functor, arity));
 }
Esempio n. 7
0
 /// <summary>
 /// Attempts to prove the specified goal.
 /// </summary>
 internal IEnumerable<CutState> Prove(Symbol functor, object[] args, PrologContext context, ushort parentFrame)
 {
     context.PushGoalStack(functor, args, parentFrame);
     context.NewStep();
     PrologPrimitives.PrimitiveImplementation prim;
     if (PrologPrimitives.Implementations.TryGetValue(functor, out prim))
     {
         return CallPrimitive(functor, prim, args, context);
     }
     return ProveFromDB(functor, args, context);
 }
Esempio n. 8
0
 internal static Structure PredicateIndicatorExpression(Symbol functor, int arity)
 {
     return new Structure(Symbol.Slash, functor, arity);
 }
Esempio n. 9
0
 public static void PushIndexicalBinding(Symbol name, object value, PrologContext context)
 {
     context.IndexicalBindingStack.Add(new KeyValuePair<Symbol, object>(name, value));
 }
Esempio n. 10
0
 private static Func<PrologContext, object> MakeLookup(Symbol name, object defaultValue)
 {
     return context =>
     {
         var bindingStack = context.IndexicalBindingStack;
         for (int i=bindingStack.Count-1; i>=0; i--)
             if (bindingStack[i].Key == name)
                 return bindingStack[i].Value;
         return defaultValue;
     };
 }
Esempio n. 11
0
 private static void MakeUserBindableIndexical(Symbol name, object defaultValue)
 {
     if (!Term.IsGround(defaultValue))
         throw new ArgumentException("Initial value of an indexical must be a ground term.");
     // We do CopyInstantiation out of paranoia that there might be some variables buried in defaultValue
     // that might get unbound in the future.
     DeclareIndexical(name, MakeLookup(name, CopyInstantiation(defaultValue)));
 }
Esempio n. 12
0
 public BadProcedureException(Symbol functor, int arity)
 {
     Procedure = new Structure(Symbol.Intern("/"), functor, arity);
 }
Esempio n. 13
0
 public GoalStackFrame(Symbol functor, object[] args, ushort parentFrame)
 {
     this.Functor = functor;
     this.Arguments = args;
     this.Parent = parentFrame;
 }
Esempio n. 14
0
        public void PushGoalStack(Symbol functor, object[] args, ushort parentFrame)
        {
            if (GoalStackDepth >= goalStack.Count)
            {
                goalStack.Add(new GoalStackFrame(functor, args, parentFrame));
                goalStackCurrentRules.Add(null);
            }
            else
            {
                goalStack[GoalStackDepth] = new GoalStackFrame(functor, args, parentFrame);
                goalStackCurrentRules[GoalStackDepth] = null;
            }

            GoalStackDepth++;
        }
Esempio n. 15
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);
            }
        }
Esempio n. 16
0
 static bool IsQuoteNeeded(Symbol s)
 {
     string name = s.Name;
     if (Char.IsUpper(name[0]))
         return true;
     foreach (char ch in name)
         if (Char.IsWhiteSpace(ch))
             return true;
     return false;
 }
Esempio n. 17
0
 public static Indexical Find(Symbol name)
 {
     Indexical result;
     return IndexicalTable.TryGetValue(name, out result) ? result : null;
 }
Esempio n. 18
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);
 }
Esempio n. 19
0
 public static void DeclareIndexical(Symbol name, Func<PrologContext, object> valueFunc)
 {
     IndexicalTable[name] = new Indexical(name, valueFunc);
 }
Esempio n. 20
0
 IEnumerable<CutState> CallPrimitive(Symbol functor, PrologPrimitives.PrimitiveImplementation handler, object[] args, PrologContext context)
 {
     if (Trace)
         context.TraceOutput("Goal: {0}", new Structure(functor, args));
     foreach (var state in handler(args, context))
     {
         if (Trace)
         context.TraceOutput((state == CutState.Continue) ? "Succeed: {0}" : "Cut: {0}", new Structure(functor, args));
         yield return state;
         if (Trace)
             context.TraceOutput("Retry: {0}", new Structure(functor, args));
     }
     if (Trace)
         context.TraceOutput("Fail: {0}", new Structure(functor, args));
     context.PopGoalStack();
 }
Esempio n. 21
0
 private Indexical(Symbol name, Func<PrologContext, object> valueFunc)
 {
     this.Name = name;
     this.valueFunc = valueFunc;
 }
Esempio n. 22
0
 public Parser(params object[] arg)
 {
     parser_arg = arg;
       symbol = new Symbol(this);
       strStartChar = '\u0027';
       strStartCharAlt = '\u0022';
       streamInPrefix = "";
       streamInPreLen = 0;
 }
Esempio n. 23
0
 private void WarnUndefined(KnowledgeBaseRule rule,Symbol functor,int arity)
 {
     rule.PrintWarning("{0}/{1} undefined", functor, arity);
 }
Esempio n. 24
0
        private static void DefinePrimitive(Symbol name, PrimitiveImplementation implementationDelegate,
                                            string manualSections, string docstring, params object[] arglist)
        {
            Implementations[name] = implementationDelegate;
            if (arglist.Length > 0 && (arglist[arglist.Length - 1] as string) == "...")
            {
                MinimumArity[name] = arglist.Length - 2;
                MaximumArity[name] = int.MaxValue;
            }
            else
            {
                MinimumArity[name] = MaximumArity[name] = arglist.Length;
                for (var i = arglist.Length - 1; i >= 0; i--)
                {
                    if (!((string)(arglist[i])).StartsWith("["))
                    {
                        // This is a non-optional parameter
                        MinimumArity[name] = i + 1;
                        break;
                    }
                }
            }

            DelegateUtils.NameProcedure(implementationDelegate, name.Name);
            Manual.AddToSections(manualSections, implementationDelegate);

            for (int i = 0; i < arglist.Length; i++)
                if (arglist[i] is string)
                    arglist[i] = Symbol.Intern((string) arglist[i]);

            DelegateUtils.Arglists[implementationDelegate] = arglist;
            DelegateUtils.Docstrings[implementationDelegate] = docstring;
        }
Esempio n. 25
0
 /// <summary>
 /// Adds assertion to GAMEOBJECT's knowledgebase.
 /// </summary>
 /// <param name="gameObject">Object whose knowledge base it should be added to</param>
 /// <param name="functor">Functor (i.e. predicate) of the assertion</param>
 /// <param name="args">Arguments to the functor</param>
 public static void Assert(this GameObject gameObject, Symbol functor, params object[] args)
 {
     gameObject.KnowledgeBase().AssertZ(new Structure(functor, args));
 }
Esempio n. 26
0
        // ReSharper restore InconsistentNaming
        
        private static IEnumerable<CutState> MapListInternal(Symbol functor, object[] args, object list1, object list2,
                                                             PrologContext context)
        {
            // maplist(_, [], []).
            // ReSharper disable UnusedVariable
#pragma warning disable 414, 168, 219
            foreach (var ignore in Term.Unify(null, list1))
                foreach (var ignore2 in Term.Unify(null, list2))
#pragma warning restore 414, 168, 219
                    // ReSharper restore UnusedVariable
                    yield return CutState.Continue;
            // maplist(P, [X | XT], [Y | YT]) :- call(P, X, Y), maplist(P, XT, YT).
            var x = new LogicVariable(SX);
            var xT = new LogicVariable(SXt);
            var y = new LogicVariable(SY);
            var yT = new LogicVariable(SYt);
            // ReSharper disable UnusedVariable
#pragma warning disable 414, 168, 219
            foreach (var ignore in Term.Unify(list1, new Structure(Symbol.PrologListConstructor, x, xT)))
                foreach (var ignore2 in Term.Unify(list2, new Structure(Symbol.PrologListConstructor, y, yT)))
#pragma warning restore 414, 168, 219
                {
                    // call(P, X, Y)
                    var realArgs = new object[args.Length + 2];
                    args.CopyTo(realArgs, 0);
                    realArgs[realArgs.Length - 2] = x;
                    realArgs[realArgs.Length - 1] = y;
#pragma warning disable 414, 168, 219
                    foreach (
                        var ignore3 in context.KnowledgeBase.Prove(functor, realArgs, context, context.CurrentFrame))
                        // maplist(P, XT, YT)
                        foreach (var ignore4 in MapListInternal(functor, args, xT, yT, context))
#pragma warning restore 414, 168, 219
                            // ReSharper restore UnusedVariable
                            yield return CutState.Continue;
                }
        }
Esempio n. 27
0
 /// <summary>
 /// Adds assertion to component's knowledgebase.
 /// </summary>
 /// <param name="component">Object whose knowledge base it should be added to</param>
 /// <param name="functor">Functor (i.e. predicate) of the assertion</param>
 /// <param name="args">Arguments to the functor</param>
 public static void Assert(this Component component, Symbol functor, params object[] args)
 {
     component.KnowledgeBase().AssertZ(new Structure(functor, args));
 }
Esempio n. 28
0
 public CSVParser(Symbol functor, char delimiter, PositionTrackingTextReader reader)
 {
     this.functor = functor;
     this.delimiter = delimiter;
     this.reader = reader;
 }
Esempio n. 29
0
 public PredicateIndicator(Symbol functor, int arity)
 {
     this.Functor = functor;
     this.Arity = arity;
 }
Esempio n. 30
0
 static object ResolveNamedValue(Symbol nameSymbol)
 {
     if (nameSymbol == Symbol.Global)
         return KnowledgeBase.Global;
     return Indexical.Find(nameSymbol) ?? ResolveNamedString(nameSymbol.Name);
 }
Esempio n. 31
0
 PredicateInfo CheckForPredicateInfoInThisKB(Symbol functor, int arity)
 {
     return CheckForPredicateInfoInThisKB(new PredicateIndicator(functor, arity));
 }