Beispiel #1
0
 internal static Expression[] GenTypedArgs(GenContext context, ParameterInfo[] parms, IPersistentVector args)
 {
     Expression[] exprs = new Expression[parms.Length];
     for (int i = 0; i < parms.Length; i++)
         exprs[i] = GenTypedArg(context,parms[i].ParameterType, (Expr)args.nth(i));
     return exprs;
 }
Beispiel #2
0
        public InvokeExpr(string source, IPersistentMap spanMap, Symbol tag, Expr fexpr, IPersistentVector args)
        {
            _source = source;
            _spanMap = spanMap;
            _fexpr = fexpr;
            _args = args;

            VarExpr varFexpr = fexpr as VarExpr;

            if (varFexpr != null)
            {
                Var fvar = varFexpr.Var;
                Var pvar = (Var)RT.get(fvar.meta(), Compiler.ProtocolKeyword);
                if (pvar != null && Compiler.ProtocolCallsitesVar.isBound)
                {
                    _isProtocol = true;
                    _siteIndex = Compiler.RegisterProtocolCallsite(fvar);
                    Object pon = RT.get(pvar.get(), _onKey);
                    _protocolOn = HostExpr.MaybeType(pon, false);
                    if (_protocolOn != null)
                    {
                        IPersistentMap mmap = (IPersistentMap)RT.get(pvar.get(), _methodMapKey);
                        Keyword mmapVal = (Keyword)mmap.valAt(Keyword.intern(fvar.sym));
                        if (mmapVal == null)
                        {
                            throw new ArgumentException(String.Format("No method of interface: {0} found for function: {1} of protocol: {2} (The protocol method may have been defined before and removed.)",
                                _protocolOn.FullName, fvar.Symbol, pvar.Symbol));
                        }
                        String mname = Compiler.munge(mmapVal.Symbol.ToString());

                        IList<MethodBase> methods = Reflector.GetMethods(_protocolOn, mname, null, args.count() - 1,  false);
                        if (methods.Count != 1)
                            throw new ArgumentException(String.Format("No single method: {0} of interface: {1} found for function: {2} of protocol: {3}",
                                mname, _protocolOn.FullName, fvar.Symbol, pvar.Symbol));
                        _onMethod = (MethodInfo) methods[0];
                    }
                }
            }

            if (tag != null)
                _tag = tag;
            else if (varFexpr != null)
            {
                object arglists = RT.get(RT.meta(varFexpr.Var), Compiler.ArglistsKeyword);
                object sigTag = null;
                for (ISeq s = RT.seq(arglists); s != null; s = s.next())
                {
                    APersistentVector sig = (APersistentVector)s.first();
                    int restOffset = sig.IndexOf(Compiler.AmpersandSym);
                    if (args.count() == sig.count() || (restOffset > -1 && args.count() >= restOffset))
                    {
                        sigTag = Compiler.TagOf(sig);
                        break;
                    }
                }
                _tag = sigTag ?? varFexpr.Tag;
            }
            else
                _tag = null;
        }
Beispiel #3
0
        public static Expr Parse(ParserContext pcon, IPersistentVector form)
        {
            ParserContext pconToUse = pcon.EvEx();
            bool constant = true;

            IPersistentVector args = PersistentVector.EMPTY;
            for (int i = 0; i < form.count(); i++ )
            {
                Expr v = Compiler.Analyze(pconToUse, form.nth(i));
                args = (IPersistentVector)args.cons(v);
                if ( !(v is LiteralExpr) )
                    constant = false;
            }

            Expr ret = new VectorExpr(args);
            if ( form is IObj && ((IObj)form).meta() != null )
                return Compiler.OptionallyGenerateMetaInit(pcon,form, ret);
            else if ( constant )
            {
                IPersistentVector rv = PersistentVector.EMPTY;
                for ( int i=0; i<args.count(); i++ )
                {
                    LiteralExpr ve = (LiteralExpr)args.nth(i);
                    rv = (IPersistentVector)rv.cons(ve.Val);
                }
                return new ConstantExpr(rv);
            }
            else
                return ret;
        }
Beispiel #4
0
 public RecurExpr(string source, IPersistentMap spanMap, IPersistentVector loopLocals, IPersistentVector args)
 {
     _loopLocals = loopLocals;
     _args = args;
     _source = source;
     _spanMap = spanMap;
 }
        public StaticMethodExpr(Type type, string methodName, IPersistentVector args)
        {
            _type = type;
            _methodName = methodName;
            _args = args;

            _method  = GetMatchingMethod(_type, _args, _methodName);
        }
Beispiel #6
0
        private static void DefineMethod(TypeBuilder proxyTB, IPersistentVector sig)
        {
            string mname = (string)sig.nth(0);
            Type[] paramTypes = GenClass.CreateTypeArray((ISeq)sig.nth(1));
            Type retType = (Type)sig.nth(2);

            MethodBuilder mb = proxyTB.DefineMethod(mname, MethodAttributes.Abstract | MethodAttributes.Public| MethodAttributes.Virtual, retType, paramTypes);
        }
Beispiel #7
0
        //readonly int _retLocal;
        //readonly int _finallyLocal;

        #endregion

        #region Ctors

        public TryExpr(Expr tryExpr, IPersistentVector catchExprs, Expr finallyExpr, int retLocal, int finallyLocal)
        {
            _tryExpr     = tryExpr;
            _catchExprs  = catchExprs;
            _finallyExpr = finallyExpr;
            //_retLocal = retLocal;
            //_finallyLocal = finallyLocal;
        }
