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;
20 using MetaType = System.Type;
21 using System.Reflection;
26 public abstract class MetadataImporter
29 // Dynamic types reader with additional logic to reconstruct a dynamic
30 // type using DynamicAttribute values
32 struct DynamicTypeReader
34 static readonly bool[] single_attribute = { true };
39 // There is no common type for CustomAttributeData and we cannot
40 // use ICustomAttributeProvider
44 // A member provider which can be used to get CustomAttributeData
46 public DynamicTypeReader (object provider)
50 this.provider = provider;
54 // Returns true when object at local position has dynamic attribute flag
56 public bool IsDynamicObject (MetadataImporter importer)
59 ReadAttribute (importer);
61 return flags != null && Position < flags.Length && flags[Position];
65 // Returns true when DynamicAttribute exists
67 public bool HasDynamicAttribute (MetadataImporter importer)
70 ReadAttribute (importer);
75 void ReadAttribute (MetadataImporter importer)
77 IList<CustomAttributeData> cad;
78 if (provider is MemberInfo) {
79 cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
80 } else if (provider is ParameterInfo) {
81 cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
89 foreach (var ca in cad) {
90 importer.GetCustomAttributeTypeName (ca, out ns, out name);
91 if (name != "DynamicAttribute" && ns != CompilerServicesNamespace)
94 if (ca.ConstructorArguments.Count == 0) {
95 flags = single_attribute;
99 var arg_type = ca.ConstructorArguments[0].ArgumentType;
101 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
102 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
103 flags = new bool[carg.Count];
104 for (int i = 0; i < flags.Length; ++i) {
105 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
106 flags[i] = (bool) carg[i].Value;
118 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
119 protected readonly Dictionary<MetaType, BuildinTypeSpec> buildin_types;
120 readonly Dictionary<Assembly, ImportedAssemblyDefinition> assembly_2_definition;
122 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
124 protected MetadataImporter ()
126 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
127 buildin_types = new Dictionary<MetaType, BuildinTypeSpec> (40, ReferenceEquality<MetaType>.Default);
128 assembly_2_definition = new Dictionary<Assembly, ImportedAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
129 IgnorePrivateMembers = true;
134 public ICollection<ImportedAssemblyDefinition> Assemblies {
136 return assembly_2_definition.Values;
140 public bool IgnorePrivateMembers { get; set; }
144 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
145 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
146 public abstract void GetCustomAttributeTypeName (CustomAttributeData cad, out string typeNamespace, out string typeName);
148 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
151 var fa = fi.Attributes;
152 switch (fa & FieldAttributes.FieldAccessMask) {
153 case FieldAttributes.Public:
154 mod = Modifiers.PUBLIC;
156 case FieldAttributes.Assembly:
157 mod = Modifiers.INTERNAL;
159 case FieldAttributes.Family:
160 mod = Modifiers.PROTECTED;
162 case FieldAttributes.FamORAssem:
163 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
166 // Ignore private fields (even for error reporting) to not require extra dependencies
167 if (IgnorePrivateMembers || HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
170 mod = Modifiers.PRIVATE;
177 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
178 } catch (Exception e) {
179 // TODO: I should construct fake TypeSpec based on TypeRef signature
180 // but there is no way to do it with System.Reflection
181 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
182 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
185 var definition = new ImportedMemberDefinition (fi, field_type, this);
187 if ((fa & FieldAttributes.Literal) != 0) {
188 var c = Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
189 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
192 if ((fa & FieldAttributes.InitOnly) != 0) {
193 if (field_type == TypeManager.decimal_type) {
194 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
196 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
199 mod |= Modifiers.READONLY;
201 var req_mod = fi.GetRequiredCustomModifiers ();
202 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
203 mod |= Modifiers.VOLATILE;
206 if ((fa & FieldAttributes.Static) != 0) {
207 mod |= Modifiers.STATIC;
209 // Fixed buffers cannot be static
210 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
211 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
213 // TODO: Sanity check on field_type (only few type are allowed)
214 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
215 return new FixedFieldSpec (declaringType, definition, fi, element_field, mod);
219 return new FieldSpec (declaringType, definition, field_type, fi, mod);
222 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
224 add.IsAccessor = true;
225 remove.IsAccessor = true;
227 if (add.Modifiers != remove.Modifiers)
228 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
230 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
231 var definition = new ImportedMemberDefinition (ei, event_type, this);
232 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
235 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
237 var tparams = type.GetGenericArguments ();
239 int parent_owned_count;
241 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
244 // System.Reflection duplicates parent type parameters for each
245 // nested type with slightly modified properties (eg. different owner)
246 // This just makes things more complicated (think of cloned constraints)
247 // therefore we remap any nested type owned by parent using `type_cache'
248 // to the single TypeParameterSpec
250 if (declaringType != null && parent_owned_count > 0) {
252 while (read_count != parent_owned_count) {
253 var tparams_count = declaringType.Arity;
254 if (tparams_count != 0) {
255 var parent_tp = declaringType.MemberDefinition.TypeParameters;
256 read_count += tparams_count;
257 for (int i = 0; i < tparams_count; i++) {
258 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
262 declaringType = declaringType.DeclaringType;
266 parent_owned_count = 0;
269 if (tparams.Length - parent_owned_count == 0)
272 return CreateGenericParameters (parent_owned_count, tparams);
275 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
277 var tspec = new TypeParameterSpec[tparams.Length - first];
278 for (int pos = first; pos < tparams.Length; ++pos) {
279 var type = tparams[pos];
280 int index = pos - first;
282 tspec [index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
288 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
292 var tspec = new TypeSpec [tparams.Length - first];
293 for (int pos = first; pos < tparams.Length; ++pos) {
294 var type = tparams[pos];
295 int index = pos - first;
298 if (type.HasElementType) {
299 var element = type.GetElementType ();
301 spec = ImportType (element, dtype);
304 throw new NotImplementedException ("Unknown element type " + type.ToString ());
307 spec = ArrayContainer.MakeType (spec, type.GetArrayRank ());
309 spec = CreateType (type, dtype, true);
312 // We treat nested generic types as inflated internally where
313 // reflection uses type definition
316 // IFoo<A<T>> foo; // A<T> is definition in this case
319 // TODO: Is full logic from CreateType needed here as well?
321 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
322 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
323 spec = spec.MakeGenericType (targs);
334 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
336 Modifiers mod = ReadMethodModifiers (mb, declaringType);
337 TypeParameterSpec[] tparams;
339 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
341 if (mb.IsGenericMethod) {
342 if (!mb.IsGenericMethodDefinition)
343 throw new NotSupportedException ("assert");
345 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
352 if (mb.MemberType == MemberTypes.Constructor) {
353 kind = MemberKind.Constructor;
354 returnType = TypeManager.void_type;
357 // Detect operators and destructors
359 string name = mb.Name;
360 kind = MemberKind.Method;
361 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
362 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
363 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
364 var op_type = Operator.GetType (name);
365 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
366 kind = MemberKind.Operator;
369 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
370 kind = MemberKind.Destructor;
371 if (declaringType == TypeManager.object_type) {
372 mod &= ~Modifiers.OVERRIDE;
373 mod |= Modifiers.VIRTUAL;
378 var mi = (MethodInfo) mb;
379 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
381 // Cannot set to OVERRIDE without full hierarchy checks
382 // this flag indicates that the method could be override
383 // but further validation is needed
384 if ((mod & Modifiers.OVERRIDE) != 0 && kind == MemberKind.Method && declaringType.BaseType != null) {
385 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
386 var candidate = MemberCache.FindMember (declaringType.BaseType, filter, BindingRestriction.None);
389 // For imported class method do additional validation to be sure that metadata
390 // override flag was correct
392 // Difference between protected internal and protected is ok
394 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
395 if (candidate == null || (candidate.Modifiers & conflict_mask) != (mod & conflict_mask) || candidate.IsStatic) {
396 mod &= ~Modifiers.OVERRIDE;
401 IMemberDefinition definition;
402 if (tparams != null) {
403 definition = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
405 definition = new ImportedParameterMemberDefinition (mb, returnType, parameters, this);
408 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, mb, parameters, mod);
416 // Imports System.Reflection parameters
418 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
420 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
422 if (pi.Length == 0 && varargs == 0)
423 return ParametersCompiled.EmptyReadOnlyParameters;
425 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
426 IParameterData[] par = new IParameterData[pi.Length + varargs];
427 bool is_params = false;
428 for (int i = 0; i < pi.Length; i++) {
429 ParameterInfo p = pi[i];
430 Parameter.Modifier mod = 0;
431 Expression default_value = null;
432 if (p.ParameterType.IsByRef) {
433 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
434 mod = Parameter.Modifier.OUT;
436 mod = Parameter.Modifier.REF;
439 // Strip reference wrapping
441 var el = p.ParameterType.GetElementType ();
442 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
443 } else if (i == 0 && method.IsStatic && parent.IsStatic && parent.MemberDefinition.DeclaringAssembly.HasExtensionMethod &&
444 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
445 mod = Parameter.Modifier.This;
446 types[i] = ImportType (p.ParameterType);
448 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
450 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
451 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
452 mod = Parameter.Modifier.PARAMS;
457 if (!is_params && p.IsOptional) {
458 object value = p.RawDefaultValue;
459 var ptype = types[i];
460 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeManager.IsReferenceType (ptype))) {
462 default_value = Constant.CreateConstant (null, ptype, null, Location.Null);
464 default_value = ImportParameterConstant (value).Resolve (null);
467 default_value = new EnumConstant ((Constant) default_value, ptype).Resolve (null);
470 } else if (value == Missing.Value) {
471 default_value = EmptyExpression.MissingValue;
472 } else if (value == null) {
473 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
474 } else if (ptype == TypeManager.decimal_type) {
475 default_value = ImportParameterConstant (value).Resolve (null);
480 par[i] = new ParameterData (p.Name, mod, default_value);
484 par[par.Length - 1] = new ArglistParameter (Location.Null);
485 types[types.Length - 1] = InternalType.Arglist;
488 return method != null ?
489 new ParametersImported (par, types, varargs != 0, is_params) :
490 new ParametersImported (par, types, is_params);
494 // Returns null when the property is not valid C# property
496 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
499 AParametersCollection param = null;
500 TypeSpec type = null;
503 param = get.Parameters;
504 type = get.ReturnType;
507 bool is_valid_property = true;
509 if (set.ReturnType != TypeManager.void_type)
510 is_valid_property = false;
512 var set_param_count = set.Parameters.Count - 1;
514 if (set_param_count < 0) {
516 is_valid_property = false;
519 var set_type = set.Parameters.Types[set_param_count];
522 AParametersCollection set_based_param;
524 if (set_param_count == 0) {
525 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
528 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
530 var data = new IParameterData[set_param_count];
531 var types = new TypeSpec[set_param_count];
532 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
533 Array.Copy (set.Parameters.Types, types, set_param_count);
534 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
538 param = set_based_param;
541 if (set_param_count != get.Parameters.Count)
542 is_valid_property = false;
544 if (get.ReturnType != set_type)
545 is_valid_property = false;
547 // Possible custom accessor modifiers
548 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
549 var get_acc = mod & Modifiers.AccessibilityMask;
550 if (get_acc != Modifiers.PUBLIC) {
551 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
552 // If the accessor modifiers are not same, do extra restriction checks
553 if (get_acc != set_acc) {
554 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
555 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
556 if (get_restr && set_restr) {
557 is_valid_property = false; // Neither is more restrictive
561 mod &= ~Modifiers.AccessibilityMask;
570 PropertySpec spec = null;
571 if (!param.IsEmpty) {
572 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
573 if (index_name == null) {
574 is_valid_property = false;
578 is_valid_property = false;
579 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
580 is_valid_property = false;
584 is_valid_property = false;
585 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
586 is_valid_property = false;
590 if (is_valid_property)
591 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
595 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
597 if (!is_valid_property) {
598 spec.IsNotRealProperty = true;
610 public TypeSpec CreateType (MetaType type)
612 return CreateType (type, new DynamicTypeReader (), true);
615 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
617 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
620 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
622 TypeSpec declaring_type;
623 if (type.IsNested && !type.IsGenericParameter)
624 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
626 declaring_type = null;
628 return CreateType (type, declaring_type, dtype, canImportBaseType);
631 TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
634 if (import_cache.TryGetValue (type, out spec)) {
635 if (spec == TypeManager.object_type) {
636 if (dtype.IsDynamicObject (this))
637 return InternalType.Dynamic;
642 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
645 if (!dtype.HasDynamicAttribute (this))
648 // We've found same object in the cache but this one has a dynamic custom attribute
649 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
650 // Do type resolve process again in that case
652 // TODO: Handle cases where they still unify
655 if (IsMissingType (type)) {
656 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
657 spec.MemberCache = MemberCache.Empty;
658 import_cache.Add (type, spec);
662 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
663 var type_def = type.GetGenericTypeDefinition ();
664 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
665 if (declaringType == null) {
666 // Simple case, no nesting
667 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
668 spec = spec.MakeGenericType (targs);
671 // Nested type case, converting .NET types like
672 // A`1.B`1.C`1<int, long, string> to typespec like
673 // A<int>.B<long>.C<string>
675 var nested_hierarchy = new List<TypeSpec> ();
676 while (declaringType.IsNested) {
677 nested_hierarchy.Add (declaringType);
678 declaringType = declaringType.DeclaringType;
682 if (declaringType.Arity > 0) {
683 spec = declaringType.MakeGenericType (targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
684 targs_pos = spec.Arity;
686 spec = declaringType;
689 for (int i = nested_hierarchy.Count; i != 0; --i) {
690 var t = nested_hierarchy [i - 1];
691 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
693 spec = spec.MakeGenericType (targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
694 targs_pos += t.Arity;
698 string name = type.Name;
699 int index = name.IndexOf ('`');
701 name = name.Substring (0, index);
703 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
704 if (spec.Arity > 0) {
705 spec = spec.MakeGenericType (targs.Skip (targs_pos).ToArray ());
709 // Don't add generic type with dynamic arguments, they can interfere with same type
710 // using object type arguments
711 if (!spec.HasDynamicElement) {
713 // Add to reading cache to speed up reading
714 if (!import_cache.ContainsKey (type))
715 import_cache.Add (type, spec);
724 var ma = type.Attributes;
725 switch (ma & TypeAttributes.VisibilityMask) {
726 case TypeAttributes.Public:
727 case TypeAttributes.NestedPublic:
728 mod = Modifiers.PUBLIC;
730 case TypeAttributes.NestedPrivate:
731 mod = Modifiers.PRIVATE;
733 case TypeAttributes.NestedFamily:
734 mod = Modifiers.PROTECTED;
736 case TypeAttributes.NestedFamORAssem:
737 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
740 mod = Modifiers.INTERNAL;
744 if ((ma & TypeAttributes.Interface) != 0) {
745 kind = MemberKind.Interface;
746 } else if (type.IsGenericParameter) {
747 kind = MemberKind.TypeParameter;
749 var base_type = type.BaseType;
750 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
751 kind = MemberKind.Class;
753 kind = DetermineKindFromBaseType (base_type);
754 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
755 mod |= Modifiers.SEALED;
759 if (kind == MemberKind.Class) {
760 if ((ma & TypeAttributes.Sealed) != 0) {
761 mod |= Modifiers.SEALED;
762 if ((ma & TypeAttributes.Abstract) != 0)
763 mod |= Modifiers.STATIC;
764 } else if ((ma & TypeAttributes.Abstract) != 0) {
765 mod |= Modifiers.ABSTRACT;
770 var definition = new ImportedTypeDefinition (type, this);
773 if (kind == MemberKind.Enum) {
774 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
775 BindingFlags.Instance |
776 BindingFlags.Public | BindingFlags.NonPublic;
778 var type_members = type.GetFields (underlying_member);
779 foreach (var type_member in type_members) {
780 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
785 kind = MemberKind.Class;
787 } else if (kind == MemberKind.TypeParameter) {
788 // Return as type_cache was updated
789 return CreateTypeParameter (type, declaringType);
790 } else if (type.IsGenericTypeDefinition) {
791 definition.TypeParameters = CreateGenericParameters (type, declaringType);
793 // Constraints are not loaded on demand and can reference this type
794 if (import_cache.TryGetValue (type, out spec))
797 } else if (buildin_types.TryGetValue (type, out pt)) {
799 pt.SetDefinition (definition, type, mod);
803 spec = new TypeSpec (kind, declaringType, definition, type, mod);
805 import_cache.Add (type, spec);
808 // Two stage setup as the base type can be inflated declaring type or
809 // another nested type inside same declaring type which has not been
810 // loaded, therefore we can import a base type of nested types once
811 // the types have been imported
813 if (canImportBaseType)
814 ImportTypeBase (spec, type);
819 public ImportedAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
821 ImportedAssemblyDefinition def;
822 if (!assembly_2_definition.TryGetValue (assembly, out def)) {
824 // This can happen in dynamic context only
825 def = new ImportedAssemblyDefinition (assembly, this);
826 assembly_2_definition.Add (assembly, def);
827 def.ReadAttributes ();
833 public void ImportTypeBase (MetaType type)
835 TypeSpec spec = import_cache[type];
837 ImportTypeBase (spec, type);
840 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
843 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
844 case GenericParameterAttributes.Covariant:
845 variance = Variance.Covariant;
847 case GenericParameterAttributes.Contravariant:
848 variance = Variance.Contravariant;
851 variance = Variance.None;
855 SpecialConstraint special = SpecialConstraint.None;
856 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
858 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
859 special |= SpecialConstraint.Struct;
860 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
861 special = SpecialConstraint.Constructor;
864 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
865 special |= SpecialConstraint.Class;
868 TypeParameterSpec spec;
869 var def = new ImportedTypeParameterDefinition (type, this);
870 if (type.DeclaringMethod != null)
871 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
873 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
875 // Add it now, so any constraint can reference it and get same instance
876 import_cache.Add (type, spec);
878 var constraints = type.GetGenericParameterConstraints ();
879 List<TypeSpec> tparams = null;
880 foreach (var ct in constraints) {
881 if (ct.IsGenericParameter) {
883 tparams = new List<TypeSpec> ();
885 tparams.Add (CreateType (ct));
889 if (!IsMissingType (ct) && ct.IsClass) {
890 spec.BaseType = CreateType (ct);
894 spec.AddInterface (CreateType (ct));
897 if (spec.BaseType == null)
898 spec.BaseType = TypeManager.object_type;
901 spec.TypeArguments = tparams.ToArray ();
907 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
908 // they can be assembly specific therefore we do check based on names only
910 public bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
912 if (attributesData.Count == 0)
916 foreach (var attr in attributesData) {
917 GetCustomAttributeTypeName (attr, out ns, out name);
918 if (name == attrName && ns == attrNamespace)
925 void ImportTypeBase (TypeSpec spec, MetaType type)
927 if (spec.Kind == MemberKind.Interface)
928 spec.BaseType = TypeManager.object_type;
929 else if (type.BaseType != null) {
931 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
932 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
934 base_type = CreateType (type.BaseType);
936 spec.BaseType = base_type;
941 ifaces = type.__GetDeclaredInterfaces ();
942 while (ifaces.Length != 0) {
943 foreach (var iface in ifaces)
944 spec.AddInterface (CreateType (iface));
946 type = type.BaseType;
947 if (type == null || type.__ContainsMissingType)
950 ifaces = type.__GetDeclaredInterfaces ();
953 ifaces = type.GetInterfaces ();
955 if (ifaces.Length > 0) {
956 foreach (var iface in ifaces) {
957 spec.AddInterface (CreateType (iface));
963 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
965 Namespace ns = targetNamespace;
966 string prev_namespace = null;
967 foreach (var t in types) {
971 // Be careful not to trigger full parent type loading
972 if (t.MemberType == MemberTypes.NestedType)
975 if (t.Name[0] == '<')
978 var it = CreateType (t, null, new DynamicTypeReader (t), true);
982 if (prev_namespace != t.Namespace) {
983 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
984 prev_namespace = t.Namespace;
989 if (it.IsStatic && hasExtensionTypes &&
990 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
991 it.SetExtensionMethodContainer ();
996 static Constant ImportParameterConstant (object value)
999 // Get type of underlying value as int constant can be used for object
1000 // parameter type. This is not allowed in C# but other languages can do that
1002 switch (System.Type.GetTypeCode (value.GetType ())) {
1003 case TypeCode.Boolean:
1004 return new BoolConstant ((bool) value, Location.Null);
1006 return new ByteConstant ((byte) value, Location.Null);
1008 return new CharConstant ((char) value, Location.Null);
1009 case TypeCode.Decimal:
1010 return new DecimalConstant ((decimal) value, Location.Null);
1011 case TypeCode.Double:
1012 return new DoubleConstant ((double) value, Location.Null);
1013 case TypeCode.Int16:
1014 return new ShortConstant ((short) value, Location.Null);
1015 case TypeCode.Int32:
1016 return new IntConstant ((int) value, Location.Null);
1017 case TypeCode.Int64:
1018 return new LongConstant ((long) value, Location.Null);
1019 case TypeCode.SByte:
1020 return new SByteConstant ((sbyte) value, Location.Null);
1021 case TypeCode.Single:
1022 return new FloatConstant ((float) value, Location.Null);
1023 case TypeCode.String:
1024 return new StringConstant ((string) value, Location.Null);
1025 case TypeCode.UInt16:
1026 return new UShortConstant ((ushort) value, Location.Null);
1027 case TypeCode.UInt32:
1028 return new UIntConstant ((uint) value, Location.Null);
1029 case TypeCode.UInt64:
1030 return new ULongConstant ((ulong) value, Location.Null);
1033 throw new NotImplementedException (value.GetType ().ToString ());
1036 public TypeSpec ImportType (MetaType type)
1038 return ImportType (type, new DynamicTypeReader (type));
1041 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1043 if (type.HasElementType) {
1044 var element = type.GetElementType ();
1046 var spec = ImportType (element, dtype);
1049 return ArrayContainer.MakeType (spec, type.GetArrayRank ());
1051 return ReferenceContainer.MakeType (spec);
1053 return PointerContainer.MakeType (spec);
1055 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1058 return CreateType (type, dtype, true);
1061 static bool IsMissingType (MetaType type)
1064 return type.__IsMissing;
1071 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1072 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1073 // DecimalConstantAttribute metadata.
1075 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1077 if (attrs.Count == 0)
1081 foreach (var ca in attrs) {
1082 GetCustomAttributeTypeName (ca, out ns, out name);
1083 if (name != "DecimalConstantAttribute" || ns != CompilerServicesNamespace)
1086 var value = new decimal (
1087 (int) (uint) ca.ConstructorArguments[4].Value,
1088 (int) (uint) ca.ConstructorArguments[3].Value,
1089 (int) (uint) ca.ConstructorArguments[2].Value,
1090 (byte) ca.ConstructorArguments[1].Value != 0,
1091 (byte) ca.ConstructorArguments[0].Value);
1093 return new DecimalConstant (value, Location.Null).Resolve (null);
1099 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1102 var ma = mb.Attributes;
1103 switch (ma & MethodAttributes.MemberAccessMask) {
1104 case MethodAttributes.Public:
1105 mod = Modifiers.PUBLIC;
1107 case MethodAttributes.Assembly:
1108 mod = Modifiers.INTERNAL;
1110 case MethodAttributes.Family:
1111 mod = Modifiers.PROTECTED;
1113 case MethodAttributes.FamORAssem:
1114 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1117 mod = Modifiers.PRIVATE;
1121 if ((ma & MethodAttributes.Static) != 0) {
1122 mod |= Modifiers.STATIC;
1125 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1126 mod |= Modifiers.ABSTRACT;
1130 if ((ma & MethodAttributes.Final) != 0)
1131 mod |= Modifiers.SEALED;
1133 // It can be sealed and override
1134 if ((ma & MethodAttributes.Virtual) != 0) {
1135 if ((ma & MethodAttributes.NewSlot) != 0 || !declaringType.IsClass) {
1136 // No private virtual or sealed virtual
1137 if ((mod & (Modifiers.PRIVATE | Modifiers.SEALED)) == 0)
1138 mod |= Modifiers.VIRTUAL;
1140 mod |= Modifiers.OVERRIDE;
1148 abstract class ImportedDefinition : IMemberDefinition
1150 protected class AttributesBag
1152 public static readonly AttributesBag Default = new AttributesBag ();
1154 public AttributeUsageAttribute AttributeUsage;
1155 public ObsoleteAttribute Obsolete;
1156 public string[] Conditionals;
1157 public string DefaultIndexerName;
1158 public bool IsNotCLSCompliant;
1159 public TypeSpec CoClass;
1161 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1163 AttributesBag bag = null;
1164 List<string> conditionals = null;
1166 // It should not throw any loading exception
1167 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1170 foreach (var a in attrs) {
1171 importer.GetCustomAttributeTypeName (a, out ns, out name);
1172 if (name == "ObsoleteAttribute") {
1177 bag = new AttributesBag ();
1179 var args = a.ConstructorArguments;
1181 if (args.Count == 1) {
1182 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1183 } else if (args.Count == 2) {
1184 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1186 bag.Obsolete = new ObsoleteAttribute ();
1192 if (name == "ConditionalAttribute") {
1193 if (ns != "System.Diagnostics")
1197 bag = new AttributesBag ();
1199 if (conditionals == null)
1200 conditionals = new List<string> (2);
1202 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1206 if (name == "CLSCompliantAttribute") {
1211 bag = new AttributesBag ();
1213 bag.IsNotCLSCompliant = !(bool) a.ConstructorArguments[0].Value;
1217 // Type only attributes
1218 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1219 if (name == "DefaultMemberAttribute") {
1220 if (ns != "System.Reflection")
1224 bag = new AttributesBag ();
1226 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1230 if (name == "AttributeUsageAttribute") {
1235 bag = new AttributesBag ();
1237 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1238 foreach (var named in a.NamedArguments) {
1239 if (named.MemberInfo.Name == "AllowMultiple")
1240 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1241 else if (named.MemberInfo.Name == "Inherited")
1242 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1247 // Interface only attribute
1248 if (name == "CoClassAttribute") {
1249 if (ns != "System.Runtime.InteropServices")
1253 bag = new AttributesBag ();
1255 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1264 if (conditionals != null)
1265 bag.Conditionals = conditionals.ToArray ();
1271 protected readonly MemberInfo provider;
1272 protected AttributesBag cattrs;
1273 protected readonly MetadataImporter importer;
1275 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1277 this.provider = provider;
1278 this.importer = importer;
1283 public bool IsImported {
1289 public virtual string Name {
1291 return provider.Name;
1297 public string[] ConditionalConditions ()
1302 return cattrs.Conditionals;
1305 public ObsoleteAttribute GetAttributeObsolete ()
1310 return cattrs.Obsolete;
1313 public bool IsNotCLSCompliant ()
1318 return cattrs.IsNotCLSCompliant;
1321 protected void ReadAttributes ()
1323 cattrs = AttributesBag.Read (provider, importer);
1326 public void SetIsAssigned ()
1328 // Unused for imported members
1331 public void SetIsUsed ()
1333 // Unused for imported members
1337 public class ImportedModuleDefinition
1339 readonly Module module;
1341 readonly MetadataImporter importer;
1343 public ImportedModuleDefinition (Module module, MetadataImporter importer)
1345 this.module = module;
1346 this.importer = importer;
1351 public bool IsCLSCompliant {
1353 return cls_compliant;
1357 public string Name {
1365 public void ReadAttributes ()
1367 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1370 foreach (var a in attrs) {
1371 importer.GetCustomAttributeTypeName (a, out ns, out name);
1372 if (name == "CLSCompliantAttribute") {
1376 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1383 // Reads assembly attributes which where attached to a special type because
1384 // module does have assembly manifest
1386 public List<Attribute> ReadAssemblyAttributes ()
1388 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1392 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1396 // TODO: implement, the idea is to fabricate specil Attribute class and
1397 // add it to OptAttributes before resolving the source code attributes
1398 // Need to build module location as well for correct error reporting
1400 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1401 //var attrs = new List<Attribute> (assembly_attributes.Count);
1402 //foreach (var a in assembly_attributes)
1404 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1405 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1407 // foreach (var carg in a.ConstructorArguments) {
1411 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1418 public class ImportedAssemblyDefinition : IAssemblyDefinition
1420 readonly Assembly assembly;
1421 readonly AssemblyName aname;
1422 readonly MetadataImporter importer;
1424 bool contains_extension_methods;
1426 List<AssemblyName> internals_visible_to;
1427 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1429 public ImportedAssemblyDefinition (Assembly assembly, MetadataImporter importer)
1431 this.assembly = assembly;
1432 this.aname = assembly.GetName ();
1433 this.importer = importer;
1438 public Assembly Assembly {
1444 public string FullName {
1446 return aname.FullName;
1450 public bool HasExtensionMethod {
1452 return contains_extension_methods;
1456 public bool HasStrongName {
1458 return aname.GetPublicKey ().Length != 0;
1462 public bool IsCLSCompliant {
1464 return cls_compliant;
1468 public string Location {
1470 return assembly.Location;
1474 public string Name {
1482 public byte[] GetPublicKeyToken ()
1484 return aname.GetPublicKeyToken ();
1487 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1489 return internals_visible_to_cache [assembly];
1492 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1494 if (internals_visible_to == null)
1497 AssemblyName is_visible = null;
1498 if (internals_visible_to_cache == null) {
1499 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1501 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1502 return is_visible != null;
1505 var token = assembly.GetPublicKeyToken ();
1506 if (token != null && token.Length == 0)
1509 foreach (var internals in internals_visible_to) {
1510 if (internals.Name != assembly.Name)
1513 if (token == null && assembly is AssemblyDefinition) {
1514 is_visible = internals;
1518 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1521 is_visible = internals;
1525 internals_visible_to_cache.Add (assembly, is_visible);
1526 return is_visible != null;
1529 public void ReadAttributes ()
1532 if (assembly.__IsMissing)
1536 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1539 foreach (var a in attrs) {
1540 importer.GetCustomAttributeTypeName (a, out ns, out name);
1542 if (name == "CLSCompliantAttribute") {
1544 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1548 if (name == "InternalsVisibleToAttribute") {
1549 if (ns != MetadataImporter.CompilerServicesNamespace)
1552 string s = a.ConstructorArguments[0].Value as string;
1556 var an = new AssemblyName (s);
1557 if (internals_visible_to == null)
1558 internals_visible_to = new List<AssemblyName> ();
1560 internals_visible_to.Add (an);
1564 if (name == "ExtensionAttribute") {
1565 if (ns == MetadataImporter.CompilerServicesNamespace)
1566 contains_extension_methods = true;
1573 public override string ToString ()
1579 class ImportedMemberDefinition : ImportedDefinition
1581 readonly TypeSpec type;
1583 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1584 : base (member, importer)
1591 public TypeSpec MemberType {
1600 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1602 readonly AParametersCollection parameters;
1604 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1605 : base (provider, type, importer)
1607 this.parameters = parameters;
1610 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1611 : base (provider, type, importer)
1613 this.parameters = parameters;
1618 public AParametersCollection Parameters {
1627 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1629 readonly TypeParameterSpec[] tparams;
1631 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1632 : base (provider, type, parameters, importer)
1634 this.tparams = tparams;
1639 public TypeParameterSpec[] TypeParameters {
1645 public int TypeParametersCount {
1647 return tparams.Length;
1654 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1656 TypeParameterSpec[] tparams;
1659 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1660 : base (type, importer)
1666 public IAssemblyDefinition DeclaringAssembly {
1668 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1672 public override string Name {
1676 if (tparams != null) {
1677 int arity_start = name.IndexOf ('`');
1678 if (arity_start > 0)
1679 name = name.Substring (0, arity_start);
1687 public string Namespace {
1689 return ((MetaType) provider).Namespace;
1693 public int TypeParametersCount {
1695 return tparams == null ? 0 : tparams.Length;
1699 public TypeParameterSpec[] TypeParameters {
1710 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1712 foreach (var t in types) {
1713 string name = t.GetSignatureForError ();
1715 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1716 ctx.Compiler.Report.Warning (1683, 1, loc,
1717 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1721 ctx.Compiler.Report.Error (12, loc,
1722 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1723 name, t.MemberDefinition.DeclaringAssembly.FullName);
1727 public TypeSpec GetAttributeCoClass ()
1732 return cattrs.CoClass;
1735 public string GetAttributeDefaultMember ()
1740 return cattrs.DefaultIndexerName;
1743 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1748 return cattrs.AttributeUsage;
1751 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1753 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1754 return a == assembly || a.IsFriendAssemblyTo (assembly);
1757 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1760 // Not interested in members of nested private types unless the importer needs them
1762 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1763 cache = MemberCache.Empty;
1767 var loading_type = (MetaType) provider;
1768 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1769 BindingFlags.Static | BindingFlags.Instance |
1770 BindingFlags.Public | BindingFlags.NonPublic;
1772 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1773 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1774 MethodAttributes.Final;
1776 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1777 List<EventSpec> imported_events = null;
1778 EventSpec event_spec;
1779 MemberSpec imported;
1783 all = loading_type.GetMembers (all_members);
1784 } catch (Exception e) {
1785 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1786 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1789 if (cache == null) {
1790 cache = new MemberCache (all.Length);
1793 // Do the types first as they can be referenced by the members before
1794 // they are found or inflated
1796 foreach (var member in all) {
1797 if (member.MemberType != MemberTypes.NestedType)
1800 var t = (MetaType) member;
1802 // Ignore compiler generated types, mostly lambda containers
1803 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate)
1806 imported = importer.CreateNestedType (t, declaringType);
1807 cache.AddMember (imported);
1810 foreach (var member in all) {
1811 if (member.MemberType != MemberTypes.NestedType)
1814 var t = (MetaType) member;
1816 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate)
1819 importer.ImportTypeBase (t);
1825 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1827 foreach (var member in all) {
1828 switch (member.MemberType) {
1829 case MemberTypes.Constructor:
1830 case MemberTypes.Method:
1831 MethodBase mb = (MethodBase) member;
1832 var attrs = mb.Attributes;
1834 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1835 if (importer.IgnorePrivateMembers)
1838 // Ignore explicitly implemented members
1839 if ((attrs & explicit_impl) == explicit_impl)
1842 // Ignore compiler generated methods
1843 if (importer.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1847 imported = importer.CreateMethod (mb, declaringType);
1848 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1849 if (possible_accessors == null)
1850 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1852 // There are no metadata rules for accessors, we have to consider any method as possible candidate
1853 possible_accessors.Add (mb, (MethodSpec) imported);
1857 case MemberTypes.Property:
1858 if (possible_accessors == null)
1861 var p = (PropertyInfo) member;
1863 // Links possible accessors with property
1865 MethodSpec get, set;
1866 m = p.GetGetMethod (true);
1867 if (m == null || !possible_accessors.TryGetValue (m, out get))
1870 m = p.GetSetMethod (true);
1871 if (m == null || !possible_accessors.TryGetValue (m, out set))
1874 // No accessors registered (e.g. explicit implementation)
1875 if (get == null && set == null)
1878 imported = importer.CreateProperty (p, declaringType, get, set);
1879 if (imported == null)
1883 case MemberTypes.Event:
1884 if (possible_accessors == null)
1887 var e = (EventInfo) member;
1889 // Links accessors with event
1891 MethodSpec add, remove;
1892 m = e.GetAddMethod (true);
1893 if (m == null || !possible_accessors.TryGetValue (m, out add))
1896 m = e.GetRemoveMethod (true);
1897 if (m == null || !possible_accessors.TryGetValue (m, out remove))
1900 // Both accessors are required
1901 if (add == null || remove == null)
1904 event_spec = importer.CreateEvent (e, declaringType, add, remove);
1905 if (!importer.IgnorePrivateMembers) {
1906 if (imported_events == null)
1907 imported_events = new List<EventSpec> ();
1909 imported_events.Add (event_spec);
1912 imported = event_spec;
1914 case MemberTypes.Field:
1915 var fi = (FieldInfo) member;
1917 imported = importer.CreateField (fi, declaringType);
1918 if (imported == null)
1922 // For dynamic binder event has to be fully restored to allow operations
1923 // within the type container to work correctly
1925 if (imported_events != null) {
1926 // The backing event field should be private but it may not
1927 int index = imported_events.FindIndex (l => l.Name == fi.Name);
1929 event_spec = imported_events[index];
1930 event_spec.BackingField = (FieldSpec) imported;
1931 imported_events.RemoveAt (index);
1937 case MemberTypes.NestedType:
1938 // Already in the cache from the first pass
1941 throw new NotImplementedException (member.ToString ());
1944 cache.AddMember (imported);
1948 if (declaringType.IsInterface && declaringType.Interfaces != null) {
1949 foreach (var iface in declaringType.Interfaces) {
1950 cache.AddInterface (iface);
1956 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
1958 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
1959 : base (type, importer)
1965 public IAssemblyDefinition DeclaringAssembly {
1967 throw new NotImplementedException ();
1971 public string Namespace {
1977 public int TypeParametersCount {
1983 public TypeParameterSpec[] TypeParameters {
1991 public TypeSpec GetAttributeCoClass ()
1996 public string GetAttributeDefaultMember ()
1998 throw new NotSupportedException ();
2001 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2003 throw new NotSupportedException ();
2006 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2008 throw new NotImplementedException ();
2011 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2013 throw new NotImplementedException ();