GetConstructor() public method

public GetConstructor ( BindingFlags bindingAttr, IKVM.Reflection.Binder binder, CallingConventions callingConvention, Type types, IKVM.Reflection.ParameterModifier modifiers ) : IKVM.Reflection.ConstructorInfo
bindingAttr BindingFlags
binder IKVM.Reflection.Binder
callingConvention CallingConventions
types Type
modifiers IKVM.Reflection.ParameterModifier
return IKVM.Reflection.ConstructorInfo
コード例 #1
0
        internal static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes, bool nonPublic)
        {
#if PORTABLE
            // pretty sure this will only ever return public, but...
            ConstructorInfo ctor = type.GetConstructor(parameterTypes);
            return (ctor != null && (nonPublic || ctor.IsPublic)) ? ctor : null;
#else
            return type.GetConstructor(
                nonPublic ? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
                          : BindingFlags.Instance | BindingFlags.Public,
                    null, parameterTypes, null);
#endif
        }
コード例 #2
0
ファイル: Conversion.cs プロジェクト: smartcaveman/runsharp
 public override void Emit(CodeGen g, Type from, Type to)
 {
     _fromConv?.Emit(g, from, Helpers.GetNullableUnderlyingType(to));
     g.IL.Emit(
         OpCodes.Newobj,
         to.GetConstructor(new[] { from }));
 }
コード例 #3
0
        bool AddDateTimeSupport(Type t)
        {
            if (system_datetime != null)
            {
                return(true);
            }

            var corlib = GetMscorlib(t);

            system_datetime = new ProcessedType(t)
            {
                Assembly = corlib,
                // this is tracked because the linker (if enabled) needs to be aware of the requirement
                // but we do not want any code to be generated (it's referenced only from native/glue code)
                IsNativeReference = true,
                Methods           = new List <ProcessedMethod> (),
                Properties        = new List <ProcessedProperty> (),
                Constructors      = new List <ProcessedConstructor> (),
            };
            var ticks = t.GetProperty("Ticks");

            system_datetime.Properties.Add(new ProcessedProperty(ticks, this, system_datetime));

            var kind = t.GetProperty("Kind");

            system_datetime.Properties.Add(new ProcessedProperty(kind, this, system_datetime));

            var dtk          = corlib.Assembly.GetType("System.DateTimeKind");
            var longT        = corlib.Assembly.GetType("System.Int64");
            var ctorLongKind = t.GetConstructor(new Type [] { longT, dtk });

            system_datetime.Constructors.Add(new ProcessedConstructor(ctorLongKind, this, system_datetime));

            var toUniversalTime = t.GetMethod("ToUniversalTime");

            system_datetime.Methods.Add(new ProcessedMethod(toUniversalTime, this, system_datetime));

            AddExtraType(system_datetime);
            return(true);
        }
コード例 #4
0
ファイル: CodeGen.cs プロジェクト: smartcaveman/runsharp
            protected internal override void EmitSet(CodeGen g, Operand value, bool allowExplicitConversion)
            {
                OperandExtensions.SetLeakedState(this, false);
                CheckScope(g);

                if (_t == null)
                {
                    _t = value.GetReturnType(g.TypeMapper);
                }

                if (_var == null)
                {
                    _var = g.IL.DeclareLocal(_t);
                }

                Type nullableUnderlyingType = Helpers.GetNullableUnderlyingType(_t);

                if (ReferenceEquals(value, null))
                {
                    if (nullableUnderlyingType != null)
                    {
                        g.InitObj(this);
                        return;
                    }
                }
                else if (nullableUnderlyingType == value.GetReturnType(g.TypeMapper))
                {
                    EmitAddressOf(g);
                    g.EmitGetHelper(value, nullableUnderlyingType, false);
                    ConstructorInfo ctor = _t.GetConstructor(new [] { nullableUnderlyingType });
                    g.IL.Emit(OpCodes.Call, ctor);
                    return;
                }
                g.EmitGetHelper(value, _t, allowExplicitConversion);

                EmitSetFromStack(g);
            }
