Inheritance: Prolog.AlphaConvertibleTerm
Example #1
0
 private static bool TryNonExclusiveQueryEnumeratedParent(
     out ELNode foundNode,
     out ELNodeEnumerator enumerator,
     object key,
     LogicVariable v,
     ELNodeEnumerator parentEnumerator)
 {
     // Enumerated parent path
     // NonUniqueParent/Something
     foundNode = null;
     if (v == null)
     {
         // NonUniqueParent/Key
         // Enumerate parent, then do deterministic lookup for child.
         enumerator = new ELNodeEnumeratorFixedChildFromParentEnumerator(parentEnumerator, key);
         return true;
     }
     if (parentEnumerator.BindsVar(v))
     {
         // We're doing a search for a variable that's aready bound.
         enumerator = new ELNodeEnumeratorPreboundVariable(parentEnumerator, v, false);
         return true;
     }
     // NonUniqueParent/Variable
     // Enumerate both parent and child.
     enumerator = new ELNodeEnumeratorLogicVariableFromParentEnumerator(parentEnumerator, v);
     return true;
 }
Example #2
0
        private static bool TryNonExclusiveQueryDeterministicParent(
            out ELNode foundNode,
            out ELNodeEnumerator enumerator,
            ELNode parentNode,
            object key,
            LogicVariable v)
        {
            // Deterministic parent path
            // The expression is UniqueParent/Something
            if (parentNode.IsExclusive)
            {
                throw new ELNodeExclusionException("Non-exclusive query of an exclusive node", parentNode, key);
            }

            if (v == null)
            {
                // fully deterministic path
                // UniqueParent/Key corresponds to at most one ELNode.
                enumerator = null;
                return parentNode.TryLookup(key, out foundNode);
            }
            // UniqueParent/Variable, so do a singly-nested iteration.
            foundNode = null;
            enumerator = new ELNodeEnumeratorLogicVariableFromNode(parentNode, v);
            return true;
        }
Example #3
0
        private static Structure ExpandDCGRuleBody(object goal, LogicVariable start, out LogicVariable rest)
        {
            var t = goal as Structure;

            if (t != null && t.IsFunctor(Symbol.Comma, 2))
            {
                var t2 = t.Argument(0) as Structure;
                if (t2 != null && t2.IsFunctor(Symbol.PrologListConstructor, 2))
                {
                    return(ExpandDCGLiteral(t2, t.Argument(1), start, out rest));
                }
                if (t2 != null && t2.IsFunctor(Symbol.CurlyBrackets, 1))
                {
                    return(ExpandDCGCurlyBracketExpression(t2.Argument(0), t.Argument(1), start, out rest));
                }
                var intermediate = new LogicVariable(LSym);
                return(new Structure(Symbol.Comma,
                                     ExpandDCGRuleGoal(t.Argument(0), start, intermediate),
                                     ExpandDCGRuleBody(t.Argument(1), intermediate, out rest)));
            }
            if (t != null && t.IsFunctor(Symbol.CurlyBrackets, 1))
            {
                Structure cg = t.Argument(0) as Structure ?? new Structure(Symbol.Call, t.Argument(0));
                rest = start;
                return(cg);
            }
            return(ExpandDCGRuleTrailingGoal(goal, start, out rest));
        }
Example #4
0
        static object CopyInstantiation(object term, Dictionary <LogicVariable, LogicVariable> subs)
        {
            term = Deref(term);
            var l = term as LogicVariable;

            if (l != null)
            {
                LogicVariable sub;
                if (subs.TryGetValue(l, out sub))
                {
                    return(sub);
                }
                var l2 = new LogicVariable(l.Name);
                subs[l] = l2;
                return(l2);
            }
            var t = term as Structure;

            if (t == null)
            {
                return(term);
            }
            var newArgs = new object[t.Arguments.Length];

            for (int i = 0; i < newArgs.Length; i++)
            {
                newArgs[i] = CopyInstantiation(t.Argument(i), subs);
            }
            return(new Structure(t.Functor, newArgs));
        }
Example #5
0
 public ELNodeEnumeratorBindEnumeratedNodesToVariable(ELNodeEnumerator nodeEnumerator, LogicVariable variableToBind)
 {
     this.nodeEnumerator = nodeEnumerator;
     this.variableToBind = variableToBind;
     if (nodeEnumerator.BindsVar(variableToBind))
         throw new InvalidOperationException("Variable appears on both the LHS and RHS of >>: "+ variableToBind.Name);
 }
Example #6
0
        private object TermExpansion(object unexpanded)
        {
            if (CheckForPredicateInfoInThisKB(term_expansion, 2) == null && Global.CheckForPredicateInfoInThisKB(term_expansion, 2) == null)
                // Don't bother if not defined.
                return unexpanded;

            // Attempt to expand it
            var expanded = new LogicVariable(expansion);
            // Try this KB
            if (CheckForPredicateInfoInThisKB(term_expansion, 2) != null)
                // ReSharper disable UnusedVariable
#pragma warning disable 0168
                foreach (var ignore in Prove(new Structure(term_expansion, unexpanded, expanded)))
#pragma warning restore 0168
                {
                    return Term.CopyInstantiation(expanded);
                }

            // Try the global KB
            if (this != Global && Global.CheckForPredicateInfoInThisKB(term_expansion, 2) != null)
#pragma warning disable 0168
                foreach (var ignore in Global.Prove(new Structure(term_expansion, unexpanded, expanded)))
#pragma warning restore 0168
                // ReSharper restore UnusedVariable
                {
                    return Term.CopyInstantiation(expanded);
                }


            // Expansion failed, so use unexpanded version.
            return unexpanded;
        }