Beispiel #8
0
        public void Setup()
        {
            IPersistentVector v = LazilyPersistentVector.createOwning(1, 2, 3);

            _testNoChange = false;
            _obj          = _objWithNullMeta = (IObj)v;
            _expectedType = typeof(PersistentVector);
        }
Beispiel #9
0
        public void PopLosesTheValue()
        {
            MapEntry          me = new MapEntry(1, "abc");
            IPersistentVector v  = (IPersistentVector)me.pop();

            Expect(v.length(), EqualTo(1));
            Expect(v.nth(0), EqualTo(1));
        }
Beispiel #10
0
        public StaticMethodExpr(Type type, string methodName, IPersistentVector args)
        {
            _type       = type;
            _methodName = methodName;
            _args       = args;

            _method = GetMatchingMethod(_type, _args, _methodName);
        }
        public InstanceMethodExpr(Expr target, string methodName, IPersistentVector args)
        {
            _target = target;
            _methodName = methodName;
            _args = args;

            _method = GetMatchingMethod(target, _args, _methodName);
        }
Beispiel #12
0
 public InvokeExpr(string source, int line, Symbol tag, Expr fexpr, IPersistentVector args)
 {
     _source = source;
     _line = line;
     _fexpr = fexpr;
     _args = args;
     _tag = tag ?? (fexpr is VarExpr ? ((VarExpr)fexpr).Tag : null);
 }
Beispiel #13
0
 public TryExpr(Expr tryExpr, IPersistentVector catchExprs, Expr finallyExpr, int retLocal, int finallyLocal)
 {
     _tryExpr = tryExpr;
     _catchExprs = catchExprs;
     _finallyExpr = finallyExpr;
     _retLocal = retLocal;
     _finallyLocal = finallyLocal;
 }
Beispiel #14
0
 public StaticInvokeExpr(Type target, Type retType, Type[] paramTypes, bool variadic, IPersistentVector args, Symbol tag)
 {
     _target = target;
     _retType = retType;
     _paramTypes = paramTypes;
     _variadic = variadic;
     _args = args;
     _tag = tag;
 }
Beispiel #15
0
 public StaticInvokeExpr(Type target, MethodInfo method, bool variadic, IPersistentVector args, object tag)
 {
     //_target = target;
     _method   = method;
     _retType  = method.ReturnType;
     _variadic = variadic;
     _args     = args;
     _tag      = tag;
 }
        static bool doEquiv(IPersistentVector v, object obj)
        {
            if (obj is IPersistentVector ipv)
            {
                if (ipv.count() != v.count())
                {
                    return(false);
                }

                for (int i = 0; i < v.count(); i++)
                {
                    if (!Util.equiv(v.nth(i), ipv.nth(i)))
                    {
                        return(false);
                    }
                }
                return(true);
            }

            if (obj is IList ilist)
            {
                if (ilist.Count != v.count())   // THis test in the JVM code can't be right:  || ma.GetHashCode() != v.GetHashCode())
                {
                    return(false);
                }

                for (int i = 0; i < v.count(); i++)
                {
                    if (!Util.equiv(v.nth(i), ilist[i]))
                    {
                        return(false);
                    }
                }
                return(true);
            }

            if (!(obj is Sequential))
            {
                return(false);
            }

            ISeq ms = RT.seq(obj);

            for (int i = 0; i < v.count(); i++, ms = ms.next())
            {
                if (ms == null || !Util.equiv(v.nth(i), ms.first()))
                {
                    return(false);
                }
            }
            if (ms != null)
            {
                return(false);
            }

            return(true);
        }
        public void AssocNAddsAtEndForEmpty()
        {
            PersistentVector  v1 = PersistentVector.create();
            IPersistentVector v2 = v1.assocN(0, "abc");

            Expect(v1.count(), EqualTo(0));
            Expect(v2.count(), EqualTo(1));
            Expect(v2.nth(0), EqualTo("abc"));
        }
Beispiel #18
0
        public static Expr Parse(IPersistentVector form)
        {
            IPersistentVector args = PersistentVector.EMPTY;
            for (int i = 0; i < form.count(); i++ )
                args = (IPersistentVector)args.cons(Compiler.GenerateAST(form.nth(i),false));

            Expr ret = new VectorExpr(args);
            return Compiler.OptionallyGenerateMetaInit(form, ret);
        }
        public void CreatingOwningOnParamsReturnsVector()
        {
            IPersistentVector v = LazilyPersistentVector.createOwning(1, 2, 3);

            Expect(v.count(), EqualTo(3));
            Expect(v.nth(0), EqualTo(1));
            Expect(v.nth(1), EqualTo(2));
            Expect(v.nth(2), EqualTo(3));
        }
        public void CreateOnNonEmptyCollectionReturnsVector()
        {
            IPersistentVector v = LazilyPersistentVector.createOwning(new object[] { 1, 2, 3 });

            Expect(v.count(), EqualTo(3));
            Expect(v.nth(0), EqualTo(1));
            Expect(v.nth(1), EqualTo(2));
            Expect(v.nth(2), EqualTo(3));
        }
        public void NthInRangeWorks()
        {
            IPersistentVector v = LazilyPersistentVector.createOwning(1, 2, 3);

            Expect(v.count(), EqualTo(3));
            Expect(v.nth(0), EqualTo(1));
            Expect(v.nth(1), EqualTo(2));
            Expect(v.nth(2), EqualTo(3));
        }
