Exemplo n.º 1
0
 public override Expression GenDlr(GenContext context)
 {
     if (_method != null)
         return Compiler.MaybeBox(GenDlrForMethod(context));
     else
         return GenDlrViaReflection(context);
 }
Exemplo n.º 2
0
        public override Expression GenDlr(GenContext context)
        {
            Expression exc = _excExpr.GenDlr(context);
            Expression exc2 = Expression.Convert(exc, typeof(Exception));

            return Expression.Throw(exc2);
        }
Exemplo n.º 3
0
        private Expression GenDlrForMethod(GenContext context)
        {
            Expression target = _target.GenDlr(context);
            Expression[] args = GenTypedArgs(context, _method.GetParameters(), _args);

            return AstUtils.SimpleCallHelper(target,_method, args); ;
        }
        internal static Type Create(GenContext context, Type baseClass)
        {
            //ModuleBuilder mb = context.ModuleBldr;
            string name = baseClass.Name + "_impl";
            //TypeBuilder baseTB = context.ModuleBldr.DefineType(name, TypeAttributes.Class | TypeAttributes.Public, baseClass);
            TypeBuilder baseTB = context.AssemblyGen.DefinePublicType(name, baseClass, true);

            ObjExpr.MarkAsSerializable(baseTB);

            baseTB.DefineDefaultConstructor(MethodAttributes.Public);

            FieldBuilder metaField = baseTB.DefineField("_meta", typeof(IPersistentMap), FieldAttributes.Public);

            MethodBuilder metaMB = baseTB.DefineMethod("meta", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.ReuseSlot, typeof(IPersistentMap), Type.EmptyTypes);
            ILGen gen = new ILGen(metaMB.GetILGenerator());
            gen.EmitLoadArg(0);
            gen.EmitFieldGet(metaField);
            gen.Emit(OpCodes.Ret);

            MethodBuilder withMB = baseTB.DefineMethod("withMeta", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.ReuseSlot, typeof(IObj), new Type[] { typeof(IPersistentMap)});
            gen = new ILGen(withMB.GetILGenerator());
            gen.EmitLoadArg(0);
            gen.EmitCall(Compiler.Method_Object_MemberwiseClone);
            gen.Emit(OpCodes.Castclass, baseTB);
            gen.Emit(OpCodes.Dup);
            gen.EmitLoadArg(1);
            gen.EmitFieldSet(metaField);
            gen.Emit(OpCodes.Ret);

            for (int i = 0; i < 20; i++ )
                DefineDelegateFieldAndOverride(baseTB, i);

            return baseTB.CreateType();
        }
Exemplo n.º 5
0
        public static Type GenerateInterface(string iName, ISeq extends, ISeq methods)
        {
            GenContext context = new GenContext(iName, CompilerMode.File);

            //            GenContext context = (GenContext)Compiler.COMPILER_CONTEXT.deref();
            //            if (context == null)
            //            {
            //#if DEBUG
            //                context = new GenContext(iName, CompilerMode.File);
            //#else
            //                throw new InvalidOperationException("No compiler context on the stack.");
            //#endif
            //            }

            Type[] interfaceTypes = GenClass.CreateTypeArray(extends == null ? null : extends.seq());

            TypeBuilder proxyTB = context.ModuleBldr.DefineType(
                iName,
                TypeAttributes.Interface | TypeAttributes.Public | TypeAttributes.Abstract,
                null,
                interfaceTypes);

            DefineMethods(proxyTB, methods);

            Type t = proxyTB.CreateType();
            context.AssyBldr.Save(iName  + ".dll");
            return t;
        }
Exemplo n.º 6
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;
 }
Exemplo n.º 7
0
        public Expression GenCode(RHC rhc, ObjExpr objx, GenContext context)
        {
            List<Expression> exprs = new List<Expression>();

            ParameterExpression parm = Expression.Parameter(typeof(Var), "v");

            Expression varExpr = objx.GenVar(context,_var);

            exprs.Add(Expression.Assign(parm, varExpr));

            // The Java code does the following in the opposite order (as modified in commit #430dd4f, Jan 19, 2010)
            // However, the call to bindRoot sets :macro to False.  I'm not sure how it works now in the JVM version.

            if (_initProvided )
                // Java doesn't Box here, but we have to deal with unboxed bool values
                exprs.Add(Expression.Call(parm, Compiler.Method_Var_bindRoot, Compiler.MaybeBox(_init.GenCode(RHC.Expression,objx,context))));

            if (_meta != null)
            {
                if (_initProvided || IncludesExplicitMetadata((MapExpr)_meta))
                {
                    // Java casts to IPersistentMap on the _meta, but Expression.Call can handle that for us.
                    exprs.Add(Expression.Call(parm, Compiler.Method_Var_setMeta, _meta.GenCode(RHC.Expression,objx,context)));
                }
            }

            exprs.Add(parm);

            return Expression.Block(new ParameterExpression[] { parm }, exprs);
        }
Exemplo n.º 8
0
        public Expression GenCode(RHC rhc, ObjExpr objx, GenContext context)
        {
            int n = _bindingInits.count();
            List<ParameterExpression> parms = new List<ParameterExpression>(n);
            List<Expression> forms = new List<Expression>(n);

            /// First, set up the environment.
            for (int i = 0; i < n; i++)
            {
                BindingInit bi = (BindingInit)_bindingInits.nth(i);
                ParameterExpression parmExpr = Expression.Parameter(typeof(IFn), bi.Binding.Name);
                bi.Binding.ParamExpression = parmExpr;
                parms.Add(parmExpr);
            }

            // Then initialize
            for (int i = 0; i < n; i++)
            {
                BindingInit bi = (BindingInit)_bindingInits.nth(i);
                ParameterExpression parmExpr = (ParameterExpression)bi.Binding.ParamExpression;
                forms.Add(Expression.Assign(parmExpr, bi.Init.GenCode(RHC.Expression,objx,context)));
            }

            // The work
            forms.Add(_body.GenCode(rhc,objx,context));
            return Expression.Block(parms,forms);
        }