コード例 #5
0
        private void WriteAssemblyAttributes(CompilerOptions options, string assemblyName, AssemblyBuilder asm)
        {
            if (!Helpers.IsNullOrEmpty(options.TargetFrameworkName))
            {
                // get [TargetFramework] from mscorlib/equivalent and burn into the new assembly
                Type versionAttribType = null;
                try
                { // this is best-endeavours only
                    versionAttribType = TypeMapper.GetType("System.Runtime.Versioning.TargetFrameworkAttribute", TypeMapper.MapType(typeof(string)).Assembly);
                }
                catch { /* don't stress */ }
                if (versionAttribType != null)
                {
                    PropertyInfo[] props;
                    object[]       propValues;
                    if (Helpers.IsNullOrEmpty(options.TargetFrameworkDisplayName))
                    {
                        props      = new PropertyInfo[0];
                        propValues = new object[0];
                    }
                    else
                    {
                        props = new PropertyInfo[1] {
                            versionAttribType.GetProperty("FrameworkDisplayName")
                        };
                        propValues = new object[1] {
                            options.TargetFrameworkDisplayName
                        };
                    }
                    CustomAttributeBuilder builder = new CustomAttributeBuilder(
                        versionAttribType.GetConstructor(new Type[] { TypeMapper.MapType(typeof(string)) }),
                        new object[] { options.TargetFrameworkName },
                        props,
                        propValues);
                    asm.SetCustomAttribute(builder);
                }
            }

            // copy assembly:InternalsVisibleTo
            Type internalsVisibleToAttribType = null;

#if !FX11
            try
            {
                internalsVisibleToAttribType = TypeMapper.MapType(typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute));
            }
            catch { /* best endeavors only */ }
#endif
            if (internalsVisibleToAttribType != null)
            {
                List <string>   internalAssemblies   = new List <string>();
                List <Assembly> consideredAssemblies = new List <Assembly>();
                foreach (Type type in _types)
                {
                    Assembly assembly = type.Assembly;
                    if (consideredAssemblies.IndexOf(assembly) >= 0)
                    {
                        continue;
                    }
                    consideredAssemblies.Add(assembly);

                    AttributeMap[] assemblyAttribsMap = AttributeMap.Create(TypeMapper, assembly);
                    for (int i = 0; i < assemblyAttribsMap.Length; i++)
                    {
                        if (assemblyAttribsMap[i].AttributeType != internalsVisibleToAttribType)
                        {
                            continue;
                        }

                        object privelegedAssemblyObj;
                        assemblyAttribsMap[i].TryGet("AssemblyName", out privelegedAssemblyObj);
                        string privelegedAssemblyName = (string)privelegedAssemblyObj;
                        if (privelegedAssemblyName == assemblyName || Helpers.IsNullOrEmpty(privelegedAssemblyName))
                        {
                            continue;                                                                                          // ignore
                        }
                        if (internalAssemblies.IndexOf(privelegedAssemblyName) >= 0)
                        {
                            continue;                                                          // seen it before
                        }
                        internalAssemblies.Add(privelegedAssemblyName);

                        CustomAttributeBuilder builder = new CustomAttributeBuilder(
                            internalsVisibleToAttribType.GetConstructor(new Type[] { TypeMapper.MapType(typeof(string)) }),
                            new object[] { privelegedAssemblyName });
                        asm.SetCustomAttribute(builder);
                    }
                }
            }
        }