Beispiel #22
0
 public StaticInvokeExpr(Type target, MethodInfo method, bool variadic, IPersistentVector args, object tag)
 {
     //_target = target;
     _method = method;
     _retType = method.ReturnType;
     _variadic = variadic;
     _args = args;
     _tag = tag;
 }
Beispiel #23
0
        public void NthInRangeWorks()
        {
            IPersistentVector v = LazilyPersistentVector.createOwning(1, 2, 3);

            Expect(v.count()).To.Equal(3);
            Expect(v.nth(0)).To.Equal(1);
            Expect(v.nth(1)).To.Equal(2);
            Expect(v.nth(2)).To.Equal(3);
        }
        private static object[] GetCtorArgs(IPersistentVector v)
        {
            object[] args = new object[v.length()];
            for (int i = 0; i < v.length(); i++)
            {
                args[i] = v.nth(i);
            }

            return(args);
        }
Beispiel #25
0
        /// <summary>
        /// Create a <see cref="PersistentVector">PersistentVector</see> from an <see cref="ISeq">ISeq</see>.
        /// </summary>
        /// <param name="items">A sequence of items.</param>
        /// <returns>An initialized vector.</returns>
        static public PersistentVector create(ISeq items)
        {
            IPersistentVector ret = EMPTY;

            for (; items != null; items = items.next())
            {
                ret = ret.cons(items.first());
            }
            return((PersistentVector)ret);
        }
Beispiel #26
0
        /// <summary>
        /// Create a <see cref="PersistentVector">PersistentVector</see> from an array of items.
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        static public PersistentVector create(params object[] items)
        {
            IPersistentVector ret = EMPTY;

            foreach (object item in items)
            {
                ret = ret.cons(item);
            }
            return((PersistentVector)ret);
        }
Beispiel #27
0
        private static Type[] SeqToTypeArray(IPersistentVector interfaces)
        {
            Type[] types = new Type[interfaces.count()];
            for (int i = 0; i < interfaces.count(); i++)
            {
                types[i] = (Type)interfaces.nth(i);
            }

            return(types);
        }
        public object Eval()
        {
            IPersistentVector ret = PersistentVector.EMPTY;

            for (int i = 0; i < _args.count(); i++)
            {
                ret = (IPersistentVector)ret.cons(((Expr)_args.nth(i)).Eval());
            }
            return(ret);
        }
        public StaticMethodExpr(string source, int line, Type type, string methodName, IPersistentVector args)
        {
            _source = source;
            _line = line;
            _type = type;
            _methodName = methodName;
            _args = args;

            _method  = GetMatchingMethod(line, _type, _args, _methodName);
        }
Beispiel #30
0
        public static Expr Parse(Var v, ISeq args, object tag)
        {
            if (!v.isBound || v.get() == null)
            {
                //Console.WriteLine("Not bound: {0}", v);
                return(null);
            }

            Type target = v.get().GetType();

            MethodInfo[] allMethods = target.GetMethods();
            bool         variadic   = false;
            int          argcount   = RT.count(args);
            MethodInfo   method     = null;

            ParameterInfo[] pInfos = null;

            foreach (MethodInfo m in allMethods)
            {
                //Console.WriteLine("Method {0}", m.Name);
                if (m.IsStatic && m.Name.Equals("invokeStatic"))
                {
                    pInfos = m.GetParameters();
                    if (argcount == pInfos.Length)
                    {
                        method   = m;
                        variadic = argcount > 0 && pInfos[pInfos.Length - 1].ParameterType == typeof(ISeq);
                        break;
                    }
                    else if (argcount > pInfos.Length &&
                             pInfos.Length > 0 &&
                             pInfos[pInfos.Length - 1].ParameterType == typeof(ISeq))
                    {
                        method   = m;
                        variadic = true;
                        break;
                    }
                }
            }

            if (method == null)
            {
                return(null);
            }

            IPersistentVector argv = PersistentVector.EMPTY;

            for (ISeq s = RT.seq(args); s != null; s = s.next())
            {
                argv = argv.cons(Compiler.Analyze(new ParserContext(RHC.Expression), s.first()));
            }

            return(new StaticInvokeExpr(target, method, variadic, argv, tag));
        }
Beispiel #31
0
        public static Expr Parse(ISeq form)
        {
            Expr fexpr             = Compiler.GenerateAST(form.first());
            IPersistentVector args = PersistentVector.EMPTY;

            for (ISeq s = RT.seq(form.next()); s != null; s = s.next())
            {
                args = args.cons(Compiler.GenerateAST(s.first()));
            }
            return(new InvokeExpr(Compiler.TagOf(form), fexpr, args));
        }
