public PartListImpl ParseBody(Tokeniser tk, string mt)
        {
            // Body -> Term {, Term...}

            PartListImpl p = new PartListImpl();
            var          i = 0;

            Term t;

            while ((t = (Term)ParseTerm(tk, mt)) != null)
            {
                p.AddPart(t);
                i++;
                if (tk.current != ",")
                {
                    break;
                }
                tk.consume();
            }

            if (i == 0)
            {
                return(null);
            }
            return(p);
        }
            public Term(string head, bool isVar, PartListImpl a0N)
            {
                _name     = head;
                headIsVar = isVar;
                partlist0 = a0N;
                var isVarName = IsVarName(head);

                if (a0N == null)
                {
                    throw ErrorBadOp("Term Arglist NULL: {0}", head);
                }
                if (isVar)
                {
                    if (!isVarName)
                    {
                        throw ErrorBadOp("Pred was supposed to be variable: {0}", this);
                    }
                }
                else
                {
                    if (isVarName)
                    {
                        throw ErrorBadOp("Pred was NOT supposed to be variable: {0}", this);
                    }
                }
                if (a0N.Arity > 0)
                {
                    Part a0 = a0N.ArgList[0];
                    if (a0 is PartListImpl)
                    {
                        Warn("Poorly constructed term: {0}", this);
                    }
                }
                a0N.TParent = this;
            }
        public ProveResult TripleQuery(Term thisTerm, PartListImpl goalList, PEnv environment, PDB db, int level, reportDelegate reportFunction)
        {
            // bagof(Term, ConditionTerm, ReturnList)
            //  PartList goalList = (PartList)goalIn;

            Part collect0 = value((Part)thisTerm.ArgList[0], environment);
            Part subgoal  = value((Part)thisTerm.ArgList[1], environment);
            Part into     = value((Part)thisTerm.ArgList[2], environment);

            Part collect = renameVariables(collect0, level, thisTerm);
            //var newGoal = new Term(subgoal.name, renameVariables(subgoal.ArgList, level, thisTerm));
            Term newGoal = new Term(subgoal.fname, false,
                                    (PartListImpl)renameVariables(((PartListImpl)subgoal), level, thisTerm));

            newGoal.parent = thisTerm;

            //var newGoals = [];
            //newGoals[0] = newGoal;
            PartListImpl newGoals = new PartListImpl();

            newGoals.AddPart(newGoal);

            // Prove this subgoal, collecting up the environments...
            PartListImpl anslist = new PartListImpl();

            anslist.renumber = -1;
            var ret = prove(newGoals, environment, db, level + 1, BagOfCollectFunction(collect, anslist));

            // Turn anslist into a proper list and unify with 'into'

            // optional here: nil anslist -> fail?
            Part answers = Atom.FromSource(FUNCTOR_NIL);

            /*
             * print("Debug: anslist = [");
             *  for (var j = 0; j < anslist.length; j++) {
             *      anslist[j].print();
             *      print(", ");
             *  }
             * print("]\n");
             */

            for (int i = anslist.Arity; i > 0; i--)
            {
                answers = MakeList(anslist.ArgList[i - 1], answers);
            }

            //print("Debug: unifying "); into.print(); print(" with "); answers.print(); print("\n");
            var env2 = unify(into, answers, environment);

            if (env2 == null)
            {
                //print("Debug: bagof cannot unify anslist with "); into.print(); print(", failing\n");
                return(null);
            }

            // Just prove the rest of the goallist, recursively.
            return(prove(goalList, env2, db, level + 1, reportFunction));
        }
 public PartListImpl(PartListImpl head, PEnv env)
 {
     this.tlist = new List <Part>();
     for (var i = 0; i < head.Count; i++)
     {
         tlist.Add(value(head[i], env));
     }
 }
 public static Term RuleToTerm(Part head, PartListImpl rulebody)
 {
     if (IsBodyAlwaysTrue(rulebody))
     {
         return(head.AsTerm());
     }
     return(MakeTerm(":-", head, RuleBodyToTerm(rulebody)));
 }
        public ProveResult ExecuteSharp(Term thisTerm, PartListImpl goalList, PEnv environment, PDB db, int level,
                                        reportDelegate reportFunction)
        {
            Term       collect0   = value((Part)thisTerm.ArgList[1], environment).AsTerm();
            string     methodName = collect0.fname;
            var        partObj    = value((Part)thisTerm.ArgList[0], environment);
            object     result;
            TextWriter warns = new StringWriter();

            try
            {
                if (partObj.IsObject)
                {
                    if (!CanInvokeObject(partObj.Functor0, methodName, collect0.ArgList, out result, warns))
                    {
                        Warn(warns);
                        return(new ProveResult()
                        {
                            Failed = true
                        });
                    }
                }
                else
                {
                    if (!CanInvokeObjectByName(partObj.Text, methodName, collect0.ArgList, true, out result, warns))
                    {
                        Warn(warns);
                        return(new ProveResult()
                        {
                            Failed = true
                        });
                    }
                }
            }
            catch (Exception e2)
            {
                Warn(warns);
                throw e2;
                return(new ProveResult()
                {
                    Failed = true
                });
            }
            //print("Debug: unifying "); into.print(); print(" with "); answers.print(); print("\n");
            var env2 = unify(thisTerm.ArgList[2], ObjectToPart(result), environment);

            if (env2 == null)
            {
                //print("Debug: bagof cannot unify anslist with "); into.print(); print(", failing\n");
                return(null);
            }

            // Just prove the rest of the goallist, recursively.
            return(prove(goalList, env2, db, level + 1, reportFunction));
        }
 public static Term RuleBodyToTerm(PartListImpl rulebody)
 {
     if (IsBodyAlwaysTrue(rulebody))
     {
         return(TERM_TRUE);
     }
     if (rulebody.Count == 1)
     {
         return(rulebody[0].AsTerm());
     }
     return(new Term(",", false, rulebody));
 }
 public Rule(Term head, PartListImpl bodylist)
     : this(head)
 {
     if (bodylist != null)
     {
         this.body   = new Body(bodylist);
         body.parent = this;
     }
     else
     {
         this.body = null;
     }
 }
            public Rule TripleToRule(Triple triple, IGraph listResolves, bool keepOriginalGraphUri)
            {
                var    s  = triple.Subject;
                var    p  = triple.Predicate;
                var    o  = triple.Object;
                string sp = triple.Predicate.ToString();

                if (!GlobalSharedSettings.TODO1Completed)
                {
                    //RdfRules rules = new RdfRules(rdfGraph);
                    Term t    = MakeTerm(TripleName, Atom.MakeNodeAtom(s), Atom.MakeNodeAtom(p), Atom.MakeNodeAtom(o));
                    var  rule = new Rule(t);
                    //rule.rdfRuleCache = rules;
                    return(rule);
                }
                var pp = Atom.MakeNodeAtom(p);

                if (sp == RdfSpecsHelper.RdfListFirst || sp == RdfSpecsHelper.RdfListRest)
                {
                    var rule =
                        new Rule(new Term(pp.fname, false, new PartListImpl(Atom.MakeNodeAtom(s), Atom.MakeNodeAtom(o))));
                    return(rule);
                }
                int argNum = GraphWithDef.GetInstanceOnArg(sp);

                if (argNum == -1)
                {
                    // assume it's one to one?
                    argNum = 0;
                }
                if (argNum != 0)
                {
                    //1: [a f (b c)]
                    //2: [b f (a c)]
                    //3: [c f (a b)]
                    PartListImpl parts = new PartListImpl();
                    AddRdfList(parts, o, argNum, s, triple, listResolves);
                    var rule = new Rule(new Term(pp.fname, false, parts));
                    return(rule);
                }
                // pred + args are in the list [db1 f (a b c)]
                if (argNum == 0)
                {
                    PartListImpl parts = new PartListImpl();
                    AddRdfList(parts, o, -1, null, triple, listResolves);
                    var rule = new Rule(new Term(pp.fname, false, parts));
                    return(rule);
                }
                return(null);
            }