コード例 #6
0
        private void InitializeJavaClassLoader()
        {
            Assembly assembly = assemblyLoader.Assembly;

            {
                Type customClassLoaderClass = null;
                LoadCustomClassLoaderRedirects();
                string assemblyName = assembly.FullName;
                foreach (KeyValuePair <string, string> kv in customClassLoaderRedirects)
                {
                    string asm = kv.Key;
                    // FXBUG
                    // We only support matching on the assembly's simple name,
                    // because there appears to be no viable alternative.
                    // There is AssemblyName.ReferenceMatchesDefinition()
                    // but it is completely broken.
                    if (assemblyName.StartsWith(asm + ","))
                    {
                        try
                        {
                            customClassLoaderClass = Type.GetType(kv.Value, true);
                        }
                        catch (Exception x)
                        {
                            Tracer.Error(Tracer.Runtime, "Unable to load custom class loader {0} specified in app.config for assembly {1}: {2}", kv.Value, assembly, x);
                        }
                        break;
                    }
                }
                if (customClassLoaderClass == null)
                {
                    object[] attribs = assembly.GetCustomAttributes(typeof(CustomAssemblyClassLoaderAttribute), false);
                    if (attribs.Length == 1)
                    {
                        customClassLoaderClass = ((CustomAssemblyClassLoaderAttribute)attribs[0]).Type;
                    }
                }
                if (customClassLoaderClass != null)
                {
                    try
                    {
                        if (!customClassLoaderClass.IsPublic && !customClassLoaderClass.Assembly.Equals(assembly))
                        {
                            throw new Exception("Type not accessible");
                        }
                        ConstructorInfo customClassLoaderCtor = customClassLoaderClass.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(Assembly) }, null);
                        if (customClassLoaderCtor == null)
                        {
                            throw new Exception("No constructor");
                        }
                        if (!customClassLoaderCtor.IsPublic && !customClassLoaderClass.Assembly.Equals(assembly))
                        {
                            customClassLoaderCtor = null;
                            throw new Exception("Constructor not accessible");
                        }
                        hasCustomClassLoader = true;
                        // NOTE we're creating an uninitialized instance of the custom class loader here, so that getClassLoader will return the proper object
                        // when it is called during the construction of the custom class loader later on. This still doesn't make it safe to use the custom
                        // class loader before it is constructed, but at least the object instance is available and should anyone cache it, they will get the
                        // right object to use later on.
                        // Note that creating the unitialized instance will (unfortunately) trigger the static initializer. The static initializer can
                        // trigger a call to getClassLoader(), which means we can end up here recursively.
                        java.lang.ClassLoader newJavaClassLoader = (java.lang.ClassLoader)GetUninitializedObject(customClassLoaderClass);
                        if (javaClassLoader == null)                         // check if we weren't invoked recursively and the nested invocation already did the work
                        {
                            javaClassLoader = newJavaClassLoader;
                            SetWrapperForClassLoader(javaClassLoader, this);
                            DoPrivileged(new CustomClassLoaderCtorCaller(customClassLoaderCtor, javaClassLoader, assembly));
                            Tracer.Info(Tracer.Runtime, "Created custom assembly class loader {0} for assembly {1}", customClassLoaderClass.FullName, assembly);
                        }
                        else
                        {
                            // we didn't initialize the object, so there is no need to finalize it
                            GC.SuppressFinalize(newJavaClassLoader);
                        }
                    }
                    catch (Exception x)
                    {
                        Tracer.Error(Tracer.Runtime, "Unable to create custom assembly class loader {0} for {1}: {2}", customClassLoaderClass.FullName, assembly, x);
                    }
                }
            }
            if (javaClassLoader == null)
            {
                javaClassLoader = (java.lang.ClassLoader)DoPrivileged(new CreateAssemblyClassLoader(assembly));
                SetWrapperForClassLoader(javaClassLoader, this);
            }
        }