Beispiel #32
0
        internal static int GetMatchingParams(string methodName, List<ParameterInfo[]> parmlists, IPersistentVector argexprs, List<Type> rets)
        {
            // Assume matching lengths
            int matchIndex = -1;
            bool tied = false;
            bool foundExact = false;

            for (int i = 0; i < parmlists.Count; i++)
            {
                bool match = true;
                ISeq aseq = argexprs.seq();
                int exact = 0;
                for (int p = 0; match && p < argexprs.count() && aseq != null; ++p, aseq = aseq.next())
                {
                    Expr arg = (Expr)aseq.first();
                    Type atype = arg.HasClrType ? arg.ClrType : typeof(object);
                    Type ptype = parmlists[i][p].ParameterType;
                    if (arg.HasClrType && atype == ptype)
                        exact++;
                    else
                        match = Reflector.ParamArgTypeMatch(ptype, atype);
                }

                if (exact == argexprs.count())
                {
                    if ( !foundExact || matchIndex == -1 || rets[matchIndex].IsAssignableFrom(rets[i]))
                        matchIndex = i;
                    foundExact = true;
                }
                else if (match && !foundExact)
                {
                    if (matchIndex == -1)
                        matchIndex = i;
                    else
                    {
                        if (Reflector.Subsumes(parmlists[i], parmlists[matchIndex]))
                        {
                            matchIndex = i;
                            tied = false;
                        }
                        else if (Array.Equals(parmlists[i], parmlists[matchIndex]))
                            if (rets[matchIndex].IsAssignableFrom(rets[i]))
                                matchIndex = i;
                            else if (!Reflector.Subsumes(parmlists[matchIndex], parmlists[i]))
                                tied = true;
                    }
                }
            }

            if (tied)
                throw new ArgumentException("More than one matching method found: " + methodName);

            return matchIndex;
        }
Beispiel #33
0
        static void AddMethod(Dictionary <IPersistentVector, List <MethodInfo> > mm, IPersistentVector sig, MethodInfo m)
        {
            List <MethodInfo> value;

            if (!mm.TryGetValue(sig, out value))
            {
                value   = new List <MethodInfo>();
                mm[sig] = value;
            }
            value.Add(m);
        }
Beispiel #34
0
        static string[] InterfaceNames(IPersistentVector interfaces)
        {
            int icnt = interfaces.count();

            string[] inames = icnt > 0 ? new string[icnt] : null;
            for (int i = 0; i < icnt; i++)
            {
                inames[i] = SlashName((Type)interfaces.nth(i));
            }
            return(inames);
        }
        public Delegate GenerateTypedDelegate(Type delegateType, Symbol optName, IPersistentVector argList, ISeq body)
        {
            ScriptSource scriptSource = Engine.CreateScriptSourceFromString("<internal>");

            LambdaExpression ast = Generator.GenerateTypedDelegateExpression(GetLanguageContext(), delegateType, optName, argList, body);
            return ast.Compile();

            //ast = new GlobalLookupRewriter().RewriteLambda(ast);  -- doesn't work unless no args
            //ScriptCode code = new ScriptCode(ast, GetSourceUnit(scriptSource));
            //return code;
        }
Beispiel #36
0
        public void ConsOnNon2IPVFails()
        {
            Dictionary <int, string> d = new Dictionary <int, string>();

            d[1] = "a";
            d[2] = "b";

            IPersistentMap m = PersistentArrayMap.create(d);

            IPersistentVector v = PersistentVector.create(2, "c", 3, "d");
            IPersistentMap    c = m.cons(v);
        }
Beispiel #37
0
            private static IPersistentVector flattenMap(object form)
            {
                IPersistentVector keyvals = PersistentVector.EMPTY;

                for (ISeq s = RT.seq(form); s != null; s = s.next())
                {
                    IMapEntry e = (IMapEntry)s.first();
                    keyvals = (IPersistentVector)keyvals.cons(e.key());
                    keyvals = (IPersistentVector)keyvals.cons(e.val());
                }
                return(keyvals);
            }
Beispiel #38
0
        static void ConsiderMethod(MethodInfo m, Dictionary <IPersistentVector, List <MethodInfo> > mm)
        {
            IPersistentVector mk = MSig(m);

            if (!(mm.ContainsKey(mk) ||
                  !(m.IsPublic || m.IsFamily) ||
                  m.IsStatic ||
                  m.IsFinal))
            {
                AddMethod(mm, mk, m);
            }
        }
        public InstanceMethodExpr(string source, int line, Expr target, string methodName, IPersistentVector args)
        {
            _source = source;
            _line = line;
            _target = target;
            _methodName = methodName;
            _args = args;

            if (target.HasClrType && target.ClrType == null)
                throw new ArgumentException(String.Format("Attempt to call instance method {0} on nil", methodName));

            _method = GetMatchingMethod(line, target, _args, _methodName);
        }
Beispiel #40
0
        internal static void EmitArgsAsArray(IPersistentVector args, ObjExpr objx, CljILGen ilg)
        {
            ilg.EmitInt(args.count());
            ilg.Emit(OpCodes.Newarr, typeof(Object));

            for (int i = 0; i < args.count(); i++)
            {
                ilg.Emit(OpCodes.Dup);
                ilg.EmitInt(i);
                ((Expr)args.nth(i)).Emit(RHC.Expression, objx, ilg);
                ilg.Emit(OpCodes.Stelem_Ref);
            }
        }
Beispiel #41
0
        public static Expr Parse(IPersistentVector form)
        {
            IPersistentVector args = PersistentVector.EMPTY;

            for (int i = 0; i < form.count(); i++)
            {
                args = (IPersistentVector)args.cons(Compiler.GenerateAST(form.nth(i)));
            }

            Expr ret = new VectorExpr(args);

            return(Compiler.OptionallyGenerateMetaInit(form, ret));
        }
