Beispiel #1
0
        public static bool TryQuery(object term, PrologContext context, out ELNode foundNode, out ELNodeEnumerator enumerator)
        {
            // Dereference any top-level variables.
            var t = Term.Deref(term);

            // Dereference indexicals
            var i = t as Indexical;
            if (i != null)
                t = i.GetValue(context);

            // A game object means the gameobject's EL KB.
            var g = t as GameObject;
            if (g != null)
                t = g.KnowledgeBase().ELRoot;

            // If it's already an ELNode, use that.
            var n = t as ELNode;
            if (n != null)
            {
                foundNode = n;
                enumerator = null;
                return true;
            }

            // Otherwise, it's an expression, so evaluate it.
            var s = t as Structure;
            if (s != null)
                return TryQueryStructure(s, context, out foundNode, out enumerator);

            var v = t as LogicVariable;
            if (v != null && !v.IsBound)
                throw new Exception("EL query root is an unbound variable: " + v);
            throw new Exception("Malformed EL query: " + ISOPrologWriter.WriteToString(term));
        }
        public static object EvalMemberExpression(object obj, object memberExpression, PrologContext context)
        {
            obj = Eval(obj, context);
            memberExpression = Term.Deref(memberExpression);
            var methodCall = memberExpression as Structure;

            if (methodCall != null)
            {
                // Method call
                var args = new object[methodCall.Arity];
                for (var i = 0; i < args.Length; i++)
                {
                    args[i] = Eval(methodCall.Argument(i), context);
                }
                return(obj.InvokeMethod(methodCall.Functor.Name, args));
            }
            var propName = memberExpression as Symbol;

            if (propName != null)
            {
                // Field or property reference
                return(obj.GetPropertyOrField(propName.Name));
            }
            throw new ArgumentException(
                      "Invalid member expression: " + ISOPrologWriter.WriteToString(new Structure(Symbol.Dot, obj, memberExpression)));
        }
Beispiel #3
0
        public static bool TryQueryStructure(
            Structure term,
            PrologContext context,
            out ELNode foundNode,
            out ELNodeEnumerator enumerator)
        {
            //
            // Dispatch based on the functor and arity.
            //

            // Handle root queries, i.e. /Key
            if (term.IsFunctor(Symbol.Slash, 1))
                return TryRootQuery(term, context, out foundNode, out enumerator);

            if (!IsELTerm(term))
                throw new Exception("Malformed EL query: " + ISOPrologWriter.WriteToString(term));

            if (term.IsFunctor(SBindNodeOperator, 2))
            {
                var variableToBind = term.Argument(1) as LogicVariable;
                if (variableToBind == null)
                    throw new ArgumentException("RHS of >> must be an uninstantiated variable: "+ ISOPrologWriter.WriteToString(term.Argument(1)));
                foundNode = null;
                return TryNodeBindingQuery(out enumerator, term.Argument(0), variableToBind, context);
            }

            return TryChildQuery(
                out foundNode,
                out enumerator,
                term.Argument(0),
                term.Argument(1),
                term.Functor == Symbol.Colon,
                context);
        }
 /// <summary>
 /// Thrown when attempting to write a non-exclusive value to an exclusive value or vice-versa.
 /// </summary>
 public ELNodeExclusionException(string message, ELNode node, object key)
     : base(string.Format("{0}: {1}{2}{3}",
                          message,
                          node,
                          node.IsExclusive?ELProlog.ExclusiveOperator:ELProlog.NonExclusiveOperator,
                          ISOPrologWriter.WriteToString(key)))
 {
 }
Beispiel #5
0
 internal void PrintWarning(string formatString, params object[] formatArgs)
 {
     //Repl.StartWarnings();
     Debug.LogException(
         new PrologWarning(string.Format(formatString, formatArgs),
                           string.Format("{0} (at {1}:{2})\n", ISOPrologWriter.WriteToString(this.Head), this.SourceFile, this.SourceLineNumber))
         );
     //Console.Write(" in predicate {0}:{1}/{2}.", kb.Name, HeadFunctor, HeadArity);
 }
