Esempio n. 1
0
 private static int PredicateArity(PlTerm term)
 {
     if (term.Name == "{}")
     {
         if (term.Arity == 1)
         {
             return(PredicateArity(term.Arg(0)));
         }
     }
     if (term.Name == ":")
     {
         if (term.Arity == 2)
         {
             return(PredicateArity(term.Arg(1)));
         }
     }
     if (term.Name == "/")
     {
         if (term.Arity == 2)
         {
             return(term.Arg(1).intValue());
         }
     }
     return(term.Arity);
 }
Esempio n. 2
0
        public static bool cliAddElement(PlTerm enumerable, PlTerm tvalue)
        {
            IEnumerable al = (IEnumerable)CastTerm(enumerable, typeof(IEnumerable));
            bool        isGeneric;

            MethodInfo[] reflectCache;
            Type         elementType;
            Type         indexType;
            Type         colType = GetColType(al, out isGeneric, out reflectCache, out elementType, out indexType);
            object       value   = CastTerm(tvalue, elementType);

            if (!isGeneric)
            {
                colAddElementFallback(al, value, reflectCache);
            }
            MethodInfo gMethod = reflectCache[6];

            if (gMethod == null)
            {
                gMethod = reflectCache[6] = typeof(PrologCLR).GetMethod("colAddElement", BindingFlagsJustStatic)
                                            .MakeGenericMethod(new[] { elementType });
            }
            gMethod.Invoke(null, new object[] { al, value, reflectCache });
            return(true);
        }
Esempio n. 3
0
 private static string PredicateName(PlTerm term)
 {
     if (term.Name == "{}")
     {
         if (term.Arity == 1)
         {
             return(PredicateName(term.Arg(0)));
         }
     }
     if (term.Name == ":")
     {
         if (term.Arity == 2)
         {
             return(PredicateName(term.Arg(1)));
         }
     }
     if (term.Name == "/")
     {
         if (term.Arity == 2)
         {
             return(PredicateName(term.Arg(0)));
         }
     }
     return(term.Name);
 }
Esempio n. 4
0
 public static bool cliToStrRaw(PlTerm obj, PlTerm str)
 {
     try
     {
         if (!str.IsVar)
         {
             var plvar = PlTerm.PlVar();
             return(cliToStrRaw(obj, plvar) && SpecialUnify(str, plvar));
         }
         if (obj.IsString)
         {
             return(str.Unify(obj));
         }
         if (obj.IsVar)
         {
             return(str.Unify((string)obj));
         }
         object o = GetInstance(obj);
         if (o == null)
         {
             return(str.FromObject("" + obj));
         }
         return(str.FromObject(ToString(o)));
     }
     catch (Exception e)
     {
         Warn("cliToString: {0}", e);
         object o = GetInstance(obj);
         if (o == null)
         {
             return(str.FromObject("" + obj));
         }
         return(str.FromObject(ToString(o)));
     }
 }
Esempio n. 5
0
        public static bool cliSetElement(PlTerm enumerable, PlTerm indexes, PlTerm tvalue)
        {
            CheckMI();
            IEnumerable al = (IEnumerable)CastTerm(enumerable, typeof(IEnumerable));
            bool        isGeneric;

            MethodInfo[] reflectCache;
            Type         elementType;
            Type         indexType;
            Type         colType = GetColType(al, out isGeneric, out reflectCache, out elementType, out indexType);
            object       value   = CastTerm(tvalue, elementType);
            object       idx     = CastTerm(indexes, indexType);

            if (colType.IsArray)
            {
                Array array = (Array)al;
                ArraySet(array, idx, value);
                return(true);
            }
            if (!isGeneric)
            {
                colSetElementFallback(al, idx, value, reflectCache);
            }
            MethodInfo gMethod = reflectCache[7];

            if (gMethod == null)
            {
                gMethod = reflectCache[7] = typeof(PrologCLR).GetMethod("colSetElement", BindingFlagsJustStatic)
                                            .MakeGenericMethod(new[] { elementType });
            }
            gMethod.Invoke(null, new object[] { al, idx, value, reflectCache });
            return(true);
        }
Esempio n. 6
0
        static public bool cliLockExit(PlTerm lockObj)
        {
            object getInstance = GetInstance(lockObj);

            Monitor.Exit(getInstance);
            return(true);
        }
Esempio n. 7
0
        static public bool cliJavaToString(PlTerm paramIn, PlTerm valueOut)
        {
            if (!valueOut.IsVar)
            {
                var plvar = PlTerm.PlVar();
                return(cliJavaToString(paramIn, plvar) && SpecialUnify(valueOut, plvar));
            }
            object getInstance = GetInstance(paramIn);

            if (getInstance == null)
            {
                return(valueOut.Unify(PlTerm.PlString("null")));
            }
#if USE_IKVM
            object val = getInstance as java.lang.Object;
            if (val == null)
            {
                Class  c = ikvm.runtime.Util.getClassFromObject(getInstance);
                string s = (string)c.getMethod("toString", new Class[0]).invoke(getInstance, ZERO_OBJECTS);
                return(valueOut.Unify(PlTerm.PlString(s)));
            }
            return(valueOut.Unify(PlTerm.PlString(val.toString())));
#else
            object val = getInstance;
            return(valueOut.Unify(PlTerm.PlString(val.ToString())));
#endif
        }
