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-2011 Novell, Inc
9 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 using System.Runtime.CompilerServices;
15 using System.Collections.Generic;
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
29 public abstract class MetadataImporter
32 // Dynamic types reader with additional logic to reconstruct a dynamic
33 // type using DynamicAttribute values
35 struct DynamicTypeReader
37 static readonly bool[] single_attribute = { true };
42 // There is no common type for CustomAttributeData and we cannot
43 // use ICustomAttributeProvider
47 // A member provider which can be used to get CustomAttributeData
49 public DynamicTypeReader (object provider)
53 this.provider = provider;
57 // Returns true when object at local position has dynamic attribute flag
59 public bool IsDynamicObject (MetadataImporter importer)
62 ReadAttribute (importer);
64 return flags != null && Position < flags.Length && flags[Position];
68 // Returns true when DynamicAttribute exists
70 public bool HasDynamicAttribute (MetadataImporter importer)
73 ReadAttribute (importer);
78 void ReadAttribute (MetadataImporter importer)
80 IList<CustomAttributeData> cad;
81 if (provider is MemberInfo) {
82 cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
83 } else if (provider is ParameterInfo) {
84 cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
91 foreach (var ca in cad) {
92 var dt = ca.Constructor.DeclaringType;
93 if (dt.Name != "DynamicAttribute" && dt.Namespace != CompilerServicesNamespace)
96 if (ca.ConstructorArguments.Count == 0) {
97 flags = single_attribute;
101 var arg_type = ca.ConstructorArguments[0].ArgumentType;
103 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
104 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
105 flags = new bool[carg.Count];
106 for (int i = 0; i < flags.Length; ++i) {
107 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
108 flags[i] = (bool) carg[i].Value;
120 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
121 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
122 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
123 readonly ModuleContainer module;
125 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
127 protected MetadataImporter (ModuleContainer module)
129 this.module = module;
131 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
132 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
133 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
134 IgnorePrivateMembers = true;
139 public ICollection<IAssemblyDefinition> Assemblies {
141 return assembly_2_definition.Values;
145 public bool IgnorePrivateMembers { get; set; }
149 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
150 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
151 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
153 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
156 var fa = fi.Attributes;
157 switch (fa & FieldAttributes.FieldAccessMask) {
158 case FieldAttributes.Public:
159 mod = Modifiers.PUBLIC;
161 case FieldAttributes.Assembly:
162 mod = Modifiers.INTERNAL;
164 case FieldAttributes.Family:
165 mod = Modifiers.PROTECTED;
167 case FieldAttributes.FamORAssem:
168 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
171 // Ignore private fields (even for error reporting) to not require extra dependencies
172 if (IgnorePrivateMembers || HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
175 mod = Modifiers.PRIVATE;
182 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
183 } catch (Exception e) {
184 // TODO: I should construct fake TypeSpec based on TypeRef signature
185 // but there is no way to do it with System.Reflection
186 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
187 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
190 var definition = new ImportedMemberDefinition (fi, field_type, this);
192 if ((fa & FieldAttributes.Literal) != 0) {
193 var c = Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
194 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
197 if ((fa & FieldAttributes.InitOnly) != 0) {
198 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
199 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
201 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
204 mod |= Modifiers.READONLY;
206 var req_mod = fi.GetRequiredCustomModifiers ();
207 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
208 mod |= Modifiers.VOLATILE;
211 if ((fa & FieldAttributes.Static) != 0) {
212 mod |= Modifiers.STATIC;
214 // Fixed buffers cannot be static
215 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
216 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
218 // TODO: Sanity check on field_type (only few types are allowed)
219 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
220 return new FixedFieldSpec (declaringType, definition, fi, element_field, mod);
224 return new FieldSpec (declaringType, definition, field_type, fi, mod);
227 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
229 add.IsAccessor = true;
230 remove.IsAccessor = true;
232 if (add.Modifiers != remove.Modifiers)
233 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
235 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
236 var definition = new ImportedMemberDefinition (ei, event_type, this);
237 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
240 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
242 var tparams = type.GetGenericArguments ();
244 int parent_owned_count;
246 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
249 // System.Reflection duplicates parent type parameters for each
250 // nested type with slightly modified properties (eg. different owner)
251 // This just makes things more complicated (think of cloned constraints)
252 // therefore we remap any nested type owned by parent using `type_cache'
253 // to the single TypeParameterSpec
255 if (declaringType != null && parent_owned_count > 0) {
257 while (read_count != parent_owned_count) {
258 var tparams_count = declaringType.Arity;
259 if (tparams_count != 0) {
260 var parent_tp = declaringType.MemberDefinition.TypeParameters;
261 read_count += tparams_count;
262 for (int i = 0; i < tparams_count; i++) {
263 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
267 declaringType = declaringType.DeclaringType;
271 parent_owned_count = 0;
274 if (tparams.Length - parent_owned_count == 0)
277 return CreateGenericParameters (parent_owned_count, tparams);
280 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
282 var tspec = new TypeParameterSpec[tparams.Length - first];
283 for (int pos = first; pos < tparams.Length; ++pos) {
284 var type = tparams[pos];
285 int index = pos - first;
287 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
293 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
297 var tspec = new TypeSpec [tparams.Length - first];
298 for (int pos = first; pos < tparams.Length; ++pos) {
299 var type = tparams[pos];
300 int index = pos - first;
303 if (type.HasElementType) {
304 var element = type.GetElementType ();
306 spec = ImportType (element, dtype);
309 throw new NotImplementedException ("Unknown element type " + type.ToString ());
312 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
314 spec = CreateType (type, dtype, true);
317 // We treat nested generic types as inflated internally where
318 // reflection uses type definition
321 // IFoo<A<T>> foo; // A<T> is definition in this case
324 // TODO: Is full logic from CreateType needed here as well?
326 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
327 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
328 spec = spec.MakeGenericType (module, targs);
339 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
341 Modifiers mod = ReadMethodModifiers (mb, declaringType);
342 TypeParameterSpec[] tparams;
344 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
346 if (mb.IsGenericMethod) {
347 if (!mb.IsGenericMethodDefinition)
348 throw new NotSupportedException ("assert");
350 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
357 if (mb.MemberType == MemberTypes.Constructor) {
358 kind = MemberKind.Constructor;
359 returnType = module.Compiler.BuiltinTypes.Void;
362 // Detect operators and destructors
364 string name = mb.Name;
365 kind = MemberKind.Method;
366 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
367 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
368 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
369 var op_type = Operator.GetType (name);
370 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
371 kind = MemberKind.Operator;
374 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
375 kind = MemberKind.Destructor;
376 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
377 mod &= ~Modifiers.OVERRIDE;
378 mod |= Modifiers.VIRTUAL;
383 var mi = (MethodInfo) mb;
384 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
386 // Cannot set to OVERRIDE without full hierarchy checks
387 // this flag indicates that the method could be override
388 // but further validation is needed
389 if ((mod & Modifiers.OVERRIDE) != 0) {
390 bool is_real_override = false;
391 if (kind == MemberKind.Method && declaringType.BaseType != null) {
392 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
393 var candidate = MemberCache.FindMember (declaringType.BaseType, filter, BindingRestriction.None);
396 // For imported class method do additional validation to be sure that metadata
397 // override flag was correct
399 // Difference between protected internal and protected is ok
401 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
402 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
403 is_real_override = true;
407 if (!is_real_override) {
408 mod &= ~Modifiers.OVERRIDE;
409 if ((mod & Modifiers.SEALED) != 0)
410 mod &= ~Modifiers.SEALED;
412 mod |= Modifiers.VIRTUAL;
417 IMemberDefinition definition;
418 if (tparams != null) {
419 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
420 foreach (var tp in gmd.TypeParameters) {
421 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
426 definition = new ImportedParameterMemberDefinition (mb, returnType, parameters, this);
429 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, mb, parameters, mod);
437 // Imports System.Reflection parameters
439 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
441 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
443 if (pi.Length == 0 && varargs == 0)
444 return ParametersCompiled.EmptyReadOnlyParameters;
446 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
447 IParameterData[] par = new IParameterData[pi.Length + varargs];
448 bool is_params = false;
449 for (int i = 0; i < pi.Length; i++) {
450 ParameterInfo p = pi[i];
451 Parameter.Modifier mod = 0;
452 Expression default_value = null;
453 if (p.ParameterType.IsByRef) {
454 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
455 mod = Parameter.Modifier.OUT;
457 mod = Parameter.Modifier.REF;
460 // Strip reference wrapping
462 var el = p.ParameterType.GetElementType ();
463 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
464 } else if (i == 0 && method.IsStatic && parent.IsStatic && parent.MemberDefinition.DeclaringAssembly.HasExtensionMethod &&
465 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
466 mod = Parameter.Modifier.This;
467 types[i] = ImportType (p.ParameterType);
469 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
471 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
472 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
473 mod = Parameter.Modifier.PARAMS;
478 if (!is_params && p.IsOptional) {
479 object value = p.RawDefaultValue;
480 var ptype = types[i];
481 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
483 default_value = Constant.CreateConstant (ptype, null, Location.Null);
485 default_value = ImportParameterConstant (value);
488 default_value = new EnumConstant ((Constant) default_value, ptype);
491 } else if (value == Missing.Value) {
492 default_value = EmptyExpression.MissingValue;
493 } else if (value == null) {
494 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
495 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
496 default_value = ImportParameterConstant (value);
501 par[i] = new ParameterData (p.Name, mod, default_value);
505 par[par.Length - 1] = new ArglistParameter (Location.Null);
506 types[types.Length - 1] = InternalType.Arglist;
509 return method != null ?
510 new ParametersImported (par, types, varargs != 0, is_params) :
511 new ParametersImported (par, types, is_params);
515 // Returns null when the property is not valid C# property
517 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
520 AParametersCollection param = null;
521 TypeSpec type = null;
524 param = get.Parameters;
525 type = get.ReturnType;
528 bool is_valid_property = true;
530 if (set.ReturnType.Kind != MemberKind.Void)
531 is_valid_property = false;
533 var set_param_count = set.Parameters.Count - 1;
535 if (set_param_count < 0) {
537 is_valid_property = false;
540 var set_type = set.Parameters.Types[set_param_count];
543 AParametersCollection set_based_param;
545 if (set_param_count == 0) {
546 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
549 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
551 var data = new IParameterData[set_param_count];
552 var types = new TypeSpec[set_param_count];
553 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
554 Array.Copy (set.Parameters.Types, types, set_param_count);
555 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
559 param = set_based_param;
562 if (set_param_count != get.Parameters.Count)
563 is_valid_property = false;
565 if (get.ReturnType != set_type)
566 is_valid_property = false;
568 // Possible custom accessor modifiers
569 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
570 var get_acc = mod & Modifiers.AccessibilityMask;
571 if (get_acc != Modifiers.PUBLIC) {
572 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
573 // If the accessor modifiers are not same, do extra restriction checks
574 if (get_acc != set_acc) {
575 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
576 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
577 if (get_restr && set_restr) {
578 is_valid_property = false; // Neither is more restrictive
582 mod &= ~Modifiers.AccessibilityMask;
591 PropertySpec spec = null;
592 if (!param.IsEmpty) {
593 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
594 if (index_name == null) {
595 is_valid_property = false;
599 is_valid_property = false;
600 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
601 is_valid_property = false;
605 is_valid_property = false;
606 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
607 is_valid_property = false;
611 if (is_valid_property)
612 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
616 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
618 if (!is_valid_property) {
619 spec.IsNotCSharpCompatible = true;
631 public TypeSpec CreateType (MetaType type)
633 return CreateType (type, new DynamicTypeReader (), true);
636 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
638 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
641 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
643 TypeSpec declaring_type;
644 if (type.IsNested && !type.IsGenericParameter)
645 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
647 declaring_type = null;
649 return CreateType (type, declaring_type, dtype, canImportBaseType);
652 TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
655 if (import_cache.TryGetValue (type, out spec)) {
656 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
657 if (dtype.IsDynamicObject (this))
658 return module.Compiler.BuiltinTypes.Dynamic;
663 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
666 if (!dtype.HasDynamicAttribute (this))
669 // We've found same object in the cache but this one has a dynamic custom attribute
670 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
671 // Do type resolve process again in that case
673 // TODO: Handle cases where they still unify
676 if (IsMissingType (type)) {
677 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
678 spec.MemberCache = MemberCache.Empty;
679 import_cache.Add (type, spec);
683 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
684 var type_def = type.GetGenericTypeDefinition ();
686 // Generic type definition can also be forwarded
687 if (compiled_types.TryGetValue (type_def, out spec))
690 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
691 if (declaringType == null) {
692 // Simple case, no nesting
693 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
694 spec = spec.MakeGenericType (module, targs);
697 // Nested type case, converting .NET types like
698 // A`1.B`1.C`1<int, long, string> to typespec like
699 // A<int>.B<long>.C<string>
701 var nested_hierarchy = new List<TypeSpec> ();
702 while (declaringType.IsNested) {
703 nested_hierarchy.Add (declaringType);
704 declaringType = declaringType.DeclaringType;
708 if (declaringType.Arity > 0) {
709 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
710 targs_pos = spec.Arity;
712 spec = declaringType;
715 for (int i = nested_hierarchy.Count; i != 0; --i) {
716 var t = nested_hierarchy [i - 1];
717 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
719 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
720 targs_pos += t.Arity;
724 string name = type.Name;
725 int index = name.IndexOf ('`');
727 name = name.Substring (0, index);
729 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
733 if (spec.Arity > 0) {
734 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
738 // Don't add generic type with dynamic arguments, they can interfere with same type
739 // using object type arguments
740 if (!spec.HasDynamicElement) {
742 // Add to reading cache to speed up reading
743 if (!import_cache.ContainsKey (type))
744 import_cache.Add (type, spec);
753 var ma = type.Attributes;
754 switch (ma & TypeAttributes.VisibilityMask) {
755 case TypeAttributes.Public:
756 case TypeAttributes.NestedPublic:
757 mod = Modifiers.PUBLIC;
759 case TypeAttributes.NestedPrivate:
760 mod = Modifiers.PRIVATE;
762 case TypeAttributes.NestedFamily:
763 mod = Modifiers.PROTECTED;
765 case TypeAttributes.NestedFamORAssem:
766 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
769 mod = Modifiers.INTERNAL;
773 if ((ma & TypeAttributes.Interface) != 0) {
774 kind = MemberKind.Interface;
775 } else if (type.IsGenericParameter) {
776 kind = MemberKind.TypeParameter;
778 var base_type = type.BaseType;
779 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
780 kind = MemberKind.Class;
782 kind = DetermineKindFromBaseType (base_type);
783 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
784 mod |= Modifiers.SEALED;
788 if (kind == MemberKind.Class) {
789 if ((ma & TypeAttributes.Sealed) != 0) {
790 mod |= Modifiers.SEALED;
791 if ((ma & TypeAttributes.Abstract) != 0)
792 mod |= Modifiers.STATIC;
793 } else if ((ma & TypeAttributes.Abstract) != 0) {
794 mod |= Modifiers.ABSTRACT;
799 var definition = new ImportedTypeDefinition (type, this);
802 if (kind == MemberKind.Enum) {
803 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
804 BindingFlags.Instance |
805 BindingFlags.Public | BindingFlags.NonPublic;
807 var type_members = type.GetFields (underlying_member);
808 foreach (var type_member in type_members) {
809 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
814 kind = MemberKind.Class;
816 } else if (kind == MemberKind.TypeParameter) {
817 spec = CreateTypeParameter (type, declaringType);
818 } else if (type.IsGenericTypeDefinition) {
819 definition.TypeParameters = CreateGenericParameters (type, declaringType);
820 } else if (compiled_types.TryGetValue (type, out pt)) {
822 // Same type was found in inside compiled types. It's
823 // either build-in type or forward referenced typed
824 // which point into just compiled assembly.
827 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
829 bts.SetDefinition (definition, type, mod);
833 spec = new TypeSpec (kind, declaringType, definition, type, mod);
835 import_cache.Add (type, spec);
838 // Two stage setup as the base type can be inflated declaring type or
839 // another nested type inside same declaring type which has not been
840 // loaded, therefore we can import a base type of nested types once
841 // the types have been imported
843 if (canImportBaseType)
844 ImportTypeBase (spec, type);
849 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
851 IAssemblyDefinition found;
852 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
854 // This can happen in dynamic context only
855 var def = new ImportedAssemblyDefinition (assembly);
856 assembly_2_definition.Add (assembly, def);
857 def.ReadAttributes ();
864 public void ImportTypeBase (MetaType type)
866 TypeSpec spec = import_cache[type];
868 ImportTypeBase (spec, type);
871 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
874 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
875 case GenericParameterAttributes.Covariant:
876 variance = Variance.Covariant;
878 case GenericParameterAttributes.Contravariant:
879 variance = Variance.Contravariant;
882 variance = Variance.None;
886 SpecialConstraint special = SpecialConstraint.None;
887 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
889 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
890 special |= SpecialConstraint.Struct;
891 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
892 special = SpecialConstraint.Constructor;
895 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
896 special |= SpecialConstraint.Class;
899 TypeParameterSpec spec;
900 var def = new ImportedTypeParameterDefinition (type, this);
901 if (type.DeclaringMethod != null) {
902 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
904 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
911 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
912 // they can be assembly specific therefore we do check based on names only
914 public bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
916 if (attributesData.Count == 0)
919 foreach (var attr in attributesData) {
920 var dt = attr.Constructor.DeclaringType;
921 if (dt.Name == attrName && dt.Namespace == attrNamespace)
928 void ImportTypeBase (TypeSpec spec, MetaType type)
930 if (spec.Kind == MemberKind.Interface)
931 spec.BaseType = module.Compiler.BuiltinTypes.Object;
932 else if (type.BaseType != null) {
934 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
935 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
937 base_type = CreateType (type.BaseType);
939 spec.BaseType = base_type;
944 ifaces = type.__GetDeclaredInterfaces ();
945 if (ifaces.Length != 0) {
946 foreach (var iface in ifaces) {
947 var it = CreateType (iface);
951 spec.AddInterface (it);
953 // Unfortunately not all languages expand inherited interfaces
954 var bifaces = it.Interfaces;
955 if (bifaces != null) {
956 foreach (var biface in bifaces) {
957 spec.AddInterface (biface);
963 if (spec.BaseType != null) {
964 var bifaces = spec.BaseType.Interfaces;
965 if (bifaces != null) {
966 foreach (var iface in bifaces)
967 spec.AddInterface (iface);
971 ifaces = type.GetInterfaces ();
973 if (ifaces.Length > 0) {
974 foreach (var iface in ifaces) {
975 spec.AddInterface (CreateType (iface));
980 if (spec.MemberDefinition.TypeParametersCount > 0) {
981 foreach (var tp in spec.MemberDefinition.TypeParameters) {
982 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
988 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
990 Namespace ns = targetNamespace;
991 string prev_namespace = null;
992 foreach (var t in types) {
996 // Be careful not to trigger full parent type loading
997 if (t.MemberType == MemberTypes.NestedType)
1000 if (t.Name[0] == '<')
1003 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1007 if (prev_namespace != t.Namespace) {
1008 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1009 prev_namespace = t.Namespace;
1012 ns.AddType (module, it);
1014 if (it.IsStatic && hasExtensionTypes &&
1015 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1016 it.SetExtensionMethodContainer ();
1021 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1023 var constraints = type.GetGenericParameterConstraints ();
1024 List<TypeSpec> tparams = null;
1025 foreach (var ct in constraints) {
1026 if (ct.IsGenericParameter) {
1027 if (tparams == null)
1028 tparams = new List<TypeSpec> ();
1030 tparams.Add (CreateType (ct));
1034 if (!IsMissingType (ct) && ct.IsClass) {
1035 spec.BaseType = CreateType (ct);
1039 spec.AddInterface (CreateType (ct));
1042 if (spec.BaseType == null)
1043 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1045 if (tparams != null)
1046 spec.TypeArguments = tparams.ToArray ();
1049 Constant ImportParameterConstant (object value)
1052 // Get type of underlying value as int constant can be used for object
1053 // parameter type. This is not allowed in C# but other languages can do that
1055 var types = module.Compiler.BuiltinTypes;
1056 switch (System.Type.GetTypeCode (value.GetType ())) {
1057 case TypeCode.Boolean:
1058 return new BoolConstant (types, (bool) value, Location.Null);
1060 return new ByteConstant (types, (byte) value, Location.Null);
1062 return new CharConstant (types, (char) value, Location.Null);
1063 case TypeCode.Decimal:
1064 return new DecimalConstant (types, (decimal) value, Location.Null);
1065 case TypeCode.Double:
1066 return new DoubleConstant (types, (double) value, Location.Null);
1067 case TypeCode.Int16:
1068 return new ShortConstant (types, (short) value, Location.Null);
1069 case TypeCode.Int32:
1070 return new IntConstant (types, (int) value, Location.Null);
1071 case TypeCode.Int64:
1072 return new LongConstant (types, (long) value, Location.Null);
1073 case TypeCode.SByte:
1074 return new SByteConstant (types, (sbyte) value, Location.Null);
1075 case TypeCode.Single:
1076 return new FloatConstant (types, (float) value, Location.Null);
1077 case TypeCode.String:
1078 return new StringConstant (types, (string) value, Location.Null);
1079 case TypeCode.UInt16:
1080 return new UShortConstant (types, (ushort) value, Location.Null);
1081 case TypeCode.UInt32:
1082 return new UIntConstant (types, (uint) value, Location.Null);
1083 case TypeCode.UInt64:
1084 return new ULongConstant (types, (ulong) value, Location.Null);
1087 throw new NotImplementedException (value.GetType ().ToString ());
1090 public TypeSpec ImportType (MetaType type)
1092 return ImportType (type, new DynamicTypeReader (type));
1095 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1097 if (type.HasElementType) {
1098 var element = type.GetElementType ();
1100 var spec = ImportType (element, dtype);
1103 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1105 return ReferenceContainer.MakeType (module, spec);
1107 return PointerContainer.MakeType (module, spec);
1109 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1112 return CreateType (type, dtype, true);
1115 static bool IsMissingType (MetaType type)
1118 return type.__IsMissing;
1125 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1126 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1127 // DecimalConstantAttribute metadata.
1129 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1131 if (attrs.Count == 0)
1134 foreach (var ca in attrs) {
1135 var dt = ca.Constructor.DeclaringType;
1136 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1139 var value = new decimal (
1140 (int) (uint) ca.ConstructorArguments[4].Value,
1141 (int) (uint) ca.ConstructorArguments[3].Value,
1142 (int) (uint) ca.ConstructorArguments[2].Value,
1143 (byte) ca.ConstructorArguments[1].Value != 0,
1144 (byte) ca.ConstructorArguments[0].Value);
1146 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1152 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1155 var ma = mb.Attributes;
1156 switch (ma & MethodAttributes.MemberAccessMask) {
1157 case MethodAttributes.Public:
1158 mod = Modifiers.PUBLIC;
1160 case MethodAttributes.Assembly:
1161 mod = Modifiers.INTERNAL;
1163 case MethodAttributes.Family:
1164 mod = Modifiers.PROTECTED;
1166 case MethodAttributes.FamORAssem:
1167 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1170 mod = Modifiers.PRIVATE;
1174 if ((ma & MethodAttributes.Static) != 0) {
1175 mod |= Modifiers.STATIC;
1178 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1179 mod |= Modifiers.ABSTRACT;
1183 // It can be sealed and override
1184 if ((ma & MethodAttributes.Final) != 0)
1185 mod |= Modifiers.SEALED;
1187 if ((ma & MethodAttributes.Virtual) != 0) {
1188 // Not every member can be detected based on MethodAttribute, we
1189 // set virtual or non-virtual only when we are certain. Further checks
1190 // to really find out what `virtual' means for this member are done
1192 if ((ma & MethodAttributes.NewSlot) != 0) {
1193 if ((mod & Modifiers.SEALED) != 0) {
1194 mod &= ~Modifiers.SEALED;
1196 mod |= Modifiers.VIRTUAL;
1199 mod |= Modifiers.OVERRIDE;
1207 abstract class ImportedDefinition : IMemberDefinition
1209 protected class AttributesBag
1211 public static readonly AttributesBag Default = new AttributesBag ();
1213 public AttributeUsageAttribute AttributeUsage;
1214 public ObsoleteAttribute Obsolete;
1215 public string[] Conditionals;
1216 public string DefaultIndexerName;
1217 public bool? CLSAttributeValue;
1218 public TypeSpec CoClass;
1220 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1222 AttributesBag bag = null;
1223 List<string> conditionals = null;
1225 // It should not throw any loading exception
1226 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1228 foreach (var a in attrs) {
1229 var dt = a.Constructor.DeclaringType;
1230 string name = dt.Name;
1231 if (name == "ObsoleteAttribute") {
1232 if (dt.Namespace != "System")
1236 bag = new AttributesBag ();
1238 var args = a.ConstructorArguments;
1240 if (args.Count == 1) {
1241 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1242 } else if (args.Count == 2) {
1243 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1245 bag.Obsolete = new ObsoleteAttribute ();
1251 if (name == "ConditionalAttribute") {
1252 if (dt.Namespace != "System.Diagnostics")
1256 bag = new AttributesBag ();
1258 if (conditionals == null)
1259 conditionals = new List<string> (2);
1261 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1265 if (name == "CLSCompliantAttribute") {
1266 if (dt.Namespace != "System")
1270 bag = new AttributesBag ();
1272 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1276 // Type only attributes
1277 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1278 if (name == "DefaultMemberAttribute") {
1279 if (dt.Namespace != "System.Reflection")
1283 bag = new AttributesBag ();
1285 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1289 if (name == "AttributeUsageAttribute") {
1290 if (dt.Namespace != "System")
1294 bag = new AttributesBag ();
1296 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1297 foreach (var named in a.NamedArguments) {
1298 if (named.MemberInfo.Name == "AllowMultiple")
1299 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1300 else if (named.MemberInfo.Name == "Inherited")
1301 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1306 // Interface only attribute
1307 if (name == "CoClassAttribute") {
1308 if (dt.Namespace != "System.Runtime.InteropServices")
1312 bag = new AttributesBag ();
1314 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1323 if (conditionals != null)
1324 bag.Conditionals = conditionals.ToArray ();
1330 protected readonly MemberInfo provider;
1331 protected AttributesBag cattrs;
1332 protected readonly MetadataImporter importer;
1334 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1336 this.provider = provider;
1337 this.importer = importer;
1342 public bool IsImported {
1348 public virtual string Name {
1350 return provider.Name;
1356 public string[] ConditionalConditions ()
1361 return cattrs.Conditionals;
1364 public ObsoleteAttribute GetAttributeObsolete ()
1369 return cattrs.Obsolete;
1372 public bool? CLSAttributeValue {
1377 return cattrs.CLSAttributeValue;
1381 protected void ReadAttributes ()
1383 cattrs = AttributesBag.Read (provider, importer);
1386 public void SetIsAssigned ()
1388 // Unused for imported members
1391 public void SetIsUsed ()
1393 // Unused for imported members
1397 public class ImportedModuleDefinition
1399 readonly Module module;
1402 public ImportedModuleDefinition (Module module)
1404 this.module = module;
1409 public bool IsCLSCompliant {
1411 return cls_compliant;
1415 public string Name {
1423 public void ReadAttributes ()
1425 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1427 foreach (var a in attrs) {
1428 var dt = a.Constructor.DeclaringType;
1429 if (dt.Name == "CLSCompliantAttribute") {
1430 if (dt.Namespace != "System")
1433 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1440 // Reads assembly attributes which where attached to a special type because
1441 // module does have assembly manifest
1443 public List<Attribute> ReadAssemblyAttributes ()
1445 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1449 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1453 // TODO: implement, the idea is to fabricate specil Attribute class and
1454 // add it to OptAttributes before resolving the source code attributes
1455 // Need to build module location as well for correct error reporting
1457 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1458 //var attrs = new List<Attribute> (assembly_attributes.Count);
1459 //foreach (var a in assembly_attributes)
1461 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1462 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1464 // foreach (var carg in a.ConstructorArguments) {
1468 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1475 public class ImportedAssemblyDefinition : IAssemblyDefinition
1477 readonly Assembly assembly;
1478 readonly AssemblyName aname;
1480 bool contains_extension_methods;
1482 List<AssemblyName> internals_visible_to;
1483 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1485 public ImportedAssemblyDefinition (Assembly assembly)
1487 this.assembly = assembly;
1488 this.aname = assembly.GetName ();
1493 public Assembly Assembly {
1499 public string FullName {
1501 return aname.FullName;
1505 public bool HasExtensionMethod {
1507 return contains_extension_methods;
1511 public bool HasStrongName {
1513 return aname.GetPublicKey ().Length != 0;
1517 public bool IsMissing {
1520 return assembly.__IsMissing;
1527 public bool IsCLSCompliant {
1529 return cls_compliant;
1533 public string Location {
1535 return assembly.Location;
1539 public string Name {
1547 public byte[] GetPublicKeyToken ()
1549 return aname.GetPublicKeyToken ();
1552 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1554 return internals_visible_to_cache [assembly];
1557 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1559 if (internals_visible_to == null)
1562 AssemblyName is_visible = null;
1563 if (internals_visible_to_cache == null) {
1564 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1566 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1567 return is_visible != null;
1570 var token = assembly.GetPublicKeyToken ();
1571 if (token != null && token.Length == 0)
1574 foreach (var internals in internals_visible_to) {
1575 if (internals.Name != assembly.Name)
1578 if (token == null && assembly is AssemblyDefinition) {
1579 is_visible = internals;
1583 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1586 is_visible = internals;
1590 internals_visible_to_cache.Add (assembly, is_visible);
1591 return is_visible != null;
1594 public void ReadAttributes ()
1597 if (assembly.__IsMissing)
1601 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1603 foreach (var a in attrs) {
1604 var dt = a.Constructor.DeclaringType;
1606 if (name == "CLSCompliantAttribute") {
1607 if (dt.Namespace == "System") {
1608 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1613 if (name == "InternalsVisibleToAttribute") {
1614 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1617 string s = a.ConstructorArguments[0].Value as string;
1621 var an = new AssemblyName (s);
1622 if (internals_visible_to == null)
1623 internals_visible_to = new List<AssemblyName> ();
1625 internals_visible_to.Add (an);
1629 if (name == "ExtensionAttribute") {
1630 if (dt.Namespace == MetadataImporter.CompilerServicesNamespace)
1631 contains_extension_methods = true;
1638 public override string ToString ()
1644 class ImportedMemberDefinition : ImportedDefinition
1646 readonly TypeSpec type;
1648 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1649 : base (member, importer)
1656 public TypeSpec MemberType {
1665 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1667 readonly AParametersCollection parameters;
1669 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1670 : base (provider, type, importer)
1672 this.parameters = parameters;
1675 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1676 : base (provider, type, importer)
1678 this.parameters = parameters;
1683 public AParametersCollection Parameters {
1692 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1694 readonly TypeParameterSpec[] tparams;
1696 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1697 : base (provider, type, parameters, importer)
1699 this.tparams = tparams;
1704 public TypeParameterSpec[] TypeParameters {
1710 public int TypeParametersCount {
1712 return tparams.Length;
1719 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1721 TypeParameterSpec[] tparams;
1724 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1725 : base (type, importer)
1731 public IAssemblyDefinition DeclaringAssembly {
1733 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1737 public override string Name {
1741 if (tparams != null) {
1742 int arity_start = name.IndexOf ('`');
1743 if (arity_start > 0)
1744 name = name.Substring (0, arity_start);
1752 public string Namespace {
1754 return ((MetaType) provider).Namespace;
1758 public int TypeParametersCount {
1760 return tparams == null ? 0 : tparams.Length;
1764 public TypeParameterSpec[] TypeParameters {
1775 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1778 // Report details about missing type and most likely cause of the problem.
1779 // csc reports 1683, 1684 as warnings but we report them only when used
1780 // or referenced from the user core in which case compilation error has to
1781 // be reported because compiler cannot continue anyway
1783 foreach (var t in types) {
1784 string name = t.GetSignatureForError ();
1786 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1787 ctx.Module.Compiler.Report.Error (1683, loc,
1788 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1790 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1791 ctx.Module.Compiler.Report.Error (12, loc,
1792 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1793 name, t.MemberDefinition.DeclaringAssembly.FullName);
1795 ctx.Module.Compiler.Report.Error (1684, loc,
1796 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1797 name, t.MemberDefinition.DeclaringAssembly.FullName);
1802 public TypeSpec GetAttributeCoClass ()
1807 return cattrs.CoClass;
1810 public string GetAttributeDefaultMember ()
1815 return cattrs.DefaultIndexerName;
1818 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1823 return cattrs.AttributeUsage;
1826 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1828 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1829 return a == assembly || a.IsFriendAssemblyTo (assembly);
1832 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1835 // Not interested in members of nested private types unless the importer needs them
1837 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1838 cache = MemberCache.Empty;
1842 var loading_type = (MetaType) provider;
1843 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1844 BindingFlags.Static | BindingFlags.Instance |
1845 BindingFlags.Public | BindingFlags.NonPublic;
1847 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1848 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1849 MethodAttributes.Final;
1851 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1852 List<EventSpec> imported_events = null;
1853 EventSpec event_spec;
1854 MemberSpec imported;
1858 all = loading_type.GetMembers (all_members);
1859 } catch (Exception e) {
1860 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1861 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1864 if (cache == null) {
1865 cache = new MemberCache (all.Length);
1868 // Do the types first as they can be referenced by the members before
1869 // they are found or inflated
1871 foreach (var member in all) {
1872 if (member.MemberType != MemberTypes.NestedType)
1875 var t = (MetaType) member;
1877 // Ignore compiler generated types, mostly lambda containers
1878 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1881 imported = importer.CreateNestedType (t, declaringType);
1882 cache.AddMemberImported (imported);
1885 foreach (var member in all) {
1886 if (member.MemberType != MemberTypes.NestedType)
1889 var t = (MetaType) member;
1891 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1894 importer.ImportTypeBase (t);
1899 // Load base interfaces first to minic behaviour of compiled members
1901 if (declaringType.IsInterface && declaringType.Interfaces != null) {
1902 foreach (var iface in declaringType.Interfaces) {
1903 cache.AddInterface (iface);
1909 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1911 foreach (var member in all) {
1912 switch (member.MemberType) {
1913 case MemberTypes.Constructor:
1914 case MemberTypes.Method:
1915 MethodBase mb = (MethodBase) member;
1916 var attrs = mb.Attributes;
1918 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1919 if (importer.IgnorePrivateMembers)
1922 // Ignore explicitly implemented members
1923 if ((attrs & explicit_impl) == explicit_impl)
1926 // Ignore compiler generated methods
1927 if (importer.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1931 imported = importer.CreateMethod (mb, declaringType);
1932 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1933 if (possible_accessors == null)
1934 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1936 // There are no metadata rules for accessors, we have to consider any method as possible candidate
1937 possible_accessors.Add (mb, (MethodSpec) imported);
1941 case MemberTypes.Property:
1942 if (possible_accessors == null)
1945 var p = (PropertyInfo) member;
1947 // Links possible accessors with property
1949 MethodSpec get, set;
1950 m = p.GetGetMethod (true);
1951 if (m == null || !possible_accessors.TryGetValue (m, out get))
1954 m = p.GetSetMethod (true);
1955 if (m == null || !possible_accessors.TryGetValue (m, out set))
1958 // No accessors registered (e.g. explicit implementation)
1959 if (get == null && set == null)
1962 imported = importer.CreateProperty (p, declaringType, get, set);
1963 if (imported == null)
1967 case MemberTypes.Event:
1968 if (possible_accessors == null)
1971 var e = (EventInfo) member;
1973 // Links accessors with event
1975 MethodSpec add, remove;
1976 m = e.GetAddMethod (true);
1977 if (m == null || !possible_accessors.TryGetValue (m, out add))
1980 m = e.GetRemoveMethod (true);
1981 if (m == null || !possible_accessors.TryGetValue (m, out remove))
1984 // Both accessors are required
1985 if (add == null || remove == null)
1988 event_spec = importer.CreateEvent (e, declaringType, add, remove);
1989 if (!importer.IgnorePrivateMembers) {
1990 if (imported_events == null)
1991 imported_events = new List<EventSpec> ();
1993 imported_events.Add (event_spec);
1996 imported = event_spec;
1998 case MemberTypes.Field:
1999 var fi = (FieldInfo) member;
2001 imported = importer.CreateField (fi, declaringType);
2002 if (imported == null)
2006 // For dynamic binder event has to be fully restored to allow operations
2007 // within the type container to work correctly
2009 if (imported_events != null) {
2010 // The backing event field should be private but it may not
2012 for (i = 0; i < imported_events.Count; ++i) {
2013 var ev = imported_events[i];
2014 if (ev.Name == fi.Name) {
2015 ev.BackingField = (FieldSpec) imported;
2016 imported_events.RemoveAt (i);
2027 case MemberTypes.NestedType:
2028 // Already in the cache from the first pass
2031 throw new NotImplementedException (member.ToString ());
2034 cache.AddMemberImported (imported);
2040 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2042 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2043 : base (type, importer)
2049 public IAssemblyDefinition DeclaringAssembly {
2051 throw new NotImplementedException ();
2055 public string Namespace {
2061 public int TypeParametersCount {
2067 public TypeParameterSpec[] TypeParameters {
2075 public TypeSpec GetAttributeCoClass ()
2080 public string GetAttributeDefaultMember ()
2082 throw new NotSupportedException ();
2085 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2087 throw new NotSupportedException ();
2090 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2092 throw new NotImplementedException ();
2095 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2097 throw new NotImplementedException ();