Example #7
0
        IEnumerable <bool> UnifyMetaVar(Metastructure m, LogicVariable l)
        {
            System.Diagnostics.Debug.Assert(l.MetaBinding == null);
            l.Value = this;
            IEnumerable <CutState> goal;

            mValue = m.MetaVarUnify(l, out goal);
            try
            {
#pragma warning disable 414, 168, 219
                // ReSharper disable UnusedVariable
                foreach (var ignore in goal)
                // ReSharper restore UnusedVariable
#pragma warning restore 414, 168, 219
                {
                    yield return(false);
                }
            }
            finally
            {
                // Reset our own binding to its previous binding
                mValue = m;
                // Reset binding of l
                l.mValue = l;
                //l.IsBound = false;
            }
        }
        internal override IEnumerable <CutState> Prove(object[] args, PrologContext context, ushort parentFrame)
        {
            object[] goal1Args = null;
            var      newVars   = new LogicVariable[FreeVariables.Count];

            object[] newArgs = Term.AlphaConvertArglist(HeadArgs, FreeVariables, newVars, context, true);
            // ReSharper disable UnusedVariable
#pragma warning disable 414, 168, 219
            foreach (bool ignore in Term.UnifyArraysFast(args, newArgs, context))
#pragma warning restore 414, 168, 219
            {
                if (goal1Args == null)
                {
                    goal1Args = Term.AlphaConvertArglist(BodyGoals[0].Arguments, FreeVariables, newVars, context, false);
                }

#pragma warning disable 414, 168, 219
                foreach (CutState ignoreFreeze in context.ProveAllWokenGoals())
#pragma warning restore 414, 168, 219
                {
                    // ReSharper restore UnusedVariable
                    foreach (CutState state1 in context.KnowledgeBase.Prove(BodyGoals[0].Functor, goal1Args, context, parentFrame))
                    {
                        yield return(state1);
                    }
                }
            }
        }
Example #9
0
 internal override Metastructure MetaVarUnify(LogicVariable l, PrologContext context)
 {
     if (DelayedGoal != null)
     {
         context.WakeUpGoal(DelayedGoal);
     }
     return(MakeSuspension(null, FrozenGoal));
 }
Example #10
0
 /// <summary>
 /// True if the specified goal is provable within this KnowledgeBase.
 /// </summary>
 /// <param name="result">Value of variable to return</param>
 /// <param name="goal">Goal to attempt to prove</param>
 /// <param name="throwOnFailure">If true, SolveFor will throw a GoalException if the goal fails</param>
 /// <param name="thisValue">Value to give ot the indexical $this during execution</param>
 /// <returns>Success</returns>
 public object SolveFor(LogicVariable result, object goal, object thisValue, bool throwOnFailure = true)
 {
     if (this.IsTrue(Term.Structurify(goal, "Argument to SolveFor() should be a valid Prolog goal."), thisValue))
         return Term.CopyInstantiation(result);
     if (throwOnFailure)
         throw new GoalException(goal, "Goal is unsatisfiable");
     return null;
 }
Example #11
0
        /// <summary>
        /// All we have to do here is check whether this is one of the variables we're looking for.
        /// </summary>
        public override object AlphaConvert(List <LogicVariable> oldVars, LogicVariable[] newVars, PrologContext context, bool evalIndexicals)
        {
            var index = oldVars.IndexOf(this);

            if (index < 0)
            {
                return(this);
            }
            return(newVars[index] ?? (newVars[index] = new LogicVariable(this.Name)));
        }
Example #12
0
                public byte InsureRegisterAndLock(LogicVariable var)
                {
                    var info = this[var];

                    if (info.register == NoRegister)
                    {
                        AllocateRegister(info);
                    }
                    info.LockInRegister = true;
                    return(info.register);
                }
Example #13
0
 public VariableInfo this[LogicVariable variable]
 {
     get
     {
         VariableInfo result;
         if (!database.TryGetValue(variable, out result))
         {
             database[variable] = result = new VariableInfo();
         }
         return(result);
     }
 }
Example #14
0
 /// <summary>
 /// Creates a PrologContext that can for at most the specified number of steps.
 /// </summary>
 public PrologContext(KnowledgeBase kb, int stepLimit)
 {
     StepsRemaining        = stepLimit;
     goalStack             = new List <GoalStackFrame>();
     goalStackCurrentRules = new List <KnowledgeBaseEntry>();
     GoalStackDepth        = 0;
     KnowledgeBase         = kb;
     traceVariables        = new LogicVariable[256];
     traceValues           = new object[256];
     tracePointer          = 0;
     IndexicalBindingStack = new List <KeyValuePair <Symbol, object> >();
     isFree = true;
 }
Example #15
0
        private IEnumerable <CutState> EnumerateArg1Driver(LogicVariable arg1, T2 arg2, PrologContext context)
        {
            int tracePointer = context.MarkTrace();

            foreach (var newValue in arg1Enumerator(arg2))
            {
                arg1.UnifyWithAtomicConstant(newValue, context);

                yield return(CutState.Continue);

                context.RestoreVariables(tracePointer);
            }
        }
Example #16
0
 /// <summary>
 /// Creates a PrologContext that can for at most the specified number of steps.
 /// </summary>
 public PrologContext(KnowledgeBase kb, int stepLimit)
 {
     StepsRemaining = stepLimit;
     goalStack = new List<GoalStackFrame>();
     goalStackCurrentRules = new List<KnowledgeBaseEntry>();
     GoalStackDepth = 0;
     KnowledgeBase = kb;
     traceVariables = new LogicVariable[256];
     traceValues = new object[256];
     tracePointer = 0;
     IndexicalBindingStack = new List<KeyValuePair<Symbol, object>>();
     isFree = true;
 }
Example #17
0
        private IEnumerable <CutState> EnumerateBothDriver(LogicVariable arg1, LogicVariable arg2, PrologContext context)
        {
            int tracePointer = context.MarkTrace();

            foreach (var pair in doubleEnumerator())
            {
                arg1.UnifyWithAtomicConstant(pair.Arg1, context);
                arg2.UnifyWithAtomicConstant(pair.Arg2, context);

                yield return(CutState.Continue);

                context.RestoreVariables(tracePointer);
            }
        }
        internal override IEnumerable <CutState> Prove(object[] args, PrologContext context, ushort parentFrame)
        {
            var newVars = new LogicVariable[FreeVariables.Count];

            object[] newArgs = Term.AlphaConvertArglist(HeadArgs, FreeVariables, newVars, context, true);
            // ReSharper disable UnusedVariable
#pragma warning disable 414, 168, 219
            foreach (bool ignore in Term.UnifyArrays(args, newArgs))
#pragma warning restore 414, 168, 219
            {
                // ReSharper restore UnusedVariable
                yield return(CutState.Continue);
            }
        }