Esempio n. 8
0
        private static bool link_swiplcs(PlTerm pathName)
        {
            try
            {
                return(true);

                if (JplSafeNativeMethodsCalled)
                {
                    bool enabled = !JplSafeNativeMethodsDisabled;
                    SafelyRun(
                        () => ConsoleTrace("JplSafeNativeMethods called again from " + pathName + " result=" + enabled));
                    return(enabled);
                }
                JplSafeNativeMethodsCalled = true;
                SafelyRun(() => ConsoleTrace("JplSafeNativeMethods call first time from " + pathName));
                JplSafeNativeMethods.install();
                //var v = new PlTerm("_1");
                //JplSafeNativeMethods.jpl_c_lib_version_1_plc(v.TermRef);
                return(true);
            }
            catch (Exception e)
            {
                JplSafeNativeMethodsDisabled = true;
                WriteException(e);
                return(false);
            }
        }
Esempio n. 9
0
        public static bool cliFindClass(PlTerm clazzName, PlTerm clazzObjectOut)
        {
            if (clazzName.IsAtom)
            {
                string className = clazzName.Name;
                Type   c         = ResolveClass(className);
                if (c != null)
                {
                    ConsoleTrace("cliFindClass:" + className + " class:" + c);
                    string tag = object_to_tag(c);
                    return(AddTagged(clazzObjectOut.TermRef, tag) != 0);
                }
                ConsoleTrace("cant ResolveClass " + className);
                return(false);
            }
            Type t = GetType(clazzName);

            if (t != null)
            {
                Type c = null;
#if USE_IKVM
                c = ikvm.runtime.Util.getFriendlyClassFromType(t);
#else
                c = t;
#endif
                string tag = object_to_tag(c);
                return(AddTagged(clazzObjectOut.TermRef, tag) != 0);
            }
            return(false);
        }
Esempio n. 10
0
        public static int ToFieldLayout(string named, string arg1, object o, Type t, PlTerm term, bool childs, bool addNames)
        {
            MemberInfo[] tGetFields = GetStructFormat(t);

            int     len = tGetFields.Length;
            PlTermV tv  = NewPlTermV(len + 1);

            tv[0].UnifyAtom(arg1);
            int tvi = 1;

            for (int i = 0; i < len; i++)
            {
                object v = GetMemberValue(tGetFields[i], o);
                if (v is IList)
                {
                    v.GetType();
                }
                tv[tvi++].FromObject((v));
            }
            if (true)
            {
                return(PlSucceedOrFail(term.Unify(PlC(named, tv))));
            }
            uint termTermRef = term.TermRef;

            uint temp = libpl.PL_new_term_ref();

            libpl.PL_cons_functor_v(temp,
                                    libpl.PL_new_functor(libpl.PL_new_atom(named), tv.Size),
                                    tv.A0);
            return(libpl.PL_unify(termTermRef, temp));
        }
Esempio n. 11
0
 private static string AsString(PlTerm term1)
 {
     if (term1.IsVar)
     {
         Warn("AsString IsVar {0}", term1);
         return(null);
     }
     if (IsTaggedObject(term1))
     {
         var obj = GetInstance(term1);
         if (obj != null)
         {
             return("" + obj);
         }
     }
     if (term1.IsCompound)
     {
         return(term1.Name);
     }
     if (term1.IsAtom)
     {
         return(term1.Name);
     }
     if (term1.IsString)
     {
         return((string)term1);
     }
     return((string)term1);
 }
Esempio n. 12
0
        public void Intern(string varname, object value)
        {
            PlTerm termin = PlTerm.PlVar();

            termin.FromObject(value);
            ModuleCall("Intern", PlNamed(varname), termin);
        }
Esempio n. 13
0
        public static PlTerm ToProlog(object value)
        {
            PlTerm t = PlTerm.PlVar();

            t.FromObject(value);
            return(t);
        }
Esempio n. 14
0
 internal static PlTerm ToPLCS(Term args)
 {
     if (args is Atom)
     {
         return(new PlTerm(args.name()));
     }
     if (args is jpl.Variable)
     {
         return(new PlTerm((uint)GetField(args, "term_")));
     }
     if (args is jpl.Float)
     {
         return(new PlTerm(args.doubleValue()));
     }
     if (args is jpl.Integer)
     {
         return(new PlTerm(args.longValue()));
     }
     if (args is jpl.Compound)
     {
         return(PlTerm.PlCompound(args.name(), ToPLCSV(args.args())));
     }
     if (args is jpl.JRef)
     {
         var jref = (jpl.JRef)args;// return new PlTerm(args.doubleValue());
         var obj  = jref.@ref();
         var t    = new PlTerm();
         t.FromObject(obj);
         return(t);
     }
     throw new ArgumentOutOfRangeException();
 }
Esempio n. 15
0
 public static object GetInstance(PlTerm classOrInstance)
 {
     if (classOrInstance.IsVar)
     {
         Warn("GetInstance(PlVar) {0}", classOrInstance);
         return null;
     }
     if (!classOrInstance.IsCompound)
     {
         if (classOrInstance.IsString)
         {
             Debug("GetInstance(string) {0}", classOrInstance);
             return (string)classOrInstance;
         }
         if (classOrInstance.IsAtom)
         {
             if (classOrInstance.Name == "[]")
             {
                 return CastCompoundTerm("[]", 0, classOrInstance, classOrInstance, null);
             }
             Type t = GetType(classOrInstance);
             // we do this for static invokations like: cliGet('java.lang.Integer','MAX_VALUE',...)
             // the arg1 denotes a type, then return null!
             if (t != null) return null;
             Warn("GetInstance(atom) {0}", classOrInstance);
             // possibly should always return null?!
         }
         return CastTerm(classOrInstance, null);
     }
     string name = classOrInstance.Name;
     int arity = classOrInstance.Arity;
     return CastCompoundTerm(name, arity, classOrInstance[1], classOrInstance, null);
 }