Beispiel #42
0
        public static Expr Parse(IPersistentSet form)
        {
            IPersistentVector keys = PersistentVector.EMPTY;

            for (ISeq s = RT.seq(form); s != null; s = s.next())
            {
                object e = s.first();
                keys = (IPersistentVector)keys.cons(Compiler.GenerateAST(e));
            }
            Expr ret = new SetExpr(keys);

            return(Compiler.OptionallyGenerateMetaInit(form, ret));
        }
Beispiel #43
0
 /// <summary>
 /// Initialize a subvector, with the given metadata and start/end indices.
 /// </summary>
 /// <param name="meta">The metatdata to attach.</param>
 /// <param name="v">The vector to subvector.</param>
 /// <param name="start">The start index of the subvector.</param>
 /// <param name="end">The end index of the subvector.</param>
 public SubVector(IPersistentMap meta, IPersistentVector v, int start, int end)
     : base(meta)
 {
     if (v is SubVector)
     {
         SubVector sv = (SubVector)v;
         start += sv._start;
         end   += sv._start;
         v      = sv._v;
     }
     _v     = v;
     _start = start;
     _end   = end;
 }
            /// <summary>
            /// Initialize a subvector, with the given metadata and start/end indices.
            /// </summary>
            /// <param name="meta">The metatdata to attach.</param>
            /// <param name="v">The vector to subvector.</param>
            /// <param name="start">The start index of the subvector.</param>
            /// <param name="end">The end index of the subvector.</param>
            public SubVector(IPersistentMap meta, IPersistentVector v, int start, int end)
            {
                _meta = meta;

                if (v is SubVector sv)
                {
                    start += sv._start;
                    end   += sv._start;
                    v      = sv._v;
                }
                _v     = v;
                _start = start;
                _end   = end;
            }
Beispiel #45
0
        public static Expr Parse(IPersistentMap form)
        {
            IPersistentVector keyvals = PersistentVector.EMPTY;

            for (ISeq s = RT.seq(form); s != null; s = s.next())
            {
                IMapEntry e = (IMapEntry)s.first();
                keyvals = (IPersistentVector)keyvals.cons(Compiler.GenerateAST(e.key()));
                keyvals = (IPersistentVector)keyvals.cons(Compiler.GenerateAST(e.val()));
            }
            Expr ret = new MapExpr(keyvals);

            return(Compiler.OptionallyGenerateMetaInit(form, ret));
        }
        public void PopOnNonEmptyWorks()
        {
            IPersistentVector v  = LazilyPersistentVector.createOwning(1, 2, 3);
            IPersistentVector v2 = (IPersistentVector)((IPersistentStack)v).pop();

            Expect(v.count(), EqualTo(3));
            Expect(v.nth(0), EqualTo(1));
            Expect(v.nth(1), EqualTo(2));
            Expect(v.nth(2), EqualTo(3));

            Expect(v2.count(), EqualTo(2));
            Expect(v2.nth(0), EqualTo(1));
            Expect(v2.nth(1), EqualTo(2));
        }
Beispiel #47
0
        public InvokeExpr(string source, IPersistentMap spanMap, Symbol tag, Expr fexpr, IPersistentVector args)
        {
            _source = source;
            _spanMap = spanMap;
            _fexpr = fexpr;
            _args = args;

            if (fexpr is VarExpr)
            {
                Var fvar = ((VarExpr)fexpr).Var;
                Var pvar = (Var)RT.get(fvar.meta(), Compiler.PROTOCOL_KEY);
                if (pvar != null && Compiler.PROTOCOL_CALLSITES.isBound)
                {
                    _isProtocol = true;
                    _siteIndex = Compiler.RegisterProtocolCallsite(fvar);
                    Object pon = RT.get(pvar.get(), _onKey);
                    _protocolOn = HostExpr.MaybeType(pon, false);
                    if (_protocolOn != null)
                    {
                        IPersistentMap mmap = (IPersistentMap)RT.get(pvar.get(), _methodMapKey);
                        Keyword mmapVal = (Keyword)mmap.valAt(Keyword.intern(fvar.sym));
                        if (mmapVal == null)
                        {
                            throw new ArgumentException(String.Format("No method of interface: {0} found for function: {1} of protocol: {2} (The protocol method may have been defined before and removed.)",
                                _protocolOn.FullName, fvar.Symbol, pvar.Symbol));
                        }
                        String mname = Compiler.munge(mmapVal.Symbol.ToString());

                        List<MethodInfo> methods = Reflector.GetMethods(_protocolOn, mname, args.count() - 1,  false);
                        if (methods.Count != 1)
                            throw new ArgumentException(String.Format("No single method: {0} of interface: {1} found for function: {2} of protocol: {3}",
                                mname, _protocolOn.FullName, fvar.Symbol, pvar.Symbol));
                        _onMethod = methods[0];
                    }
                }
                //else if (pvar == null && Compiler.VAR_CALLSITES.isBound
                //    && fvar.Namespace.Name.Name.StartsWith("clojure")
                //    && !RT.booleanCast(RT.get(RT.meta(fvar), _dynamicKey)))
                //{
                //    // Java TODO: more specific criteria for binding these
                //    _isDirect = true;
                //    _siteIndex = Compiler.RegisterVarCallsite(fvar);
                //}
            }

            _tag = tag ?? (fexpr is VarExpr ? ((VarExpr)fexpr).Tag : null);
        }