Exemplo n.º 9
0
 public override Expression GenDlr(GenContext context)
 {
     Expression getTypeExpr = Expression.Call(null, Compiler.Method_RT_classForName, Expression.Constant(_c));
     //Expression getNsExpr = Expression.Call(null, Compiler.Method_Compiler_CurrentNamespace);
     Expression getNsExpr = Expression.Property(null, Compiler.Method_Compiler_CurrentNamespace);
     return Expression.Call(getNsExpr, Compiler.Method_Namespace_importClass1, getTypeExpr);
 }
Exemplo n.º 10
0
 public override Expression GenDlrUnboxed(GenContext context)
 {
     if (_method != null)
         return GenDlrForMethod(context);
     else
         throw new InvalidOperationException("Unboxed emit of unknown member.");
 }
Exemplo n.º 11
0
        public override Expression GenDlr(GenContext context)
        {
            Expression basicBody = _tryExpr.GenDlr(context);
            // Wrap the basic body, a Comma, in a return to a label
            LabelTarget target = Expression.Label(basicBody.Type, "ret_label");
            //Expression tryBody = Expression.Return(target, basicBody);
            Expression tryBody = basicBody;

            CatchBlock[] catches = new CatchBlock[_catchExprs.count()];
            for ( int i=0; i<_catchExprs.count(); i++ )
            {
                CatchClause clause = (CatchClause) _catchExprs.nth(i);
                ParameterExpression parmExpr = Expression.Parameter(clause.Type, clause.Lb.Name);
                clause.Lb.ParamExpression = parmExpr;
                catches[i] = Expression.Catch(parmExpr,clause.Handler.GenDlr(context));
            }

            TryExpression tryStmt = _finallyExpr == null
                ? Expression.TryCatch(tryBody, catches)
                : Expression.TryCatchFinally(tryBody, _finallyExpr.GenDlr(context), catches);

            Expression defaultValue = Expression.Default(basicBody.Type);
            Expression whole = Expression.Block(tryStmt, Expression.Label(target, defaultValue));
            return whole;
        }
Exemplo n.º 12
0
        public override Expression GenCode(RHC rhc, ObjExpr objx, GenContext context)
        {
            Expression exc = _excExpr.GenCode(RHC.Expression, objx, context);
            Expression exc2 = Expression.Convert(exc, typeof(Exception));

            return Expression.Throw(exc2,typeof(object));
        }
Exemplo n.º 13
0
 internal static Expression GenTypedArg(GenContext context, Type type, Expr arg)
 {
     if (Compiler.MaybePrimitiveType(arg) == type)
         return ((MaybePrimitiveExpr)arg).GenDlrUnboxed(context);
     else
         // Java has emitUnboxArg -- should we do something similar?
         return arg.GenDlr(context);
 }
Exemplo n.º 14
0
 internal static Expression GenTypedArg(GenContext context, Type type, Expr arg)
 {
     if (Compiler.MaybePrimitiveType(arg) == type)
         return ((MaybePrimitiveExpr)arg).GenDlrUnboxed(context);
     else
     {
         Expression argExpr = arg.GenDlr(context);
         return GenMaybeUnboxedArg(type, argExpr);
     }
 }
Exemplo n.º 15
0
        public override Expression GenCode(RHC rhc, ObjExpr objx, GenContext context)
        {
            Expression call;

            if (_method != null)
                call = GenDlrForMethod(objx, context);
            else
                call = GenerateComplexCall(objx, context);
            call = Compiler.MaybeAddDebugInfo(call, _spanMap, context.IsDebuggable);
            return call;
        }
Exemplo n.º 16
0
        public Expression GenCode(RHC rhc, ObjExpr objx, GenContext context)
        {
            Expression objExpr = _expr.GenCode(RHC.Expression, objx, context);
            Expression iobjExpr = Expression.Convert(objExpr, typeof(IObj));

            Expression metaExpr = _meta.GenCode(RHC.Expression, objx, context);
            metaExpr = Expression.Convert(metaExpr, typeof(IPersistentMap));

            Expression ret = Expression.Call(iobjExpr, Compiler.Method_IObj_withMeta, metaExpr);

            return ret;
        }
Exemplo n.º 17
0
        public Expression GenCode(RHC rhc, ObjExpr objx, GenContext context)
        {
            Expression objExpr = _expr.GenCode(RHC.Expression, objx, context);
            Expression iobjExpr = Expression.Convert(objExpr, typeof(IObj));

            Expression metaExpr = _meta.GenCode(RHC.Expression, objx, context);
            // Do we need a conversion here?  probably not.

            Expression ret = Expression.Call(iobjExpr, Compiler.Method_IObj_withMeta, metaExpr);

            return ret;
        }
Exemplo n.º 18
0
        public Expression GenCodeUnboxed(RHC rhc, ObjExpr objx, GenContext context)
        {
            Type t = _n.GetType();

            if (t == typeof(int))
                return Expression.Constant((long)(int)_n, typeof(long));
            else if (t == typeof(double))
                return Expression.Constant((double)_n, typeof(double));
            else if ( t == typeof(long) )
                return Expression.Constant((long)_n,typeof(long));

            throw new ArgumentException("Unsupported Number type: " + _n.GetType().Name);
        }
Exemplo n.º 19
0
        internal static Type Create(GenContext context, Type baseClass)
        {
            ModuleBuilder mb = context.ModuleBldr;
            string name = baseClass.Name + "_impl";
            TypeBuilder baseTB = context.ModuleBldr.DefineType(name, TypeAttributes.Class | TypeAttributes.Public, baseClass);

            baseTB.DefineDefaultConstructor(MethodAttributes.Public);

            for (int i = 0; i < 20; i++ )
                DefineDelegateFieldAndOverride(baseTB, i);

            return baseTB.CreateType();
        }
Exemplo n.º 20
0
        static public void EmitDynamicCallPostlude(LambdaExpression lambda, Type delType, MethodBuilder mbLambda, CljILGen ilg)
        {
            GenContext context = Compiler.CompilerContextVar.deref() as GenContext;

            if (context == null)
            {
                // light compile

                MethodInfo mi = delType.GetMethod("Invoke");
                ilg.Emit(OpCodes.Callvirt, mi);
            }
            else
            {
                ilg.Emit(OpCodes.Call, mbLambda);
            }
        }