Example #19
0
 /// <summary>
 /// Saves the current value of a variable on the trace (i.e. the undo stack).
 /// </summary>
 public void SaveVariable(LogicVariable lvar)
 {
     if (tracePointer == traceVariables.Length)
     {
         var newTraceVariables = new LogicVariable[traceVariables.Length * 2];
         var newTraceValues    = new object[traceVariables.Length * 2];
         traceVariables.CopyTo(newTraceVariables, 0);
         traceValues.CopyTo(newTraceValues, 0);
         traceVariables = newTraceVariables;
         traceValues    = newTraceValues;
     }
     traceVariables[tracePointer] = lvar;
     traceValues[tracePointer]    = lvar.mValue;
     tracePointer++;
 }
Example #20
0
        private static Structure ExpandDCGRuleHead(object expression, LogicVariable start, LogicVariable rest)
        {
            var t = expression as Structure;
            var s = expression as Symbol;

            if (t != null)
            {
                return(t.AddArguments(start, rest));
            }
            if (s != null)
            {
                return(new Structure(s, start, rest));
            }
            throw new ArgumentException("Invalid expression in grammar rule: " + ToStringInPrologFormat(expression), "expression");
        }
Example #21
0
        // ReSharper disable InconsistentNaming
        private Structure ExpandDCGRule()
        {
            var start = new LogicVariable(StartSym);

            if (Argument(1) == null) // name --> [].
            {
                return(ExpandDCGRuleHead(Argument(0), start, start));
            }
            LogicVariable rest;
            Structure     body = ExpandDCGRuleBody(Argument(1), start, out rest);

            return(new Structure(Symbol.Implication,
                                 ExpandDCGRuleHead(Argument(0), start, rest),
                                 body));
        }
Example #22
0
        private void WritePrologList(StringBuilder s)
        {
            s.Append('[');
            bool          first   = true;
            object        current = Canonicalize(this);
            LogicVariable l       = current as LogicVariable;

            if (l != null && l.IsBound)
            {
                current = l.Value;
            }
            while (current != null)
            {
                Structure t = current as Structure;

                if (first)
                {
                    first = false;
                }
                else if (t == null)
                {
                    s.Append(" | ");
                }
                else
                {
                    s.Append(", ");
                }
                if (t == null)
                {
                    Write(s, current);
                    current = null;
                }
                else
                {
                    if (t.IsFunctor(Symbol.PrologListConstructor, 2))
                    {
                        Write(s, t.Argument(0));
                        current = t.Argument(1);
                    }
                    else
                    {
                        WriteAndPossiblyParenthesize(s, current);
                        current = null;
                    }
                }
            }
            s.Append(']');
        }
Example #23
0
 static void AddBinding(LogicVariable lv, object value, ref List <LogicVariable> vars, ref List <object> values)
 {
     if (vars == null)
     {
         vars = new List <LogicVariable> {
             lv
         };
         values = new List <object> {
             value
         };
     }
     else
     {
         vars.Add(lv);
         values.Add(value);
     }
 }
Example #24
0
        private static Structure ExpandDCGLiteral(Structure literal, object afterward, LogicVariable start, out LogicVariable rest)
        {
            if (literal == null)
            {
                return(ExpandDCGRuleBody(afterward, start, out rest));
            }
            if (literal.Argument(1) == null && afterward == null)
            {
                rest = new LogicVariable(RestSym);
                return(new Structure(DefiniteClauseCapitalC, start, literal.Argument(0), rest));
            }
            var intermediate = new LogicVariable(LSym);

            return(new Structure(Symbol.Comma,
                                 new Structure(DefiniteClauseCapitalC, start, literal.Argument(0), intermediate),
                                 ExpandDCGLiteral((Structure)literal.Argument(1), afterward, intermediate, out rest)));
        }
Example #25
0
        private static bool TryExclusiveQueryEnumeratedParent(
            out ELNode foundNode,
            out ELNodeEnumerator enumerator,
            ELNodeEnumerator parentEnumerator,
            object key,
            LogicVariable v)
        {
            // Non-deterministic parent path
            // NonUniqueParent:Something
            foundNode = null;

            enumerator = (v == null)
                ? new ELNodeEnumeratorEnumerateParentAndLookupExclusiveKey(parentEnumerator, key)
                : (parentEnumerator.BindsVar(v)? (ELNodeEnumerator)new ELNodeEnumeratorPreboundVariable(parentEnumerator, v, true)
                                                 : new ELNodeEnumeratorEnumerateParentAndBindVariable(parentEnumerator, v));
            return true;
        }
Example #26
0
        private static bool TryExclusiveQuery(
            out ELNode foundNode,
            out ELNodeEnumerator enumerator,
            ELNode parentNode,
            ELNodeEnumerator parentEnumerator,
            object key,
            LogicVariable v)
        {
            //
            // Expression is Parent:Something
            //
            if (parentNode != null)
            {
                return TryExclusiveQueryDeterministicParent(out foundNode, out enumerator, parentNode, key, v);
            }

            return TryExclusiveQueryEnumeratedParent(out foundNode, out enumerator, parentEnumerator, key, v);
        }
Example #27
0
        private static Structure ExpandDCGRuleGoal(object expression, LogicVariable start, LogicVariable rest)
        {
            var t = expression as Structure;
            var s = expression as Symbol;

            if (t != null)
            {
                if (t.IsFunctor(Symbol.PrologListConstructor, 2))
                {
                    return(ExpandDCGLiteral(t, null, start, out rest));
                }
                return(t.AddArguments(start, rest));
            }
            if (s != null)
            {
                return(new Structure(s, start, rest));
            }
            throw new ArgumentException("Invalid expression in grammar rule: " + ToStringInPrologFormat(expression), "expression");
        }
