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);
90 foreach (var ca in cad) {
91 var dt = ca.Constructor.DeclaringType;
92 if (dt.Name != "DynamicAttribute" && dt.Namespace != CompilerServicesNamespace)
95 if (ca.ConstructorArguments.Count == 0) {
96 flags = single_attribute;
100 var arg_type = ca.ConstructorArguments[0].ArgumentType;
102 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
103 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
104 flags = new bool[carg.Count];
105 for (int i = 0; i < flags.Length; ++i) {
106 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
107 flags[i] = (bool) carg[i].Value;
119 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
120 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
121 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
122 readonly ModuleContainer module;
124 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
126 protected MetadataImporter (ModuleContainer module)
128 this.module = module;
130 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
131 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
132 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
133 IgnorePrivateMembers = true;
138 public ICollection<IAssemblyDefinition> Assemblies {
140 return assembly_2_definition.Values;
144 public bool IgnorePrivateMembers { get; set; }
148 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
149 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
150 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
152 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
155 var fa = fi.Attributes;
156 switch (fa & FieldAttributes.FieldAccessMask) {
157 case FieldAttributes.Public:
158 mod = Modifiers.PUBLIC;
160 case FieldAttributes.Assembly:
161 mod = Modifiers.INTERNAL;
163 case FieldAttributes.Family:
164 mod = Modifiers.PROTECTED;
166 case FieldAttributes.FamORAssem:
167 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
170 // Ignore private fields (even for error reporting) to not require extra dependencies
171 if (IgnorePrivateMembers || HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
174 mod = Modifiers.PRIVATE;
181 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
182 } catch (Exception e) {
183 // TODO: I should construct fake TypeSpec based on TypeRef signature
184 // but there is no way to do it with System.Reflection
185 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
186 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
189 var definition = new ImportedMemberDefinition (fi, field_type, this);
191 if ((fa & FieldAttributes.Literal) != 0) {
192 var c = Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
193 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
196 if ((fa & FieldAttributes.InitOnly) != 0) {
197 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
198 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
200 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
203 mod |= Modifiers.READONLY;
205 var req_mod = fi.GetRequiredCustomModifiers ();
206 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
207 mod |= Modifiers.VOLATILE;
210 if ((fa & FieldAttributes.Static) != 0) {
211 mod |= Modifiers.STATIC;
213 // Fixed buffers cannot be static
214 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
215 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
217 // TODO: Sanity check on field_type (only few types are allowed)
218 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
219 return new FixedFieldSpec (declaringType, definition, fi, element_field, mod);
223 return new FieldSpec (declaringType, definition, field_type, fi, mod);
226 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
228 add.IsAccessor = true;
229 remove.IsAccessor = true;
231 if (add.Modifiers != remove.Modifiers)
232 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
234 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
235 var definition = new ImportedMemberDefinition (ei, event_type, this);
236 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
239 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
241 var tparams = type.GetGenericArguments ();
243 int parent_owned_count;
245 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
248 // System.Reflection duplicates parent type parameters for each
249 // nested type with slightly modified properties (eg. different owner)
250 // This just makes things more complicated (think of cloned constraints)
251 // therefore we remap any nested type owned by parent using `type_cache'
252 // to the single TypeParameterSpec
254 if (declaringType != null && parent_owned_count > 0) {
256 while (read_count != parent_owned_count) {
257 var tparams_count = declaringType.Arity;
258 if (tparams_count != 0) {
259 var parent_tp = declaringType.MemberDefinition.TypeParameters;
260 read_count += tparams_count;
261 for (int i = 0; i < tparams_count; i++) {
262 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
266 declaringType = declaringType.DeclaringType;
270 parent_owned_count = 0;
273 if (tparams.Length - parent_owned_count == 0)
276 return CreateGenericParameters (parent_owned_count, tparams);
279 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
281 var tspec = new TypeParameterSpec[tparams.Length - first];
282 for (int pos = first; pos < tparams.Length; ++pos) {
283 var type = tparams[pos];
284 int index = pos - first;
286 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
292 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
296 var tspec = new TypeSpec [tparams.Length - first];
297 for (int pos = first; pos < tparams.Length; ++pos) {
298 var type = tparams[pos];
299 int index = pos - first;
302 if (type.HasElementType) {
303 var element = type.GetElementType ();
305 spec = ImportType (element, dtype);
308 throw new NotImplementedException ("Unknown element type " + type.ToString ());
311 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
313 spec = CreateType (type, dtype, true);
316 // We treat nested generic types as inflated internally where
317 // reflection uses type definition
320 // IFoo<A<T>> foo; // A<T> is definition in this case
323 // TODO: Is full logic from CreateType needed here as well?
325 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
326 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
327 spec = spec.MakeGenericType (module, targs);
338 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
340 Modifiers mod = ReadMethodModifiers (mb, declaringType);
341 TypeParameterSpec[] tparams;
343 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
345 if (mb.IsGenericMethod) {
346 if (!mb.IsGenericMethodDefinition)
347 throw new NotSupportedException ("assert");
349 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
356 if (mb.MemberType == MemberTypes.Constructor) {
357 kind = MemberKind.Constructor;
358 returnType = module.Compiler.BuiltinTypes.Void;
361 // Detect operators and destructors
363 string name = mb.Name;
364 kind = MemberKind.Method;
365 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
366 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
367 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
368 var op_type = Operator.GetType (name);
369 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
370 kind = MemberKind.Operator;
373 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
374 kind = MemberKind.Destructor;
375 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
376 mod &= ~Modifiers.OVERRIDE;
377 mod |= Modifiers.VIRTUAL;
382 var mi = (MethodInfo) mb;
383 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
385 // Cannot set to OVERRIDE without full hierarchy checks
386 // this flag indicates that the method could be override
387 // but further validation is needed
388 if ((mod & Modifiers.OVERRIDE) != 0) {
389 bool is_real_override = false;
390 if (kind == MemberKind.Method && declaringType.BaseType != null) {
391 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
392 var candidate = MemberCache.FindMember (declaringType.BaseType, filter, BindingRestriction.None);
395 // For imported class method do additional validation to be sure that metadata
396 // override flag was correct
398 // Difference between protected internal and protected is ok
400 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
401 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
402 is_real_override = true;
406 if (!is_real_override) {
407 mod &= ~Modifiers.OVERRIDE;
408 if ((mod & Modifiers.SEALED) != 0)
409 mod &= ~Modifiers.SEALED;
411 mod |= Modifiers.VIRTUAL;
416 IMemberDefinition definition;
417 if (tparams != null) {
418 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
419 foreach (var tp in gmd.TypeParameters) {
420 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
425 definition = new ImportedParameterMemberDefinition (mb, returnType, parameters, this);
428 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, mb, parameters, mod);
436 // Imports System.Reflection parameters
438 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
440 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
442 if (pi.Length == 0 && varargs == 0)
443 return ParametersCompiled.EmptyReadOnlyParameters;
445 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
446 IParameterData[] par = new IParameterData[pi.Length + varargs];
447 bool is_params = false;
448 for (int i = 0; i < pi.Length; i++) {
449 ParameterInfo p = pi[i];
450 Parameter.Modifier mod = 0;
451 Expression default_value = null;
452 if (p.ParameterType.IsByRef) {
453 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
454 mod = Parameter.Modifier.OUT;
456 mod = Parameter.Modifier.REF;
459 // Strip reference wrapping
461 var el = p.ParameterType.GetElementType ();
462 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
463 } else if (i == 0 && method.IsStatic && parent.IsStatic && parent.MemberDefinition.DeclaringAssembly.HasExtensionMethod &&
464 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
465 mod = Parameter.Modifier.This;
466 types[i] = ImportType (p.ParameterType);
468 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
470 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
471 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
472 mod = Parameter.Modifier.PARAMS;
477 if (!is_params && p.IsOptional) {
478 object value = p.RawDefaultValue;
479 var ptype = types[i];
480 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
482 default_value = Constant.CreateConstant (ptype, null, Location.Null);
484 default_value = ImportParameterConstant (value);
487 default_value = new EnumConstant ((Constant) default_value, ptype);
490 } else if (value == Missing.Value) {
491 default_value = EmptyExpression.MissingValue;
492 } else if (value == null) {
493 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
494 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
495 default_value = ImportParameterConstant (value);
500 par[i] = new ParameterData (p.Name, mod, default_value);
504 par[par.Length - 1] = new ArglistParameter (Location.Null);
505 types[types.Length - 1] = InternalType.Arglist;
508 return method != null ?
509 new ParametersImported (par, types, varargs != 0, is_params) :
510 new ParametersImported (par, types, is_params);
514 // Returns null when the property is not valid C# property
516 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
519 AParametersCollection param = null;
520 TypeSpec type = null;
523 param = get.Parameters;
524 type = get.ReturnType;
527 bool is_valid_property = true;
529 if (set.ReturnType.Kind != MemberKind.Void)
530 is_valid_property = false;
532 var set_param_count = set.Parameters.Count - 1;
534 if (set_param_count < 0) {
536 is_valid_property = false;
539 var set_type = set.Parameters.Types[set_param_count];
542 AParametersCollection set_based_param;
544 if (set_param_count == 0) {
545 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
548 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
550 var data = new IParameterData[set_param_count];
551 var types = new TypeSpec[set_param_count];
552 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
553 Array.Copy (set.Parameters.Types, types, set_param_count);
554 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
558 param = set_based_param;
561 if (set_param_count != get.Parameters.Count)
562 is_valid_property = false;
564 if (get.ReturnType != set_type)
565 is_valid_property = false;
567 // Possible custom accessor modifiers
568 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
569 var get_acc = mod & Modifiers.AccessibilityMask;
570 if (get_acc != Modifiers.PUBLIC) {
571 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
572 // If the accessor modifiers are not same, do extra restriction checks
573 if (get_acc != set_acc) {
574 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
575 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
576 if (get_restr && set_restr) {
577 is_valid_property = false; // Neither is more restrictive
581 mod &= ~Modifiers.AccessibilityMask;
590 PropertySpec spec = null;
591 if (!param.IsEmpty) {
592 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
593 if (index_name == null) {
594 is_valid_property = false;
598 is_valid_property = false;
599 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
600 is_valid_property = false;
604 is_valid_property = false;
605 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
606 is_valid_property = false;
610 if (is_valid_property)
611 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
615 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
617 if (!is_valid_property) {
618 spec.IsNotCSharpCompatible = true;
630 public TypeSpec CreateType (MetaType type)
632 return CreateType (type, new DynamicTypeReader (), true);
635 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
637 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
640 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
642 TypeSpec declaring_type;
643 if (type.IsNested && !type.IsGenericParameter)
644 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
646 declaring_type = null;
648 return CreateType (type, declaring_type, dtype, canImportBaseType);
651 TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
654 if (import_cache.TryGetValue (type, out spec)) {
655 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
656 if (dtype.IsDynamicObject (this))
657 return module.Compiler.BuiltinTypes.Dynamic;
662 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
665 if (!dtype.HasDynamicAttribute (this))
668 // We've found same object in the cache but this one has a dynamic custom attribute
669 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
670 // Do type resolve process again in that case
672 // TODO: Handle cases where they still unify
675 if (IsMissingType (type)) {
676 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
677 spec.MemberCache = MemberCache.Empty;
678 import_cache.Add (type, spec);
682 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
683 var type_def = type.GetGenericTypeDefinition ();
685 // Generic type definition can also be forwarded
686 if (compiled_types.TryGetValue (type_def, out spec))
689 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
690 if (declaringType == null) {
691 // Simple case, no nesting
692 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
693 spec = spec.MakeGenericType (module, targs);
696 // Nested type case, converting .NET types like
697 // A`1.B`1.C`1<int, long, string> to typespec like
698 // A<int>.B<long>.C<string>
700 var nested_hierarchy = new List<TypeSpec> ();
701 while (declaringType.IsNested) {
702 nested_hierarchy.Add (declaringType);
703 declaringType = declaringType.DeclaringType;
707 if (declaringType.Arity > 0) {
708 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
709 targs_pos = spec.Arity;
711 spec = declaringType;
714 for (int i = nested_hierarchy.Count; i != 0; --i) {
715 var t = nested_hierarchy [i - 1];
716 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
718 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
719 targs_pos += t.Arity;
723 string name = type.Name;
724 int index = name.IndexOf ('`');
726 name = name.Substring (0, index);
728 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
732 if (spec.Arity > 0) {
733 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
737 // Don't add generic type with dynamic arguments, they can interfere with same type
738 // using object type arguments
739 if (!spec.HasDynamicElement) {
741 // Add to reading cache to speed up reading
742 if (!import_cache.ContainsKey (type))
743 import_cache.Add (type, spec);
752 var ma = type.Attributes;
753 switch (ma & TypeAttributes.VisibilityMask) {
754 case TypeAttributes.Public:
755 case TypeAttributes.NestedPublic:
756 mod = Modifiers.PUBLIC;
758 case TypeAttributes.NestedPrivate:
759 mod = Modifiers.PRIVATE;
761 case TypeAttributes.NestedFamily:
762 mod = Modifiers.PROTECTED;
764 case TypeAttributes.NestedFamORAssem:
765 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
768 mod = Modifiers.INTERNAL;
772 if ((ma & TypeAttributes.Interface) != 0) {
773 kind = MemberKind.Interface;
774 } else if (type.IsGenericParameter) {
775 kind = MemberKind.TypeParameter;
777 var base_type = type.BaseType;
778 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
779 kind = MemberKind.Class;
781 kind = DetermineKindFromBaseType (base_type);
782 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
783 mod |= Modifiers.SEALED;
787 if (kind == MemberKind.Class) {
788 if ((ma & TypeAttributes.Sealed) != 0) {
789 mod |= Modifiers.SEALED;
790 if ((ma & TypeAttributes.Abstract) != 0)
791 mod |= Modifiers.STATIC;
792 } else if ((ma & TypeAttributes.Abstract) != 0) {
793 mod |= Modifiers.ABSTRACT;
798 var definition = new ImportedTypeDefinition (type, this);
801 if (kind == MemberKind.Enum) {
802 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
803 BindingFlags.Instance |
804 BindingFlags.Public | BindingFlags.NonPublic;
806 var type_members = type.GetFields (underlying_member);
807 foreach (var type_member in type_members) {
808 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
813 kind = MemberKind.Class;
815 } else if (kind == MemberKind.TypeParameter) {
816 spec = CreateTypeParameter (type, declaringType);
817 } else if (type.IsGenericTypeDefinition) {
818 definition.TypeParameters = CreateGenericParameters (type, declaringType);
819 } else if (compiled_types.TryGetValue (type, out pt)) {
821 // Same type was found in inside compiled types. It's
822 // either build-in type or forward referenced typed
823 // which point into just compiled assembly.
826 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
828 bts.SetDefinition (definition, type, mod);
832 spec = new TypeSpec (kind, declaringType, definition, type, mod);
834 import_cache.Add (type, spec);
837 // Two stage setup as the base type can be inflated declaring type or
838 // another nested type inside same declaring type which has not been
839 // loaded, therefore we can import a base type of nested types once
840 // the types have been imported
842 if (canImportBaseType)
843 ImportTypeBase (spec, type);
848 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
850 IAssemblyDefinition found;
851 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
853 // This can happen in dynamic context only
854 var def = new ImportedAssemblyDefinition (assembly);
855 assembly_2_definition.Add (assembly, def);
856 def.ReadAttributes ();
863 public void ImportTypeBase (MetaType type)
865 TypeSpec spec = import_cache[type];
867 ImportTypeBase (spec, type);
870 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
873 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
874 case GenericParameterAttributes.Covariant:
875 variance = Variance.Covariant;
877 case GenericParameterAttributes.Contravariant:
878 variance = Variance.Contravariant;
881 variance = Variance.None;
885 SpecialConstraint special = SpecialConstraint.None;
886 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
888 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
889 special |= SpecialConstraint.Struct;
890 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
891 special = SpecialConstraint.Constructor;
894 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
895 special |= SpecialConstraint.Class;
898 TypeParameterSpec spec;
899 var def = new ImportedTypeParameterDefinition (type, this);
900 if (type.DeclaringMethod != null) {
901 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
903 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
910 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
911 // they can be assembly specific therefore we do check based on names only
913 public bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
915 if (attributesData.Count == 0)
918 foreach (var attr in attributesData) {
919 var dt = attr.Constructor.DeclaringType;
920 if (dt.Name == attrName && dt.Namespace == attrNamespace)
927 void ImportTypeBase (TypeSpec spec, MetaType type)
929 if (spec.Kind == MemberKind.Interface)
930 spec.BaseType = module.Compiler.BuiltinTypes.Object;
931 else if (type.BaseType != null) {
933 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
934 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
936 base_type = CreateType (type.BaseType);
938 spec.BaseType = base_type;
943 ifaces = type.__GetDeclaredInterfaces ();
944 if (ifaces.Length != 0) {
945 foreach (var iface in ifaces) {
946 var it = CreateType (iface);
950 spec.AddInterface (it);
952 // Unfortunately not all languages expand inherited interfaces
953 var bifaces = it.Interfaces;
954 if (bifaces != null) {
955 foreach (var biface in bifaces) {
956 spec.AddInterface (biface);
962 if (spec.BaseType != null) {
963 var bifaces = spec.BaseType.Interfaces;
964 if (bifaces != null) {
965 foreach (var iface in bifaces)
966 spec.AddInterface (iface);
970 ifaces = type.GetInterfaces ();
972 if (ifaces.Length > 0) {
973 foreach (var iface in ifaces) {
974 spec.AddInterface (CreateType (iface));
979 if (spec.MemberDefinition.TypeParametersCount > 0) {
980 foreach (var tp in spec.MemberDefinition.TypeParameters) {
981 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
987 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
989 Namespace ns = targetNamespace;
990 string prev_namespace = null;
991 foreach (var t in types) {
995 // Be careful not to trigger full parent type loading
996 if (t.MemberType == MemberTypes.NestedType)
999 if (t.Name[0] == '<')
1002 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1006 if (prev_namespace != t.Namespace) {
1007 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1008 prev_namespace = t.Namespace;
1011 ns.AddType (module, it);
1013 if (it.IsStatic && hasExtensionTypes &&
1014 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1015 it.SetExtensionMethodContainer ();
1020 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1022 var constraints = type.GetGenericParameterConstraints ();
1023 List<TypeSpec> tparams = null;
1024 foreach (var ct in constraints) {
1025 if (ct.IsGenericParameter) {
1026 if (tparams == null)
1027 tparams = new List<TypeSpec> ();
1029 tparams.Add (CreateType (ct));
1033 if (!IsMissingType (ct) && ct.IsClass) {
1034 spec.BaseType = CreateType (ct);
1038 spec.AddInterface (CreateType (ct));
1041 if (spec.BaseType == null)
1042 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1044 if (tparams != null)
1045 spec.TypeArguments = tparams.ToArray ();
1048 Constant ImportParameterConstant (object value)
1051 // Get type of underlying value as int constant can be used for object
1052 // parameter type. This is not allowed in C# but other languages can do that
1054 var types = module.Compiler.BuiltinTypes;
1055 switch (System.Type.GetTypeCode (value.GetType ())) {
1056 case TypeCode.Boolean:
1057 return new BoolConstant (types, (bool) value, Location.Null);
1059 return new ByteConstant (types, (byte) value, Location.Null);
1061 return new CharConstant (types, (char) value, Location.Null);
1062 case TypeCode.Decimal:
1063 return new DecimalConstant (types, (decimal) value, Location.Null);
1064 case TypeCode.Double:
1065 return new DoubleConstant (types, (double) value, Location.Null);
1066 case TypeCode.Int16:
1067 return new ShortConstant (types, (short) value, Location.Null);
1068 case TypeCode.Int32:
1069 return new IntConstant (types, (int) value, Location.Null);
1070 case TypeCode.Int64:
1071 return new LongConstant (types, (long) value, Location.Null);
1072 case TypeCode.SByte:
1073 return new SByteConstant (types, (sbyte) value, Location.Null);
1074 case TypeCode.Single:
1075 return new FloatConstant (types, (float) value, Location.Null);
1076 case TypeCode.String:
1077 return new StringConstant (types, (string) value, Location.Null);
1078 case TypeCode.UInt16:
1079 return new UShortConstant (types, (ushort) value, Location.Null);
1080 case TypeCode.UInt32:
1081 return new UIntConstant (types, (uint) value, Location.Null);
1082 case TypeCode.UInt64:
1083 return new ULongConstant (types, (ulong) value, Location.Null);
1086 throw new NotImplementedException (value.GetType ().ToString ());
1089 public TypeSpec ImportType (MetaType type)
1091 return ImportType (type, new DynamicTypeReader (type));
1094 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1096 if (type.HasElementType) {
1097 var element = type.GetElementType ();
1099 var spec = ImportType (element, dtype);
1102 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1104 return ReferenceContainer.MakeType (module, spec);
1106 return PointerContainer.MakeType (module, spec);
1108 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1111 return CreateType (type, dtype, true);
1114 static bool IsMissingType (MetaType type)
1117 return type.__IsMissing;
1124 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1125 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1126 // DecimalConstantAttribute metadata.
1128 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1130 if (attrs.Count == 0)
1133 foreach (var ca in attrs) {
1134 var dt = ca.Constructor.DeclaringType;
1135 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1138 var value = new decimal (
1139 (int) (uint) ca.ConstructorArguments[4].Value,
1140 (int) (uint) ca.ConstructorArguments[3].Value,
1141 (int) (uint) ca.ConstructorArguments[2].Value,
1142 (byte) ca.ConstructorArguments[1].Value != 0,
1143 (byte) ca.ConstructorArguments[0].Value);
1145 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1151 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1154 var ma = mb.Attributes;
1155 switch (ma & MethodAttributes.MemberAccessMask) {
1156 case MethodAttributes.Public:
1157 mod = Modifiers.PUBLIC;
1159 case MethodAttributes.Assembly:
1160 mod = Modifiers.INTERNAL;
1162 case MethodAttributes.Family:
1163 mod = Modifiers.PROTECTED;
1165 case MethodAttributes.FamORAssem:
1166 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1169 mod = Modifiers.PRIVATE;
1173 if ((ma & MethodAttributes.Static) != 0) {
1174 mod |= Modifiers.STATIC;
1177 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1178 mod |= Modifiers.ABSTRACT;
1182 // It can be sealed and override
1183 if ((ma & MethodAttributes.Final) != 0)
1184 mod |= Modifiers.SEALED;
1186 if ((ma & MethodAttributes.Virtual) != 0) {
1187 // Not every member can be detected based on MethodAttribute, we
1188 // set virtual or non-virtual only when we are certain. Further checks
1189 // to really find out what `virtual' means for this member are done
1191 if ((ma & MethodAttributes.NewSlot) != 0) {
1192 if ((mod & Modifiers.SEALED) != 0) {
1193 mod &= ~Modifiers.SEALED;
1195 mod |= Modifiers.VIRTUAL;
1198 mod |= Modifiers.OVERRIDE;
1206 abstract class ImportedDefinition : IMemberDefinition
1208 protected class AttributesBag
1210 public static readonly AttributesBag Default = new AttributesBag ();
1212 public AttributeUsageAttribute AttributeUsage;
1213 public ObsoleteAttribute Obsolete;
1214 public string[] Conditionals;
1215 public string DefaultIndexerName;
1216 public bool? CLSAttributeValue;
1217 public TypeSpec CoClass;
1219 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1221 AttributesBag bag = null;
1222 List<string> conditionals = null;
1224 // It should not throw any loading exception
1225 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1227 foreach (var a in attrs) {
1228 var dt = a.Constructor.DeclaringType;
1229 string name = dt.Name;
1230 if (name == "ObsoleteAttribute") {
1231 if (dt.Namespace != "System")
1235 bag = new AttributesBag ();
1237 var args = a.ConstructorArguments;
1239 if (args.Count == 1) {
1240 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1241 } else if (args.Count == 2) {
1242 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1244 bag.Obsolete = new ObsoleteAttribute ();
1250 if (name == "ConditionalAttribute") {
1251 if (dt.Namespace != "System.Diagnostics")
1255 bag = new AttributesBag ();
1257 if (conditionals == null)
1258 conditionals = new List<string> (2);
1260 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1264 if (name == "CLSCompliantAttribute") {
1265 if (dt.Namespace != "System")
1269 bag = new AttributesBag ();
1271 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1275 // Type only attributes
1276 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1277 if (name == "DefaultMemberAttribute") {
1278 if (dt.Namespace != "System.Reflection")
1282 bag = new AttributesBag ();
1284 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1288 if (name == "AttributeUsageAttribute") {
1289 if (dt.Namespace != "System")
1293 bag = new AttributesBag ();
1295 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1296 foreach (var named in a.NamedArguments) {
1297 if (named.MemberInfo.Name == "AllowMultiple")
1298 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1299 else if (named.MemberInfo.Name == "Inherited")
1300 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1305 // Interface only attribute
1306 if (name == "CoClassAttribute") {
1307 if (dt.Namespace != "System.Runtime.InteropServices")
1311 bag = new AttributesBag ();
1313 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1322 if (conditionals != null)
1323 bag.Conditionals = conditionals.ToArray ();
1329 protected readonly MemberInfo provider;
1330 protected AttributesBag cattrs;
1331 protected readonly MetadataImporter importer;
1333 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1335 this.provider = provider;
1336 this.importer = importer;
1341 public bool IsImported {
1347 public virtual string Name {
1349 return provider.Name;
1355 public string[] ConditionalConditions ()
1360 return cattrs.Conditionals;
1363 public ObsoleteAttribute GetAttributeObsolete ()
1368 return cattrs.Obsolete;
1371 public bool? CLSAttributeValue {
1376 return cattrs.CLSAttributeValue;
1380 protected void ReadAttributes ()
1382 cattrs = AttributesBag.Read (provider, importer);
1385 public void SetIsAssigned ()
1387 // Unused for imported members
1390 public void SetIsUsed ()
1392 // Unused for imported members
1396 public class ImportedModuleDefinition
1398 readonly Module module;
1401 public ImportedModuleDefinition (Module module)
1403 this.module = module;
1408 public bool IsCLSCompliant {
1410 return cls_compliant;
1414 public string Name {
1422 public void ReadAttributes ()
1424 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1426 foreach (var a in attrs) {
1427 var dt = a.Constructor.DeclaringType;
1428 if (dt.Name == "CLSCompliantAttribute") {
1429 if (dt.Namespace != "System")
1432 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1439 // Reads assembly attributes which where attached to a special type because
1440 // module does have assembly manifest
1442 public List<Attribute> ReadAssemblyAttributes ()
1444 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1448 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1452 // TODO: implement, the idea is to fabricate specil Attribute class and
1453 // add it to OptAttributes before resolving the source code attributes
1454 // Need to build module location as well for correct error reporting
1456 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1457 //var attrs = new List<Attribute> (assembly_attributes.Count);
1458 //foreach (var a in assembly_attributes)
1460 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1461 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1463 // foreach (var carg in a.ConstructorArguments) {
1467 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1474 public class ImportedAssemblyDefinition : IAssemblyDefinition
1476 readonly Assembly assembly;
1477 readonly AssemblyName aname;
1479 bool contains_extension_methods;
1481 List<AssemblyName> internals_visible_to;
1482 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1484 public ImportedAssemblyDefinition (Assembly assembly)
1486 this.assembly = assembly;
1487 this.aname = assembly.GetName ();
1492 public Assembly Assembly {
1498 public string FullName {
1500 return aname.FullName;
1504 public bool HasExtensionMethod {
1506 return contains_extension_methods;
1510 public bool HasStrongName {
1512 return aname.GetPublicKey ().Length != 0;
1516 public bool IsMissing {
1519 return assembly.__IsMissing;
1526 public bool IsCLSCompliant {
1528 return cls_compliant;
1532 public string Location {
1534 return assembly.Location;
1538 public string Name {
1546 public byte[] GetPublicKeyToken ()
1548 return aname.GetPublicKeyToken ();
1551 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1553 return internals_visible_to_cache [assembly];
1556 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1558 if (internals_visible_to == null)
1561 AssemblyName is_visible = null;
1562 if (internals_visible_to_cache == null) {
1563 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1565 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1566 return is_visible != null;
1569 var token = assembly.GetPublicKeyToken ();
1570 if (token != null && token.Length == 0)
1573 foreach (var internals in internals_visible_to) {
1574 if (internals.Name != assembly.Name)
1577 if (token == null && assembly is AssemblyDefinition) {
1578 is_visible = internals;
1582 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1585 is_visible = internals;
1589 internals_visible_to_cache.Add (assembly, is_visible);
1590 return is_visible != null;
1593 public void ReadAttributes ()
1596 if (assembly.__IsMissing)
1600 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1602 foreach (var a in attrs) {
1603 var dt = a.Constructor.DeclaringType;
1605 if (name == "CLSCompliantAttribute") {
1606 if (dt.Namespace == "System") {
1607 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1612 if (name == "InternalsVisibleToAttribute") {
1613 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1616 string s = a.ConstructorArguments[0].Value as string;
1620 var an = new AssemblyName (s);
1621 if (internals_visible_to == null)
1622 internals_visible_to = new List<AssemblyName> ();
1624 internals_visible_to.Add (an);
1628 if (name == "ExtensionAttribute") {
1629 if (dt.Namespace == MetadataImporter.CompilerServicesNamespace)
1630 contains_extension_methods = true;
1637 public override string ToString ()
1643 class ImportedMemberDefinition : ImportedDefinition
1645 readonly TypeSpec type;
1647 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1648 : base (member, importer)
1655 public TypeSpec MemberType {
1664 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1666 readonly AParametersCollection parameters;
1668 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1669 : base (provider, type, importer)
1671 this.parameters = parameters;
1674 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1675 : base (provider, type, importer)
1677 this.parameters = parameters;
1682 public AParametersCollection Parameters {
1691 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1693 readonly TypeParameterSpec[] tparams;
1695 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1696 : base (provider, type, parameters, importer)
1698 this.tparams = tparams;
1703 public TypeParameterSpec[] TypeParameters {
1709 public int TypeParametersCount {
1711 return tparams.Length;
1718 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1720 TypeParameterSpec[] tparams;
1723 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1724 : base (type, importer)
1730 public IAssemblyDefinition DeclaringAssembly {
1732 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1736 public override string Name {
1740 if (tparams != null) {
1741 int arity_start = name.IndexOf ('`');
1742 if (arity_start > 0)
1743 name = name.Substring (0, arity_start);
1751 public string Namespace {
1753 return ((MetaType) provider).Namespace;
1757 public int TypeParametersCount {
1759 return tparams == null ? 0 : tparams.Length;
1763 public TypeParameterSpec[] TypeParameters {
1774 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1777 // Report details about missing type and most likely cause of the problem.
1778 // csc reports 1683, 1684 as warnings but we report them only when used
1779 // or referenced from the user core in which case compilation error has to
1780 // be reported because compiler cannot continue anyway
1782 foreach (var t in types) {
1783 string name = t.GetSignatureForError ();
1785 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1786 ctx.Module.Compiler.Report.Error (1683, loc,
1787 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1789 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1790 ctx.Module.Compiler.Report.Error (12, loc,
1791 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1792 name, t.MemberDefinition.DeclaringAssembly.FullName);
1794 ctx.Module.Compiler.Report.Error (1684, loc,
1795 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1796 name, t.MemberDefinition.DeclaringAssembly.FullName);
1801 public TypeSpec GetAttributeCoClass ()
1806 return cattrs.CoClass;
1809 public string GetAttributeDefaultMember ()
1814 return cattrs.DefaultIndexerName;
1817 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1822 return cattrs.AttributeUsage;
1825 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1827 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1828 return a == assembly || a.IsFriendAssemblyTo (assembly);
1831 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1834 // Not interested in members of nested private types unless the importer needs them
1836 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1837 cache = MemberCache.Empty;
1841 var loading_type = (MetaType) provider;
1842 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1843 BindingFlags.Static | BindingFlags.Instance |
1844 BindingFlags.Public | BindingFlags.NonPublic;
1846 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1847 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1848 MethodAttributes.Final;
1850 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1851 List<EventSpec> imported_events = null;
1852 EventSpec event_spec;
1853 MemberSpec imported;
1857 all = loading_type.GetMembers (all_members);
1858 } catch (Exception e) {
1859 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1860 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1863 if (cache == null) {
1864 cache = new MemberCache (all.Length);
1867 // Do the types first as they can be referenced by the members before
1868 // they are found or inflated
1870 foreach (var member in all) {
1871 if (member.MemberType != MemberTypes.NestedType)
1874 var t = (MetaType) member;
1876 // Ignore compiler generated types, mostly lambda containers
1877 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1880 imported = importer.CreateNestedType (t, declaringType);
1881 cache.AddMemberImported (imported);
1884 foreach (var member in all) {
1885 if (member.MemberType != MemberTypes.NestedType)
1888 var t = (MetaType) member;
1890 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1893 importer.ImportTypeBase (t);
1898 // Load base interfaces first to minic behaviour of compiled members
1900 if (declaringType.IsInterface && declaringType.Interfaces != null) {
1901 foreach (var iface in declaringType.Interfaces) {
1902 cache.AddInterface (iface);
1908 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1910 foreach (var member in all) {
1911 switch (member.MemberType) {
1912 case MemberTypes.Constructor:
1913 case MemberTypes.Method:
1914 MethodBase mb = (MethodBase) member;
1915 var attrs = mb.Attributes;
1917 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1918 if (importer.IgnorePrivateMembers)
1921 // Ignore explicitly implemented members
1922 if ((attrs & explicit_impl) == explicit_impl)
1925 // Ignore compiler generated methods
1926 if (importer.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1930 imported = importer.CreateMethod (mb, declaringType);
1931 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1932 if (possible_accessors == null)
1933 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1935 // There are no metadata rules for accessors, we have to consider any method as possible candidate
1936 possible_accessors.Add (mb, (MethodSpec) imported);
1940 case MemberTypes.Property:
1941 if (possible_accessors == null)
1944 var p = (PropertyInfo) member;
1946 // Links possible accessors with property
1948 MethodSpec get, set;
1949 m = p.GetGetMethod (true);
1950 if (m == null || !possible_accessors.TryGetValue (m, out get))
1953 m = p.GetSetMethod (true);
1954 if (m == null || !possible_accessors.TryGetValue (m, out set))
1957 // No accessors registered (e.g. explicit implementation)
1958 if (get == null && set == null)
1961 imported = importer.CreateProperty (p, declaringType, get, set);
1962 if (imported == null)
1966 case MemberTypes.Event:
1967 if (possible_accessors == null)
1970 var e = (EventInfo) member;
1972 // Links accessors with event
1974 MethodSpec add, remove;
1975 m = e.GetAddMethod (true);
1976 if (m == null || !possible_accessors.TryGetValue (m, out add))
1979 m = e.GetRemoveMethod (true);
1980 if (m == null || !possible_accessors.TryGetValue (m, out remove))
1983 // Both accessors are required
1984 if (add == null || remove == null)
1987 event_spec = importer.CreateEvent (e, declaringType, add, remove);
1988 if (!importer.IgnorePrivateMembers) {
1989 if (imported_events == null)
1990 imported_events = new List<EventSpec> ();
1992 imported_events.Add (event_spec);
1995 imported = event_spec;
1997 case MemberTypes.Field:
1998 var fi = (FieldInfo) member;
2000 imported = importer.CreateField (fi, declaringType);
2001 if (imported == null)
2005 // For dynamic binder event has to be fully restored to allow operations
2006 // within the type container to work correctly
2008 if (imported_events != null) {
2009 // The backing event field should be private but it may not
2011 for (i = 0; i < imported_events.Count; ++i) {
2012 var ev = imported_events[i];
2013 if (ev.Name == fi.Name) {
2014 ev.BackingField = (FieldSpec) imported;
2015 imported_events.RemoveAt (i);
2026 case MemberTypes.NestedType:
2027 // Already in the cache from the first pass
2030 throw new NotImplementedException (member.ToString ());
2033 cache.AddMemberImported (imported);
2039 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2041 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2042 : base (type, importer)
2048 public IAssemblyDefinition DeclaringAssembly {
2050 throw new NotImplementedException ();
2054 public string Namespace {
2060 public int TypeParametersCount {
2066 public TypeParameterSpec[] TypeParameters {
2074 public TypeSpec GetAttributeCoClass ()
2079 public string GetAttributeDefaultMember ()
2081 throw new NotSupportedException ();
2084 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2086 throw new NotSupportedException ();
2089 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2091 throw new NotImplementedException ();
2094 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2096 throw new NotImplementedException ();