Exemplo n.º 21
0
        public override Expression GenDlr(GenContext context)
        {
            Expression fn = _fexpr.GenDlr(context);
            fn = Expression.Convert(fn, typeof(IFn));

            int argCount = _args.count();

            Expression[] args = new Expression[argCount];

            for (int i = 0; i < argCount; i++ )
                args[i] = Compiler.MaybeBox(((Expr)_args.nth(i)).GenDlr(context));

            Expression call = GenerateInvocation(InvocationReturnType, fn, args);

            return call;
        }
Exemplo n.º 22
0
        private void EmitStaticConstructorBody(CljILGen ilg)
        {
            GenContext.EmitDebugInfo(ilg, SpanMap);

            if (Constants.count() > 0)
            {
                EmitConstantFieldInits(ilg);
            }

            if (KeywordCallsites.count() > 0)
            {
                EmitKeywordCallsiteInits(ilg);
            }

            ilg.Emit(OpCodes.Ret);
        }
Exemplo n.º 23
0
        GenProxy(string className)
        {
            if (Compiler.IsCompiling)
            {
                //string path = (string)Compiler.COMPILE_PATH.deref();
                //if (path == null)
                //    throw new Exception("*compile-path* not set");

                ////string dir = (string)Compiler.SOURCE_PATH.deref();

                //_context = new GenContext(className, ".dll", path, CompilerMode.File);
                _context = (GenContext)Compiler.CompilerContextVar.deref();
            }
            else
                _context = GenContext.CreateWithInternalAssembly("proxy" + (++_saveId).ToString(), false);
        }
Exemplo n.º 24
0
        internal LambdaExpression GenerateImmediateLambda(RHC rhc, ObjExpr objx, GenContext context)
        {
            List <ParameterExpression> parmExprs = new List <ParameterExpression>(_argLocals.count());

            if (_thisBinding != null)
            {
                _thisBinding.ParamExpression = objx.ThisParam;
            }

            try
            {
                LabelTarget loopLabel = Expression.Label("top");

                Var.pushThreadBindings(RT.map(Compiler.LoopLabelVar, loopLabel, Compiler.MethodVar, this));

                for (int i = 0; i < _argLocals.count(); i++)
                {
                    LocalBinding b = (LocalBinding)_argLocals.nth(i);

                    ParameterExpression pexpr = Expression.Parameter(typeof(object), b.Name);
                    b.ParamExpression = pexpr;
                    parmExprs.Add(pexpr);
                }

                List <Expression> bodyExprs = new List <Expression>();
                //bodyExprs.AddRange(typedParmInitExprs);
                bodyExprs.Add(Expression.Label(loopLabel));
                bodyExprs.Add(Compiler.MaybeBox(_body.GenCode(rhc, objx, context)));


                Expression block;
                //if (typedParmExprs.Count > 0)
                //    block = Expression.Block(typedParmExprs, bodyExprs);
                //else
                block = Expression.Block(bodyExprs);

                return(Expression.Lambda(
                           FuncTypeHelpers.GetFFuncType(parmExprs.Count),
                           block,
                           Objx.ThisName,
                           parmExprs));
            }
            finally
            {
                Var.popThreadBindings();
            }
        }
Exemplo n.º 25
0
        internal static Expression GenTypedArg(ObjExpr objx, GenContext context, Type paramType, Expr arg)
        {
            Type primt = Compiler.MaybePrimitiveType(arg);

            if (primt == paramType)
            {
                Expression expr = ((MaybePrimitiveExpr)arg).GenCodeUnboxed(RHC.Expression, objx, context);
                return(expr);
            }
            else if (primt == typeof(int) && paramType == typeof(long))
            {
                Expression expr = ((MaybePrimitiveExpr)arg).GenCodeUnboxed(RHC.Expression, objx, context);
                expr = Expression.Convert(expr, typeof(long));
                return(expr);
            }
            else if (primt == typeof(long) && paramType == typeof(int))
            {
                Expression expr = ((MaybePrimitiveExpr)arg).GenCodeUnboxed(RHC.Expression, objx, context);
                if (RT.booleanCast(RT.UncheckedMathVar.deref()))
                {
                    expr = Expression.Call(Compiler.Method_RT_uncheckedIntCast_long, expr);
                }
                else
                {
                    expr = Expression.Call(Compiler.Method_RT_intCast_long, expr);
                }
                return(expr);
            }
            else if (primt == typeof(float) && paramType == typeof(double))
            {
                Expression expr = ((MaybePrimitiveExpr)arg).GenCodeUnboxed(RHC.Expression, objx, context);
                expr = Expression.Convert(expr, typeof(double));
                return(expr);
            }
            else if (primt == typeof(double) && paramType == typeof(float))
            {
                Expression expr = ((MaybePrimitiveExpr)arg).GenCodeUnboxed(RHC.Expression, objx, context);
                expr = Expression.Convert(expr, typeof(float));
                return(expr);
            }
            else
            {
                Expression argExpr = arg.GenCode(RHC.Expression, objx, context);
                return(GenUnboxArg(argExpr, paramType));
            }
        }
Exemplo n.º 26
0
        private Expression GenTargetExpression(ObjExpr objx, GenContext context)
        {
            if (Compiler.CompileStubOrigClassVar.isBound && Compiler.CompileStubOrigClassVar.deref() != null && objx.TypeBuilder != null)
            {
                return(Expression.Constant(objx.TypeBuilder, typeof(Type)));
            }

            if (_type != null)
            {
                return(Expression.Constant(_type, typeof(Type)));
            }

            throw new ArgumentException("Cannot generate type for NewExpr. Serious!");

            //string name = Compiler.DestubClassName(_type.FullName);
            //return Expression.Call(null, Compiler.Method_RT_classForName, Expression.Constant(name));
        }
Exemplo n.º 27
0
        public override Expression GenDlr(GenContext context)
        {
            List<Expression> exprs = new List<Expression>(_exprs.count());

            for (int i = 0; i < _exprs.count() - 1; i++)
            {
                Expr e = (Expr)_exprs.nth(i);
                exprs.Add(e.GenDlr(context));
            }

            // In Java version, this is split off because the Context in the calls above is forced to be C.STATEMENT.
            // TODO: Wrap this into the loop above.  No real need to do this way.
            Expr last = (Expr)_exprs.nth(_exprs.count() - 1);
            exprs.Add(last.GenDlr(context));

            return Expression.Block(exprs);
        }