Beispiel #6
0
        //
        // these write a single nodes, so they don't need to loop like queries do.
        //

        /// <summary>
        /// Write TERM to EL KB, creating any nodes that need to be cerated.
        /// </summary>
        /// <param name="term">Prolog-format term to store into KB</param>
        /// <param name="knowledgeBase">KB in which to assert the term.</param>
        /// <returns></returns>
        public static ELNode Update(object term, KnowledgeBase knowledgeBase)
        {
            term = Term.Deref(term);
            var s = term as Structure;
            if (s != null)
                return UpdateStructure(s, knowledgeBase);
            var n = term as ELNode;
            if (n != null)
                return n;

            throw new Exception("Malformed EL assertion: " + ISOPrologWriter.WriteToString(term));
        }
Beispiel #7
0
 public string SourceFor(PredicateIndicator p)
 {
     // ReSharper disable once NotResolvedInText
     if (p.Functor == null) throw new ArgumentNullException("functor");
     var s = new StringWriter();
     var writer = new ISOPrologWriter(s);
     var predicateInfo = CheckForPredicateInfo(p);
     if (predicateInfo == null)
         throw new ArgumentException(string.Format("Unknown predicate: {0}.", p));
     SourceFromPredicateInfo(p, predicateInfo, writer);
     return s.ToString();
 }
Beispiel #8
0
 /// <summary>
 /// Prints to the console the disassembled bytecode for all rules in this predicate.
 /// </summary>
 public void Disassemble()
 {
     foreach (var knowledgeBaseEntry in Entries)
     {
         var rule = (ByteCompiledRule)knowledgeBaseEntry;
         Console.WriteLine("");
         Console.Write(ISOPrologWriter.WriteToString(rule.Head));
         Console.Write(" :- \n    ");
         Console.Write(ISOPrologWriter.WriteToString(rule.Body));
         Console.WriteLine(".");
         rule.Disassemble();
     }
 }
        internal void PrintWarning(string formatString, params object[] formatArgs)
        {
#if DisableUnity
            Console.Write("{0} (at {1}:{2}): ",
                          ISOPrologWriter.WriteToString(this.Head), this.SourceFile, this.SourceLineNumber);
            Console.WriteLine(formatString, formatArgs);
#else
            //Repl.StartWarnings();
            Debug.LogException(
                new PrologWarning(string.Format(formatString, formatArgs),
                                  string.Format("{0} (at {1}:{2})\n", ISOPrologWriter.WriteToString(this.Head), this.SourceFile, this.SourceLineNumber))
                );
#endif
        }