Beispiel #48
0
        public InvokeExpr(string source, IPersistentMap spanMap, Symbol tag, Expr fexpr, IPersistentVector args)
        {
            _source = source;
            _spanMap = spanMap;
            _fexpr = fexpr;
            _args = args;

            if (fexpr is VarExpr)
            {
                Var fvar = ((VarExpr)fexpr).Var;
                Var pvar = (Var)RT.get(fvar.meta(), Compiler.PROTOCOL_KEY);
                if (pvar != null && Compiler.PROTOCOL_CALLSITES.isBound)
                {
                    _isProtocol = true;
                    _siteIndex = Compiler.RegisterProtocolCallsite(fvar);
                    Object pon = RT.get(pvar.get(), _onKey);
                    _protocolOn = HostExpr.MaybeType(pon, false);
                    if (_protocolOn != null)
                    {
                        IPersistentMap mmap = (IPersistentMap)RT.get(pvar.get(), _methodMapKey);
                        Keyword mmapVal = (Keyword)mmap.valAt(Keyword.intern(fvar.sym));
                        if (mmapVal == null)
                        {
                            throw new ArgumentException(String.Format("No method of interface: {0} found for function: {1} of protocol: {2} (The protocol method may have been defined before and removed.)",
                                _protocolOn.FullName, fvar.Symbol, pvar.Symbol));
                        }
                        String mname = Compiler.munge(mmapVal.Symbol.ToString());

                        List<MethodBase> methods = Reflector.GetMethods(_protocolOn, mname, null, args.count() - 1,  false);
                        if (methods.Count != 1)
                            throw new ArgumentException(String.Format("No single method: {0} of interface: {1} found for function: {2} of protocol: {3}",
                                mname, _protocolOn.FullName, fvar.Symbol, pvar.Symbol));
                        _onMethod = (MethodInfo) methods[0];
                    }
                }
            }

            _tag = tag ?? (fexpr is VarExpr ? ((VarExpr)fexpr).Tag : null);
        }
Beispiel #49
0
        private static void DefineMethod(TypeBuilder proxyTB, IPersistentVector sig)
        {
            Symbol mname = (Symbol)sig.nth(0);
            Type[] paramTypes = GenClass.CreateTypeArray((ISeq)sig.nth(1));
            Type retType = (Type)sig.nth(2);
            ISeq pmetas = (ISeq)(sig.count() >= 4 ? sig.nth(3) : null);

            MethodBuilder mb = proxyTB.DefineMethod(mname.Name, MethodAttributes.Abstract | MethodAttributes.Public| MethodAttributes.Virtual, retType, paramTypes);

            SetCustomAttributes(mb, GenInterface.ExtractAttributes(RT.meta(mname)));
            int i=1;
            for (ISeq s = pmetas; s != null; s = s.next(), i++)
            {
                IPersistentMap meta = GenInterface.ExtractAttributes((IPersistentMap)s.first());
                if (meta != null && meta.count() > 0)
                {
                    ParameterBuilder pb = mb.DefineParameter(i, ParameterAttributes.None, String.Format("p_{0}",i));
                    GenInterface.SetCustomAttributes(pb, meta);
                }
            }
        }