Exemplo n.º 28
0
 internal Expression GenLocal(GenContext context, LocalBinding lb)
 {
     if (context.Mode == CompilerMode.File && _closes.containsKey(lb))
     {
         Expression expr      = Expression.Field(_thisParam, lb.Name);
         Type       primtType = lb.PrimitiveType;
         if (primtType != null)
         {
             expr = Compiler.MaybeBox(Expression.Convert(expr, primtType));
         }
         return(expr);
     }
     else
     {
         return(lb.ParamExpression);
     }
 }
Exemplo n.º 29
0
        static public void EmitDynamicCallPreamble(DynamicExpression dyn, IPersistentMap spanMap, string methodName, Type returnType, List <ParameterExpression> paramExprs, Type[] paramTypes, CljILGen ilg, out LambdaExpression lambda, out Type delType, out MethodBuilder mbLambda)
        {
            Expression call = dyn;

            GenContext context = Compiler.CompilerContextVar.deref() as GenContext;

            if (context != null && context.DynInitHelper != null)
            {
                call = context.DynInitHelper.ReduceDyn(dyn);
            }

            if (returnType == typeof(void))
            {
                call       = Expression.Block(call, Expression.Default(typeof(object)));
                returnType = typeof(object);
            }
            else if (returnType != call.Type)
            {
                call = Expression.Convert(call, returnType);
            }

            call = GenContext.AddDebugInfo(call, spanMap);


            delType  = Microsoft.Scripting.Generation.Snippets.Shared.DefineDelegate("__interop__", returnType, paramTypes);
            lambda   = Expression.Lambda(delType, call, paramExprs);
            mbLambda = null;

            if (context == null)
            {
                // light compile

                Delegate d   = lambda.Compile();
                int      key = RT.nextID();
                CacheDelegate(key, d);

                ilg.EmitInt(key);
                ilg.Emit(OpCodes.Call, Method_MethodExpr_GetDelegate);
                ilg.Emit(OpCodes.Castclass, delType);
            }
            else
            {
                mbLambda = context.TB.DefineMethod(methodName, MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, returnType, paramTypes);
                lambda.CompileToMethod(mbLambda);
            }
        }
Exemplo n.º 30
0
        GenProxy(string className)
        {
            if (Compiler.IsCompiling)
            {
                //string path = (string)Compiler.COMPILE_PATH.deref();
                //if (path == null)
                //    throw new Exception("*compile-path* not set");

                ////string dir = (string)Compiler.SOURCE_PATH.deref();

                //_context = new GenContext(className, ".dll", path, CompilerMode.File);
                _context = (GenContext)Compiler.COMPILER_CONTEXT.deref();
            }
            else
                //_context = new GenContext("proxy" + (++_saveId).ToString(), CompilerMode.Immediate);
                _context = new GenContext("proxy" + (++_saveId).ToString(), false);
        }
Exemplo n.º 31
0
        public Expression GenCode(RHC rhc, ObjExpr objx, GenContext context)
        {
            Type collType;

            if (_coll is IPersistentList)
                collType = typeof(PersistentList);
            else if (_coll is IPersistentVector)
                collType = typeof(PersistentVector);
            else if (_coll is IPersistentMap)
                collType = typeof(PersistentArrayMap);
            else if (_coll is IPersistentSet)
                collType = typeof(PersistentHashSet);
            else
                throw new InvalidOperationException("Unknown collection type.");

            return Expression.Field(null, collType, "EMPTY");
        }
Exemplo n.º 32
0
        public override void EmitUnboxed(RHC rhc, ObjExpr objx, CljILGen ilg)
        {
            Type targetType = _targetType;

            GenContext.EmitDebugInfo(ilg, _spanMap);

            if (targetType != null && _tinfo != null)
            {
                _target.Emit(RHC.Expression, objx, ilg);
                MethodExpr.EmitPrepForCall(ilg, typeof(object), FieldDeclaringType);
                EmitGet(ilg);
            }
            else
            {
                throw new InvalidOperationException("Unboxed emit of unknown member.");
            }
        }
Exemplo n.º 33
0
        private ConstructorBuilder EmitConstructorForNonDefType(TypeBuilder fnTB, Type baseType)
        {
            ConstructorBuilder cb  = fnTB.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, CtorTypes());
            CljILGen           gen = new CljILGen(cb.GetILGenerator());

            GenContext.EmitDebugInfo(gen, SpanMap);

            //Call base constructor
            ConstructorInfo baseCtorInfo = baseType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Type.EmptyTypes, null);

            if (baseCtorInfo == null)
            {
                throw new InvalidOperationException("Unable to find default constructor for " + baseType.FullName);
            }

            gen.EmitLoadArg(0);
            gen.Emit(OpCodes.Call, baseCtorInfo);

            // Store Meta
            if (SupportsMeta)
            {
                gen.EmitLoadArg(0);
                gen.EmitLoadArg(1);
                gen.Emit(OpCodes.Castclass, typeof(IPersistentMap));
                gen.EmitFieldSet(MetaField);
            }

            // store closed-overs in their fields
            int a      = 0;
            int offset = !SupportsMeta ? 1 : 2;

            for (ISeq s = RT.keys(Closes); s != null; s = s.next(), a++)
            {
                //LocalBinding lb = (LocalBinding)s.first();
                FieldBuilder fb         = ClosedOverFields[a];
                bool         isVolatile = IsVolatile(ClosedOverFieldsToBindingsMap[fb]);

                gen.EmitLoadArg(0);             // gen.Emit(OpCodes.Ldarg_0);
                gen.EmitLoadArg(a + offset);    // gen.Emit(OpCodes.Ldarg, a + 1);
                gen.MaybeEmitVolatileOp(isVolatile);
                gen.Emit(OpCodes.Stfld, fb);
            }
            gen.Emit(OpCodes.Ret);
            return(cb);
        }