Esempio n. 10
0
        public Rule ParseRule(Tokeniser tk, string mt)
        {
            // A rule is a Head followed by . or by :- Body

            var p = ParseHead(tk, mt);

            if (p == null)
            {
                prolog_reader_debug("cant parse Rule head: " + tk);
                return(null);
            }
            Term h = p as Term;

            if (h == null)
            {
                if (!(p is Atom))
                {
                    prolog_reader_debug("didn't parse Rule head as atom or term: " + tk);
                    // return null;
                }
                h = p.AsTerm();
            }
            if (tk.current == ".")
            {
                // A simple rule.
                tk.consume();
                return(new Rule(h));
            }

            if (tk.current != ":-")
            {
                prolog_reader_debug("Rule neck missing: " + tk);
                return(null);
            }
            tk.consume();
            PartListImpl b = ParseBody(tk, mt);

            if (b == null)
            {
                prolog_reader_debug("Rule body not present: " + tk);
                return(null);
            }
            if (tk.current == "." || tk.current == "eof")
            {
                tk.consume();
                return(new Rule(h, b));
            }
            prolog_reader_debug("Rule body not terminated: " + tk);
            return(null);
        }
Esempio n. 11
0
            public override string ToSource(SourceLanguage language)
            {
                language = language.Inner();
                string result = "";

                if (IsListName(this.fname) && Arity == 2)
                {
                    Part x = this;
                    {
                        result += "[";
                        var com = false;
                        while (IsList(x))
                        {
                            if (com)
                            {
                                result += ", ";
                            }
                            result += x.ArgList[0].ToSource(language); // May need to case var/atom/term
                            com     = true;
                            x       = x.ArgList[1];
                        }
                        if (x.ToSource(SourceLanguage.Prolog) != "[]")
                        {
                            result += " | ";
                            result += x.ToSource(language);
                        }
                        result += "]";
                        return(result);
                    }
                }
                if (Arity == 0)
                {
                    if (fname == "cut")
                    {
                        return("!");
                    }
                    return(ReadableName);
                }
                PartListImpl argList = this.ArgList;

                if (argList == null)
                {
                    return(result + "()");
                }
                result += "" + ReadableName + "(";
                result += argList.ToSource(language);
                result += ")";
                return(result);
            }