Beispiel #10
0
 public static ELNode UpdateStructure(Structure term, KnowledgeBase knowledgeBase)
 {
     if (term.Functor == Symbol.Slash)
     {
         if (term.Arity == 1)
             return knowledgeBase.ELRoot.StoreNonExclusive(Term.CopyInstantiation(term.Argument(0)));
         return Update(term.Argument(0), knowledgeBase).StoreNonExclusive(Term.CopyInstantiation(term.Argument(1)));
     }
     if (term.Functor == Symbol.Colon)
     {
         return Update(term.Argument(0), knowledgeBase).StoreExclusive(Term.CopyInstantiation(term.Argument(1)), true); 
     }
     throw new Exception("Malformed EL assertion: "+ISOPrologWriter.WriteToString(term));
 }
        public override string ToString()
        {
            switch (Type)
            {
            case IndexerType.Structure:
                return(string.Format("{0}/{1}", ((Symbol)Functor).Name, Arity));

            case IndexerType.Atom:
                return(ISOPrologWriter.WriteToString(Functor));

            case IndexerType.Variable:
                return("Var");

            case IndexerType.Null:
                return("NullIndexer");
            }
            return("<PredicateArgumentIndexer with invalid type>");
        }
        /// <summary>
        /// Testing jig for byte compiler
        /// </summary>
        public void Test(string call)
        {
            var term = (Structure)(new ISOPrologReader(call).ReadTerm());

            if (term.Arity != predicate.Arity)
            {
                throw new Exception("Wrong number of arguments");
            }
            using (var c = PrologContext.Allocate(KnowledgeBase.Global, null))
            {
                c.PushArguments(term.Arguments);
                int solutions = 0;
                foreach (var x in StackCall(c))
                {
                    foreach (var arg in term.Arguments)
                    {
                        if (arg is LogicVariable)
                        {
                            var l = arg as LogicVariable;
                            Console.WriteLine("{0}={1}", l.Name, ISOPrologWriter.WriteToString(l.Value));
                        }
                    }
                    Console.WriteLine(x);
                    if (solutions++ > 10)
                    {
                        Console.WriteLine("Max solutions found; terminating search");
                        c.PopFrame(0);
                        goto abort;
                    }
                }
                Console.WriteLine("fail");
abort:
                int tos = c.MakeFrame(0);
                if (tos != 0)
                {
                    Console.WriteLine("Error: tos is " + tos);
                }
            }
        }
        string CaptureStack()
        {
            List<object> result = new List<object>();
            if (this.TokenString != "")
                result.Add(this.TokenString);
            StackFrame s = pStack;
            while (s != null)
            {
                object item;
                switch(s.tokentype)
                {
                    case EOFFILE:
                        item = "end_of_file";
                        break;

                    case OPEN_TOKEN:
                    case OPEN_CT_TOKEN:
                        item = '(';
                        break;

                    case CLOSE_TOKEN:
                        item = ')';
                        break;

                    case OPEN_LIST_TOKEN:
                        item = '[';
                        break;

                    case CLOSE_LIST_TOKEN:
                        item = ']';
                        break;

                    case OPEN_CURLY_TOKEN:
                        item = '{';
                        break;

                    case CLOSE_CURLY_TOKEN:
                        item = '}';
                        break;

                    case HEAD_TAIL_SEPARATOR_TOKEN:
                        item = '|';
                        break;

                    case COMMA_TOKEN:
                        item = ',';
                        break;

                    case END_TOKEN:
                        item = '.';
                        break;

                    default:
                        item = s.term;
                        break;
                }
                result.Insert(0, item);  // okay, so this is technically quadratic, but the stack shouldn't be deep, and this only runs when syntax errors are thrown
                s = s.down;
            }
            StringWriter sw = new StringWriter();
            ISOPrologWriter w = new ISOPrologWriter(sw);
            bool first = true;
            foreach (var t in result)
            {
                if (first)
                    first = false;
                else
                    w.WriteString(" ");
                w.Write(t);
            }

            return sw.ToString();
        }
Beispiel #14
0
 public GoalException(object goal, string message) : base(string.Format("{0}: {1}", message, ISOPrologWriter.WriteToString(goal)))
 {
     Goal = goal;
 }
 public override string ToString()
 {
     return(ISOPrologWriter.WriteToString(new Structure(":-", head, Body)));
 }
Beispiel #16
0
        // This ought to get refactored so that it's shared with the render code in the main class.
        private void AddItem(object data)
        {
            var op = data as Structure;

            if (op != null)
            {
                switch (op.Functor.Name)
                {
                case "cons":
                    AddItem(op.Argument(0));
                    AddItem(op.Argument(1));
                    break;

                case "line":
                    foreach (var arg in op.Arguments)
                    {
                        AddItem(arg);
                    }
                    textBuilder.AppendLine();
                    break;

                case "color":
                    textBuilder.AppendFormat("<color={0}>", op.Argument(0));
                    for (int i = 1; i < op.Arity; i++)
                    {
                        AddItem(op.Argument(i));
                    }
                    textBuilder.Append("</color>");
                    break;

                case "size":
                    textBuilder.AppendFormat("<size={0}>", op.Argument(0));
                    for (int i = 1; i < op.Arity; i++)
                    {
                        AddItem(op.Argument(i));
                    }
                    textBuilder.Append("</size>");
                    break;

                case "bold":
                    textBuilder.AppendFormat("<b>");
                    for (int i = 0; i < op.Arity; i++)
                    {
                        AddItem(op.Argument(i));
                    }
                    textBuilder.Append("</b>");
                    break;

                case "italic":
                    textBuilder.AppendFormat("<i>");
                    for (int i = 0; i < op.Arity; i++)
                    {
                        AddItem(op.Argument(i));
                    }
                    textBuilder.Append("</i>");
                    break;

                case "term":
                    textBuilder.Append(ISOPrologWriter.WriteToString(op.Argument(0)));
                    break;

                default:
                    textBuilder.Append(ISOPrologWriter.WriteToString(op));
                    break;
                }
            }
            else
            {
                var str = data as string;
                textBuilder.Append(str ?? ISOPrologWriter.WriteToString(data));
            }
        }