コード例 #7
0
 private void WriteConstructors(TypeBuilder type, ref int index, SerializerPair[] methodPairs, ref ILGenerator il, int knownTypesCategory, FieldBuilder knownTypes, Type knownTypesLookupType, Compiler.CompilerContext ctx)
 {
     type.DefineDefaultConstructor(MethodAttributes.Public);
     il = type.DefineTypeInitializer().GetILGenerator();
     switch (knownTypesCategory)
     {
         case KnownTypes_Array:
             {
                 Compiler.CompilerContext.LoadValue(il, types.Count);
                 il.Emit(OpCodes.Newarr, ctx.MapType(typeof(System.Type)));
                 index = 0;
                 foreach (SerializerPair pair in methodPairs)
                 {
                     il.Emit(OpCodes.Dup);
                     Compiler.CompilerContext.LoadValue(il, index);
                     il.Emit(OpCodes.Ldtoken, pair.Type.Type);
                     il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null);
                     il.Emit(OpCodes.Stelem_Ref);
                     index++;
                 }
                 il.Emit(OpCodes.Stsfld, knownTypes);
                 il.Emit(OpCodes.Ret);
             }
             break;
         case KnownTypes_Dictionary:
             {
                 Compiler.CompilerContext.LoadValue(il, types.Count);
                 //LocalBuilder loc = il.DeclareLocal(knownTypesLookupType);
                 il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[] { MapType(typeof(int)) }));
                 il.Emit(OpCodes.Stsfld, knownTypes);
                 int typeIndex = 0;
                 foreach (SerializerPair pair in methodPairs)
                 {
                     il.Emit(OpCodes.Ldsfld, knownTypes);
                     il.Emit(OpCodes.Ldtoken, pair.Type.Type);
                     il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null);
                     int keyIndex = typeIndex++, lastKey = pair.BaseKey;
                     if (lastKey != pair.MetaKey) // not a base-type; need to give the index of the base-type
                     {
                         keyIndex = -1; // assume epic fail
                         for (int j = 0; j < methodPairs.Length; j++)
                         {
                             if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey)
                             {
                                 keyIndex = j;
                                 break;
                             }
                         }
                     }
                     Compiler.CompilerContext.LoadValue(il, keyIndex);
                     il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[] { MapType(typeof(System.Type)), MapType(typeof(int)) }), null);
                 }
                 il.Emit(OpCodes.Ret);
             }
             break;
         case KnownTypes_Hashtable:
             {
                 Compiler.CompilerContext.LoadValue(il, types.Count);
                 il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[] { MapType(typeof(int)) }));
                 il.Emit(OpCodes.Stsfld, knownTypes);
                 int typeIndex = 0;
                 foreach (SerializerPair pair in methodPairs)
                 {
                     il.Emit(OpCodes.Ldsfld, knownTypes);
                     il.Emit(OpCodes.Ldtoken, pair.Type.Type);
                     il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null);
                     int keyIndex = typeIndex++, lastKey = pair.BaseKey;
                     if (lastKey != pair.MetaKey) // not a base-type; need to give the index of the base-type
                     {
                         keyIndex = -1; // assume epic fail
                         for (int j = 0; j < methodPairs.Length; j++)
                         {
                             if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey)
                             {
                                 keyIndex = j;
                                 break;
                             }
                         }
                     }
                     Compiler.CompilerContext.LoadValue(il, keyIndex);
                     il.Emit(OpCodes.Box, MapType(typeof(int)));
                     il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[] { MapType(typeof(object)), MapType(typeof(object)) }), null);
                 }
                 il.Emit(OpCodes.Ret);
             }
             break;
         default:
             throw new InvalidOperationException();
     }
 }