Esempio n. 12
0
        static public PartListImpl ParseConjuncts(Tokeniser tk, string mt, string requiredEnd, string sep, bool eofReturnsPart)
        {
            // Body -> Term {, Term...}

            PartListImpl p = new PartListImpl();
            var          i = 0;

            while (true)
            {
                if (tk.current == requiredEnd)
                {
                    tk.consume();
                    break;
                }
                if (tk.current == "eof")
                {
                    if (!eofReturnsPart)
                    {
                        prolog_reader_debug("read EOF " + tk);
                        return(null);
                    }
                    break;
                }
                if (tk.current == sep)
                {
                    tk.consume();
                    continue;
                }
                Part t = ParsePart(tk, mt);
                if (t == null)
                {
                    prolog_reader_debug("cant read Conjuct item " + tk);
                    return(null);
                }
                p.AddPart(t);
                i++;
            }

            if (i == 0)
            {
                prolog_reader_debug("no items read " + tk);
                return(null);
            }
            return(p);
        }
 // Aux function: return the reportFunction to use with a bagof subgoal
 public reportDelegate IstQueryCollectFunction(Part collect, PartListImpl anslist)
 {
     return(delegate(PEnv env)
     {
         /*
          * print("DEBUG: solution in bagof/3 found...\n");
          * print("Value of collection term ");
          * collect.print();
          * print(" in this environment = ");
          * (value(collect, env)).print();
          * print("\n");
          * printEnv(env);
          */
         // Rename this appropriately and throw it into anslist
         anslist.AddPart(renameVariables(value(collect, env), anslist.renumber--, null));
         return true;
     });
 }
            public static bool AddRdfList(PartListImpl parts, INode node, int argNum, INode obj, Triple triple,
                                          IGraph listResolves)
            {
                if (parts.Count + 1 == argNum)
                {
                    bool a = AddRdfList(parts, obj, -1, null, triple, listResolves);
                    bool b = AddRdfList(parts, node, -1, null, triple, listResolves);
                    return(a && b);
                }
                switch (node.NodeType)
                {
                case NodeType.Uri:
                case NodeType.Literal:
                    parts.AddPart(Atom.MakeNodeAtom(node));
                    return(true);

                case NodeType.Variable:
                    parts.AddPart(new Variable(node.ToString().Substring(1)));
                    return(true);

                case NodeType.Blank:
                {
                    INode f, r;
                    if (GetRdfList(node, listResolves, out f, out r, triple))
                    {
                        bool a = AddRdfList(parts, f, argNum, obj, triple, listResolves);
                        bool b = AddRdfList(parts, r, argNum, obj, triple, listResolves);
                        return(a && b);
                    }
                }
                    parts.AddPart(Atom.MakeNodeAtom(node));
                    return(foundNodeMoreThanTriple(listResolves, node, triple));

                // case NodeType.GraphLiteral:
                //   break;
                default:
                    Warn("cant intern " + node);
                    return(false);

                    throw new ArgumentOutOfRangeException();
                }
            }