Beispiel #17
0
        private void Render(object renderingOperation)
        {
            renderingOperation = Term.Deref(renderingOperation);
            if (renderingOperation == null)
            {
                return;
            }

            var op = renderingOperation as Structure;

            if (op != null)
            {
                switch (op.Functor.Name)
                {
                case "cons":
                    Render(op.Argument(0));
                    Render(op.Argument(1));
                    break;

                case "line":
                    foreach (var arg in op.Arguments)
                    {
                        Render(arg);
                    }
                    textBuilder.AppendLine();
                    break;

                case "color":
                    textBuilder.AppendFormat("<color={0}>", op.Argument(0));
                    for (int i = 1; i < op.Arity; i++)
                    {
                        Render(op.Argument(i));
                    }
                    textBuilder.Append("</color>");
                    break;

                case "size":
                    textBuilder.AppendFormat("<size={0}>", op.Argument(0));
                    for (int i = 1; i < op.Arity; i++)
                    {
                        Render(op.Argument(i));
                    }
                    textBuilder.Append("</size>");
                    break;

                case "bold":
                    textBuilder.AppendFormat("<b>");
                    for (int i = 0; i < op.Arity; i++)
                    {
                        Render(op.Argument(i));
                    }
                    textBuilder.Append("</b>");
                    break;

                case "italic":
                    textBuilder.AppendFormat("<i>");
                    for (int i = 0; i < op.Arity; i++)
                    {
                        Render(op.Argument(i));
                    }
                    textBuilder.Append("</i>");
                    break;

                case "term":
                    textBuilder.Append(ISOPrologWriter.WriteToString(op.Argument(0)));
                    break;

                case "table":
                    MakeTable(op.Argument(0));
                    break;

                default:
                    textBuilder.Append(ISOPrologWriter.WriteToString(op));
                    break;
                }
            }
            else
            {
                var str = renderingOperation as string;
                textBuilder.Append(str ?? ISOPrologWriter.WriteToString(renderingOperation));
            }
        }
 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");
     }
 }
 public string SourceFor(PredicateIndicator p)
 {
     // ReSharper disable once NotResolvedInText
     if (p.Functor == null) throw new ArgumentNullException("functor");
     var s = new StringWriter();
     var writer = new ISOPrologWriter(s);
     var predicateInfo = CheckForPredicateInfo(p);
     if (predicateInfo == null)
         throw new ArgumentException(string.Format("Unknown predicate: {0}.", p));
     SourceFromPredicateInfo(p, predicateInfo, writer);
     return s.ToString();
 }
Beispiel #20
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");
     }
 }
Beispiel #21
0
 /// <summary>
 /// Renders term in Prolog format
 /// </summary>
 public override string ToString()
 {
     return(ISOPrologWriter.WriteToString(this));
 }
Beispiel #22
0
        public static PredicateIndicator FromExpression(object expression)
        {
            var s = Term.Deref(expression) as Structure;

            if (s == null ||
                (!s.IsFunctor(Symbol.Slash, 2) && !s.IsFunctor(Symbol.SlashSlash, 2)) ||
                !(s.Argument(0) is Symbol) ||
                !(s.Argument(1) is int))
            {
                throw new ArgumentException("Predicate indicator should be of the form functor/arity, but got " + ISOPrologWriter.WriteToString(expression));
            }
            return(new PredicateIndicator((Symbol)s.Argument(0), (int)s.Argument(1)));
        }
Beispiel #23
0
 /// <summary>
 /// Converts an arbitrary object to a string in Prolog format.
 /// </summary>
 public static string ToStringInPrologFormat(object value)
 {
     return(ISOPrologWriter.WriteToString(value));
 }