Exemplo n.º 34
0
        void GenerateMethod(MethodInfo staticMethodInfo, GenContext context)
        {
            string methodName = IsVariadic ? "doInvoke" : "invoke";

            TypeBuilder tb = context.FnExpr.TypeBuilder;

            // TODO: Cache all the CreateObjectTypeArray values
            MethodBuilder mb  = tb.DefineMethod(methodName, MethodAttributes.ReuseSlot | MethodAttributes.Public | MethodAttributes.Virtual, typeof(object), Compiler.CreateObjectTypeArray(NumParams));
            ILGenerator   gen = mb.GetILGenerator();

            gen.Emit(OpCodes.Ldarg_0);
            for (int i = 1; i <= _argLocals.count(); i++)
            {
                gen.Emit(OpCodes.Ldarg, i);
            }
            gen.Emit(OpCodes.Call, staticMethodInfo);
            gen.Emit(OpCodes.Ret);
        }
Exemplo n.º 35
0
        public override Expression GenDlr(GenContext context)
        {
            List <Expression> exprs = new List <Expression>(_exprs.count());

            for (int i = 0; i < _exprs.count() - 1; i++)
            {
                Expr e = (Expr)_exprs.nth(i);
                exprs.Add(e.GenDlr(context));
            }

            // In Java version, this is split off because the Context in the calls above is forced to be C.STATEMENT.
            // TODO: Wrap this into the loop above.  No real need to do this way.
            Expr last = (Expr)_exprs.nth(_exprs.count() - 1);

            exprs.Add(last.GenDlr(context));

            return(Expression.Block(exprs));
        }
Exemplo n.º 36
0
        public static GenContext CreateWithInternalAssembly(string assyName, bool createDynInitHelper)
        {
            GenContext ctx = CreateGenContext(assyName, assyName, ".dll", null, createDynInitHelper);

            AddInternalAssembly(ctx.AssemblyBuilder);

#if CLR2
            // Massive kludge for .net 3.5 -- the RuntimeAssemblyBuilder yielded by reflection is not the same as AssemblyBuilder.
            Type       t = CreateDummyType(ctx.ModuleBuilder);
            MethodInfo m = t.GetMethod("test");
            if (m != null && m.DeclaringType.Assembly != ctx.AssemblyBuilder)
            {
                AddInternalAssembly(m.DeclaringType.Assembly);
            }
#endif

            return(ctx);
        }
Exemplo n.º 37
0
        public override Expression GenDlrUnboxed(GenContext context)
        {
            Expression target = _target.GenDlr(context);

            if (_targetType != null && (_fieldInfo != null || _propertyInfo != null))
            {
                Expression convTarget = Expression.Convert(target, _targetType);
                Expression access     = _fieldInfo != null
                    ? Expression.Field(convTarget, _fieldInfo)
                    : Expression.Property(convTarget, _propertyInfo);

                return(access);
            }
            else
            {
                throw new InvalidOperationException("Unboxed emit of unknown member.");
            }
        }
Exemplo n.º 38
0
        public override void EmitUnboxed(RHC rhc, ObjExpr objx, CljILGen ilg)
        {
            GenContext.EmitDebugInfo(ilg, _spanMap);

            if (_method != null)
            {
                EmitForMethod(objx, ilg);
            }
            else
            {
                throw new InvalidOperationException("Unboxed emit of unknown member.");
            }

            if (rhc == RHC.Statement)
            {
                ilg.Emit(OpCodes.Pop);
            }
        }
Exemplo n.º 39
0
        public override Expression GenDlr(GenContext context)
        {
            LabelTarget loopLabel = (LabelTarget)Compiler.LOOP_LABEL.deref();

            if (loopLabel == null)
            {
                throw new InvalidOperationException("Recur not in proper context.");
            }

            int argCount = _args.count();

            List <ParameterExpression> tempVars     = new List <ParameterExpression>(argCount);
            List <Expression>          tempAssigns  = new List <Expression>(argCount);
            List <Expression>          finalAssigns = new List <Expression>(argCount);

            // Evaluate all the init forms into local variables.
            // TODO: Check the typing here.
            for (int i = 0; i < _loopLocals.count(); i++)
            {
                LocalBinding        b       = (LocalBinding)_loopLocals.nth(i);
                Expr                arg     = (Expr)_args.nth(i);
                ParameterExpression tempVar = Expression.Parameter(b.ParamExpression.Type, "__local__" + i);  //asdf-tag
                Expression          valExpr = ((Expr)_args.nth(i)).GenDlr(context);
                tempVars.Add(tempVar);

                if (tempVar.Type == typeof(Object))
                {
                    tempAssigns.Add(Expression.Assign(tempVar, Compiler.MaybeBox(valExpr)));
                }
                else
                {
                    tempAssigns.Add(Expression.Assign(tempVar, Expression.Convert(valExpr, tempVar.Type))); //asdf-tag
                }
                finalAssigns.Add(Expression.Assign(b.ParamExpression, tempVar));                            //asdf-tag
            }

            List <Expression> exprs = tempAssigns;

            exprs.AddRange(finalAssigns);
            exprs.Add(Expression.Goto(loopLabel));
            // need to do this to get a return value in the type inferencing -- else can't use this in a then or else clause.
            exprs.Add(Expression.Constant(null));
            return(Expression.Block(tempVars, exprs));
        }
Exemplo n.º 40
0
        public override void EmitAssign(RHC rhc, ObjExpr objx, CljILGen ilg, Expr val)
        {
            if (_tinfo.IsInitOnly)
            {
                throw new InvalidOperationException(String.Format("Attempt to set readonly static field {0} in class {1}", _tinfo.Name, _tinfo.DeclaringType));
            }

            GenContext.EmitDebugInfo(ilg, _spanMap);

            val.Emit(RHC.Expression, objx, ilg);
            ilg.Emit(OpCodes.Dup);
            HostExpr.EmitUnboxArg(objx, ilg, FieldType);
            ilg.MaybeEmitVolatileOp(_tinfo);
            ilg.EmitFieldSet(_tinfo);
            if (rhc == RHC.Statement)
            {
                ilg.Emit(OpCodes.Pop);
            }
        }