Beispiel #50
0
 public SetExpr(IPersistentVector keys)
 {
     _keys = keys;
 }
        internal static ObjExpr Build(
            IPersistentVector interfaceSyms,
            IPersistentVector fieldSyms,
            Symbol thisSym,
            string tagName,
            Symbol className,
            Symbol typeTag,
            ISeq methodForms,
            Object frm)
        {
            NewInstanceExpr ret = new NewInstanceExpr(null);
            ret._src = frm;
            ret._name = className.ToString();
            ret._classMeta = GenInterface.ExtractAttributes(RT.meta(className));
            ret.InternalName = ret.Name;  // ret.Name.Replace('.', '/');
            // Java: ret.objtype = Type.getObjectType(ret.internalName);

            if (thisSym != null)
                ret._thisName = thisSym.Name;

            if (fieldSyms != null)
            {
                IPersistentMap fmap = PersistentHashMap.EMPTY;
                object[] closesvec = new object[2 * fieldSyms.count()];
                for (int i = 0; i < fieldSyms.count(); i++)
                {
                    Symbol sym = (Symbol)fieldSyms.nth(i);
                    LocalBinding lb = new LocalBinding(-1, sym, null, new MethodParamExpr(Compiler.TagType(Compiler.TagOf(sym))), false, false);
                    fmap = fmap.assoc(sym, lb);
                    closesvec[i * 2] = lb;
                    closesvec[i * 2 + 1] = lb;
                }
                // Java TODO: inject __meta et al into closes - when?
                // use array map to preserve ctor order
                ret._closes = new PersistentArrayMap(closesvec);
                ret._fields = fmap;
                for (int i = fieldSyms.count() - 1; i >= 0 && ((Symbol)fieldSyms.nth(i)).Name.StartsWith("__"); --i)
                    ret._altCtorDrops++;
            }

            // Java TODO: set up volatiles
            //ret._volatiles = PersistentHashSet.create(RT.seq(RT.get(ret._optionsMap, volatileKey)));

            IPersistentVector interfaces = PersistentVector.EMPTY;
            for (ISeq s = RT.seq(interfaceSyms); s != null; s = s.next())
            {
                Type t = (Type)Compiler.Resolve((Symbol)s.first());
                if (!t.IsInterface)
                    throw new ArgumentException("only interfaces are supported, had: " + t.Name);
                interfaces = interfaces.cons(t);
            }
            Type superClass = typeof(Object);

            Dictionary<IPersistentVector, List<MethodInfo>> overrideables;
            GatherMethods(superClass, RT.seq(interfaces), out overrideables);

            ret._methodMap = overrideables;

            //string[] inames = InterfaceNames(interfaces);

            Type stub = CompileStub(superClass, ret, SeqToTypeArray(interfaces),frm);
            Symbol thisTag = Symbol.intern(null, stub.FullName);
            //Symbol stubTag = Symbol.intern(null,stub.FullName);
            //Symbol thisTag = Symbol.intern(null, tagName);

            // Needs its own GenContext so it has its own DynInitHelper
            // Can't reuse Compiler.EvalContext if it is a DefType because we have to use the given name and will get a conflict on redefinition
            GenContext context = Compiler.COMPILER_CONTEXT.get() as GenContext ?? (ret.IsDefType ? new GenContext("deftype" + RT.nextID().ToString(),".dll",".",true) : Compiler.EvalContext);
            GenContext genC = context.WithNewDynInitHelper(ret.InternalName + "__dynInitHelper_" + RT.nextID().ToString());
            //genC.FnCompileMode = FnMode.Full;

            try
            {
                Var.pushThreadBindings(
                    RT.map(
                        Compiler.CONSTANTS, PersistentVector.EMPTY,
                        Compiler.CONSTANT_IDS, new IdentityHashMap(),
                        Compiler.KEYWORDS, PersistentHashMap.EMPTY,
                        Compiler.VARS, PersistentHashMap.EMPTY,
                        Compiler.KEYWORD_CALLSITES, PersistentVector.EMPTY,
                        Compiler.PROTOCOL_CALLSITES, PersistentVector.EMPTY,
                        Compiler.VAR_CALLSITES, PersistentVector.EMPTY,
                        Compiler.COMPILER_CONTEXT, genC
                        ));

                if (ret.IsDefType)
                {
                    Var.pushThreadBindings(
                        RT.map(
                            Compiler.METHOD, null,
                            Compiler.LOCAL_ENV, ret._fields,
                            Compiler.COMPILE_STUB_SYM, Symbol.intern(null, tagName),
                            Compiler.COMPILE_STUB_CLASS, stub
                            ));
                }
                // now (methodname [args] body)*
                // TODO: SourceLocation?
                //ret.line = (Integer)LINE.deref();
                IPersistentCollection methods = null;
                for (ISeq s = methodForms; s != null; s = RT.next(s))
                {
                    NewInstanceMethod m = NewInstanceMethod.Parse(ret, (ISeq)RT.first(s), thisTag, overrideables);
                    methods = RT.conj(methods, m);
                }

                ret._methods = methods;
                ret.Keywords = (IPersistentMap)Compiler.KEYWORDS.deref();
                ret.Vars = (IPersistentMap)Compiler.VARS.deref();
                ret.Constants = (PersistentVector)Compiler.CONSTANTS.deref();
                ret._constantsID = RT.nextID();
                ret.KeywordCallsites = (IPersistentVector)Compiler.KEYWORD_CALLSITES.deref();
                ret.ProtocolCallsites = (IPersistentVector)Compiler.PROTOCOL_CALLSITES.deref();
                ret.VarCallsites = (IPersistentVector)Compiler.VAR_CALLSITES.deref();
            }
            finally
            {
                if (ret.IsDefType)
                    Var.popThreadBindings();
                Var.popThreadBindings();
            }

            ret.Compile(stub, interfaces, false, genC);
            Compiler.RegisterDuplicateType(ret.CompiledType);

            return ret;
        }
Beispiel #52
0
        internal static Expression[] GenTypedArgArray(GenContext context, ParameterInfo[] infos, IPersistentVector args)
        {
            Expression[] exprs = new Expression[args.count()];

            for (int i = 0; i < infos.Length; i++)
            {
                Expr e = (Expr)args.nth(i);
                // Java: this is in a try/catch, where the catch prints a stack trace
                if (MaybePrimitiveType(e) == infos[i].ParameterType)
                    exprs[i] = ((MaybePrimitiveExpr)e).GenDlrUnboxed(context);
                else
                    // Java follows this with: HostExpr.emitUnboxArg(fn, gen, parameterTypes[i]);
                    //exprs[i] = e.GenDlr(context);
                    exprs[i] = Expression.Convert(e.GenDlr(context), infos[i].ParameterType); ;
            }
            return exprs;
        }
        private static Type[] SeqToTypeArray(IPersistentVector interfaces)
        {
            Type[] types = new Type[interfaces.count()];
            for (int i = 0; i < interfaces.count(); i++)
                types[i] = (Type)interfaces.nth(i);

            return types;
        }