Example #28
0
 public static bool TryNodeBindingQuery(
     out ELNodeEnumerator enumerator,
     object nodeExpression,
     LogicVariable variableToBind,
     PrologContext context)
 {
     // Decode the node expression
     ELNode foundNode;
     ELNodeEnumerator nodeEnumerator;
     if (!TryQuery(nodeExpression, context, out foundNode, out nodeEnumerator))
     {
         // Parent failed, so we fail
         enumerator = null;
         return false;
     }
     enumerator = (foundNode != null)
         ? (ELNodeEnumerator)new ELNodeEnumeratorBindFixedNodeToVariable(foundNode, variableToBind)
         : new ELNodeEnumeratorBindEnumeratedNodesToVariable(nodeEnumerator, variableToBind);
     return true;
 }
Example #29
0
 public static bool TryNodeBindingQuery(
     out ELNodeEnumerator enumerator,
     object nodeExpression,
     LogicVariable variableToBind,
     PrologContext context)
 {
     // Decode the node expression
     ELNode foundNode;
     ELNodeEnumerator nodeEnumerator;
     if (!TryQuery(nodeExpression, context, out foundNode, out nodeEnumerator))
     {
         // Parent failed, so we fail
         enumerator = null;
         return false;
     }
     enumerator = (foundNode != null)
         ? (ELNodeEnumerator)new ELNodeEnumeratorBindFixedNodeToVariable(foundNode, variableToBind)
         : new ELNodeEnumeratorBindEnumeratedNodesToVariable(nodeEnumerator, variableToBind);
     return true;
 }
Example #30
0
        private static Structure ExpandDCGCurlyBracketExpression(object goalExpression, object afterward, LogicVariable start, out LogicVariable rest)
        {
            var t = goalExpression as Structure;

            if (afterward == null)
            {
                if (t == null)
                {
                    t = new Structure(Symbol.Call, goalExpression);
                }
                rest = start;
                return(t);
            }
            if (t != null && t.IsFunctor(Symbol.Comma, 2))
            {
                return(new Structure(Symbol.Comma,
                                     t.Argument(0),
                                     ExpandDCGCurlyBracketExpression(t.Argument(1), afterward, start, out rest)));
            }
            return(new Structure(Symbol.Comma,
                                 goalExpression,
                                 ExpandDCGRuleBody(afterward, start, out rest)));
        }
Example #31
0
        private static bool TryExclusiveQueryDeterministicParent(
            out ELNode foundNode,
            out ELNodeEnumerator enumerator,
            ELNode parentNode,
            object key,
            LogicVariable v)
        {
            // Deterministic parent path
            // UniqueParent:Something

            if (parentNode.IsNonExclusive)
            {
                throw new ELNodeExclusionException("Exclusive query of an non-exclusive node", parentNode, key);
            }

            if (v == null)
            {
                // Deterministic child path
                // UniqueParent:Key
                enumerator = null;
                return parentNode.TryLookup(key, out foundNode);
            }

            // Enumerated child path
            // UniqueParent:Variable
            if (parentNode.Children.Count > 0)
            {
                foundNode = null;
                enumerator = new ELNodeEnumeratorBindAndUnbindVariable(parentNode.Children[0], v);
                return true;
            }

            // parentNode is exclusive, but is childless, so we can't match.
            foundNode = null;
            enumerator = null;
            return false;
        }
Example #32
0
 /// <summary>
 /// Called after the variable bound to this Metastructure is unified with an unbound variable
 /// that is not (itself) bound to a Metastructure.
 /// </summary>
 /// <param name="them">The logic variable with which to unify</param>
 /// <param name="filter">Test for whether the merging succeeded.  Generally a woken goal.</param>
 /// <returns>The Metastructure to bind to the newly aliased variables.</returns>
 public Metastructure MetaVarUnify(LogicVariable them, out IEnumerable<CutState> filter)
 {
     filter = Prover(DelayedGoal);
     return MakeSuspension(null, FrozenGoal);
 }
Example #33
0
 /// <summary>
 /// Called after the variable bound to this Metastructure is unified with an unbound variable
 /// that is not (itself) bound to a Metastructure.
 /// </summary>
 /// <param name="l">The logic variable with which to Unify.</param>
 /// <param name="context">Context in which to execute suspended goals.</param>
 /// <returns>The Metastructure to bind to the newly aliased variables.</returns>
 public Metastructure MetaVarUnify(LogicVariable l, PrologContext context)
 {
     if (DelayedGoal != null)
         context.WakeUpGoal(DelayedGoal);
     return MakeSuspension(null, FrozenGoal);
 }
Example #34
0
 public ELNodeEnumeratorPreboundVariable(ELNodeEnumerator parentEnumerator, LogicVariable variable, bool exclusive)
 {
     this.parentEnumerator = parentEnumerator;
     this.variable = variable;
     this.exclusive = exclusive;
 }
Example #35
0
 public override bool BindsVar(LogicVariable v)
 {
     return parentEnumerator.BindsVar(v);
 }
Example #36
0
 public ELNodeEnumeratorBindEnumeratedNodesToVariable(ELNodeEnumerator nodeEnumerator, LogicVariable variableToBind)
 {
     this.nodeEnumerator = nodeEnumerator;
     this.variableToBind = variableToBind;
     if (nodeEnumerator.BindsVar(variableToBind))
         throw new InvalidOperationException("Variable appears on both the LHS and RHS of >>: "+ variableToBind.Name);
 }
Example #37
0
 public override bool BindsVar(LogicVariable v)
 {
     return v == this.variable || parentEnumerator.BindsVar(v);
 }
Example #38
0
 public ELNodeEnumeratorLogicVariableFromNode(ELNode parentNode, LogicVariable v)
 {
     this.parentNode = parentNode;
     this.variable = v;
     childIndex = parentNode.Children.Count - 1;
 }