Exemplo n.º 41
0
        public override Expression GenDlr(GenContext context)
        {
            throw new NotImplementedException();

            //List<ParameterExpression> parms = new List<ParameterExpression>();
            //List<Expression> forms = new List<Expression>();

            //for (int i = 0; i < _bindingInits.count(); i++)
            //{
            //    BindingInit bi = (BindingInit)_bindingInits.nth(i);
            //    Type primType = Compiler.MaybePrimitiveType(bi.Init);
            //    ParameterExpression parmExpr = Expression.Parameter(primType ?? typeof(object), bi.Binding.Name);
            //    bi.Binding.ParamExpression = parmExpr;
            //    parms.Add(parmExpr);
            //    //forms.Add(Expression.Assign(parmExpr, Compiler.MaybeBox(bi.Init.GenDlr(context))));
            //    Expression initExpr = primType != null ? ((MaybePrimitiveExpr)bi.Init).GenDlrUnboxed(context) : Compiler.MaybeBox(bi.Init.GenDlr(context));
            //    forms.Add(Expression.Assign(parmExpr, initExpr));
            //}
        }
Exemplo n.º 42
0
        public void Emit(RHC rhc, ObjExpr objx, CljILGen ilg)
        {
            GenContext.EmitDebugInfo(ilg, _spanMap);

            if (_isProtocol)
            {
                EmitProto(rhc, objx, ilg);
            }
            else
            {
                _fexpr.Emit(RHC.Expression, objx, ilg);
                ilg.Emit(OpCodes.Castclass, typeof(IFn));
                EmitArgsAndCall(0, rhc, objx, ilg);
            }
            if (rhc == RHC.Statement)
            {
                ilg.Emit(OpCodes.Pop);
            }
        }
Exemplo n.º 43
0
        public override Expression GenDlr(GenContext context)
        {
            Expression target = _target.GenDlr(context);

            if (_targetType != null && (_fieldInfo != null || _propertyInfo != null))
            {
                Expression convTarget = Expression.Convert(target, _targetType);
                Expression access     = _fieldInfo != null
                    ? Expression.Field(convTarget, _fieldInfo)
                    : Expression.Property(convTarget, _propertyInfo);

                return(Compiler.MaybeBox(access));
            }
            else
            {
                return(Compiler.MaybeBox(Expression.PropertyOrField(target, _fieldName)));
            }
            //Or maybe this should call Reflector.invokeNoArgInstanceMember
        }
Exemplo n.º 44
0
        public Expression GenCodeUnboxed(RHC rhc, ObjExpr objx, GenContext context)
        {
            Type t = _n.GetType();

            if (t == typeof(int))
            {
                return(Expression.Constant((long)(int)_n, typeof(long)));
            }
            else if (t == typeof(double))
            {
                return(Expression.Constant((double)_n, typeof(double)));
            }
            else if (t == typeof(long))
            {
                return(Expression.Constant((long)_n, typeof(long)));
            }

            throw new ArgumentException("Unsupported Number type: " + _n.GetType().Name);
        }
Exemplo n.º 45
0
        public override Expression GenDlr(GenContext context)
        {
            Expression fn = _fexpr.GenDlr(context);

            fn = Expression.Convert(fn, typeof(IFn));

            int argCount = _args.count();

            Expression[] args = new Expression[argCount];

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

            Expression call = GenerateInvocation(InvocationReturnType, fn, args);

            return(call);
        }
Exemplo n.º 46
0
        public override Expression GenDlr(GenContext context)
        {
            throw new NotImplementedException();

            //List<ParameterExpression> parms = new List<ParameterExpression>();
            //List<Expression> forms = new List<Expression>();

            //for (int i = 0; i < _bindingInits.count(); i++)
            //{
            //    BindingInit bi = (BindingInit)_bindingInits.nth(i);
            //    Type primType = Compiler.MaybePrimitiveType(bi.Init);
            //    ParameterExpression parmExpr = Expression.Parameter(primType ?? typeof(object), bi.Binding.Name);
            //    bi.Binding.ParamExpression = parmExpr;
            //    parms.Add(parmExpr);
            //    //forms.Add(Expression.Assign(parmExpr, Compiler.MaybeBox(bi.Init.GenDlr(context))));
            //    Expression initExpr = primType != null ? ((MaybePrimitiveExpr)bi.Init).GenDlrUnboxed(context) : Compiler.MaybeBox(bi.Init.GenDlr(context));
            //    forms.Add(Expression.Assign(parmExpr, initExpr));
            //}
        }
Exemplo n.º 47
0
        public override Expression GenDlr(GenContext context)
        {
            LabelTarget loopLabel = Expression.Label();

            List <ParameterExpression> parms = new List <ParameterExpression>();
            List <Expression>          forms = new List <Expression>();

            for (int i = 0; i < _bindingInits.count(); i++)
            {
                BindingInit         bi       = (BindingInit)_bindingInits.nth(i);
                Type                primType = Compiler.MaybePrimitiveType(bi.Init);
                ParameterExpression parmExpr = Expression.Parameter(primType ?? typeof(object), bi.Binding.Name);
                bi.Binding.ParamExpression = parmExpr;
                parms.Add(parmExpr);
                //forms.Add(Expression.Assign(parmExpr, Compiler.MaybeBox(bi.Init.GenDlr(context))));
                Expression initExpr = primType != null ? ((MaybePrimitiveExpr)bi.Init).GenDlrUnboxed(context) : Compiler.MaybeBox(bi.Init.GenDlr(context));
                forms.Add(Expression.Assign(parmExpr, initExpr));
            }


            forms.Add(Expression.Label(loopLabel));

            try
            {
                if (_isLoop)
                {
                    Var.pushThreadBindings(PersistentHashMap.create(Compiler.LOOP_LABEL, loopLabel));
                }

                forms.Add(_body.GenDlr(context));
            }
            finally
            {
                if (_isLoop)
                {
                    Var.popThreadBindings();
                }
            }

            Expression block = Expression.Block(parms, forms);

            return(block);
        }