Esempio n. 16
0
 //[TestMethod]
 public void StreamRead()
 {
     PlEngine.SetStreamReader(Sread);
     // NOTE: read/1 needs a dot ('.') at the end
     PlQuery.PlCall("assert( (test_read(A) :- read(A)) )");
     PlTerm t = PlQuery.PlCallQuery("test_read(A)");
     //     Assert.AreEqual(ref_string_read, t.ToString() + ".");
 }
Esempio n. 17
0
        internal static Term ToJPL(PlTerm o)
        {
            switch (o.PlType)
            {
            case PlType.PlAtom:
            {
                return(new Atom((string)o));
            }
            break;

            case PlType.PlInteger:
            {
                return(new jpl.Integer((long)o));
            }
            break;

            case PlType.PlFloat:
            {
                return(new jpl.Float((double)o));
            }
            break;

            case PlType.PlString:
            {
                return(new jpl.Atom((string)o));
            }
            break;

            case PlType.PlTerm:
            {
                var a = o.Arity;
                var c = new jpl.Compound(o.Name, a);
                for (int i = 1; i <= a; i++)
                {
                    c.setArg(i, ToJPL(o[i]));
                }
                return(c);
            }
            break;

            case PlType.PlVariable:
            {
                var v = new jpl.Variable();
                SetField(v, "term_", o.TermRef);
                return(v);
            }
            break;

            case PlType.PlUnknown:
            {
                return(jpl.Util.textToTerm((string)o));
            }
            break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Esempio n. 18
0
        static public bool cliAddRecomposer(PlTerm clazzSpec, PlTerm memberSpec, PlTerm obj2r, PlTerm r2obj)
        {
            Type   type  = GetType(clazzSpec);
            string name  = memberSpec.Name;
            int    arity = memberSpec.Arity;

            AddPrologTermRecomposer(type, "user", obj2r.Name, r2obj.Name, name, arity);
            return(true);
        }
Esempio n. 19
0
 public static Class GetTypeThrowIfMissing(PlTerm clazzSpec)
 {
     Type fi = GetType(clazzSpec);
     if (fi == null)
     {
         throw new PlException("cant find class" + clazzSpec);
     }
     return fi;
 }
Esempio n. 20
0
        static public bool cliIsLayout(PlTerm predIndic)
        {
            string key = PredicateName(predIndic) + "/" + PredicateArity(predIndic);

            lock (FunctorToLayout)
            {
                return(FunctorToLayout.ContainsKey(key));
            }
        }
Esempio n. 21
0
        private static void AddMemberToList(MemberInfo info, List <PlTerm> list, string cname, int ordinal)
        {
            PlTerm memb = MemberTerm(info, cname, ordinal);

            if (memb.TermRef != 0)
            {
                list.Add(memb);
            }
        }
Esempio n. 22
0
        public static Class GetTypeThrowIfMissing(PlTerm clazzSpec)
        {
            Type fi = GetType(clazzSpec);

            if (fi == null)
            {
                throw new PlException("cant find class" + clazzSpec);
            }
            return(fi);
        }
Esempio n. 23
0
        public object GetSymbol(string name)
        {
            PlTerm termout = PlTerm.PlVar();

            if (!ModuleCall("GetSymbol", PlNamed(name), termout))
            {
                return(null);
            }
            return(PrologCLR.CastTerm(termout, typeof(System.Object)));
        }
Esempio n. 24
0
        private static PlTerm ToPlListParams(ParameterInfo[] terms)
        {
            PlTerm listOf = ATOM_NIL;

            for (int i = terms.Length - 1; i >= 0; i--)
            {
                PlTerm term = typeToSpec(terms[i].ParameterType);
                listOf = PlTerm.PlCompound(".", term, listOf);
            }
            return(listOf);
        }
Esempio n. 25
0
        private static PlTerm ToPlListTypes(Type[] terms)
        {
            PlTerm listOf = ATOM_NIL;

            for (int i = terms.Length - 1; i >= 0; i--)
            {
                PlTerm term = typeToSpec(terms[i]);
                listOf = PlTerm.PlCompound(".", term, listOf);
            }
            return(listOf);
        }
Esempio n. 26
0
        static public bool cliMemberDoc(PlTerm membIn, PlTerm docOut, PlTerm xmlOut)
        {
            var mi = GetInstance(membIn) as MemberInfo;

            if (mi != null)
            {
                XElement xmls = GetDocString(mi);
                return(xmlOut.Unify(ToProlog(xmls)) && docOut.Unify(PlTerm.PlString(xmls == null ? "" : xmls.InnerXml)));
            }
            return(true);
        }
Esempio n. 27
0
 public static bool IsDefined(string module, string functor, int arity)
 {
     if (!ClientReady)
     {
         return(false);
     }
     return(InvokeFromC(() => PlQuery.PlCall(null, "predicate_property",
                                             new PlTermV(
                                                 ModuleTerm(module,
                                                            FunctorTerm(functor, arity)),
                                                 PlTerm.PlVar())), true));
 }
Esempio n. 28
0
 private static PlTerm ModuleTerm(string module, PlTerm term)
 {
     if (module == null)
     {
         return(term);
     }
     if (term.IsCompound && term.Arity == 2 && term.Name == ":")
     {
         return(term);
     }
     return(PlC(":", new[] { PlTerm.PlAtom(module), term }));
 }
Esempio n. 29
0
        private static void FillArray(PlTerm[] terms, Type elementType, Array al)
        {
            int termsLength = terms.Length;
            var idxIter     = new ArrayIndexEnumerator(al);

            for (int i = 0; i < termsLength; i++)
            {
                idxIter.MoveNext();
                PlTerm term = terms[i];
                al.SetValue(CastTerm(term, elementType), idxIter.Current);
            }
        }
Esempio n. 30
0
 private static int ToVMNumber(object o, PlTerm term)
 {
     if (o is int)
     {
         return(libpl.PL_unify_integer(term.TermRef, (int)Convert.ToInt32(o)));
     }
     if (PreserveObjectType)
     {
         return(PlSucceedOrFail(UnifyTagged(o, term)));
     }
     // signed types
     if (o is short || o is sbyte)
     {
         return(libpl.PL_unify_integer(term.TermRef, (int)Convert.ToInt32(o)));
     }
     if (o is long)
     {
         return(libpl.PL_unify_integer(term.TermRef, (long)Convert.ToInt64(o)));
     }
     if (o is decimal || o is Single || o is float || o is double)
     {
         return(libpl.PL_unify_float(term.TermRef, (double)Convert.ToDouble(o)));
     }
     // unsigned types
     if (o is ushort || o is byte)
     {
         return(libpl.PL_unify_integer(term.TermRef, (int)Convert.ToInt32(o)));
     }
     if (o is UInt32)
     {
         return(libpl.PL_unify_integer(term.TermRef, (long)Convert.ToInt64(o)));
     }
     // potentually too big?!
     if (o is ulong)
     {
         ulong u64 = (ulong)o;
         if (u64 <= Int64.MaxValue)
         {
             return(libpl.PL_unify_integer(term.TermRef, (long)Convert.ToInt64(o)));
         }
         return(PlSucceedOrFail(term.Unify(u64)));
         //return libpl.PL_unify_float(term.TermRef, (double)Convert.ToDouble(o));
     }
     if (o is IntPtr)
     {
         return(libpl.PL_unify_intptr(term.TermRef, (IntPtr)o));
     }
     if (o is UIntPtr)
     {
         return(libpl.PL_unify_intptr(term.TermRef, (IntPtr)o));
     }
     return(-1);
 }
Esempio n. 31
0
 /// <summary>
 /// cliLoadAssembly('SwiPlCs.dll').
 /// cliLoadAssembly('Cogbot.exe').
 /// </summary>
 /// <param name="term1"></param>
 /// <returns></returns>
 public static bool cliLoadAssembly(PlTerm term1)
 {
     PingThreadFactories();
     try
     {
         return(cliLoadAssemblyUncaught(term1));
     }
     catch (Exception e)
     {
         Warn("cliLoadAssembly: {0} caused {1}", term1, e);
         return(false);
     }
 }
Esempio n. 32
0
        private static PlTermV ToPLCSV1(PlTerm a0, PlTerm[] terms)
        {
            int     size   = terms.Length;
            PlTermV target = NewPlTermV(size + 1);
            int     to     = 1;

            target[0] = a0;
            for (int i = 0; i < size; i++)
            {
                target[to++] = terms[i];
            }
            return(target);
        }
Esempio n. 33
0
 internal static PlTerm ToPLCS(Term args)
 {
     if (args is Atom) return new PlTerm(args.name());
     if (args is jpl.Variable) return new PlTerm((uint)GetField(args, "term_"));
     if (args is jpl.Float) return new PlTerm(args.doubleValue());
     if (args is jpl.Integer) return new PlTerm(args.longValue());
     if (args is jpl.Compound) return PlTerm.PlCompound(args.name(), ToPLCSV(args.args()));
     if (args is jpl.JRef)
     {
         var jref = (jpl.JRef)args;// return new PlTerm(args.doubleValue());
         var obj = jref.@ref();
         var t = new PlTerm();
         t.FromObject(obj);
         return t;
     }
     throw new ArgumentOutOfRangeException();
 }
Esempio n. 34
0
 public CycTypeInfo(PlTerm fort, Type type)
 {
     cycFort = fort;
     CType = type;
     typeFort[type] = this;
     if (type.IsEnum)
     {
         SetupEnum();
     }
     else if (type.IsInterface)
     {
         SetupType("Interface");
     }
     else if (type.IsClass)
     {
         SetupType("Class");
     }
 }
Esempio n. 35
0
 static public bool cliPropsForType(PlTerm clazzSpec, PlTerm memberSpecList)
 {
     Type type = GetType(clazzSpec);
     var props = GetPropsForTypes(type);
     var value = props.Key.ToArray();
     int len = value.Length;
     var termv = ATOM_NIL;
     for (int i = len - 1; i >= 0; i--)
     {
         termv = PlC(".", ToProlog((value[i].Name)), termv);
     }
     var value2 = props.Value.ToArray();
     len = value2.Length;
     for (int i = len - 1; i >= 0; i--)
     {
         termv = PlC(".", ToProlog((value2[i].Name)), termv);
     }
     return memberSpecList.Unify(termv);
 }
Esempio n. 36
0
 private static bool UnifySpecialObject(PlTerm plTerm, object ret1)
 {
     if (plTerm.IsVar)
     {
         return plTerm.FromObject(ret1);
     }
     else
     {
         var plvar = PlTerm.PlVar();
         return plvar.FromObject(ret1) && SpecialUnify(plTerm, plvar);
     }
 }
Esempio n. 37
0
 private static bool SpecialUnify(PlTerm valueOut, PlTerm plvar)
 {
     bool b = valueOut.Unify(plvar);
     if (b) return true;
     object obj1 = GetInstance(plvar);
     if (ReferenceEquals(obj1, null))
     {
         return false;
     }
     Type t1 = obj1.GetType();
     object obj2 = CastTerm(valueOut, t1);
     if (ReferenceEquals(obj2, null))
     {
         return false;
     }
     Type t2 = obj2.GetType();
     if (obj1.Equals(obj2))
     {
         return true;
     }
     if (t1 == t2)
     {
         return false;
     }
     return false;
 }
Esempio n. 38
0
 private static PlTermV ToPlTermV(PlTerm[] terms)
 {
     var tv = NewPlTermV(terms.Length);
     for (int i = 0; i < terms.Length; i++)
     {
         tv[i] = terms[i];
     }
     return tv;
 }
Esempio n. 39
0
 private static PlTerm ModuleTerm(string module, PlTerm term)
 {
     if (module == null) return term;
     if (term.IsCompound && term.Arity == 2 && term.Name == ":") return term;
     return PlC(":", new[] {PlTerm.PlAtom(module), term});
 }
Esempio n. 40
0
        static public bool cliJavaToString(PlTerm paramIn, PlTerm valueOut)
        {
            if (!valueOut.IsVar)
            {
                var plvar = PlTerm.PlVar();
                return cliJavaToString(paramIn, plvar) && SpecialUnify(valueOut, plvar);
            }
            object getInstance = GetInstance(paramIn);
            if (getInstance == null) return valueOut.Unify(PlTerm.PlString("null"));
#if USE_IKVM
            object val = getInstance as java.lang.Object;
            if (val == null)
            {
                Class c = ikvm.runtime.Util.getClassFromObject(getInstance);
                string s = (string)c.getMethod("toString", new Class[0]).invoke(getInstance, ZERO_OBJECTS);
                return valueOut.Unify(PlTerm.PlString(s));
            }
            return valueOut.Unify(PlTerm.PlString(val.toString()));
#else
            object val = getInstance;
            return valueOut.Unify(PlTerm.PlString(val.ToString()));
#endif
        }
Esempio n. 41
0
 private static bool GetInstanceAndType(PlTerm clazzOrInstance, out object getInstance, out Type c)
 {
     if (clazzOrInstance.IsVar)
     {
         c = null;
         getInstance = null;
         return Error("Cant find instance {0}", clazzOrInstance);
     }
     getInstance = GetInstance(clazzOrInstance);
     c = GetTypeFromInstance(getInstance, clazzOrInstance);
     if (getInstance == null && c == null)
     {
         return Error("Cant find instance or type {0}", clazzOrInstance);
     }
     return true;
 }
Esempio n. 42
0
        private static bool NeedsToMakeRef(object al, PlTerm newVar)
        {
            var resoreMadeARef = MadeARef;
            var restoreMakeNoRefs = MakeNoRefs;
            try
            {

                MadeARef = false;
                MakeNoRefs = true;
                int doit = UnifyToPrologImmediate(al, newVar);
                if (!MadeARef)
                {
                    return false;
                }
                return true;
            }
            finally
            {
                MadeARef = resoreMadeARef;
                MakeNoRefs = restoreMakeNoRefs;
            }
        }
Esempio n. 43
0
 public static bool cliBreak(PlTerm ex)
 {
     Trace();
     return WarnMissing(ToString(ex)) || true;
 }
Esempio n. 44
0
 private static PlTermV ToPLCSV(PlTerm[] terms)
 {
     int size = terms.Length;
     PlTermV target = NewPlTermV(size);
     for (int i = 0; i < size; i++)
     {
         target[i] = terms[i];
     }
     return target;
 }
Esempio n. 45
0
 public static bool cliMakeDefault(PlTerm typeSpec, PlTerm valueOut)
 {
     CheckMI();
     MethodInfo rc = MakeDefaultViaReflectionInfo.MakeGenericMethod(GetType(typeSpec));
     return UnifyTagged(rc.Invoke(null, ZERO_OBJECTS), valueOut);
 }
Esempio n. 46
0
 private static PlTermV ToPLCSV1(PlTerm a0, PlTerm[] terms)
 {
     int size = terms.Length;
     PlTermV target = NewPlTermV(size + 1);
     int to = 1;
     target[0] = a0;
     for (int i = 0; i < size; i++)
     {
         target[to++] = terms[i];
     }
     return target;
 }
Esempio n. 47
0
 internal static Term ToJPL(PlTerm o)
 {
     switch (o.PlType)
     {
         case PlType.PlAtom:
             {
                 return new Atom((string)o);
             }
             break;
         case PlType.PlInteger:
             {
                 return new jpl.Integer((long)o);
             }
             break;
         case PlType.PlFloat:
             {
                 return new jpl.Float((double)o);
             }
             break;
         case PlType.PlString:
             {
                 return new jpl.Atom((string)o);
             }
             break;
         case PlType.PlTerm:
             {
                 var a = o.Arity;
                 var c = new jpl.Compound(o.Name, a);
                 for (int i = 1; i <= a; i++)
                 {
                     c.setArg(i, ToJPL(o[i]));
                 }
                 return c;
             }
             break;
         case PlType.PlVariable:
             {
                 var v = new jpl.Variable();
                 SetField(v, "term_", o.TermRef);
                 return v;
             }
             break;
         case PlType.PlUnknown:
             {
                 return jpl.Util.textToTerm((string)o);
             }
             break;
         default:
             throw new ArgumentOutOfRangeException();
     }
 }
Esempio n. 48
0
 private static PlTerm ToPlList(PlTerm[] terms)
 {
     int termLen = terms.Length;
     if (termLen == 0) return ATOM_NIL;
     termLen--;
     PlTerm ret = listOfOne(terms[termLen]);
     while (--termLen >= 0)
     {
         ret = PlTerm.PlCompound(".", terms[termLen], ret);
     }
     return ret;
 }
Esempio n. 49
0
        /// <summary>
        /// Returns the Type when denoated by a 'namespace.type' (usefull for static instance specification)
        ///    if a @C#234234  the type of the object unless its a a class
        ///    c(a) => System.Char   "sdfsdf" =>  System.String   uint(5) => System.UInt32
        /// 
        ///    instanceMaybe maybe Null.. it is passed in so the method code doesn't have to call GetInstance again
        ///       on classOrInstance
        /// </summary>
        /// <param name="instanceMaybe"></param>
        /// <param name="classOrInstance"></param>
        /// <returns></returns>
        private static Type GetTypeFromInstance(object instanceMaybe, PlTerm classOrInstance)
        {
            if (classOrInstance.IsAtom)
            {
                return GetType(classOrInstance);
            }
            if (classOrInstance.IsString)
            {
                if (instanceMaybe != null) return instanceMaybe.GetType();
                return typeof(string);
            }
            if (classOrInstance.IsCompound)
            {
                if (classOrInstance.Name == "static")
                {
                    return GetType(classOrInstance[1]);
                }
            }

            object val = instanceMaybe ?? GetInstance(classOrInstance);
            //if (val is Type) return (Type)val;
            if (val == null)
            {
                Warn("GetTypeFromInstance: {0}", classOrInstance);
                return null;
            }
            return val.GetType();
        }
Esempio n. 50
0
        public static int UnifyToPrologImmediate(object o, PlTerm term)
        {
            uint TermRef = term.TermRef;
            if (o is PlTerm)
            {
                return libpl.PL_unify(TermRef, ((PlTerm)o).TermRef);
            } 
            if (o is string)
            {
                string s = (string)o;
                switch (VMStringsAsAtoms)
                {
                    case libpl.CVT_STRING:
                        {
                            try
                            {
                                return libpl.PL_unify_string_chars(TermRef, (string)o);
                            }
                            catch (Exception)
                            {

                                return UnifyAtom(TermRef, s);
                            }
                        }
                    case libpl.CVT_ATOM:
                        try
                        {
                            return libpl.PL_unify_atom_chars(TermRef, (string)o);
                        }
                        catch (Exception)
                        {

                            return UnifyAtom(TermRef, s);
                        }
                    case libpl.CVT_LIST:
                        return libpl.PL_unify_list_chars(TermRef, (string)o);
                    default:
                        Warn("UNKNOWN VMStringsAsAtoms {0}", VMStringsAsAtoms);
                        return libpl.PL_fail;
                }
            }
            if (o == null)
            {
                return AddTagged(TermRef, "null");
            }

            if (o is Type || o is Type)
            {
                if (true)
                {
                    //lock (ToFromConvertLock)
                    {
                        var tag = object_to_tag(o);
                        AddTagged(TermRef, tag);
                        return libpl.PL_succeed;
                    }
                }
                return PlSucceedOrFail(term.Unify(typeToSpec((Type)o)));
            }

            Type t = o.GetType();
            if (t == typeof(void))
            {
                return AddTagged(TermRef, "void");
            }
            if (o is ValueType)
            {
                if (o is bool)
                {
                    bool tf = (bool)o;
                    return AddTagged(TermRef, tf ? "true" : "false");
                }
                if (o is char)
                {
                    try
                    {
                        char ch = (char)o;
                        string cs = new string(ch, 1);
                        switch (VMStringsAsAtoms)
                        {
                            case libpl.CVT_STRING:
                                return libpl.PL_unify_atom_chars(TermRef, cs);
                            case libpl.CVT_ATOM:
                                return libpl.PL_unify_atom_chars(TermRef, cs);
                            case libpl.CVT_LIST:
                                return libpl.PL_unify_integer(TermRef, (int)ch);
                            default:
                                Warn("UNKNOWN VMStringsAsAtoms {0}", VMStringsAsAtoms);
                                return libpl.PL_fail;
                        }
                    }
                    catch (Exception e)
                    {
                        Warn("@TODO unmappable errors? {0} type {1}", o, t);
                        //
                    }
                }
                if (t.IsEnum)
                {
                    int res = FromEnum(TermRef, o, t);
                    ///term.ToString();
                    return res;
                }
                if (t.IsPrimitive)
                {
                    try
                    {
                        int res = ToVMNumber(o, term);
                        if (res == libpl.PL_succeed) return res;
                        if (res == libpl.PL_fail) return res;
                        if (res != -1)
                        {
                            // Warn("@TODO Missing code for ToVmNumber? " + o + " type " + t);
                            return res;
                        }
                        if (t.IsPrimitive)
                        {
                            Warn("@TODO Missing code for primitive? {0} type {1}", o, t);
                        }
                    }
                    catch (Exception e)
                    {
                        Warn("@TODO unmappable errors? {0} type {1}", o, t);
                    }
                }
            }
            lock (FunctorToLayout)
            {
                PrologTermLayout layout;
                if (TypeToLayout.TryGetValue(t, out layout))
                {
                    MemberInfo[] tGetFields = layout.FieldInfos;// GetStructFormat(t);
                    int len = tGetFields.Length;
                    PlTermV tv = NewPlTermV(len);
                    for (int i = 0; i < len; i++)
                    {
                        object v = GetMemberValue(tGetFields[i], o);
                        tv[i].FromObject((v));
                    }
                    return PlSucceedOrFail(term.Unify(PlC(layout.Name, tv)));
                }
            }
            lock (FunctorToRecomposer)
            {
                PrologTermRecomposer layout = GetTypeMap(t, TypeToRecomposer);
                if (layout != null)
                {
                    lock (ToFromConvertLock)
                    {
                        var tag = object_to_tag(o);
                        uint newref = libpl.PL_new_term_refs(2);
                        AddTagged(newref, tag);
                        PlTerm into = new PlTerm(newref);
                        PlTerm outto = new PlTerm(newref + 1);
                        var ret = PlQuery.PlCall(layout.module, layout.obj2r, new PlTermV(into, outto));
                        if (ret)
                        {
                            return term.Unify(outto) ? libpl.PL_succeed
                                   : libpl.PL_fail;

                        }
                    }
                }
            }
            if (o is IList)
            {

            }
            if (IsStructRecomposable(t))
            {
                return ToFieldLayout("struct", typeToName(t), o, t, term, false, false);
            }
            if (o is EventArgs)
            {
                return ToFieldLayout("event", typeToName(t), o, t, term, false, false);
            }
            if (t.IsArray)
            {
                Array al = (Array) o;
                if (false && al.Length > 0 && al.Length < 1024)
                {
                    Type et = t.GetElementType();
                    object firstNonNull = null;
                    foreach (var ele in al)
                    {
                        if (ele!=null)
                        {
                            firstNonNull = ele;
                        }
                    }
                    var needMake = firstNonNull != null;
                    if (needMake)
                    {
                        PlTerm newVar = PlTerm.PlVar();
                        needMake = NeedsToMakeRef(firstNonNull, newVar);
                    }
                    if (!needMake)
                    {
                        return PlSucceedOrFail(unifyArrayToTerm(al, term));
                    }
                }
            }
            return PlObject(TermRef, o);
        }
Esempio n. 51
0
 public static bool cliThrow(PlTerm ex)
 {
     throw (Exception) CastTerm(ex, typeof (Exception));
 }
Esempio n. 52
0
        public static int UnifyToProlog(object o, PlTerm term)
        {
            if (!term.IsVar)
            {
                Warn("Not a free var {0}", term);
                return libpl.PL_fail;
            }
            uint TermRef = term.TermRef;
            if (TermRef == 0)
            {
                Warn("Not a allocated term {0}", o);
                return libpl.PL_fail;
            }

#if USE_IKVM
            if (o is Term) return UnifyToProlog(ToPLCS((Term)o), term);
#endif
            if (PreserveObjectType)
            {
                return PlSucceedOrFail(UnifyTagged(o, term));
            }
            return UnifyToPrologImmediate(o, term);
        }
Esempio n. 53
0
 public static bool cliToStrRaw(PlTerm obj, PlTerm str)
 {
     try
     {
         if (!str.IsVar)
         {
             var plvar = PlTerm.PlVar();
             return cliToStrRaw(obj, plvar) && SpecialUnify(str, plvar);
         }
         if (obj.IsString) return str.Unify(obj);
         if (obj.IsVar) return str.Unify((string)obj);
         object o = GetInstance(obj);
         if (o == null) return str.FromObject("" + obj);
         return str.FromObject(ToString(o));
     }
     catch (Exception e)
     {
         Warn("cliToString: {0}", e);
         object o = GetInstance(obj);
         if (o == null) return str.FromObject("" + obj);
         return str.FromObject(ToString(o));
     }
 }
Esempio n. 54
0
        public static Class GetType(PlTerm clazzSpec, bool canBeObjects)
        {
            if (clazzSpec.IsVar)
            {
                Error("GetType IsVar {0}", clazzSpec);
                return null;
            }
            if (IsTaggedObject(clazzSpec))
            {
                object tagObj = tag_to_object(clazzSpec[1].Name);
                var r = tagObj as Type;
                if (r != null) return r;
                if (!canBeObjects)
                {
                    Warn("cant find tagged object as class: {0}=>{1}", clazzSpec, tagObj);
                }
                if (tagObj != null)
                {
                    return tagObj.GetType();
                }
                return null;
            }
            Type type = null;
            if (clazzSpec.IsAtom || clazzSpec.IsString)
            {
                if (canBeObjects) return typeof (string);
                string name = (string)clazzSpec;
                type = ResolveType(name);
                if (type != null) return type;
                if (!canBeObjects)
                {
                    Warn("cant find atom/string as class: {0}", clazzSpec);
                    type = ResolveType(name);
                }
                return null;
            }
            if (clazzSpec.IsCompound)
            {
                string clazzName = clazzSpec.Name;
                int arity = clazzSpec.Arity;
                if (clazzName == "arrayOf")
                {
                    if (arity != 1)
                    {
                        return GetType(clazzSpec[1]).MakeArrayType(clazzSpec[2].intValue());
                    }
                    return GetType(clazzSpec[1]).MakeArrayType();
                }
                if (clazzName == "type")
                {
                    return (GetInstance(clazzSpec[1]) ?? NEW_OBJECTFORTYPE).GetType();
                }
                if (clazzName == "static" || clazzName == "typeof")
                {
                    return GetType(clazzSpec[1]);
                }
                if (clazzName == "{}")
                {
                    return typeof (PlTerm);
                }
                if (clazzName == "pointer")
                {
                    return GetType(clazzSpec[1]).MakePointerType();
                }
                if (clazzName == "byref")
                {
                    return GetType(clazzSpec[1]).MakeByRefType();
                }
                if (clazzName == "nullable")
                {
                    return typeof(Nullable<>).MakeGenericType(new[] { GetType(clazzSpec[1]) });
                }
                type = ResolveType(clazzName + "`" + arity);
                if (type != null)
                {
                    // 'Dictionary'('Int32','string').
                    if (type.IsGenericType)
                    {
                        Type[] genr = type.GetGenericArguments();
                        Type[] genrc = null;
                        Type genrb = null;
                        try
                        {
                            if (type.IsGenericParameter)
                            {
                                genrc = type.GetGenericParameterConstraints();
                            }
                        }
                        catch (Exception e)
                        {
                            Warn("GetGenericParameterConstraints: {0}", e);
                        }
                        try
                        {
                            genrb = type.GetGenericTypeDefinition();
                        }
                        catch (Exception e)
                        {
                            Warn("GetGenericTypeDefinition: {0}", e);
                        }

                        if (arity == genr.Length)
                        {
                            var vt = GetParamSpec(ToTermArray(clazzSpec), false);
                            return type.MakeGenericType(vt);
                        }
                    }
                    //  return type;
                }
                string key = clazzName + "/" + arity;
                lock (FunctorToLayout)
                {
                    PrologTermLayout pltl;
                    if (FunctorToLayout.TryGetValue(key, out pltl))
                    {
                        return pltl.ObjectType;
                    }
                }
                lock (FunctorToRecomposer)
                {
                    PrologTermRecomposer layout;
                    if (FunctorToRecomposer.TryGetValue(key, out layout))
                    {
                        return layout.ToType;
                    }
                }
                WarnMissing("cant find compound as class: " + clazzSpec);
            }
            object toObject = GetInstance(clazzSpec);
            if (toObject is Type) return (Type)toObject;
            if (toObject != null)
            {
                return toObject.GetType();
            }
            Warn("@TODO cant figure type from {0}", clazzSpec);
            return typeof(object);
            //return null;
        }
Esempio n. 55
0
 static public bool cliLockExit(PlTerm lockObj)
 {
     object getInstance = GetInstance(lockObj);
     Monitor.Exit(getInstance);
     return true;
 }
Esempio n. 56
0
 internal static jpl.fli.term_t ToFLI(PlTerm args)
 {
     return ToFLI(args.TermRef);
 }
Esempio n. 57
0
 public static bool cliMemberDoc(PlTerm membIn, PlTerm docOut, PlTerm xmlOut)
 {
     var mi = GetInstance(membIn) as MemberInfo;
     if (mi != null)
     {
         XElement xmls = GetDocString(mi);
         return xmlOut.Unify(ToProlog(xmls)) && docOut.Unify(PlTerm.PlString(xmls == null ? "" : xmls.InnerXml));
     }
     return true;
 }
Esempio n. 58
0
 private static PlTerm listOfOne(PlTerm term)
 {
     return PlTerm.PlCompound(".", term, ATOM_NIL);
 }
Esempio n. 59
0
 private static bool link_swiplcs(PlTerm pathName)
 {
     try
     {
         return true;
         if (JplSafeNativeMethodsCalled)
         {
             bool enabled = !JplSafeNativeMethodsDisabled;
             SafelyRun(
                 () => ConsoleTrace("JplSafeNativeMethods called again from " + pathName + " result=" + enabled));
             return enabled;
         }
         JplSafeNativeMethodsCalled = true;
         SafelyRun(() => ConsoleTrace("JplSafeNativeMethods call first time from " + pathName));
         JplSafeNativeMethods.install();
         //var v = new PlTerm("_1");
         //JplSafeNativeMethods.jpl_c_lib_version_1_plc(v.TermRef);
         return true;
     }
     catch (Exception e)
     {
         JplSafeNativeMethodsDisabled = true;
         WriteException(e);
         return false;
     }
 }
Esempio n. 60
0
        public static bool cliMembers(PlTerm clazzOrInstance, PlTerm membersSpecListOut)
        {
            object getInstance;
            Type c;
            if (!GetInstanceAndType(clazzOrInstance, out getInstance, out c)) return false;
            MemberInfo[] members = c.GetMembers(BindingFlagsALL);
            List<PlTerm> list = new List<PlTerm>();
            string cname = c.Name;
            List<MemberInfo> exclude = new List<MemberInfo>();
            int ordinal = 0;
            foreach (var info in c.GetFields(BindingFlagsALL))
            {
                AddMemberToList(info, list, cname, ordinal++);
                exclude.Add(info);
            }
            ordinal = 0;
            foreach (var info in c.GetProperties(BindingFlagsALL))
            {
                AddMemberToList(info, list, cname, ordinal++);
                exclude.Add(info);
            }
            ordinal = 0;
            foreach (var info in c.GetMethods(BindingFlagsALL))
            {
                AddMemberToList(info, list, cname, ordinal++);
                exclude.Add(info);
            }
            ordinal = 0;
            foreach (var info in c.GetConstructors(BindingFlagsALL))
            {
                AddMemberToList(info, list, cname, ordinal++);
                exclude.Add(info);
            }
            ordinal = 0;
            foreach (var info in c.GetEvents(BindingFlagsALL))
            {
                AddMemberToList(info, list, cname, ordinal++);
                exclude.Add(info);
            }

            foreach (MemberInfo info in members)
            {
                break;
                try
                {
                    if (exclude.Contains(info)) continue;
                }
                catch (Exception e)
                {
                    Embedded.Debug("Warn exclude.Contains {0}: {1}", info, e);
                    continue;
                }
                AddMemberToList(info, list, cname, ordinal++);
                exclude.Add(info);
            }

            return membersSpecListOut.Unify(ToPlArray(list.ToArray()));
        }