Esempio n. 15
0
 static public Part MakeTermPostReader(String f, bool isHeadVar, PartListImpl partlist)
 {
     if (partlist.Arity == 0)
     {
         if (isHeadVar)
         {
             return(new Variable(f));
         }
         return(Atom.FromName(f));
     }
     if (f == "$obj")
     {
         Part partlist1 = partlist[0];
         if (partlist1.fname == "$literal")
         {
             return(Atom.MakeLiteral(partlist[1].AsString(), partlist[2].AsString(), partlist[3].AsString()));
         }
         Warn("Not sure how to create a " + partlist);
     }
     return(new Term(f, isHeadVar, partlist));
 }
 public Body(PartListImpl l)
 {
     plist        = l;
     plist.parent = this;
 }
Esempio n. 17
0
 public static bool IsBodyAlwaysTrue(PartListImpl rulebody)
 {
     return(rulebody == null || rulebody.Count == 0 ||
            (rulebody.Count == 1 && TERM_TRUE.Equals(rulebody[0])));
 }
Esempio n. 18
0
        // This was a beautiful piece of code. It got kludged to add [a,b,c|Z] sugar.
        static public Part ParsePart(Tokeniser tk, string mt)
        {
//            string mt = threadLocal.curKB;
            // Part -> var | id | id(optParamList)
            // Part -> [ listBit ] ::-> cons(...)
            if (tk.type == "punc" && tk.current == "[")
            {
                // Parse a list (syntactic sugar goes here)
                tk.consume();
                // Special case: [] = Atom.Make(nil).
                if (tk.type == "punc" && tk.current == "]")
                {
                    tk.consume();
                    return(Atom.FromSource(FUNCTOR_NIL));
                }

                // Get a list of parts into l
                ArrayList l = new ArrayList();
                int       i = 0;

                while (true)
                {
                    var t = ParsePart(tk, mt);
                    if (t == null)
                    {
                        prolog_reader_debug("cant parse List Part " + tk);
                        return(null);
                    }

                    l.Insert(i++, t);
                    if (tk.current != ",")
                    {
                        break;
                    }
                    tk.consume();
                }

                // Find the end of the list ... "| Var ]" or "]".
                Part append;
                if (tk.current == "|")
                {
                    tk.consume();
                    append = ParsePart(tk, mt);
                }
                else
                {
                    append = Atom.FromSource(FUNCTOR_NIL);
                }
                if (tk.current != "]")
                {
                    prolog_reader_debug("Unclosed List " + tk);
                    return(null);
                }
                tk.consume();
                // Return the new cons.... of all this rubbish.
                for (--i; i >= 0; i--)
                {
                    append = MakeList((Part)l[i], append);
                }
                return(append);
            }
            var notthis = false;

            if (tk.current == "NOTTHIS")
            {
                notthis = true;
                tk.consume();
            }
            var type        = tk.type;
            var name        = tk.current;
            var quotingType = tk.typeSyntax;

            tk.consume();
            if (quotingType == SYNTAX_DoubleQuotes)
            {
                return(Atom.FromSourceReader(name, quotingType));
            }
            // fail shorthand for fail(), ie, fail/0
            if (type == "id" && name == "fail")
            {
                return(MakeTerm("fail"));
            }
            // Parse ! as cut/0
            if (type == "punc" && name == "!")
            {
                return(MakeTerm("cut"));
            }
            // Parse [id|var](ParamList)
            if (tk.current == "(")
            {
                tk.consume();

                PartListImpl p = ParseConjuncts(tk, mt, ")", ",", false);
                if (p == null)
                {
                    prolog_reader_debug("cant read termargs " + tk);
                    return(null);
                }
                Part term = MakeTermPostReader(name, type == "var", p);
                if (term is Term)
                {
                    if (notthis)
                    {
                        ((Term)term).excludeThis = true;
                    }
                }
                return(term);
            }
            if (type == "var")
            {
                return(new Variable(name));
            }
            return(Atom.FromSourceReader(name, quotingType));
        }