Exemplo n.º 48
0
        public override Expression GenDlr(GenContext context)
        {
            if (_ctor != null)
            {
                // The ctor is uniquely determined.

                Expression[] args = Compiler.GenTypedArgArray(context, _ctor.GetParameters(), _args);
                return(Expression.New(_ctor, args));

                // JAVA: emitClearLocals
            }
            else
            {
                Expression typeExpr = Expression.Call(Compiler.Method_RT_classForName, Expression.Constant(_type.FullName));
                Expression args     = Compiler.GenArgArray(context, _args);
                // Java: emitClearLocals

                return(Expression.Call(Compiler.Method_Reflector_InvokeConstructor, typeExpr, args));
            }
        }
Exemplo n.º 49
0
        public override Expression GenDlr(GenContext context)
        {
            if ( _ctor != null )
            {
                // The ctor is uniquely determined.

                Expression[] args = Compiler.GenTypedArgArray(context, _ctor.GetParameters(), _args);
                return Expression.New(_ctor, args);

                // JAVA: emitClearLocals
            }
            else
            {
                Expression typeExpr = Expression.Call(Compiler.Method_RT_classForName, Expression.Constant(_type.FullName));
                Expression args = Compiler.GenArgArray(context, _args);
                // Java: emitClearLocals

                return Expression.Call(Compiler.Method_Reflector_InvokeConstructor,typeExpr,args);
            }
        }
Exemplo n.º 50
0
        public Expression GenCode(RHC rhc, ObjExpr objx, GenContext context)
        {
            Expression call;

            if (_ctor != null)
            {
                call = GenDlrForMethod(rhc, objx, context);
            }
            else if (_isNoArgValueTypeCtor)
            {
                call = Expression.Default(_type);
            }
            else
            {
                call = GenerateComplexCall(rhc, objx, context);
            }

            call = Compiler.MaybeAddDebugInfo(call, _spanMap, context.IsDebuggable);
            return(call);
        }
Exemplo n.º 51
0
        public override Expression GenCodeUnboxed(RHC rhc, ObjExpr objx, GenContext context)
        {
            Expression target = _target.GenCode(RHC.Expression, objx, context);

            Type returnType = HasClrType ? ClrType : typeof(object);

            // TODO: Get rid of Default
            GetMemberBinder   binder = new ClojureGetZeroArityMemberBinder(ClojureContext.Default, _memberName, false);
            DynamicExpression dyn    = Expression.Dynamic(binder, returnType, new Expression[] { target });

            Expression call = dyn;

            if (context.DynInitHelper != null)
            {
                call = context.DynInitHelper.ReduceDyn(dyn);
            }

            call = Compiler.MaybeAddDebugInfo(call, _spanMap, context.IsDebuggable);
            return(call);
        }
Exemplo n.º 52
0
        public override Expression GenCode(RHC rhc, ObjExpr objx, GenContext context)
        {
            Expression call;
            Type       retType;

            if (_method != null)
            {
                call    = GenDlrForMethod(objx, context);
                retType = _method.ReturnType;
            }
            else
            {
                call    = GenerateComplexCall(objx, context);
                retType = typeof(object);
            }

            call = HostExpr.GenBoxReturn(call, retType, objx, context);
            call = Compiler.MaybeAddDebugInfo(call, _spanMap, context.IsDebuggable);
            return(call);
        }
Exemplo n.º 53
0
        public Expression GenCode(RHC rhc, ObjExpr objx, GenContext context)
        {
            //if (context.Mode == CompilerMode.Immediate)
            if (objx.FnMode == FnMode.Light )
            {
                // This will emit a plain Keyword reference, rather than a callsite.
                InvokeExpr ie = new InvokeExpr(_source, _spanMap, (Symbol)_tag, _kw, RT.vector(_target));
                return ie.GenCode(rhc, objx, context);
            }
            else
            {

                ParameterExpression thunkParam = Expression.Parameter(typeof(ILookupThunk), "thunk");
                Expression assignThunk = Expression.Assign(thunkParam, Expression.Field(null, objx.ThunkField(_siteIndex)));

                ParameterExpression targetParam = Expression.Parameter(typeof(object), "target");
                Expression assignTarget = Expression.Assign(targetParam,_target.GenCode(RHC.Expression, objx, context));

                ParameterExpression valParam = Expression.Parameter(typeof(Object), "val");
                Expression assignVal = Expression.Assign(valParam, Expression.Call(thunkParam, Compiler.Method_ILookupThunk_get,targetParam));

                ParameterExpression siteParam = Expression.Parameter(typeof(KeywordLookupSite), "site");
                Expression assignSite = Expression.Assign(siteParam, Expression.Field(null, objx.KeywordLookupSiteField(_siteIndex)));

                Expression block =
                    Expression.Block(typeof(Object), new ParameterExpression[] { thunkParam, valParam, targetParam },
                        assignThunk,
                        assignTarget,
                        assignVal,
                        Expression.Condition(
                            Expression.NotEqual(valParam, thunkParam),
                            valParam,
                            Expression.Block(typeof(Object), new ParameterExpression[] { siteParam },
                                assignSite,
                                Expression.Call(siteParam, Compiler.Method_ILookupSite_fault, targetParam, objx.ThisParam)),
                            typeof(object)));

                block = Compiler.MaybeAddDebugInfo(block, _spanMap);
                return block;
            }
        }
Exemplo n.º 54
0
        public override Expression GenDlr(GenContext context)
        {
            List<Expression> exprs = new List<Expression>(_exprs.count());

            // In Java version, this is split off because the Context in the calls above is forced to be C.STATEMENT.
            //for (int i = 0; i < _exprs.count() - 1; i++)
            //{
            //    Expr e = (Expr)_exprs.nth(i);
            //    exprs.Add(e.GenDlr(context));
            //}
            //Expr last = (Expr)_exprs.nth(_exprs.count() - 1);
            //exprs.Add(last.GenDlr(context));

            for (int i = 0; i < _exprs.count(); i++)
            {
                Expr e = (Expr)_exprs.nth(i);
                exprs.Add(e.GenDlr(context));
            }

            return Expression.Block(exprs);
        }