コード例 #8
0
		internal void SetMain(MethodInfo m, PEFileKinds target, Dictionary<string, string> props, bool noglobbing, Type apartmentAttributeType)
		{
			MethodBuilder mainStub = this.GetTypeWrapperFactory().ModuleBuilder.DefineGlobalMethod("main", MethodAttributes.Public | MethodAttributes.Static, Types.Int32, new Type[] { Types.String.MakeArrayType() });
			if(apartmentAttributeType != null)
			{
				mainStub.SetCustomAttribute(new CustomAttributeBuilder(apartmentAttributeType.GetConstructor(Type.EmptyTypes), new object[0]));
			}
			CodeEmitter ilgen = CodeEmitter.Create(mainStub);
			CodeEmitterLocal rc = ilgen.DeclareLocal(Types.Int32);
			TypeWrapper startupType = LoadClassByDottedName("ikvm.runtime.Startup");
			if(props.Count > 0)
			{
				ilgen.Emit(OpCodes.Newobj, JVM.Import(typeof(System.Collections.Generic.Dictionary<string, string>)).GetConstructor(Type.EmptyTypes));
				foreach(KeyValuePair<string, string> kv in props)
				{
					ilgen.Emit(OpCodes.Dup);
					ilgen.Emit(OpCodes.Ldstr, kv.Key);
					ilgen.Emit(OpCodes.Ldstr, kv.Value);
					if(kv.Value.IndexOf('%') < kv.Value.LastIndexOf('%'))
					{
						ilgen.Emit(OpCodes.Call, JVM.Import(typeof(Environment)).GetMethod("ExpandEnvironmentVariables", new Type[] { Types.String }));
					}
					ilgen.Emit(OpCodes.Callvirt, JVM.Import(typeof(System.Collections.Generic.Dictionary<string, string>)).GetMethod("Add"));
				}
				startupType.GetMethodWrapper("setProperties", "(Lcli.System.Collections.IDictionary;)V", false).EmitCall(ilgen);
			}
			ilgen.BeginExceptionBlock();
			startupType.GetMethodWrapper("enterMainThread", "()V", false).EmitCall(ilgen);
			ilgen.Emit(OpCodes.Ldarg_0);
			if (!noglobbing)
			{
				ilgen.Emit(OpCodes.Ldc_I4_0);
				startupType.GetMethodWrapper("glob", "([Ljava.lang.String;I)[Ljava.lang.String;", false).EmitCall(ilgen);
			}
			ilgen.Emit(OpCodes.Call, m);
			CodeEmitterLabel label = ilgen.DefineLabel();
			ilgen.Emit(OpCodes.Leave, label);
			ilgen.BeginCatchBlock(Types.Exception);
			LoadClassByDottedName("ikvm.runtime.Util").GetMethodWrapper("mapException", "(Ljava.lang.Throwable;)Ljava.lang.Throwable;", false).EmitCall(ilgen);
			CodeEmitterLocal exceptionLocal = ilgen.DeclareLocal(Types.Exception);
			ilgen.Emit(OpCodes.Stloc, exceptionLocal);
			TypeWrapper threadTypeWrapper = ClassLoaderWrapper.LoadClassCritical("java.lang.Thread");
			CodeEmitterLocal threadLocal = ilgen.DeclareLocal(threadTypeWrapper.TypeAsLocalOrStackType);
			threadTypeWrapper.GetMethodWrapper("currentThread", "()Ljava.lang.Thread;", false).EmitCall(ilgen);
			ilgen.Emit(OpCodes.Stloc, threadLocal);
			ilgen.Emit(OpCodes.Ldloc, threadLocal);
			threadTypeWrapper.GetMethodWrapper("getThreadGroup", "()Ljava.lang.ThreadGroup;", false).EmitCallvirt(ilgen);
			ilgen.Emit(OpCodes.Ldloc, threadLocal);
			ilgen.Emit(OpCodes.Ldloc, exceptionLocal);
			ClassLoaderWrapper.LoadClassCritical("java.lang.ThreadGroup").GetMethodWrapper("uncaughtException", "(Ljava.lang.Thread;Ljava.lang.Throwable;)V", false).EmitCallvirt(ilgen);
			ilgen.Emit(OpCodes.Ldc_I4_1);
			ilgen.Emit(OpCodes.Stloc, rc);
			ilgen.Emit(OpCodes.Leave, label);
			ilgen.BeginFinallyBlock();
			startupType.GetMethodWrapper("exitMainThread", "()V", false).EmitCall(ilgen);
			ilgen.Emit(OpCodes.Endfinally);
			ilgen.EndExceptionBlock();
			ilgen.MarkLabel(label);
			ilgen.Emit(OpCodes.Ldloc, rc);
			ilgen.Emit(OpCodes.Ret);
			ilgen.DoEmit();
			assemblyBuilder.SetEntryPoint(mainStub, target);
		}
コード例 #9
0
ファイル: CodeEmitter.cs プロジェクト: Semogj/ikvm-fork
		internal void ThrowException(Type excType)
		{
			Emit(OpCodes.Newobj, excType.GetConstructor(Type.EmptyTypes));
			Emit(OpCodes.Throw);
		}
コード例 #10
0
ファイル: Conversion.cs プロジェクト: AqlaSolutions/runsharp
            public override void Emit(CodeGen g, Type from, Type to)
		    {
                _fromConv?.Emit(g, from, Helpers.GetNullableUnderlyingType(to));
		        g.IL.Emit(
		            OpCodes.Newobj,
		            to.GetConstructor(new[] { from }));
		    }
