internal override Type Get(ILGenerator generator) { if (Property == null && Field == null) { Resolve(null); } if (Property != null) { // Call the get method: generator.Call(Property.GetMethod); return(_Type); } if (Field != null) { // Load the field: generator.LoadField(Field); } else if (IsConstant) { // Emit the default constant value: EmitHelpers.EmitValue(generator, ConstantValue); } else { // Emit undefined: EmitHelpers.EmitUndefined(generator); } return(_Type); }
/// <summary> /// Generates a method that does type conversion and calls the bound method. /// </summary> /// <param name="generator"> The ILGenerator used to output the body of the method. </param> /// <param name="argumentCount"> The number of arguments that will be passed to the delegate. </param> /// <returns> A delegate that does type conversion and calls the method represented by this /// object. </returns> protected override void GenerateStub(Jurassic.Compiler.ILGenerator generator, int argumentCount) { // Emit undefined. EmitHelpers.EmitUndefined(generator); // End the IL. generator.Complete(); }
public void GeneratePoco_WorksOk() { var pocoType = EmitHelpers.CreatePocoType("Jalla", "Dummy", new KeyValuePair <string, Type>[] { new KeyValuePair <string, Type>("Lala", typeof(string)), }); var pocoInstance = Activator.CreateInstance(pocoType); Assert.That(pocoInstance, Is.Not.Null); }
public void CreateSimplePropertySetter() { var labelNoChange = Generator.DefineLabel(); EmitHelpers.GenerateJumpIfEqual(Generator, PropertyInfo.PropertyType, labelNoChange, g => g.Ldarg(0).Ldfld(DefaultFieldBuilder), g => g.Ldarg(1)); Generator .Ldarg(0) .Ldarg(1) .Stfld(DefaultFieldBuilder); CallObjectModified(Generator); Generator.Mark(labelNoChange); }
public void CreatePropertySetter(FieldHandlerCreateImpl ctx) { var ilGenerator = ctx.Generator; var fieldBuilder = ctx.DefaultFieldBuilder; var labelNoChange = ilGenerator.DefineLabel(); ilGenerator.DeclareLocal(typeof(ulong)); ilGenerator .Ldarg(0) .Ldfld(ctx.FieldMidLevelDBTransaction) .Ldarg(1) .Callvirt(() => ((IObjectDBTransactionInternal)null).GetOid(null)) .Stloc(0); EmitHelpers.GenerateJumpIfEqual(ilGenerator, typeof(ulong), labelNoChange, g => g.Ldarg(0).Ldfld(fieldBuilder), g => g.Ldloc(0)); ilGenerator .Ldarg(0) .Ldloc(0) .Stfld(fieldBuilder); ctx.CallObjectModified(ilGenerator); ilGenerator .Mark(labelNoChange); }
public GuidFieldHandler() : base( EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).ReadGuid()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).SkipGuid()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedWriter)null).WriteGuid(new Guid()))) { }
private MethodBuilder BuildMethodAsync(TypeBuilder type, MethodInfo serviceAction) { const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot; var method = type.DefineMethod(serviceAction.Name, methodAttributes); // Preparing Reflection instances var method1 = typeof(RestWrapper).GetMethod( "GetParameters", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new[] { typeof(string), typeof(object[]) }, null ); var method2 = typeof(RestWrapper).GetMethod(serviceAction.ReturnType.GetGenericArguments().Length == 0 ? "InvokeVoidAsync" : "InvokeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new[] { typeof(string), typeof(ParameterWrapper[]) }, null); if (serviceAction.ReturnType.GenericTypeArguments.Any()) { method2 = method2.MakeGenericMethod(serviceAction.ReturnType.GenericTypeArguments); } // Setting return type method.SetReturnType(serviceAction.ReturnType); // Adding parameters method.SetParameters(serviceAction.GetParameters().Select(p => p.ParameterType).ToArray()); var i = 1; foreach (var parameterInfo in serviceAction.GetParameters()) { var param = method.DefineParameter(i, ParameterAttributes.None, parameterInfo.Name); i++; } ILGenerator gen = method.GetILGenerator(); // Preparing locals LocalBuilder par = gen.DeclareLocal(typeof(Object[])); LocalBuilder parameters = gen.DeclareLocal(typeof(ParameterWrapper[])); LocalBuilder result = gen.DeclareLocal(serviceAction.ReturnType); LocalBuilder str = gen.DeclareLocal(serviceAction.ReturnType); // Preparing labels Label label55 = gen.DefineLabel(); // Writing body var ps = serviceAction.GetParameters(); EmitHelpers.EmitInt32(gen, ps.Length); gen.Emit(OpCodes.Newarr, typeof(object)); for (int j = 0; j < ps.Length; j++) { gen.Emit(OpCodes.Dup); EmitHelpers.EmitInt32(gen, j); EmitHelpers.EmitLdarg(gen, j + 1); var paramType = ps[j].ParameterType; if (paramType.IsValueType) { gen.Emit(OpCodes.Box, paramType); } gen.Emit(OpCodes.Stelem_Ref); } gen.Emit(OpCodes.Stloc_0); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldstr, serviceAction.Name); gen.Emit(OpCodes.Ldloc_0); gen.Emit(OpCodes.Call, method1); gen.Emit(OpCodes.Stloc_1); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldstr, serviceAction.Name); gen.Emit(OpCodes.Ldloc_1); gen.Emit(OpCodes.Call, method2); gen.Emit(OpCodes.Stloc_2); gen.Emit(OpCodes.Ldloc_2); gen.Emit(OpCodes.Stloc_3); gen.Emit(OpCodes.Br_S, label55); gen.MarkLabel(label55); gen.Emit(OpCodes.Ldloc_3); gen.Emit(OpCodes.Ret); // finished return(method); }
public SignedFieldHandler() : base("Signed", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadVInt64()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipVInt64()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteVInt64(0))) { }
/// <summary> /// Generates CIL for the expression. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> public override void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo) { //if (optimizationInfo.SuppressReturnValue == true) // return; EmitHelpers.LoadThis(generator); }
static BasicSerializersFactory() { var fh = new List <IFieldHandler>(); var des = new List <ITypeDescriptor>(); AddJustOrderable(fh, "StringOrderable", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadStringOrdered()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipStringOrdered()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteStringOrdered(null))); Add(fh, des, "String", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadString()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipString()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteString(null))); Add(fh, des, "UInt8", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadUInt8()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipUInt8()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteUInt8(0))); AddJustOrderable(fh, "Int8Orderable", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadInt8Ordered()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipInt8Ordered()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteInt8Ordered(0))); Add(fh, des, "Int8", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadInt8()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipInt8()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteInt8(0))); fh.Add(new SignedFieldHandler()); fh.Add(new UnsignedFieldHandler()); AddDescriptor(des, "VInt16", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadVInt16()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipVInt16()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteVInt16(0))); AddDescriptor(des, "VUInt16", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadVUInt16()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipVUInt16()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteVUInt16(0))); AddDescriptor(des, "VInt32", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadVInt32()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipVInt32()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteVInt32(0))); AddDescriptor(des, "VUInt32", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadVUInt32()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipVUInt32()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteVUInt32(0))); AddDescriptor(des, "VInt64", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadVInt64()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipVInt64()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteVInt64(0))); AddDescriptor(des, "VUInt64", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadVUInt64()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipVUInt64()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteVUInt64(0))); Add(fh, des, "Bool", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadBool()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipBool()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteBool(false))); Add(fh, des, "Single", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadSingle()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipSingle()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteSingle(0))); Add(fh, des, "Double", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadDouble()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipDouble()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteDouble(0))); Add(fh, des, "Decimal", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadDecimal()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipDecimal()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteDecimal(0))); AddJustOrderable(fh, "DateTime", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadDateTime()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipDateTime()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteDateTimeForbidUnspecifiedKind(new DateTime()))); Add(fh, des, "DateTime", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadDateTime()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipDateTime()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteDateTime(new DateTime()))); Add(fh, des, "TimeSpan", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadTimeSpan()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipTimeSpan()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteTimeSpan(new TimeSpan()))); Add(fh, des, "Guid", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadGuid()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipGuid()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteGuid(new Guid()))); fh.Add(new ByteArrayLastFieldHandler()); fh.Add(new ByteArrayFieldHandler()); des.Add(new ByteArrayTypeDescriptor()); Add(fh, des, "IPAddress", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadIPAddress()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipIPAddress()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteIPAddress(IPAddress.Any))); Add(fh, des, "Version", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadVersion()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipVersion()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteVersion(null))); fh.Add(new OrderedEncryptedStringHandler()); fh.Add(new EncryptedStringHandler()); des.Add(new EncryptedStringDescriptor()); Add(fh, des, "DateTimeOffset", EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).ReadDateTimeOffset()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedReader).SkipDateTimeOffset()), EmitHelpers.GetMethodInfo(() => default(AbstractBufferedWriter).WriteDateTimeOffset(new DateTimeOffset()))); FieldHandlers = fh.ToArray(); TypeDescriptors = des.ToArray(); }
public static Func <object> ConstructType(Type type) { return(EmitHelpers.EmitDynamicMethod <Func <object> >("Construct_" + type.Name + "_" + Guid.NewGuid(), type.Module, il => EmitCode(type, il))); }
public BoolFieldHandler() : base( EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).ReadBool()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).SkipBool()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedWriter)null).WriteBool(false))) { }
/// <summary> /// Builds delegate that creates uninitialized class instance for purposes of deserialization and reflection. /// </summary> static bool TryBuildCreateEmptyObjectFunc(PhpTypeInfo tinfo, out Func <Context, object> activator) { Debug.Assert(tinfo != null); activator = null; if (tinfo.IsInterface) { // cannot be instantiated } else if (tinfo.Type.IsAbstract) { // abstract class, // generate a non-abstract class that implements this one: var dummytype = EmitHelpers.CreatDefaultAbstractClassImplementation(tinfo.Type, out var ctor); activator = _ctx => ctor.Invoke(new object[] { _ctx }); } else if (tinfo.IsTrait) { // trait class, can be instantiated using following (and the only) .ctor: // .ctor( Context, TSelf ) if (tinfo.Type.IsGenericTypeDefinition) { // trait class must be constructed first! throw new NotSupportedException("Trait type is not constructed, cannot be created."); // tinfo = tinfo.Type.MakeGenericType(typeof(object)); } else { foreach (var c in tinfo.Type.GetConstructors()) { // there is only one .ctor: var ps = c.GetParameters(); if (ps.Length == 2 && ps[0].IsContextParameter() && ps[1].ParameterType == typeof(object) && c.IsPublic) { activator = _ctx => c.Invoke(new[] { _ctx, new object(), }); } } } } else { // regular instantiable class foreach (var c in tinfo.Type.DeclaredConstructors) { if (c.IsStatic || c.IsPrivate || c.IsPhpHidden()) { continue; } var ps = c.GetParameters(); switch (ps.Length) { // .ctor() case 0: activator = (_ctx) => c.Invoke(Array.Empty <object>()); break; // .ctor(Context) case 1 when ps[0].IsContextParameter():
public DateTimeFieldHandler() : base( EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).ReadDateTime()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).SkipDateTime()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedWriter)null).WriteDateTime(new DateTime()))) { }
/// <summary> /// Generates CIL for the expression. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> public override void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo) { EmitHelpers.LoadNewTarget(generator); }
/// <summary> /// Generates CIL for the expression. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> public override void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo) { // The left hand side needs to be a variable reference or member access. var target = this.GetOperand(0) as IReferenceExpression; if (target == null) { // Emit an error message. switch (this.OperatorType) { case OperatorType.PostIncrement: case OperatorType.PostDecrement: EmitHelpers.EmitThrow(generator, "ReferenceError", "Invalid left-hand side in postfix operation", optimizationInfo); break; case OperatorType.PreIncrement: case OperatorType.PreDecrement: EmitHelpers.EmitThrow(generator, "ReferenceError", "Invalid left-hand side in prefix operation", optimizationInfo); break; default: EmitHelpers.EmitThrow(generator, "ReferenceError", "Invalid left-hand side in assignment", optimizationInfo); break; } //if (optimizationInfo.SuppressReturnValue == false) EmitHelpers.EmitDefaultValue(generator, this.ResultType); return; } // The left hand side cannot be "arguments" or "eval" in strict mode. if (optimizationInfo.StrictMode && target is NameExpression) { if (((NameExpression)target).Name == "eval") { throw new JavaScriptException(optimizationInfo.Engine, "SyntaxError", "The variable 'eval' cannot be modified in strict mode.", optimizationInfo.SourceSpan.StartLine, optimizationInfo.Source.Path, optimizationInfo.FunctionName); } if (((NameExpression)target).Name == "arguments") { throw new JavaScriptException(optimizationInfo.Engine, "SyntaxError", "The variable 'arguments' cannot be modified in strict mode.", optimizationInfo.SourceSpan.StartLine, optimizationInfo.Source.Path, optimizationInfo.FunctionName); } } switch (this.OperatorType) { case OperatorType.Assignment: // Standard assignment operator. GenerateAssignment(generator, optimizationInfo, target); break; case OperatorType.PostIncrement: GenerateIncrementOrDecrement(generator, optimizationInfo, target, true, true); break; case OperatorType.PostDecrement: GenerateIncrementOrDecrement(generator, optimizationInfo, target, true, false); break; case OperatorType.PreIncrement: GenerateIncrementOrDecrement(generator, optimizationInfo, target, false, true); break; case OperatorType.PreDecrement: GenerateIncrementOrDecrement(generator, optimizationInfo, target, false, false); break; case OperatorType.CompoundAdd: // Special case += GenerateCompoundAddAssignment(generator, optimizationInfo, target); break; default: // All other compound operators. GenerateCompoundAssignment(generator, optimizationInfo, target); break; } }
public DecimalFieldHandler() : base( EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).ReadDecimal()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).SkipDecimal()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedWriter)null).WriteDecimal(0))) { }
public Type CreateDelegate(MethodInfo targetMethod, TypeBuilder parent, List <ParameterWrapper> methodParams) { typeCounter++; var typeBuilder = myModuleBuilder.DefineType(string.Format("TempModule.Controllers.{0}{1}{2}Delegate{3}", targetMethod.DeclaringType.Name, targetMethod.Name, targetMethod.GetParameters().Length, typeCounter), TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(object)); //var typeBuilder = myModuleBuilder.DefineType(string.Format("{0}{1}{2}Delegate", targetMethod.DeclaringType.Name, targetMethod.Name, targetMethod.GetParameters().Length), TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(object)); var imp = typeBuilder.DefineField("implementation", parent, FieldAttributes.Public); var baseController = typeof(ServiceWrapperBase <>).MakeGenericType(targetMethod.DeclaringType).GetField("implementation", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var param = typeBuilder.DefineField("parameters", typeof(ParameterWrapper[]), FieldAttributes.Public); CreateDelegateCtor(typeBuilder); // Declaring method builder // Method attributes System.Reflection.MethodAttributes methodAttributes = System.Reflection.MethodAttributes.Assembly | System.Reflection.MethodAttributes.HideBySig; MethodBuilder method = typeBuilder.DefineMethod(targetMethod.Name, methodAttributes); // Preparing Reflection instances //FieldInfo field1 = typeof(<> c__DisplayClass2_0).GetField("<>4__this", BindingFlags.Public | BindingFlags.NonPublic); //FieldInfo field2 = typeof(Stardust.Interstellar.Rest.Service.ServiceWrapperBase<>).MakeGenericType(typeof(ITestApi)).GetField("implementation", BindingFlags.Public | BindingFlags.NonPublic); //FieldInfo field3 = typeof(<> c__DisplayClass2_0).GetField("serviceParameters", BindingFlags.Public | BindingFlags.NonPublic); MethodInfo method4 = typeof(ParameterWrapper).GetMethod( "get_value", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null ); MethodInfo method5 = targetMethod; // Setting return type method.SetReturnType(targetMethod.ReturnType); // Adding parameters ILGenerator gen = method.GetILGenerator(); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, imp); gen.Emit(OpCodes.Ldfld, baseController); var iii = 0; foreach (var item in methodParams) { gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, param); EmitHelpers.EmitInt32(gen, iii); gen.Emit(OpCodes.Ldelem_Ref); gen.Emit(OpCodes.Callvirt, method4); if (item.Type.IsValueType) { gen.Emit(OpCodes.Unbox_Any, item.Type); } else { gen.Emit(OpCodes.Castclass, item.Type); } iii++; } gen.Emit(OpCodes.Callvirt, method5); gen.Emit(OpCodes.Ret); // finished var t = typeBuilder.CreateType(); return(t); }
/// <summary> /// Generates CIL for the expression. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> public override void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo) { // Note: we use GetRawOperand() so that grouping operators are not ignored. var operand = this.GetRawOperand(0); var functionCallExpressionOperand = operand as FunctionCallExpression; // There is only one operand, and it can be either a reference or a function call. // We need to split the operand into a function and some arguments. // If the operand is a reference, it is equivalent to a function call with no arguments. if (functionCallExpressionOperand != null) { // Emit the function instance first. var function = functionCallExpressionOperand.Target; function.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, function.ResultType); } else { // Emit the function instance first. operand.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, operand.ResultType); } // Check the object really is a function - if not, throw an exception. generator.IsInstance(typeof(Library.FunctionInstance)); generator.Duplicate(); var endOfTypeCheck = generator.CreateLabel(); generator.BranchIfNotNull(endOfTypeCheck); // Throw an nicely formatted exception. var targetValue = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(targetValue); EmitHelpers.LoadScriptEngine(generator); generator.LoadString("TypeError"); generator.LoadString("The new operator requires a function, found a '{0}' instead"); generator.LoadInt32(1); generator.NewArray(typeof(object)); generator.Duplicate(); generator.LoadInt32(0); generator.LoadVariable(targetValue); generator.Call(ReflectionHelpers.TypeUtilities_TypeOf.Value); generator.StoreArrayElement(typeof(object)); generator.Call(ReflectionHelpers.String_Format.Value); generator.LoadInt32(optimizationInfo.SourceSpan.StartLine); generator.LoadStringOrNull(optimizationInfo.Source.Path); generator.LoadStringOrNull(optimizationInfo.FunctionName); generator.NewObject(ReflectionHelpers.JavaScriptException_Constructor_Error.Value); generator.Throw(); generator.DefineLabelPosition(endOfTypeCheck); generator.ReleaseTemporaryVariable(targetValue); if (functionCallExpressionOperand != null) { // Emit an array containing the function arguments. ((FunctionCallExpression)operand).GenerateArgumentsArray(generator, optimizationInfo); } else { // Emit an empty array. generator.LoadInt32(0); generator.NewArray(typeof(object)); } // Call FunctionInstance.ConstructLateBound(argumentValues) generator.Call(ReflectionHelpers.FunctionInstance_ConstructLateBound.Value); }
private MethodBuilder VoidMethodBuilder(MethodInfo implementationMethod, MethodBuilder method, Type[] pTypes, List <ParameterWrapper> methodParams) { MethodInfo gatherParams = typeof(ServiceWrapperBase <>).MakeGenericType(implementationMethod.DeclaringType).GetMethod( "GatherParameters", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(String), typeof(Object[]) }, null ); var baseType = typeof(ServiceWrapperBase <>).MakeGenericType(implementationMethod.DeclaringType); var implementation = baseType.GetRuntimeFields().Single(f => f.Name == "implementation"); MethodInfo getValue = typeof(ParameterWrapper).GetMethod( "get_value", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null ); MethodInfo createResponse = typeof(ServiceWrapperBase <>).MakeGenericType(implementationMethod.DeclaringType).GetMethod("CreateResponse", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (implementationMethod.ReturnType == typeof(void)) { createResponse = createResponse.MakeGenericMethod(typeof(object)); } else { createResponse = createResponse.MakeGenericMethod(implementationMethod.ReturnType); } MethodInfo method9 = typeof(ServiceWrapperBase <>).MakeGenericType(implementationMethod.DeclaringType).GetMethod( "CreateErrorResponse", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(Exception) }, null ); ILGenerator gen = method.GetILGenerator(); // Preparing locals LocalBuilder parameters = gen.DeclareLocal(typeof(Object[])); LocalBuilder serviceParameters = gen.DeclareLocal(typeof(ParameterWrapper[])); LocalBuilder message = gen.DeclareLocal(typeof(IActionResult)); LocalBuilder ex = gen.DeclareLocal(typeof(Exception)); // Writing body gen.Emit(OpCodes.Nop); gen.BeginExceptionBlock(); gen.Emit(OpCodes.Nop); var ps = pTypes; EmitHelpers.EmitInt32(gen, ps.Length); gen.Emit(OpCodes.Newarr, typeof(object)); for (int j = 0; j < ps.Length; j++) { gen.Emit(OpCodes.Dup); EmitHelpers.EmitInt32(gen, j); EmitHelpers.EmitLdarg(gen, j + 1); var paramType = ps[j]; if (paramType.IsValueType) { gen.Emit(OpCodes.Box, paramType); } gen.Emit(OpCodes.Stelem_Ref); } gen.Emit(OpCodes.Stloc_0); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldstr, implementationMethod.Name); gen.Emit(OpCodes.Ldloc_0); gen.Emit(OpCodes.Call, gatherParams); gen.Emit(OpCodes.Stloc_1); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, implementation); int iii = 0; foreach (var parameterWrapper in methodParams) { gen.Emit(OpCodes.Ldloc_1); EmitHelpers.EmitInt32(gen, iii);//gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ldelem_Ref); gen.Emit(OpCodes.Callvirt, getValue); if (parameterWrapper.Type.IsValueType) { gen.Emit(OpCodes.Unbox_Any, parameterWrapper.Type); } else { gen.Emit(OpCodes.Castclass, parameterWrapper.Type); } iii++; } gen.Emit(OpCodes.Callvirt, implementationMethod); if (implementationMethod.ReturnType != typeof(void)) { gen.Emit(OpCodes.Stloc_2); } gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldc_I4, 200); if (implementationMethod.ReturnType != typeof(void)) { gen.Emit(OpCodes.Ldloc_2); } else { gen.Emit(OpCodes.Ldnull); } gen.Emit(OpCodes.Call, createResponse); gen.Emit(OpCodes.Stloc_2); gen.BeginCatchBlock(typeof(Exception)); gen.Emit(OpCodes.Stloc_3); gen.Emit(OpCodes.Nop); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldloc_3); gen.Emit(OpCodes.Call, method9); gen.Emit(OpCodes.Stloc_2); gen.EndExceptionBlock(); gen.Emit(OpCodes.Ldloc_2); gen.Emit(OpCodes.Ret); // finished return(method); }
public UnsignedFieldHandler() : base( EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).ReadVUInt64()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).SkipVUInt64()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedWriter)null).WriteVUInt64(0))) { }
private MethodBuilder BuildAsyncVoidMethodBody(MethodInfo implementationMethod, MethodBuilder method, Type[] pTypes, List <ParameterWrapper> methodParams, TypeBuilder parent) { MethodInfo gatherParams = typeof(ServiceWrapperBase <>).MakeGenericType(implementationMethod.DeclaringType).GetMethod( "GatherParameters", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(string), typeof(object[]) }, null ); var delegateType = new VoidDelegateBuilder(myModuleBuilder).CreateVoidDelegate(implementationMethod, parent, methodParams); var delegateCtor = delegateType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null); var baseType = typeof(ServiceWrapperBase <>).MakeGenericType(implementationMethod.DeclaringType); var implementation = baseType.GetRuntimeFields().Single(f => f.Name == "implementation"); MethodInfo getValue = typeof(ParameterWrapper).GetMethod( "get_value", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null ); ConstructorInfo ctor9 = typeof(System.Func <>).MakeGenericType(typeof(Task)).GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(Object), typeof(IntPtr) }, null ); MethodInfo createResponse = typeof(ServiceWrapperBase <>).MakeGenericType(implementationMethod.DeclaringType).GetMethod("CreateResponseAsync", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); //createResponse = createResponse.MakeGenericMethod(implementationMethod.ReturnType.GetGenericArguments()); MethodInfo method9 = typeof(ServiceWrapperBase <>).MakeGenericType(implementationMethod.DeclaringType).GetMethod( "CreateErrorResponse", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(Exception) }, null ); var delegateMethod = delegateType.GetMethod(implementationMethod.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);//.MakeGenericMethod(implementationMethod.ReturnType.GenericTypeArguments); var method10 = typeof(ServiceWrapperBase <>).MakeGenericType(implementationMethod.DeclaringType) .GetMethod("ExecuteMethodVoidAsync", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field7 = delegateType.GetField("parameters", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); FieldInfo field5 = delegateType.GetField("implementation", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); MethodInfo fromResult = typeof(Task).GetMethod("FromResult").MakeGenericMethod(typeof(IActionResult)); ILGenerator gen = method.GetILGenerator(); // Preparing locals LocalBuilder del = gen.DeclareLocal(delegateType); LocalBuilder serviceParameters = gen.DeclareLocal(typeof(object[])); LocalBuilder result = gen.DeclareLocal(typeof(Task <>).MakeGenericType(typeof(IActionResult))); LocalBuilder ex = gen.DeclareLocal(typeof(Exception)); // Preparing labels Label label97 = gen.DefineLabel(); // Writing body gen.Emit(OpCodes.Nop); gen.BeginExceptionBlock(); gen.Emit(OpCodes.Newobj, delegateCtor); gen.Emit(OpCodes.Stloc_0); gen.Emit(OpCodes.Ldloc_0); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Stfld, field5); var ps = pTypes; EmitHelpers.EmitInt32(gen, ps.Length); gen.Emit(OpCodes.Newarr, typeof(object)); for (int j = 0; j < ps.Length; j++) { gen.Emit(OpCodes.Dup); EmitHelpers.EmitInt32(gen, j); EmitHelpers.EmitLdarg(gen, j + 1); var paramType = ps[j]; if (paramType.IsValueType) { gen.Emit(OpCodes.Box, paramType); } gen.Emit(OpCodes.Stelem_Ref); } gen.Emit(OpCodes.Stloc_1); gen.Emit(OpCodes.Ldloc_0); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldstr, implementationMethod.Name); gen.Emit(OpCodes.Ldloc_1); gen.Emit(OpCodes.Call, gatherParams); gen.Emit(OpCodes.Stfld, field7); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldloc_0); gen.Emit(OpCodes.Ldftn, delegateMethod); gen.Emit(OpCodes.Newobj, ctor9); gen.Emit(OpCodes.Call, method10); gen.Emit(OpCodes.Stloc_2); gen.Emit(OpCodes.Leave_S, label97); gen.Emit(OpCodes.Leave_S, label97); gen.BeginCatchBlock(typeof(Exception)); gen.Emit(OpCodes.Stloc_S, 3); gen.Emit(OpCodes.Nop); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldloc_S, 3); gen.Emit(OpCodes.Call, method9); gen.Emit(OpCodes.Call, fromResult); gen.Emit(OpCodes.Stloc_2); gen.Emit(OpCodes.Leave_S, label97); gen.EndExceptionBlock(); gen.MarkLabel(label97); gen.Emit(OpCodes.Ldloc_2); gen.Emit(OpCodes.Ret); // finished return(method); }
public StringFieldHandler() : base( EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).ReadString()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedReader)null).SkipString()), EmitHelpers.GetMethodInfo(() => ((AbstractBufferedWriter)null).WriteString(null))) { }
public MethodBuilder BuildAsyncVoidMethod(TypeBuilder type, MethodInfo implementationMethod) { // Declaring method builder // Method attributes const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot; var method = type.DefineMethod(implementationMethod.Name, methodAttributes); // Preparing Reflection instances #region MyRegion ConstructorInfo route = typeof(RouteAttribute).GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(String) }, null ); ConstructorInfo httpGet = httpMethodAttribute(implementationMethod); ConstructorInfo uriAttrib = typeof(FromUriAttribute).GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null ); ConstructorInfo bodyAttrib = typeof(FromBodyAttribute).GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null ); MethodInfo gatherParams = typeof(ServiceWrapperBase <>).MakeGenericType(implementationMethod.DeclaringType).GetMethod( "GatherParameters", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(string), typeof(object[]) }, null ); var baseType = typeof(ServiceWrapperBase <>).MakeGenericType(implementationMethod.DeclaringType); var implementation = baseType.GetRuntimeFields().Single(f => f.Name == "implementation"); MethodInfo getValue = typeof(ParameterWrapper).GetMethod( "get_value", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null ); MethodInfo createResponse = baseType.GetMethod("CreateResponseVoidAsync", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); MethodInfo method9 = baseType.GetMethod( "CreateErrorResponse", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(Exception) }, null ); MethodInfo fromResult = typeof(Task).GetMethod("FromResult").MakeGenericMethod(typeof(HttpResponseMessage)); #endregion // Setting return type method.SetReturnType(typeof(Task <HttpResponseMessage>)); // Adding parameters var methodParams = new List <ParameterWrapper>(); foreach (var parameterInfo in implementationMethod.GetParameters()) { var @in = parameterInfo.GetCustomAttribute <InAttribute>(true); if (@in == null) { var fromBody = parameterInfo.GetCustomAttribute <FromBodyAttribute>(true); if (fromBody != null) { @in = new InAttribute(InclutionTypes.Body); } if (@in == null) { var fromUri = parameterInfo.GetCustomAttribute <FromUriAttribute>(true); if (fromUri != null) { @in = new InAttribute(InclutionTypes.Path); } } } if (@in.InclutionType != InclutionTypes.Header) { methodParams.Add(new ParameterWrapper { Name = parameterInfo.Name, Type = parameterInfo.ParameterType, In = @in?.InclutionType ?? InclutionTypes.Body }); } } var pTypes = methodParams.Select(p => p.Type).ToArray(); method.SetParameters(pTypes.ToArray()); // Parameter id int pid = 1; foreach (var parameterWrapper in methodParams) { try { var p = method.DefineParameter(pid, ParameterAttributes.None, parameterWrapper.Name); if (parameterWrapper.In == InclutionTypes.Path) { p.SetCustomAttribute(new CustomAttributeBuilder(uriAttrib, new Type[] { })); } else if (parameterWrapper.In == InclutionTypes.Body) { p.SetCustomAttribute(new CustomAttributeBuilder(bodyAttrib, new Type[] { })); } pid++; } catch (Exception) { throw; } } // Adding custom attributes to method // [RouteAttribute] method.SetCustomAttribute( new CustomAttributeBuilder( route, new[] { implementationMethod.GetCustomAttribute <RouteAttribute>().Template } ) ); method.SetCustomAttribute( new CustomAttributeBuilder( httpGet, new Type[] { } ) ); ILGenerator gen = method.GetILGenerator(); // Preparing locals LocalBuilder parameters = gen.DeclareLocal(typeof(Object[])); LocalBuilder serviceParameters = gen.DeclareLocal(typeof(ParameterWrapper[])); LocalBuilder result = gen.DeclareLocal(typeof(Task)); LocalBuilder message = gen.DeclareLocal(typeof(Task <HttpResponseMessage>)); LocalBuilder ex = gen.DeclareLocal(typeof(Exception)); // Preparing labels // Writing body gen.Emit(OpCodes.Nop); gen.BeginExceptionBlock(); gen.Emit(OpCodes.Nop); var ps = pTypes; EmitHelpers.EmitInt32(gen, ps.Length); gen.Emit(OpCodes.Newarr, typeof(object)); for (int j = 0; j < ps.Length; j++) { gen.Emit(OpCodes.Dup); EmitHelpers.EmitInt32(gen, j); EmitHelpers.EmitLdarg(gen, j + 1); var paramType = ps[j]; if (paramType.IsValueType) { gen.Emit(OpCodes.Box, paramType); } gen.Emit(OpCodes.Stelem_Ref); } gen.Emit(OpCodes.Stloc_0); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldstr, implementationMethod.Name); gen.Emit(OpCodes.Ldloc_0); gen.Emit(OpCodes.Call, gatherParams); gen.Emit(OpCodes.Stloc_1); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, implementation); int iii = 0; foreach (var parameterWrapper in methodParams) { gen.Emit(OpCodes.Ldloc_1); EmitHelpers.EmitInt32(gen, iii); gen.Emit(OpCodes.Ldelem_Ref); gen.Emit(OpCodes.Callvirt, getValue); if (parameterWrapper.Type.IsValueType) { gen.Emit(OpCodes.Unbox_Any, parameterWrapper.Type); } else { gen.Emit(OpCodes.Castclass, parameterWrapper.Type); } iii++; } gen.Emit(OpCodes.Callvirt, implementationMethod); gen.Emit(OpCodes.Stloc_2); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldc_I4, 200); gen.Emit(OpCodes.Ldloc_2); gen.Emit(OpCodes.Call, createResponse); gen.Emit(OpCodes.Stloc_3); gen.BeginCatchBlock(typeof(Exception)); gen.Emit(OpCodes.Stloc_S, 4); gen.Emit(OpCodes.Nop); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldloc_S, 4); gen.Emit(OpCodes.Call, method9); gen.Emit(OpCodes.Call, fromResult); gen.Emit(OpCodes.Stloc_3); gen.EndExceptionBlock(); gen.Emit(OpCodes.Ldloc_3); gen.Emit(OpCodes.Ret); // finished return(method); }