Exemplo n.º 55
0
        private void EmitStaticConstructorBody(CljILGen ilg)
        {
            GenContext.EmitDebugInfo(ilg, SpanMap);

            if (Constants.count() > 0)
            {
                EmitConstantFieldInits(ilg);
            }

            if (KeywordCallsites.count() > 0)
            {
                EmitKeywordCallsiteInits(ilg);
            }

            if (IsDefType && RT.booleanCast(RT.get(Opts, Compiler.LoadNsKeyword)))
            {
                EmitLoadNsInitForDeftype(ilg);
            }

            ilg.Emit(OpCodes.Ret);
        }
Exemplo n.º 56
0
        public virtual void Emit(ObjExpr fn, TypeBuilder tb)
        {
            MethodBuilder mb = tb.DefineMethod(MethodName, MethodAttributes.Public, ReturnType, ArgTypes);

            CljILGen ilg       = new CljILGen(mb.GetILGenerator());
            Label    loopLabel = ilg.DefineLabel();

            GenContext.EmitDebugInfo(ilg, SpanMap);

            try
            {
                Var.pushThreadBindings(RT.map(Compiler.LoopLabelVar, loopLabel, Compiler.MethodVar, this));
                ilg.MarkLabel(loopLabel);
                Body.Emit(RHC.Return, fn, ilg);
                ilg.Emit(OpCodes.Ret);
            }
            finally
            {
                Var.popThreadBindings();
            }
        }
Exemplo n.º 57
0
        void GeneratePrimMethod(ObjExpr objx, GenContext context)
        {
            TypeBuilder   tb = objx.TypeBuilder;
            MethodBuilder mb = tb.DefineMethod("invokePrim", MethodAttributes.ReuseSlot | MethodAttributes.Public | MethodAttributes.Virtual, StaticReturnType, StaticMethodArgTypes);


            //Console.Write("InMd: {0} {1}(", ReturnType.Name, "invokePrim");
            //foreach (Type t in ArgTypes)
            //    Console.Write("{0}", t.Name);
            //Console.WriteLine(")");

            GenInterface.SetCustomAttributes(mb, _methodMeta);
            if (_parms != null)
            {
                for (int i = 0; i < _parms.count(); i++)
                {
                    IPersistentMap meta = GenInterface.ExtractAttributes(RT.meta(_parms.nth(i)));
                    if (meta != null && meta.count() > 0)
                    {
                        ParameterBuilder pb = mb.DefineParameter(i + 1, ParameterAttributes.None, ((Symbol)_parms.nth(i)).Name);
                        GenInterface.SetCustomAttributes(pb, meta);
                    }
                }
            }

            ILGen gen = new ILGen(mb.GetILGenerator());

            gen.EmitLoadArg(0);
            for (int i = 1; i <= _argLocals.count(); i++)
            {
                gen.EmitLoadArg(i);
            }
            gen.EmitCall(_staticMethodBuilder);
            gen.Emit(OpCodes.Ret);

            if (IsExplicit)
            {
                tb.DefineMethodOverride(mb, _explicitMethodInfo);
            }
        }
Exemplo n.º 58
0
        public override Expression GenDlr(GenContext context)
        {
            List<Expression> exprs = new List<Expression>();

            ParameterExpression parm = Expression.Parameter(typeof(Var), "v");

            Expression varExpr = context.FnExpr.GenVar(context,_var);

            exprs.Add(Expression.Assign(parm, varExpr));

            if (_initProvided)
                // Java doesn't Box here, but we have to deal with unboxed bool values
                exprs.Add(Expression.Call(parm, Compiler.Method_Var_BindRoot, Compiler.MaybeBox(_init.GenDlr(context))));

            if (_meta != null)
                // Java casts to IPersistentMap on the _meta, but Expression.Call can handle that for us.
                exprs.Add(Expression.Call(parm, Compiler.Method_Var_setMeta, _meta.GenDlr(context)));

            exprs.Add(parm);

            return Expression.Block(new ParameterExpression[] { parm }, exprs);
        }
Exemplo n.º 59
0
        public Expression GenCode(RHC rhc, ObjExpr objx, GenContext context)
        {
            Expression basicBody = _tryExpr.GenCode(rhc, objx, context);
            if (basicBody.Type == typeof(void))
                basicBody = Expression.Block(basicBody, Expression.Default(typeof(object)));
            Expression tryBody = Expression.Convert(basicBody,typeof(object));

            CatchBlock[] catches = new CatchBlock[_catchExprs.count()];
            for ( int i=0; i<_catchExprs.count(); i++ )
            {
                CatchClause clause = (CatchClause) _catchExprs.nth(i);
                ParameterExpression parmExpr = Expression.Parameter(clause.Type, clause.Lb.Name);
                clause.Lb.ParamExpression = parmExpr;
                catches[i] = Expression.Catch(parmExpr, Expression.Convert(clause.Handler.GenCode(rhc, objx, context), typeof(object)));
            }

            TryExpression tryStmt = _finallyExpr == null
                ? Expression.TryCatch(tryBody, catches)
                : Expression.TryCatchFinally(tryBody, _finallyExpr.GenCode(RHC.Statement, objx, context), catches);

            return tryStmt;
        }
Exemplo n.º 60
0
        Type CompileBaseClass(GenContext context, Type super, Type[] interfaces, Object frm)
        {
            //TypeBuilder tb = context.ModuleBuilder.DefineType(Compiler.CompileStubPrefix + "." + InternalName + RT.nextID(), TypeAttributes.Public | TypeAttributes.Abstract, super, interfaces);
            TypeBuilder tb = context.ModuleBuilder.DefineType(Compiler.DeftypeBaseClassNamePrefix + "." + InternalName + RT.nextID(), TypeAttributes.Public | TypeAttributes.Abstract, super, interfaces);

            tb.DefineDefaultConstructor(MethodAttributes.Public);
            EmitClosedOverFields(tb);
            DefineBaseClassClosedOverConstructors(super, tb);
            DefineBaseClassMethods(interfaces, tb);

            Type t = tb.CreateType();

            BaseClass = t;

            BaseClassClosedOverCtor = GetConstructorWithArgCount(t, CtorTypes().Length);
            if (AltCtorDrops > 0)
            {
                BaseClassAltCtor = GetConstructorWithArgCount(t, CtorTypes().Length - AltCtorDrops);
            }

            return(t);
        }