コード例 #11
0
ファイル: AssemblyClassLoader.cs プロジェクト: xamidi/ikvm
 private void InitializeJavaClassLoader(JavaClassLoaderConstructionInProgress jclcip, Type customClassLoaderClass)
 {
     Assembly assembly = assemblyLoader.Assembly;
     {
         if (customClassLoaderClass != null)
         {
             try
             {
                 if (!customClassLoaderClass.IsPublic && !customClassLoaderClass.Assembly.Equals(assembly))
                 {
                     throw new Exception("Type not accessible");
                 }
                 ConstructorInfo customClassLoaderCtor = customClassLoaderClass.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(Assembly) }, null);
                 if (customClassLoaderCtor == null)
                 {
                     throw new Exception("No constructor");
                 }
                 if (!customClassLoaderCtor.IsPublic && !customClassLoaderClass.Assembly.Equals(assembly))
                 {
                     customClassLoaderCtor = null;
                     throw new Exception("Constructor not accessible");
                 }
                 // NOTE we're creating an uninitialized instance of the custom class loader here, so that getClassLoader will return the proper object
                 // when it is called during the construction of the custom class loader later on. This still doesn't make it safe to use the custom
                 // class loader before it is constructed, but at least the object instance is available and should anyone cache it, they will get the
                 // right object to use later on.
                 // Note that creating the unitialized instance will (unfortunately) trigger the static initializer. The static initializer can
                 // trigger a call to getClassLoader(), which means we can end up here recursively.
                 java.lang.ClassLoader newJavaClassLoader = (java.lang.ClassLoader)GetUninitializedObject(customClassLoaderClass);
                 if (jclcip.javaClassLoader == null) // check if we weren't invoked recursively and the nested invocation already did the work
                 {
                     jclcip.javaClassLoader = newJavaClassLoader;
                     SetWrapperForClassLoader(jclcip.javaClassLoader, this);
                     DoPrivileged(new CustomClassLoaderCtorCaller(customClassLoaderCtor, jclcip.javaClassLoader, assembly));
                     Tracer.Info(Tracer.Runtime, "Created custom assembly class loader {0} for assembly {1}", customClassLoaderClass.FullName, assembly);
                 }
                 else
                 {
                     // we didn't initialize the object, so there is no need to finalize it
                     GC.SuppressFinalize(newJavaClassLoader);
                 }
             }
             catch (Exception x)
             {
                 Tracer.Error(Tracer.Runtime, "Unable to create custom assembly class loader {0} for {1}: {2}", customClassLoaderClass.FullName, assembly, x);
             }
         }
     }
     if (jclcip.javaClassLoader == null)
     {
         jclcip.javaClassLoader = new ikvm.runtime.AssemblyClassLoader();
         SetWrapperForClassLoader(jclcip.javaClassLoader, this);
     }
     // finally we publish the class loader for other threads to see
     Thread.MemoryBarrier();
     javaClassLoader = jclcip.javaClassLoader;
 }
コード例 #12
0
ファイル: Helpers.cs プロジェクト: 2asoft/SpaceEngineers
        internal static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes, bool nonPublic)
        {
#if PORTABLE
            // pretty sure this will only ever return public, but...
            ConstructorInfo ctor = type.GetConstructor(parameterTypes);
            return (ctor != null && (nonPublic || ctor.IsPublic)) ? ctor : null;
#else
            return type.GetConstructor(
                nonPublic ? BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
                          : BindingFlags.Instance | BindingFlags.Public,
                    null, parameterTypes, null);
#endif

        }
