2 // import.cs: System.Reflection conversions
4 // Authors: Marek Safar (marek.safar@gmail.com)
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 // Copyright 2009, 2010 Novell, Inc
12 using System.Runtime.CompilerServices;
14 using System.Collections.Generic;
17 using MetaType = IKVM.Reflection.Type;
18 using IKVM.Reflection;
19 using IKVM.Reflection.Emit;
21 using MetaType = System.Type;
22 using System.Reflection;
23 using System.Reflection.Emit;
28 public abstract class MetadataImporter
31 // Dynamic types reader with additional logic to reconstruct a dynamic
32 // type using DynamicAttribute values
34 struct DynamicTypeReader
36 static readonly bool[] single_attribute = { true };
41 // There is no common type for CustomAttributeData and we cannot
42 // use ICustomAttributeProvider
46 // A member provider which can be used to get CustomAttributeData
48 public DynamicTypeReader (object provider)
52 this.provider = provider;
56 // Returns true when object at local position has dynamic attribute flag
58 public bool IsDynamicObject (MetadataImporter importer)
61 ReadAttribute (importer);
63 return flags != null && Position < flags.Length && flags[Position];
67 // Returns true when DynamicAttribute exists
69 public bool HasDynamicAttribute (MetadataImporter importer)
72 ReadAttribute (importer);
77 void ReadAttribute (MetadataImporter importer)
79 IList<CustomAttributeData> cad;
80 if (provider is MemberInfo) {
81 cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
82 } else if (provider is ParameterInfo) {
83 cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
91 foreach (var ca in cad) {
92 importer.GetCustomAttributeTypeName (ca, out ns, out name);
93 if (name != "DynamicAttribute" && ns != CompilerServicesNamespace)
96 if (ca.ConstructorArguments.Count == 0) {
97 flags = single_attribute;
101 var arg_type = ca.ConstructorArguments[0].ArgumentType;
103 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
104 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
105 flags = new bool[carg.Count];
106 for (int i = 0; i < flags.Length; ++i) {
107 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
108 flags[i] = (bool) carg[i].Value;
120 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
121 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
122 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
124 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
126 protected MetadataImporter ()
128 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
129 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
130 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
131 IgnorePrivateMembers = true;
136 public ICollection<IAssemblyDefinition> Assemblies {
138 return assembly_2_definition.Values;
142 public bool IgnorePrivateMembers { get; set; }
146 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
147 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
148 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
149 public abstract void GetCustomAttributeTypeName (CustomAttributeData cad, out string typeNamespace, out string typeName);
151 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
154 var fa = fi.Attributes;
155 switch (fa & FieldAttributes.FieldAccessMask) {
156 case FieldAttributes.Public:
157 mod = Modifiers.PUBLIC;
159 case FieldAttributes.Assembly:
160 mod = Modifiers.INTERNAL;
162 case FieldAttributes.Family:
163 mod = Modifiers.PROTECTED;
165 case FieldAttributes.FamORAssem:
166 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
169 // Ignore private fields (even for error reporting) to not require extra dependencies
170 if (IgnorePrivateMembers || HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
173 mod = Modifiers.PRIVATE;
180 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
181 } catch (Exception e) {
182 // TODO: I should construct fake TypeSpec based on TypeRef signature
183 // but there is no way to do it with System.Reflection
184 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
185 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
188 var definition = new ImportedMemberDefinition (fi, field_type, this);
190 if ((fa & FieldAttributes.Literal) != 0) {
191 var c = Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
192 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
195 if ((fa & FieldAttributes.InitOnly) != 0) {
196 if (field_type == TypeManager.decimal_type) {
197 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
199 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
202 mod |= Modifiers.READONLY;
204 var req_mod = fi.GetRequiredCustomModifiers ();
205 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
206 mod |= Modifiers.VOLATILE;
209 if ((fa & FieldAttributes.Static) != 0) {
210 mod |= Modifiers.STATIC;
212 // Fixed buffers cannot be static
213 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
214 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
216 // TODO: Sanity check on field_type (only few type are allowed)
217 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
218 return new FixedFieldSpec (declaringType, definition, fi, element_field, mod);
222 return new FieldSpec (declaringType, definition, field_type, fi, mod);
225 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
227 add.IsAccessor = true;
228 remove.IsAccessor = true;
230 if (add.Modifiers != remove.Modifiers)
231 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
233 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
234 var definition = new ImportedMemberDefinition (ei, event_type, this);
235 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
238 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
240 var tparams = type.GetGenericArguments ();
242 int parent_owned_count;
244 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
247 // System.Reflection duplicates parent type parameters for each
248 // nested type with slightly modified properties (eg. different owner)
249 // This just makes things more complicated (think of cloned constraints)
250 // therefore we remap any nested type owned by parent using `type_cache'
251 // to the single TypeParameterSpec
253 if (declaringType != null && parent_owned_count > 0) {
255 while (read_count != parent_owned_count) {
256 var tparams_count = declaringType.Arity;
257 if (tparams_count != 0) {
258 var parent_tp = declaringType.MemberDefinition.TypeParameters;
259 read_count += tparams_count;
260 for (int i = 0; i < tparams_count; i++) {
261 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
265 declaringType = declaringType.DeclaringType;
269 parent_owned_count = 0;
272 if (tparams.Length - parent_owned_count == 0)
275 return CreateGenericParameters (parent_owned_count, tparams);
278 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
280 var tspec = new TypeParameterSpec[tparams.Length - first];
281 for (int pos = first; pos < tparams.Length; ++pos) {
282 var type = tparams[pos];
283 int index = pos - first;
285 tspec [index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
291 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
295 var tspec = new TypeSpec [tparams.Length - first];
296 for (int pos = first; pos < tparams.Length; ++pos) {
297 var type = tparams[pos];
298 int index = pos - first;
301 if (type.HasElementType) {
302 var element = type.GetElementType ();
304 spec = ImportType (element, dtype);
307 throw new NotImplementedException ("Unknown element type " + type.ToString ());
310 spec = ArrayContainer.MakeType (spec, type.GetArrayRank ());
312 spec = CreateType (type, dtype, true);
315 // We treat nested generic types as inflated internally where
316 // reflection uses type definition
319 // IFoo<A<T>> foo; // A<T> is definition in this case
322 // TODO: Is full logic from CreateType needed here as well?
324 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
325 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
326 spec = spec.MakeGenericType (targs);
337 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
339 Modifiers mod = ReadMethodModifiers (mb, declaringType);
340 TypeParameterSpec[] tparams;
342 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
344 if (mb.IsGenericMethod) {
345 if (!mb.IsGenericMethodDefinition)
346 throw new NotSupportedException ("assert");
348 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
355 if (mb.MemberType == MemberTypes.Constructor) {
356 kind = MemberKind.Constructor;
357 returnType = TypeManager.void_type;
360 // Detect operators and destructors
362 string name = mb.Name;
363 kind = MemberKind.Method;
364 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
365 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
366 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
367 var op_type = Operator.GetType (name);
368 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
369 kind = MemberKind.Operator;
372 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
373 kind = MemberKind.Destructor;
374 if (declaringType == TypeManager.object_type) {
375 mod &= ~Modifiers.OVERRIDE;
376 mod |= Modifiers.VIRTUAL;
381 var mi = (MethodInfo) mb;
382 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
384 // Cannot set to OVERRIDE without full hierarchy checks
385 // this flag indicates that the method could be override
386 // but further validation is needed
387 if ((mod & Modifiers.OVERRIDE) != 0 && kind == MemberKind.Method && declaringType.BaseType != null) {
388 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
389 var candidate = MemberCache.FindMember (declaringType.BaseType, filter, BindingRestriction.None);
392 // For imported class method do additional validation to be sure that metadata
393 // override flag was correct
395 // Difference between protected internal and protected is ok
397 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
398 if (candidate == null || (candidate.Modifiers & conflict_mask) != (mod & conflict_mask) || candidate.IsStatic) {
399 mod &= ~Modifiers.OVERRIDE;
400 mod |= Modifiers.VIRTUAL;
405 IMemberDefinition definition;
406 if (tparams != null) {
407 definition = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
409 definition = new ImportedParameterMemberDefinition (mb, returnType, parameters, this);
412 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, mb, parameters, mod);
420 // Imports System.Reflection parameters
422 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
424 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
426 if (pi.Length == 0 && varargs == 0)
427 return ParametersCompiled.EmptyReadOnlyParameters;
429 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
430 IParameterData[] par = new IParameterData[pi.Length + varargs];
431 bool is_params = false;
432 for (int i = 0; i < pi.Length; i++) {
433 ParameterInfo p = pi[i];
434 Parameter.Modifier mod = 0;
435 Expression default_value = null;
436 if (p.ParameterType.IsByRef) {
437 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
438 mod = Parameter.Modifier.OUT;
440 mod = Parameter.Modifier.REF;
443 // Strip reference wrapping
445 var el = p.ParameterType.GetElementType ();
446 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
447 } else if (i == 0 && method.IsStatic && parent.IsStatic && parent.MemberDefinition.DeclaringAssembly.HasExtensionMethod &&
448 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
449 mod = Parameter.Modifier.This;
450 types[i] = ImportType (p.ParameterType);
452 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
454 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
455 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
456 mod = Parameter.Modifier.PARAMS;
461 if (!is_params && p.IsOptional) {
462 object value = p.RawDefaultValue;
463 var ptype = types[i];
464 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeManager.IsReferenceType (ptype))) {
466 default_value = Constant.CreateConstant (null, ptype, null, Location.Null);
468 default_value = ImportParameterConstant (value).Resolve (null);
471 default_value = new EnumConstant ((Constant) default_value, ptype).Resolve (null);
474 } else if (value == Missing.Value) {
475 default_value = EmptyExpression.MissingValue;
476 } else if (value == null) {
477 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
478 } else if (ptype == TypeManager.decimal_type) {
479 default_value = ImportParameterConstant (value).Resolve (null);
484 par[i] = new ParameterData (p.Name, mod, default_value);
488 par[par.Length - 1] = new ArglistParameter (Location.Null);
489 types[types.Length - 1] = InternalType.Arglist;
492 return method != null ?
493 new ParametersImported (par, types, varargs != 0, is_params) :
494 new ParametersImported (par, types, is_params);
498 // Returns null when the property is not valid C# property
500 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
503 AParametersCollection param = null;
504 TypeSpec type = null;
507 param = get.Parameters;
508 type = get.ReturnType;
511 bool is_valid_property = true;
513 if (set.ReturnType != TypeManager.void_type)
514 is_valid_property = false;
516 var set_param_count = set.Parameters.Count - 1;
518 if (set_param_count < 0) {
520 is_valid_property = false;
523 var set_type = set.Parameters.Types[set_param_count];
526 AParametersCollection set_based_param;
528 if (set_param_count == 0) {
529 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
532 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
534 var data = new IParameterData[set_param_count];
535 var types = new TypeSpec[set_param_count];
536 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
537 Array.Copy (set.Parameters.Types, types, set_param_count);
538 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
542 param = set_based_param;
545 if (set_param_count != get.Parameters.Count)
546 is_valid_property = false;
548 if (get.ReturnType != set_type)
549 is_valid_property = false;
551 // Possible custom accessor modifiers
552 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
553 var get_acc = mod & Modifiers.AccessibilityMask;
554 if (get_acc != Modifiers.PUBLIC) {
555 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
556 // If the accessor modifiers are not same, do extra restriction checks
557 if (get_acc != set_acc) {
558 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
559 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
560 if (get_restr && set_restr) {
561 is_valid_property = false; // Neither is more restrictive
565 mod &= ~Modifiers.AccessibilityMask;
574 PropertySpec spec = null;
575 if (!param.IsEmpty) {
576 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
577 if (index_name == null) {
578 is_valid_property = false;
582 is_valid_property = false;
583 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
584 is_valid_property = false;
588 is_valid_property = false;
589 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
590 is_valid_property = false;
594 if (is_valid_property)
595 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
599 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
601 if (!is_valid_property) {
602 spec.IsNotRealProperty = true;
614 public TypeSpec CreateType (MetaType type)
616 return CreateType (type, new DynamicTypeReader (), true);
619 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
621 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
624 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
626 TypeSpec declaring_type;
627 if (type.IsNested && !type.IsGenericParameter)
628 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
630 declaring_type = null;
632 return CreateType (type, declaring_type, dtype, canImportBaseType);
635 TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
638 if (import_cache.TryGetValue (type, out spec)) {
639 if (spec == TypeManager.object_type) {
640 if (dtype.IsDynamicObject (this))
641 return InternalType.Dynamic;
646 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
649 if (!dtype.HasDynamicAttribute (this))
652 // We've found same object in the cache but this one has a dynamic custom attribute
653 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
654 // Do type resolve process again in that case
656 // TODO: Handle cases where they still unify
659 if (IsMissingType (type)) {
660 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
661 spec.MemberCache = MemberCache.Empty;
662 import_cache.Add (type, spec);
666 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
667 var type_def = type.GetGenericTypeDefinition ();
668 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
669 if (declaringType == null) {
670 // Simple case, no nesting
671 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
672 spec = spec.MakeGenericType (targs);
675 // Nested type case, converting .NET types like
676 // A`1.B`1.C`1<int, long, string> to typespec like
677 // A<int>.B<long>.C<string>
679 var nested_hierarchy = new List<TypeSpec> ();
680 while (declaringType.IsNested) {
681 nested_hierarchy.Add (declaringType);
682 declaringType = declaringType.DeclaringType;
686 if (declaringType.Arity > 0) {
687 spec = declaringType.MakeGenericType (targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
688 targs_pos = spec.Arity;
690 spec = declaringType;
693 for (int i = nested_hierarchy.Count; i != 0; --i) {
694 var t = nested_hierarchy [i - 1];
695 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
697 spec = spec.MakeGenericType (targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
698 targs_pos += t.Arity;
702 string name = type.Name;
703 int index = name.IndexOf ('`');
705 name = name.Substring (0, index);
707 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
708 if (spec.Arity > 0) {
709 spec = spec.MakeGenericType (targs.Skip (targs_pos).ToArray ());
713 // Don't add generic type with dynamic arguments, they can interfere with same type
714 // using object type arguments
715 if (!spec.HasDynamicElement) {
717 // Add to reading cache to speed up reading
718 if (!import_cache.ContainsKey (type))
719 import_cache.Add (type, spec);
728 var ma = type.Attributes;
729 switch (ma & TypeAttributes.VisibilityMask) {
730 case TypeAttributes.Public:
731 case TypeAttributes.NestedPublic:
732 mod = Modifiers.PUBLIC;
734 case TypeAttributes.NestedPrivate:
735 mod = Modifiers.PRIVATE;
737 case TypeAttributes.NestedFamily:
738 mod = Modifiers.PROTECTED;
740 case TypeAttributes.NestedFamORAssem:
741 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
744 mod = Modifiers.INTERNAL;
748 if ((ma & TypeAttributes.Interface) != 0) {
749 kind = MemberKind.Interface;
750 } else if (type.IsGenericParameter) {
751 kind = MemberKind.TypeParameter;
753 var base_type = type.BaseType;
754 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
755 kind = MemberKind.Class;
757 kind = DetermineKindFromBaseType (base_type);
758 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
759 mod |= Modifiers.SEALED;
763 if (kind == MemberKind.Class) {
764 if ((ma & TypeAttributes.Sealed) != 0) {
765 mod |= Modifiers.SEALED;
766 if ((ma & TypeAttributes.Abstract) != 0)
767 mod |= Modifiers.STATIC;
768 } else if ((ma & TypeAttributes.Abstract) != 0) {
769 mod |= Modifiers.ABSTRACT;
774 var definition = new ImportedTypeDefinition (type, this);
777 if (kind == MemberKind.Enum) {
778 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
779 BindingFlags.Instance |
780 BindingFlags.Public | BindingFlags.NonPublic;
782 var type_members = type.GetFields (underlying_member);
783 foreach (var type_member in type_members) {
784 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
789 kind = MemberKind.Class;
791 } else if (kind == MemberKind.TypeParameter) {
792 // Return as type_cache was updated
793 return CreateTypeParameter (type, declaringType);
794 } else if (type.IsGenericTypeDefinition) {
795 definition.TypeParameters = CreateGenericParameters (type, declaringType);
797 // Constraints are not loaded on demand and can reference this type
798 if (import_cache.TryGetValue (type, out spec))
801 } else if (compiled_types.TryGetValue (type, out pt)) {
803 // Same type was found in inside compiled types. It's
804 // either build-in type or forward referenced typed
805 // which point into just compiled assembly.
808 BuildinTypeSpec bts = pt as BuildinTypeSpec;
810 bts.SetDefinition (definition, type, mod);
814 spec = new TypeSpec (kind, declaringType, definition, type, mod);
816 import_cache.Add (type, spec);
819 // Two stage setup as the base type can be inflated declaring type or
820 // another nested type inside same declaring type which has not been
821 // loaded, therefore we can import a base type of nested types once
822 // the types have been imported
824 if (canImportBaseType)
825 ImportTypeBase (spec, type);
830 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
832 IAssemblyDefinition found;
833 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
835 // This can happen in dynamic context only
836 var def = new ImportedAssemblyDefinition (assembly, this);
837 assembly_2_definition.Add (assembly, def);
838 def.ReadAttributes ();
845 public void ImportTypeBase (MetaType type)
847 TypeSpec spec = import_cache[type];
849 ImportTypeBase (spec, type);
852 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
855 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
856 case GenericParameterAttributes.Covariant:
857 variance = Variance.Covariant;
859 case GenericParameterAttributes.Contravariant:
860 variance = Variance.Contravariant;
863 variance = Variance.None;
867 SpecialConstraint special = SpecialConstraint.None;
868 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
870 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
871 special |= SpecialConstraint.Struct;
872 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
873 special = SpecialConstraint.Constructor;
876 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
877 special |= SpecialConstraint.Class;
880 TypeParameterSpec spec;
881 var def = new ImportedTypeParameterDefinition (type, this);
882 if (type.DeclaringMethod != null)
883 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
885 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
887 // Add it now, so any constraint can reference it and get same instance
888 import_cache.Add (type, spec);
890 var constraints = type.GetGenericParameterConstraints ();
891 List<TypeSpec> tparams = null;
892 foreach (var ct in constraints) {
893 if (ct.IsGenericParameter) {
895 tparams = new List<TypeSpec> ();
897 tparams.Add (CreateType (ct));
901 if (!IsMissingType (ct) && ct.IsClass) {
902 spec.BaseType = CreateType (ct);
906 spec.AddInterface (CreateType (ct));
909 if (spec.BaseType == null)
910 spec.BaseType = TypeManager.object_type;
913 spec.TypeArguments = tparams.ToArray ();
919 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
920 // they can be assembly specific therefore we do check based on names only
922 public bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
924 if (attributesData.Count == 0)
928 foreach (var attr in attributesData) {
929 GetCustomAttributeTypeName (attr, out ns, out name);
930 if (name == attrName && ns == attrNamespace)
937 void ImportTypeBase (TypeSpec spec, MetaType type)
939 if (spec.Kind == MemberKind.Interface)
940 spec.BaseType = TypeManager.object_type;
941 else if (type.BaseType != null) {
943 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
944 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
946 base_type = CreateType (type.BaseType);
948 spec.BaseType = base_type;
953 ifaces = type.__GetDeclaredInterfaces ();
954 if (ifaces.Length != 0) {
955 foreach (var iface in ifaces)
956 spec.AddInterface (CreateType (iface));
959 if (spec.BaseType != null) {
960 var bifaces = spec.BaseType.Interfaces;
961 if (bifaces != null) {
962 foreach (var iface in bifaces)
963 spec.AddInterface (iface);
967 ifaces = type.GetInterfaces ();
969 if (ifaces.Length > 0) {
970 foreach (var iface in ifaces) {
971 spec.AddInterface (CreateType (iface));
977 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
979 Namespace ns = targetNamespace;
980 string prev_namespace = null;
981 foreach (var t in types) {
985 // Be careful not to trigger full parent type loading
986 if (t.MemberType == MemberTypes.NestedType)
989 if (t.Name[0] == '<')
992 var it = CreateType (t, null, new DynamicTypeReader (t), true);
996 if (prev_namespace != t.Namespace) {
997 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
998 prev_namespace = t.Namespace;
1003 if (it.IsStatic && hasExtensionTypes &&
1004 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1005 it.SetExtensionMethodContainer ();
1010 static Constant ImportParameterConstant (object value)
1013 // Get type of underlying value as int constant can be used for object
1014 // parameter type. This is not allowed in C# but other languages can do that
1016 switch (System.Type.GetTypeCode (value.GetType ())) {
1017 case TypeCode.Boolean:
1018 return new BoolConstant ((bool) value, Location.Null);
1020 return new ByteConstant ((byte) value, Location.Null);
1022 return new CharConstant ((char) value, Location.Null);
1023 case TypeCode.Decimal:
1024 return new DecimalConstant ((decimal) value, Location.Null);
1025 case TypeCode.Double:
1026 return new DoubleConstant ((double) value, Location.Null);
1027 case TypeCode.Int16:
1028 return new ShortConstant ((short) value, Location.Null);
1029 case TypeCode.Int32:
1030 return new IntConstant ((int) value, Location.Null);
1031 case TypeCode.Int64:
1032 return new LongConstant ((long) value, Location.Null);
1033 case TypeCode.SByte:
1034 return new SByteConstant ((sbyte) value, Location.Null);
1035 case TypeCode.Single:
1036 return new FloatConstant ((float) value, Location.Null);
1037 case TypeCode.String:
1038 return new StringConstant ((string) value, Location.Null);
1039 case TypeCode.UInt16:
1040 return new UShortConstant ((ushort) value, Location.Null);
1041 case TypeCode.UInt32:
1042 return new UIntConstant ((uint) value, Location.Null);
1043 case TypeCode.UInt64:
1044 return new ULongConstant ((ulong) value, Location.Null);
1047 throw new NotImplementedException (value.GetType ().ToString ());
1050 public TypeSpec ImportType (MetaType type)
1052 return ImportType (type, new DynamicTypeReader (type));
1055 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1057 if (type.HasElementType) {
1058 var element = type.GetElementType ();
1060 var spec = ImportType (element, dtype);
1063 return ArrayContainer.MakeType (spec, type.GetArrayRank ());
1065 return ReferenceContainer.MakeType (spec);
1067 return PointerContainer.MakeType (spec);
1069 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1072 return CreateType (type, dtype, true);
1075 static bool IsMissingType (MetaType type)
1078 return type.__IsMissing;
1085 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1086 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1087 // DecimalConstantAttribute metadata.
1089 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1091 if (attrs.Count == 0)
1095 foreach (var ca in attrs) {
1096 GetCustomAttributeTypeName (ca, out ns, out name);
1097 if (name != "DecimalConstantAttribute" || ns != CompilerServicesNamespace)
1100 var value = new decimal (
1101 (int) (uint) ca.ConstructorArguments[4].Value,
1102 (int) (uint) ca.ConstructorArguments[3].Value,
1103 (int) (uint) ca.ConstructorArguments[2].Value,
1104 (byte) ca.ConstructorArguments[1].Value != 0,
1105 (byte) ca.ConstructorArguments[0].Value);
1107 return new DecimalConstant (value, Location.Null).Resolve (null);
1113 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1116 var ma = mb.Attributes;
1117 switch (ma & MethodAttributes.MemberAccessMask) {
1118 case MethodAttributes.Public:
1119 mod = Modifiers.PUBLIC;
1121 case MethodAttributes.Assembly:
1122 mod = Modifiers.INTERNAL;
1124 case MethodAttributes.Family:
1125 mod = Modifiers.PROTECTED;
1127 case MethodAttributes.FamORAssem:
1128 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1131 mod = Modifiers.PRIVATE;
1135 if ((ma & MethodAttributes.Static) != 0) {
1136 mod |= Modifiers.STATIC;
1139 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1140 mod |= Modifiers.ABSTRACT;
1144 if ((ma & MethodAttributes.Final) != 0)
1145 mod |= Modifiers.SEALED;
1147 // It can be sealed and override
1148 if ((ma & MethodAttributes.Virtual) != 0) {
1149 if ((ma & MethodAttributes.NewSlot) != 0 || !declaringType.IsClass) {
1150 // No private virtual or sealed virtual
1151 if ((mod & (Modifiers.PRIVATE | Modifiers.SEALED)) == 0)
1152 mod |= Modifiers.VIRTUAL;
1154 mod |= Modifiers.OVERRIDE;
1162 abstract class ImportedDefinition : IMemberDefinition
1164 protected class AttributesBag
1166 public static readonly AttributesBag Default = new AttributesBag ();
1168 public AttributeUsageAttribute AttributeUsage;
1169 public ObsoleteAttribute Obsolete;
1170 public string[] Conditionals;
1171 public string DefaultIndexerName;
1172 public bool? CLSAttributeValue;
1173 public TypeSpec CoClass;
1175 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1177 AttributesBag bag = null;
1178 List<string> conditionals = null;
1180 // It should not throw any loading exception
1181 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1184 foreach (var a in attrs) {
1185 importer.GetCustomAttributeTypeName (a, out ns, out name);
1186 if (name == "ObsoleteAttribute") {
1191 bag = new AttributesBag ();
1193 var args = a.ConstructorArguments;
1195 if (args.Count == 1) {
1196 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1197 } else if (args.Count == 2) {
1198 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1200 bag.Obsolete = new ObsoleteAttribute ();
1206 if (name == "ConditionalAttribute") {
1207 if (ns != "System.Diagnostics")
1211 bag = new AttributesBag ();
1213 if (conditionals == null)
1214 conditionals = new List<string> (2);
1216 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1220 if (name == "CLSCompliantAttribute") {
1225 bag = new AttributesBag ();
1227 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1231 // Type only attributes
1232 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1233 if (name == "DefaultMemberAttribute") {
1234 if (ns != "System.Reflection")
1238 bag = new AttributesBag ();
1240 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1244 if (name == "AttributeUsageAttribute") {
1249 bag = new AttributesBag ();
1251 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1252 foreach (var named in a.NamedArguments) {
1253 if (named.MemberInfo.Name == "AllowMultiple")
1254 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1255 else if (named.MemberInfo.Name == "Inherited")
1256 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1261 // Interface only attribute
1262 if (name == "CoClassAttribute") {
1263 if (ns != "System.Runtime.InteropServices")
1267 bag = new AttributesBag ();
1269 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1278 if (conditionals != null)
1279 bag.Conditionals = conditionals.ToArray ();
1285 protected readonly MemberInfo provider;
1286 protected AttributesBag cattrs;
1287 protected readonly MetadataImporter importer;
1289 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1291 this.provider = provider;
1292 this.importer = importer;
1297 public bool IsImported {
1303 public virtual string Name {
1305 return provider.Name;
1311 public string[] ConditionalConditions ()
1316 return cattrs.Conditionals;
1319 public ObsoleteAttribute GetAttributeObsolete ()
1324 return cattrs.Obsolete;
1327 public bool? CLSAttributeValue {
1332 return cattrs.CLSAttributeValue;
1336 protected void ReadAttributes ()
1338 cattrs = AttributesBag.Read (provider, importer);
1341 public void SetIsAssigned ()
1343 // Unused for imported members
1346 public void SetIsUsed ()
1348 // Unused for imported members
1352 public class ImportedModuleDefinition
1354 readonly Module module;
1356 readonly MetadataImporter importer;
1358 public ImportedModuleDefinition (Module module, MetadataImporter importer)
1360 this.module = module;
1361 this.importer = importer;
1366 public bool IsCLSCompliant {
1368 return cls_compliant;
1372 public string Name {
1380 public void ReadAttributes ()
1382 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1385 foreach (var a in attrs) {
1386 importer.GetCustomAttributeTypeName (a, out ns, out name);
1387 if (name == "CLSCompliantAttribute") {
1391 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1398 // Reads assembly attributes which where attached to a special type because
1399 // module does have assembly manifest
1401 public List<Attribute> ReadAssemblyAttributes ()
1403 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1407 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1411 // TODO: implement, the idea is to fabricate specil Attribute class and
1412 // add it to OptAttributes before resolving the source code attributes
1413 // Need to build module location as well for correct error reporting
1415 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1416 //var attrs = new List<Attribute> (assembly_attributes.Count);
1417 //foreach (var a in assembly_attributes)
1419 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1420 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1422 // foreach (var carg in a.ConstructorArguments) {
1426 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1433 public class ImportedAssemblyDefinition : IAssemblyDefinition
1435 readonly Assembly assembly;
1436 readonly AssemblyName aname;
1437 readonly MetadataImporter importer;
1439 bool contains_extension_methods;
1441 List<AssemblyName> internals_visible_to;
1442 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1444 public ImportedAssemblyDefinition (Assembly assembly, MetadataImporter importer)
1446 this.assembly = assembly;
1447 this.aname = assembly.GetName ();
1448 this.importer = importer;
1453 public Assembly Assembly {
1459 public string FullName {
1461 return aname.FullName;
1465 public bool HasExtensionMethod {
1467 return contains_extension_methods;
1471 public bool HasStrongName {
1473 return aname.GetPublicKey ().Length != 0;
1477 public bool IsMissing {
1480 return assembly.__IsMissing;
1487 public bool IsCLSCompliant {
1489 return cls_compliant;
1493 public string Location {
1495 return assembly.Location;
1499 public string Name {
1507 public byte[] GetPublicKeyToken ()
1509 return aname.GetPublicKeyToken ();
1512 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1514 return internals_visible_to_cache [assembly];
1517 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1519 if (internals_visible_to == null)
1522 AssemblyName is_visible = null;
1523 if (internals_visible_to_cache == null) {
1524 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1526 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1527 return is_visible != null;
1530 var token = assembly.GetPublicKeyToken ();
1531 if (token != null && token.Length == 0)
1534 foreach (var internals in internals_visible_to) {
1535 if (internals.Name != assembly.Name)
1538 if (token == null && assembly is AssemblyDefinition) {
1539 is_visible = internals;
1543 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1546 is_visible = internals;
1550 internals_visible_to_cache.Add (assembly, is_visible);
1551 return is_visible != null;
1554 public void ReadAttributes ()
1557 if (assembly.__IsMissing)
1561 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1564 foreach (var a in attrs) {
1565 importer.GetCustomAttributeTypeName (a, out ns, out name);
1567 if (name == "CLSCompliantAttribute") {
1568 if (ns == "System") {
1570 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1577 if (name == "InternalsVisibleToAttribute") {
1578 if (ns != MetadataImporter.CompilerServicesNamespace)
1583 s = a.ConstructorArguments[0].Value as string;
1591 var an = new AssemblyName (s);
1592 if (internals_visible_to == null)
1593 internals_visible_to = new List<AssemblyName> ();
1595 internals_visible_to.Add (an);
1599 if (name == "ExtensionAttribute") {
1600 if (ns == MetadataImporter.CompilerServicesNamespace)
1601 contains_extension_methods = true;
1608 public override string ToString ()
1614 class ImportedMemberDefinition : ImportedDefinition
1616 readonly TypeSpec type;
1618 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1619 : base (member, importer)
1626 public TypeSpec MemberType {
1635 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1637 readonly AParametersCollection parameters;
1639 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1640 : base (provider, type, importer)
1642 this.parameters = parameters;
1645 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1646 : base (provider, type, importer)
1648 this.parameters = parameters;
1653 public AParametersCollection Parameters {
1662 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1664 readonly TypeParameterSpec[] tparams;
1666 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1667 : base (provider, type, parameters, importer)
1669 this.tparams = tparams;
1674 public TypeParameterSpec[] TypeParameters {
1680 public int TypeParametersCount {
1682 return tparams.Length;
1689 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1691 TypeParameterSpec[] tparams;
1694 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1695 : base (type, importer)
1701 public IAssemblyDefinition DeclaringAssembly {
1703 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1707 public override string Name {
1711 if (tparams != null) {
1712 int arity_start = name.IndexOf ('`');
1713 if (arity_start > 0)
1714 name = name.Substring (0, arity_start);
1722 public string Namespace {
1724 return ((MetaType) provider).Namespace;
1728 public int TypeParametersCount {
1730 return tparams == null ? 0 : tparams.Length;
1734 public TypeParameterSpec[] TypeParameters {
1745 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1748 // Report details about missing type and most likely cause of the problem.
1749 // csc reports 1683, 1684 as warnings but we report them only when used
1750 // or referenced from the user core in which case compilation error has to
1751 // be reported because compiler cannot continue anyway
1753 foreach (var t in types) {
1754 string name = t.GetSignatureForError ();
1756 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1757 ctx.Compiler.Report.Error (1683, loc,
1758 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1760 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1761 ctx.Compiler.Report.Error (12, loc,
1762 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1763 name, t.MemberDefinition.DeclaringAssembly.FullName);
1765 ctx.Compiler.Report.Error (1684, loc,
1766 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1767 name, t.MemberDefinition.DeclaringAssembly.FullName);
1772 public TypeSpec GetAttributeCoClass ()
1777 return cattrs.CoClass;
1780 public string GetAttributeDefaultMember ()
1785 return cattrs.DefaultIndexerName;
1788 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1793 return cattrs.AttributeUsage;
1796 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1798 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1799 return a == assembly || a.IsFriendAssemblyTo (assembly);
1802 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1805 // Not interested in members of nested private types unless the importer needs them
1807 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1808 cache = MemberCache.Empty;
1812 var loading_type = (MetaType) provider;
1813 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1814 BindingFlags.Static | BindingFlags.Instance |
1815 BindingFlags.Public | BindingFlags.NonPublic;
1817 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1818 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1819 MethodAttributes.Final;
1821 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1822 List<EventSpec> imported_events = null;
1823 EventSpec event_spec;
1824 MemberSpec imported;
1828 all = loading_type.GetMembers (all_members);
1829 } catch (Exception e) {
1830 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1831 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1834 if (cache == null) {
1835 cache = new MemberCache (all.Length);
1838 // Do the types first as they can be referenced by the members before
1839 // they are found or inflated
1841 foreach (var member in all) {
1842 if (member.MemberType != MemberTypes.NestedType)
1845 var t = (MetaType) member;
1847 // Ignore compiler generated types, mostly lambda containers
1848 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1851 imported = importer.CreateNestedType (t, declaringType);
1852 cache.AddMemberImported (imported);
1855 foreach (var member in all) {
1856 if (member.MemberType != MemberTypes.NestedType)
1859 var t = (MetaType) member;
1861 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1864 importer.ImportTypeBase (t);
1870 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1872 foreach (var member in all) {
1873 switch (member.MemberType) {
1874 case MemberTypes.Constructor:
1875 case MemberTypes.Method:
1876 MethodBase mb = (MethodBase) member;
1877 var attrs = mb.Attributes;
1879 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1880 if (importer.IgnorePrivateMembers)
1883 // Ignore explicitly implemented members
1884 if ((attrs & explicit_impl) == explicit_impl)
1887 // Ignore compiler generated methods
1888 if (importer.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1892 imported = importer.CreateMethod (mb, declaringType);
1893 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1894 if (possible_accessors == null)
1895 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1897 // There are no metadata rules for accessors, we have to consider any method as possible candidate
1898 possible_accessors.Add (mb, (MethodSpec) imported);
1902 case MemberTypes.Property:
1903 if (possible_accessors == null)
1906 var p = (PropertyInfo) member;
1908 // Links possible accessors with property
1910 MethodSpec get, set;
1911 m = p.GetGetMethod (true);
1912 if (m == null || !possible_accessors.TryGetValue (m, out get))
1915 m = p.GetSetMethod (true);
1916 if (m == null || !possible_accessors.TryGetValue (m, out set))
1919 // No accessors registered (e.g. explicit implementation)
1920 if (get == null && set == null)
1923 imported = importer.CreateProperty (p, declaringType, get, set);
1924 if (imported == null)
1928 case MemberTypes.Event:
1929 if (possible_accessors == null)
1932 var e = (EventInfo) member;
1934 // Links accessors with event
1936 MethodSpec add, remove;
1937 m = e.GetAddMethod (true);
1938 if (m == null || !possible_accessors.TryGetValue (m, out add))
1941 m = e.GetRemoveMethod (true);
1942 if (m == null || !possible_accessors.TryGetValue (m, out remove))
1945 // Both accessors are required
1946 if (add == null || remove == null)
1949 event_spec = importer.CreateEvent (e, declaringType, add, remove);
1950 if (!importer.IgnorePrivateMembers) {
1951 if (imported_events == null)
1952 imported_events = new List<EventSpec> ();
1954 imported_events.Add (event_spec);
1957 imported = event_spec;
1959 case MemberTypes.Field:
1960 var fi = (FieldInfo) member;
1962 imported = importer.CreateField (fi, declaringType);
1963 if (imported == null)
1967 // For dynamic binder event has to be fully restored to allow operations
1968 // within the type container to work correctly
1970 if (imported_events != null) {
1971 // The backing event field should be private but it may not
1973 for (i = 0; i < imported_events.Count; ++i) {
1974 var ev = imported_events[i];
1975 if (ev.Name == fi.Name) {
1976 ev.BackingField = (FieldSpec) imported;
1977 imported_events.RemoveAt (i);
1988 case MemberTypes.NestedType:
1989 // Already in the cache from the first pass
1992 throw new NotImplementedException (member.ToString ());
1995 cache.AddMemberImported (imported);
1999 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2000 foreach (var iface in declaringType.Interfaces) {
2001 cache.AddInterface (iface);
2007 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2009 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2010 : base (type, importer)
2016 public IAssemblyDefinition DeclaringAssembly {
2018 throw new NotImplementedException ();
2022 public string Namespace {
2028 public int TypeParametersCount {
2034 public TypeParameterSpec[] TypeParameters {
2042 public TypeSpec GetAttributeCoClass ()
2047 public string GetAttributeDefaultMember ()
2049 throw new NotSupportedException ();
2052 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2054 throw new NotSupportedException ();
2057 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2059 throw new NotImplementedException ();
2062 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2064 throw new NotImplementedException ();