Example #39
0
 /// <summary>
 /// Indicates a variable that shouldn't be bound is bound
 /// </summary>
 public InstantiatedVariableException(LogicVariable offendingVariable, string message)
     : base(offendingVariable, message)
 { }
Example #40
0
 public ELNodeEnumeratorEnumerateParentAndBindVariable(ELNodeEnumerator parentEnumerator, LogicVariable variable)
 {
     this.parentEnumerator = parentEnumerator;
     this.variable = variable;
 }
        internal override IEnumerable <CutState> Prove(object[] args, PrologContext context, ushort parentFrame)
        {
            object[] goal1Args = null;
            object[] goal2Args = null;
            object[] goal3Args = null;
            object[] goal4Args = null;
            object[] goal5Args = null;
            object[] goal6Args = null;
            object[] goal7Args = null;
            object[] goal8Args = null;

            var newVars = new LogicVariable[FreeVariables.Count];

            object[] newArgs = Term.AlphaConvertArglist(HeadArgs, FreeVariables, newVars, context, true);
// ReSharper disable UnusedVariable
            foreach (bool ignore in Term.UnifyArraysFast(args, newArgs, context))
            {
                if (goal1Args == null)
                {
                    goal1Args = Term.AlphaConvertArglist(BodyGoals[0].Arguments, FreeVariables, newVars, context, false);
                }

                foreach (CutState ignoreFreeze in context.ProveAllWokenGoals())
                {
                    // ReSharper restore UnusedVariable
                    foreach (CutState state1 in context.KnowledgeBase.Prove(BodyGoals[0].Functor, goal1Args, context, parentFrame))
                    {
                        if (state1 == CutState.ForceFail)
                        {
                            yield return(CutState.ForceFail);
                        }
                        if (goal2Args == null)
                        {
                            goal2Args = Term.AlphaConvertArglist(BodyGoals[1].Arguments, FreeVariables, newVars, context, false);
                        }

                        foreach (CutState state2 in context.KnowledgeBase.Prove(BodyGoals[1].Functor, goal2Args, context, parentFrame))
                        {
                            if (state2 == CutState.ForceFail)
                            {
                                yield return(CutState.ForceFail);
                            }
                            if (goal3Args == null)
                            {
                                goal3Args = Term.AlphaConvertArglist(BodyGoals[2].Arguments, FreeVariables, newVars, context, false);
                            }

                            foreach (CutState state3 in context.KnowledgeBase.Prove(BodyGoals[2].Functor, goal3Args, context, parentFrame))
                            {
                                if (state3 == CutState.ForceFail)
                                {
                                    yield return(CutState.ForceFail);
                                }
                                if (goal4Args == null)
                                {
                                    goal4Args = Term.AlphaConvertArglist(BodyGoals[3].Arguments, FreeVariables, newVars, context, false);
                                }

                                foreach (CutState state4 in context.KnowledgeBase.Prove(BodyGoals[3].Functor, goal4Args, context, parentFrame))
                                {
                                    if (state4 == CutState.ForceFail)
                                    {
                                        yield return(CutState.ForceFail);
                                    }
                                    if (goal5Args == null)
                                    {
                                        goal5Args = Term.AlphaConvertArglist(BodyGoals[4].Arguments, FreeVariables, newVars, context, false);
                                    }

                                    foreach (CutState state5 in context.KnowledgeBase.Prove(BodyGoals[4].Functor, goal5Args, context, parentFrame))
                                    {
                                        if (state5 == CutState.ForceFail)
                                        {
                                            yield return(CutState.ForceFail);
                                        }
                                        if (goal6Args == null)
                                        {
                                            goal6Args = Term.AlphaConvertArglist(BodyGoals[5].Arguments, FreeVariables, newVars, context, false);
                                        }

                                        foreach (CutState state6 in context.KnowledgeBase.Prove(BodyGoals[5].Functor, goal6Args, context, parentFrame))
                                        {
                                            if (state6 == CutState.ForceFail)
                                            {
                                                yield return(CutState.ForceFail);
                                            }
                                            if (goal7Args == null)
                                            {
                                                goal7Args = Term.AlphaConvertArglist(BodyGoals[6].Arguments, FreeVariables, newVars, context, false);
                                            }

                                            foreach (CutState state7 in context.KnowledgeBase.Prove(BodyGoals[6].Functor, goal7Args, context, parentFrame))
                                            {
                                                if (state7 == CutState.ForceFail)
                                                {
                                                    yield return(CutState.ForceFail);
                                                }
                                                if (goal8Args == null)
                                                {
                                                    goal8Args = Term.AlphaConvertArglist(BodyGoals[7].Arguments, FreeVariables, newVars, context, false);
                                                }

                                                foreach (CutState state8 in context.KnowledgeBase.Prove(BodyGoals[7].Functor, goal8Args, context, parentFrame))
                                                {
                                                    yield return(state8);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #42
0
 /// <summary>
 /// Finds the value of result in the first solution when proving goal within this Component's GameObject's knowledge base.
 /// </summary>
 /// <param name="gameObject">GameObject whose KB should be queried.</param>
 /// <param name="result">Value of the variable to solve for</param>
 /// <param name="functor">Functor of the goal.</param>
 /// <param name="args">Arguments for the goal.</param>
 /// <returns>Value found for the variable.</returns>
 public static object SolveFor(this GameObject gameObject, LogicVariable result, string functor, params object[] args)
 {
     return gameObject.SolveFor(result, new Structure(functor, args));
 }
Example #43
0
 /// <summary>
 /// Finds the value of result in the first solution when proving goal within this Component's GameObject's knowledge base.
 /// </summary>
 /// <param name="component">Component whose KB should be queried.</param>
 /// <param name="result">Value of the variable to solve for</param>
 /// <param name="functor">Functor of the goal.</param>
 /// <param name="args">Arguments for the goal.</param>
 /// <returns>Value found for the variable.</returns>
 public static object SolveFor(this Component component, LogicVariable result, string functor, params object[] args)
 {
     return component.SolveFor(result, new Structure(functor, args));
 }
        internal override IEnumerable<CutState> Prove(object[] args, PrologContext context, ushort parentFrame)
        {
            object[] goal1Args = null;
            object[] goal2Args = null;
            var newVars = new LogicVariable[FreeVariables.Count];
            object[] newArgs = Term.AlphaConvertArglist(HeadArgs, FreeVariables, newVars, context, true);
            // ReSharper disable UnusedVariable
            #pragma warning disable 414, 168, 219
            foreach (bool ignore in Term.UnifyArraysFast(args, newArgs, context))
            #pragma warning restore 414, 168, 219
            {
                if (goal1Args == null)
                    goal1Args = Term.AlphaConvertArglist(BodyGoals[0].Arguments, FreeVariables, newVars, context, false);

            #pragma warning disable 414, 168, 219
                foreach (CutState ignoreFreeze in context.ProveAllWokenGoals())
                    // ReSharper restore UnusedVariable
                    foreach (CutState state1 in context.KnowledgeBase.Prove(BodyGoals[0].Functor, goal1Args, context, parentFrame))
            #pragma warning restore 414, 168, 219
                    {
                    if (state1 == CutState.ForceFail) yield return CutState.ForceFail;
                    if (goal2Args == null)
                        goal2Args = Term.AlphaConvertArglist(BodyGoals[1].Arguments, FreeVariables, newVars, context, false);

                    foreach (CutState state2 in context.KnowledgeBase.Prove(BodyGoals[1].Functor, goal2Args, context, parentFrame))
                        yield return state2;
                }
            }
        }
 /// <summary>
 /// Recopy the term to replace variables.  If term contains no variables, no recopying is done.
 /// </summary>
 /// <param name="oldVars">Variables to be replaced</param>
 /// <param name="newVars">The corresponding variables that are replacing the oldVars</param>
 /// <param name="context">PrologContext to evaluating indexicals</param>
 /// <param name="evalIndexicals">If true, any indexicals will be replaced with their values.</param>
 /// <returns>Converted term or original term if not conversion necessary</returns>
 public abstract object AlphaConvert(
     List<LogicVariable> oldVars,
     LogicVariable[] newVars,
     PrologContext context,
     bool evalIndexicals);
Example #46
0
 public override bool BindsVar(LogicVariable v)
 {
     return v == this.variable;
 }
Example #47
0
 /// <summary>
 /// Indicates a variable that should/shouldn't be bound isn't/is bound
 /// </summary>
 public InstantiationException(LogicVariable offendingVariable, string message)
     : base(message)
 {
     Variable = offendingVariable;
 }
Example #48
0
 public ELNodeEnumeratorLogicVariableFromParentEnumerator(ELNodeEnumerator parentEnumerator, LogicVariable v)
 {
     this.parentEnumerator = parentEnumerator;
     this.variable = v;
     childIndex = -1;
 }
 internal override IEnumerable<CutState> Prove(object[] args, PrologContext context, ushort parentFrame)
 {
     var newVars = new LogicVariable[FreeVariables.Count];
     object[] newArgs = Term.AlphaConvertArglist(HeadArgs, FreeVariables, newVars, context, true);
     // ReSharper disable UnusedVariable
     #pragma warning disable 414, 168, 219
     foreach (bool ignore in Term.UnifyArrays(args, newArgs))
     #pragma warning restore 414, 168, 219
         // ReSharper restore UnusedVariable
         yield return CutState.Continue;
 }
Example #50
0
 public ELNodeEnumeratorBindAndUnbindVariable(ELNode child, LogicVariable v)
 {
     this.child = child;
     this.variable = v;
 }
        internal override IEnumerable<CutState> Prove(object[] args, PrologContext context, ushort parentFrame)
        {
            object[] goal1Args = null;
            object[] goal2Args = null;
            object[] goal3Args = null;
            object[] goal4Args = null;
            object[] goal5Args = null;
            object[] goal6Args = null;
            object[] goal7Args = null;
            object[] goal8Args = null;

            var newVars = new LogicVariable[FreeVariables.Count];
            object[] newArgs = Term.AlphaConvertArglist(HeadArgs, FreeVariables, newVars, context, true);
            // ReSharper disable UnusedVariable
            foreach (bool ignore in Term.UnifyArraysFast(args, newArgs, context))
            {
                if (goal1Args == null)
                    goal1Args = Term.AlphaConvertArglist(BodyGoals[0].Arguments, FreeVariables, newVars, context, false);

                foreach (CutState ignoreFreeze in context.ProveAllWokenGoals())
                    // ReSharper restore UnusedVariable
                    foreach (CutState state1 in context.KnowledgeBase.Prove(BodyGoals[0].Functor, goal1Args, context, parentFrame))
                {
                    if (state1 == CutState.ForceFail) yield return CutState.ForceFail;
                    if (goal2Args == null)
                        goal2Args = Term.AlphaConvertArglist(BodyGoals[1].Arguments, FreeVariables, newVars, context, false);

                    foreach (CutState state2 in context.KnowledgeBase.Prove(BodyGoals[1].Functor, goal2Args, context, parentFrame))
                    {
                        if (state2 == CutState.ForceFail) yield return CutState.ForceFail;
                        if (goal3Args == null)
                            goal3Args = Term.AlphaConvertArglist(BodyGoals[2].Arguments, FreeVariables, newVars, context, false);

                        foreach (CutState state3 in context.KnowledgeBase.Prove(BodyGoals[2].Functor, goal3Args, context, parentFrame))
                        {
                            if (state3 == CutState.ForceFail) yield return CutState.ForceFail;
                            if (goal4Args == null)
                                goal4Args = Term.AlphaConvertArglist(BodyGoals[3].Arguments, FreeVariables, newVars, context, false);

                            foreach (CutState state4 in context.KnowledgeBase.Prove(BodyGoals[3].Functor, goal4Args, context, parentFrame))
                            {
                                if (state4 == CutState.ForceFail) yield return CutState.ForceFail;
                                if (goal5Args == null)
                                    goal5Args = Term.AlphaConvertArglist(BodyGoals[4].Arguments, FreeVariables, newVars, context, false);

                                foreach (CutState state5 in context.KnowledgeBase.Prove(BodyGoals[4].Functor, goal5Args, context, parentFrame))
                                {
                                    if (state5 == CutState.ForceFail) yield return CutState.ForceFail;
                                    if (goal6Args == null)
                                        goal6Args = Term.AlphaConvertArglist(BodyGoals[5].Arguments, FreeVariables, newVars, context, false);

                                    foreach (CutState state6 in context.KnowledgeBase.Prove(BodyGoals[5].Functor, goal6Args, context, parentFrame))
                                    {
                                        if (state6 == CutState.ForceFail) yield return CutState.ForceFail;
                                        if (goal7Args == null)
                                            goal7Args = Term.AlphaConvertArglist(BodyGoals[6].Arguments, FreeVariables, newVars, context, false);

                                        foreach (CutState state7 in context.KnowledgeBase.Prove(BodyGoals[6].Functor, goal7Args, context, parentFrame))
                                        {
                                            if (state7 == CutState.ForceFail) yield return CutState.ForceFail;
                                            if (goal8Args == null)
                                                goal8Args = Term.AlphaConvertArglist(BodyGoals[7].Arguments, FreeVariables, newVars, context, false);

                                            foreach (CutState state8 in context.KnowledgeBase.Prove(BodyGoals[7].Functor, goal8Args, context, parentFrame))
                                            {
                                                yield return state8;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #52
0
 public ELNodeEnumeratorBindFixedNodeToVariable(ELNode node, LogicVariable variableToBind)
 {
     this.node = node;
     this.variableToBind = variableToBind;
 }
Example #53
0
 public override bool BindsVar(LogicVariable v)
 {
     return v == variableToBind || nodeEnumerator.BindsVar(v);
 }
Example #54
0
 public override bool BindsVar(LogicVariable v)
 {
     return v == variableToBind;
 }
Example #55
0
 /// <summary>
 /// Finds the value of result in the first solution when proving goal within this GameObject's knowledge base.
 /// </summary>
 /// <param name="gameObject">GameObject whose KB should be queried.</param>
 /// <param name="result">Value of the variable to solve for</param>
 /// <param name="goal">Constraint on the value of the variable</param>
 /// <returns>Value found for the variable.</returns>
 public static object SolveFor(this GameObject gameObject, LogicVariable result, object goal)
 {
     return gameObject.KnowledgeBase().SolveFor(result, goal, gameObject, gameObject);
 }
Example #56
0
 private static bool TryNonExclusiveQuery(out ELNode foundNode, out ELNodeEnumerator enumerator, ELNode parentNode, object key, LogicVariable v, ELNodeEnumerator parentEnumerator)
 {
     if (parentNode != null)
     {
         return TryNonExclusiveQueryDeterministicParent(out foundNode, out enumerator, parentNode, key, v);
     }
     return TryNonExclusiveQueryEnumeratedParent(out foundNode, out enumerator, key, v, parentEnumerator);
 }
Example #57
0
 /// <summary>
 /// Finds the value of result in the first solution when proving goal within this Component's GameObject's knowledge base.
 /// </summary>
 /// <param name="component">Component whose KB should be queried.</param>
 /// <param name="result">Value of the variable to solve for</param>
 /// <param name="goal">Constraint on the value of the variable</param>
 /// <returns>Value found for the variable.</returns>
 public static object SolveFor(this Component component, LogicVariable result, object goal)
 {
     return component.KnowledgeBase().SolveFor(result, goal, component, component.gameObject);
 }
Example #58
0
        private static bool TryNonExclusiveQueryDeterministicParent(
            out ELNode foundNode,
            out ELNodeEnumerator enumerator,
            ELNode parentNode,
            object key,
            LogicVariable v)
        {
            // Deterministic parent path
            // The expression is UniqueParent/Something
            if (parentNode.IsExclusive)
            {
                throw new ELNodeExclusionException("Non-exclusive query of an exclusive node", parentNode, key);
            }

            if (v == null)
            {
                // fully deterministic path
                // UniqueParent/Key corresponds to at most one ELNode.
                enumerator = null;
                return parentNode.TryLookup(key, out foundNode);
            }
            // UniqueParent/Variable, so do a singly-nested iteration.
            foundNode = null;
            enumerator = new ELNodeEnumeratorLogicVariableFromNode(parentNode, v);
            return true;
        }
Example #59
0
        /*
         *  term = integer ;        (* 6.3.1.1 *)
         *  term = float number ;   (* 6.3.1.1 *)
         *  term = - integer ;      (* 6.3.1.2 *)
         *  term = - float number ; (* 6.3.1.2 *)
         *  term = atom ; (not an operator)  (* 6.3.1.2 *)
         *  term = atom ; (an operator )     (* 6.3.1.2 *)
         *    atom = name ;
         *    atom = empty list ;
         *       empty list = open list, close list ;
         *    atom = curly brackets ;
         *       curly brackets = open curly, close curly ;
         *  term = variable
         */
        private void shifttoken(int tok)
        {
            switch (tok)
            {
                case NAME_TOKEN:
                    {
                        int prepri, inpri, postpri, spec;
                        int inpostpri, sumpri;

                        if (Operator(this.TokenString, out prepri, out inpri, out postpri, out spec))
                        {
                            /* an operator */
                            if (prepri > 0 && (inpostpri = inpri + postpri) > 0)
                            {
                                /* infix and postfix do never occur together 6.3.4.2 */
                                if (open_char(LOOKAHEAD_CHAR))
                                {
                                    /* prefix can never be followed directly by an open char */
                                    reduce(inpostpri);
                                    shift(NAME_TOKEN, Symbol.Intern(this.TokenString), inpostpri,
                                          spec & (XFX | XFY | YFX | YF | XF));
                                }
                                else
                                {
                                    if (pStack != null)
                                    {
                                        reduce(inpostpri); /* must be done before testing the stack */
                                        if (isterm(pStack.specifier))
                                        {
                                            /* can be either infix of postfix */
                                            shift(NAME_TOKEN, Symbol.Intern(this.TokenString), inpostpri,
                                                  spec & (XFX | XFY | YFX | XF | YF));
                                        }
                                        else
                                        {
                                            /* in the beginning of an expression . must be prefix */
                                            shift(NAME_TOKEN, Symbol.Intern(this.TokenString), prepri, prefixbits(spec));
                                        }
                                    }
                                    else /* empty stack */
                                        shift(NAME_TOKEN, Symbol.Intern(this.TokenString), prepri, spec & (FX | FY));
                                }
                            }
                            else
                            {
                                /* there is only one specifier with priority sumpri */
                                reduce(sumpri = prepri + inpri + postpri);
                                shift(NAME_TOKEN, Symbol.Intern(this.TokenString), sumpri, spec);
                            }
                        }
                        else /* not an operator */
                            switch (this.TokenString)
                            {
                                    // GROSS KLUGE ADDED BY IAN TO DEAL WITH CONSTANTS YOU WANT FOR .NET
                                case "null":
                                    shift(NAME_TOKEN, null, 0, TERM);
                                    break;

                                case "true":
                                    shift(NAME_TOKEN, true, 0, TERM);
                                    break;

                                case "false":
                                    shift(NAME_TOKEN, false, 0, TERM);
                                    break;

                                default:
                                    shift(NAME_TOKEN, Symbol.Intern(this.TokenString), 0, TERM);
                                    break;
                            }
                        break;
                    }
                case VARIABLE_TOKEN:
                    string name = this.TokenString;
                    // Look for existing variable if name doesn't start with underscore
                    var lv = (name[0] == '_')?null:vars.Find(v => v.Name.Name == name);
                    if (lv == null)
                    {
                        // Anonymous or otherwise new variable
                        lv = new LogicVariable(Symbol.Intern(name));
                        vars.Add(lv);
                    }
                    shift(VARIABLE_TOKEN, lv, 0, TERM);
                    break;
                case INTEGER_TOKEN:
                    if (pStack != null && pStack.term != null &&
                        (pStack.term is Symbol) && isprefix(pStack.specifier))
                    {
                        /*
                         *  if a is a numeric constant, f is not -
                         */
                        string s = ((Symbol) (pStack.term)).Name;
                        if (s[0] == '-' && s.Length == 1)
                        {
                            //StackFrame sp = pStack;
                            pStack = pStack.down;
                            //BFREE(sp);
                            shift(INTEGER_TOKEN, -integertoken, 0, TERM);
                            break;
                        }
                    }
                    shift(INTEGER_TOKEN, integertoken, 0, TERM);
                    break;
                case FLOAT_NUMBER_TOKEN:
                    if (pStack != null && pStack.term != null &&
                        (pStack.term is Symbol) && isprefix(pStack.specifier))
                    {
                        /*
                         *  if a is a numeric constant, f is not -
                         */
                        string s = ((Symbol) (pStack.term)).Name;
                        if (s[0] == '-' && s.Length == 1)
                        {
                            //StackFrame sp = pStack;
                            pStack = pStack.down;
                            //BFREE(sp);
                            shift(FLOAT_NUMBER_TOKEN, -floattoken, 0, TERM);
                            break;
                        }
                    }
                    shift(FLOAT_NUMBER_TOKEN, floattoken, 0, TERM);
                    break;
                case CHAR_CODE_LIST_TOKEN:
                    shift_char_code_list(this.TokenString);
                    break;
                case OPEN_TOKEN:
                    shift(OPEN_TOKEN, null, 1300, DELIMITER);
                    break;
                case OPEN_CT_TOKEN:
                    shift(OPEN_CT_TOKEN, null, 1300, DELIMITER);
                    break;
                case CLOSE_TOKEN:
                    if (!reduceterm())
                        if (!reducebrackets())
                            //seterr(ERR_NONDET);
                            SyntaxError("Ambiguous input");
                    break;
                case OPEN_LIST_TOKEN:
                    shift(OPEN_LIST_TOKEN, null, 1300, DELIMITER);
                    break;
                case CLOSE_LIST_TOKEN:
                    if (!reducelist()) SyntaxError("Parse error in list");//puts("Error in reducelist");
                    break;
                case OPEN_CURLY_TOKEN:
                    shift(OPEN_CURLY_TOKEN, null, 1300, DELIMITER);
                    break;
                case CLOSE_CURLY_TOKEN:
                    if (!reducecurly()) SyntaxError("Parse error in { } expression");//puts("Error in reducecurly");
                    break;
                case HEAD_TAIL_SEPARATOR_TOKEN:
                    reduce(1000);
                    shift(HEAD_TAIL_SEPARATOR_TOKEN, null, 1000, DELIMITER);
                    break;
                case COMMA_TOKEN:
                    reduce(1000);
                    shift(COMMA_TOKEN, Symbol.Comma, 1000, XFY);
                    break;
                case EOFFILE:
                    reduce(1400);
                    shift(EOFFILE, Symbol.EndOfFile, 1400, DELIMITER);
                    break;
                case END_TOKEN:
                    break;
            }
        }
Example #60
0
 private static bool TryNonExclusiveQueryEnumeratedParent(
     out ELNode foundNode,
     out ELNodeEnumerator enumerator,
     object key,
     LogicVariable v,
     ELNodeEnumerator parentEnumerator)
 {
     // Enumerated parent path
     // NonUniqueParent/Something
     foundNode = null;
     if (v == null)
     {
         // NonUniqueParent/Key
         // Enumerate parent, then do deterministic lookup for child.
         enumerator = new ELNodeEnumeratorFixedChildFromParentEnumerator(parentEnumerator, key);
         return true;
     }
     if (parentEnumerator.BindsVar(v))
     {
         // We're doing a search for a variable that's aready bound.
         enumerator = new ELNodeEnumeratorPreboundVariable(parentEnumerator, v, false);
         return true;
     }
     // NonUniqueParent/Variable
     // Enumerate both parent and child.
     enumerator = new ELNodeEnumeratorLogicVariableFromParentEnumerator(parentEnumerator, v);
     return true;
 }