コード例 #13
0
        private void WriteConstructors(TypeBuilder type, ref int index, SerializerPair[] methodPairs, ref ILGenerator il, int knownTypesCategory, FieldBuilder knownTypes, Type knownTypesLookupType, Compiler.CompilerContext ctx)
        {
            type.DefineDefaultConstructor(MethodAttributes.Public);
            il = type.DefineTypeInitializer().GetILGenerator();
            switch (knownTypesCategory)
            {
            case KnownTypes_Array:
            {
                Compiler.CompilerContext.LoadValue(il, _types.Count);
                il.Emit(OpCodes.Newarr, ctx.MapType(typeof(System.Type)));
                index = 0;
                foreach (SerializerPair pair in methodPairs)
                {
                    il.Emit(OpCodes.Dup);
                    Compiler.CompilerContext.LoadValue(il, index);
                    il.Emit(OpCodes.Ldtoken, pair.Type.Type);
                    il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null);
                    il.Emit(OpCodes.Stelem_Ref);
                    index++;
                }
                il.Emit(OpCodes.Stsfld, knownTypes);
                il.Emit(OpCodes.Ret);
            }
            break;

            case KnownTypes_Dictionary:
            {
                Compiler.CompilerContext.LoadValue(il, _types.Count);
                //LocalBuilder loc = il.DeclareLocal(knownTypesLookupType);
                il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[] { MapType(typeof(int)) }));
                il.Emit(OpCodes.Stsfld, knownTypes);
                int typeIndex = 0;
                foreach (SerializerPair pair in methodPairs)
                {
                    il.Emit(OpCodes.Ldsfld, knownTypes);
                    il.Emit(OpCodes.Ldtoken, pair.Type.Type);
                    il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null);
                    int keyIndex = typeIndex++, lastKey = pair.BaseKey;
                    if (lastKey != pair.MetaKey) // not a base-type; need to give the index of the base-type
                    {
                        keyIndex = -1;           // assume epic fail
                        for (int j = 0; j < methodPairs.Length; j++)
                        {
                            if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey)
                            {
                                keyIndex = j;
                                break;
                            }
                        }
                    }
                    Compiler.CompilerContext.LoadValue(il, keyIndex);
                    il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[] { MapType(typeof(System.Type)), MapType(typeof(int)) }), null);
                }
                il.Emit(OpCodes.Ret);
            }
            break;

            case KnownTypes_Hashtable:
            {
                Compiler.CompilerContext.LoadValue(il, _types.Count);
                il.Emit(OpCodes.Newobj, knownTypesLookupType.GetConstructor(new Type[] { MapType(typeof(int)) }));
                il.Emit(OpCodes.Stsfld, knownTypes);
                int typeIndex = 0;
                foreach (SerializerPair pair in methodPairs)
                {
                    il.Emit(OpCodes.Ldsfld, knownTypes);
                    il.Emit(OpCodes.Ldtoken, pair.Type.Type);
                    il.EmitCall(OpCodes.Call, ctx.MapType(typeof(System.Type)).GetMethod("GetTypeFromHandle"), null);
                    int keyIndex = typeIndex++, lastKey = pair.BaseKey;
                    if (lastKey != pair.MetaKey) // not a base-type; need to give the index of the base-type
                    {
                        keyIndex = -1;           // assume epic fail
                        for (int j = 0; j < methodPairs.Length; j++)
                        {
                            if (methodPairs[j].BaseKey == lastKey && methodPairs[j].MetaKey == lastKey)
                            {
                                keyIndex = j;
                                break;
                            }
                        }
                    }
                    Compiler.CompilerContext.LoadValue(il, keyIndex);
                    il.Emit(OpCodes.Box, MapType(typeof(int)));
                    il.EmitCall(OpCodes.Callvirt, knownTypesLookupType.GetMethod("Add", new Type[] { MapType(typeof(object)), MapType(typeof(object)) }), null);
                }
                il.Emit(OpCodes.Ret);
            }
            break;

            default:
                throw new InvalidOperationException();
            }
        }