Beispiel #54
0
        public Type Compile(Type superType, Type stubType, IPersistentVector interfaces, bool onetimeUse, GenContext context)
        {
            if (_compiledType != null)
                return _compiledType;

            string publicTypeName = IsDefType || (_isStatic && Compiler.IsCompiling) ? InternalName : InternalName + "__" + RT.nextID();

            //Console.WriteLine("DefFn {0}, {1}", publicTypeName, context.AssemblyBuilder.GetName().Name);

            _typeBuilder = context.AssemblyGen.DefinePublicType(publicTypeName, superType, true);
            context = context.WithNewDynInitHelper().WithTypeBuilder(_typeBuilder);

            Var.pushThreadBindings(RT.map(Compiler.CompilerContextVar, context));

            try
            {
                if (interfaces != null)
                {
                    for (int i = 0; i < interfaces.count(); i++)
                        _typeBuilder.AddInterfaceImplementation((Type)interfaces.nth(i));
                }

                ObjExpr.MarkAsSerializable(_typeBuilder);
                GenInterface.SetCustomAttributes(_typeBuilder, _classMeta);

                try
                {
                    if (IsDefType)
                    {
                        Compiler.RegisterDuplicateType(_typeBuilder);

                        Var.pushThreadBindings(RT.map(
                            Compiler.CompileStubOrigClassVar, stubType
                            ));
                        //,
                        //Compiler.COMPILE_STUB_CLASS, _baseType));
                    }
                    EmitConstantFieldDefs(_typeBuilder);
                    EmitKeywordCallsiteDefs(_typeBuilder);

                    DefineStaticConstructor(_typeBuilder);

                    if (SupportsMeta)
                        _metaField = _typeBuilder.DefineField("__meta", typeof(IPersistentMap), FieldAttributes.Public | FieldAttributes.InitOnly);

                    EmitClosedOverFields(_typeBuilder);
                    EmitProtocolCallsites(_typeBuilder);

                    _ctorInfo = EmitConstructor(_typeBuilder, superType);

                    if (_altCtorDrops > 0)
                        EmitFieldOnlyConstructor(_typeBuilder, superType);

                    if (SupportsMeta)
                    {
                        EmitNonMetaConstructor(_typeBuilder, superType);
                        EmitMetaFunctions(_typeBuilder);
                    }

                    EmitStatics(_typeBuilder);
                    EmitMethods(_typeBuilder);

                    //if (KeywordCallsites.count() > 0)
                    //    EmitSwapThunk(_typeBuilder);

                    _compiledType = _typeBuilder.CreateType();

                    if (context.DynInitHelper != null)
                        context.DynInitHelper.FinalizeType();

                    //  If we don't pick up the ctor after we finalize the type,
                    //    we sometimes get a ctor which is not a RuntimeConstructorInfo
                    //  This causes System.DynamicILGenerator.Emit(opcode,ContructorInfo) to blow up.
                    //    The error says the ConstructorInfo is null, but there is a second case in the code.
                    //  Thank heavens one can run Reflector on mscorlib.

                    ConstructorInfo[] cis = _compiledType.GetConstructors();
                    foreach (ConstructorInfo ci in cis)
                    {
                        if (ci.GetParameters().Length == CtorTypes().Length)
                        {
                            _ctorInfo = ci;
                            break;
                        }
                    }

                    return _compiledType;
                }
                finally
                {
                    if (IsDefType)
                        Var.popThreadBindings();
                }
            }
            finally
            {
                Var.popThreadBindings();
            }
        }
Beispiel #55
0
        internal static Expression GenArgArray(GenContext context, IPersistentVector args)
        {
            Expression[] exprs = new Expression[args.count()];

            for (int i = 0; i < args.count(); i++)
            {
                Expr arg = (Expr)args.nth(i);
                exprs[i] = Compiler.MaybeBox(arg.GenDlr(context));
            }

            Expression argArray = Expression.NewArrayInit(typeof(object), exprs);
            return argArray;
        }
Beispiel #56
0
 /// <summary>
 /// Send an action (encapsulated message).
 /// </summary>
 /// <param name="action">The action to execute.</param>
 /// <remarks>
 /// <para>If there is a transaction running on this thread, 
 /// defer execution until the transaction ends 
 /// (enqueue the action on the transaction).</para>
 /// <para>If there is already an action running, enqueue it (nested).</para>
 /// <para>Otherwise, queue it for execution.</para>
 /// </remarks>
 internal static void DispatchAction(Action action)
 {
     LockingTransaction trans = LockingTransaction.GetRunning();
     if (trans != null)
         trans.Enqueue(action);
     else if (_nested != null)
         _nested = _nested.cons(action);
     else
         action.Agent.Enqueue(action);
 }
Beispiel #57
0
        private static object[] GetCtorArgs(IPersistentVector v)
        {
            object[] args = new object[v.length()];
            for (int i = 0; i < v.length(); i++)
                args[i] = v.nth(i);

            return args;
        }
 static string[] InterfaceNames(IPersistentVector interfaces)
 {
     int icnt = interfaces.count();
     string[] inames = icnt > 0 ? new string[icnt] : null;
     for (int i = 0; i < icnt; i++)
         inames[i] = SlashName((Type)interfaces.nth(i));
     return inames;
 }
Beispiel #59
0
 public LetFnExpr(IPersistentVector bindingInits, Expr body)
 {
     _bindingInits = bindingInits;
     _body = body;
 }
Beispiel #60
0
 internal static Expression[] GenTypedArgs(ObjExpr objx, GenContext context, Type[] paramTypes, IPersistentVector args)
 {
     Expression[] exprs = new Expression[paramTypes.Length];
     for (int i = 0; i < paramTypes.Length; i++)
         exprs[i] = GenTypedArg(objx, context, paramTypes[i], (Expr)args.nth(i));
     return exprs;
 }