コード例 #14
0
        private static void LoadAll()
        {
            // Types
            function  = Load(typeof(TotemFunction));
            value     = Load(typeof(TotemValue));
            tstring   = Load(typeof(TotemString));
            arguments = Load(typeof(TotemArguments));
            parameter = Load(typeof(TotemParameter));
            @bool     = Load(typeof(TotemBool));
            map       = Load(typeof(TotemMap));
            array     = Load(typeof(TotemArray));
            scope     = Load(typeof(TotemFunction.ScopeWrapper));

            arr_parameters = Load(typeof(TotemParameter[]));
            sys_bool       = Load(typeof(bool));

            // Methods
            value_val = Load(typeof(TotemValue)).GetProperty("ByTotemValue").GetGetMethod();

            function_run       = Load(typeof(TotemFunction)).GetMethod("TotemRun", r.BindingFlags.NonPublic | r.BindingFlags.Instance);
            execute            = Load(typeof(TotemValue)).GetMethod("Execute");
            function_ctor      = Load(typeof(TotemFunction)).GetConstructor(r.BindingFlags.NonPublic | r.BindingFlags.Instance, null, new IKType[] { Load(typeof(TotemScope)), Load(typeof(string)), Load(typeof(TotemParameter[])) }, null);
            function_local_set = Load(typeof(TotemFunction)).GetMethod("LocalSet", r.BindingFlags.NonPublic | r.BindingFlags.Instance);
            function_local_get = Load(typeof(TotemFunction)).GetMethod("LocalGet", r.BindingFlags.NonPublic | r.BindingFlags.Instance);
            function_local_dec = Load(typeof(TotemFunction)).GetMethod("LocalDec", r.BindingFlags.NonPublic | r.BindingFlags.Instance);
            function_env       = Load(typeof(TotemFunction)).GetProperty("Scope", r.BindingFlags.NonPublic | r.BindingFlags.Instance).GetGetMethod(true);

            arguments_ctor = Load(typeof(TotemArguments)).GetConstructor(IKType.EmptyTypes);
            arguments_add  = Load(typeof(TotemArguments)).GetMethod("Add", r.BindingFlags.Public | r.BindingFlags.Instance | r.BindingFlags.DeclaredOnly);

            number_ctor_long = Load(typeof(TotemNumber)).GetConstructor(new IKType[] { Load(typeof(long)) });

            string_ctor = Load(typeof(TotemString)).GetConstructor(new IKType[] { Load(typeof(string)) });

            parameter_ctor = Load(typeof(TotemParameter)).GetConstructor(new IKType[] { Load(typeof(string)), Load(typeof(TotemValue)) });

            undefined = Load(typeof(TotemValue)).GetProperty("Undefined").GetGetMethod();
            @null     = Load(typeof(TotemValue)).GetProperty("Null").GetGetMethod();

            value_add        = Load(typeof(TotemValue)).GetMethod("op_Addition", r.BindingFlags.Static | r.BindingFlags.Public);
            value_sub        = Load(typeof(TotemValue)).GetMethod("op_Subtraction", r.BindingFlags.Static | r.BindingFlags.Public);
            value_mul        = Load(typeof(TotemValue)).GetMethod("op_Multiply", r.BindingFlags.Static | r.BindingFlags.Public);
            value_div        = Load(typeof(TotemValue)).GetMethod("op_Division", r.BindingFlags.Static | r.BindingFlags.Public);
            value_eq         = Load(typeof(TotemValue)).GetMethod("op_Equality", r.BindingFlags.Static | r.BindingFlags.Public);
            value_neq        = Load(typeof(TotemValue)).GetMethod("op_Inequality", r.BindingFlags.Static | r.BindingFlags.Public);
            value_lt         = Load(typeof(TotemValue)).GetMethod("op_LessThan", r.BindingFlags.Static | r.BindingFlags.Public);
            value_gt         = Load(typeof(TotemValue)).GetMethod("op_GreaterThan", r.BindingFlags.Static | r.BindingFlags.Public);
            value_lte        = Load(typeof(TotemValue)).GetMethod("op_LessThanOrEqual", r.BindingFlags.Static | r.BindingFlags.Public);
            value_gte        = Load(typeof(TotemValue)).GetMethod("op_GreaterThanOrEqual", r.BindingFlags.Static | r.BindingFlags.Public);
            value_incr       = Load(typeof(TotemValue)).GetMethod("op_Increment", r.BindingFlags.Static | r.BindingFlags.Public);
            value_decr       = Load(typeof(TotemValue)).GetMethod("op_Decrement", r.BindingFlags.Static | r.BindingFlags.Public);
            value_istrue     = Load(typeof(TotemValue)).GetMethod("op_Explicit", r.BindingFlags.Static | r.BindingFlags.Public, null, r.CallingConventions.Standard, new IKType[] { Load(typeof(TotemValue)) }, null);
            value_lookup_get = Load(typeof(TotemValue)).GetProperty("Item", value, new IKType[] { value }).GetGetMethod();
            value_lookup_set = Load(typeof(TotemValue)).GetProperty("Item", value, new IKType[] { value }).GetSetMethod();

            scope_ctor = Load(typeof(TotemFunction.ScopeWrapper)).GetConstructor(new IKType[] { Load(typeof(TotemFunction)) });

            dispose = Load(typeof(IDisposable)).GetMethod("Dispose");

            get_prop = Load(typeof(TotemValue)).GetMethod("GetProp");
            set_prop = Load(typeof(TotemValue)).GetMethod("SetProp");

            bool_ctor = Load(typeof(TotemBool)).GetConstructor(new IKType[] { Load(typeof(bool)) });

            map_ctor = map.GetConstructor(IKType.EmptyTypes);
            map_add  = map.GetMethod("AddItem");

            array_ctor = array.GetConstructor(IKType.EmptyTypes);
            array_add  = array.GetMethod("AddItem");
        }