2 // import.cs: System.Reflection conversions
4 // Authors: Marek Safar (marek.safar@gmail.com)
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 // Copyright 2009, 2010 Novell, Inc
12 using System.Runtime.CompilerServices;
14 using System.Collections.Generic;
17 using MetaType = IKVM.Reflection.Type;
18 using IKVM.Reflection;
19 using IKVM.Reflection.Emit;
21 using MetaType = System.Type;
22 using System.Reflection;
23 using System.Reflection.Emit;
28 public abstract class MetadataImporter
31 // Dynamic types reader with additional logic to reconstruct a dynamic
32 // type using DynamicAttribute values
34 struct DynamicTypeReader
36 static readonly bool[] single_attribute = { true };
41 // There is no common type for CustomAttributeData and we cannot
42 // use ICustomAttributeProvider
46 // A member provider which can be used to get CustomAttributeData
48 public DynamicTypeReader (object provider)
52 this.provider = provider;
56 // Returns true when object at local position has dynamic attribute flag
58 public bool IsDynamicObject (MetadataImporter importer)
61 ReadAttribute (importer);
63 return flags != null && Position < flags.Length && flags[Position];
67 // Returns true when DynamicAttribute exists
69 public bool HasDynamicAttribute (MetadataImporter importer)
72 ReadAttribute (importer);
77 void ReadAttribute (MetadataImporter importer)
79 IList<CustomAttributeData> cad;
80 if (provider is MemberInfo) {
81 cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
82 } else if (provider is ParameterInfo) {
83 cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
91 foreach (var ca in cad) {
92 importer.GetCustomAttributeTypeName (ca, out ns, out name);
93 if (name != "DynamicAttribute" && ns != CompilerServicesNamespace)
96 if (ca.ConstructorArguments.Count == 0) {
97 flags = single_attribute;
101 var arg_type = ca.ConstructorArguments[0].ArgumentType;
103 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
104 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
105 flags = new bool[carg.Count];
106 for (int i = 0; i < flags.Length; ++i) {
107 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
108 flags[i] = (bool) carg[i].Value;
120 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
121 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
122 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
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);
152 public abstract void GetCustomAttributeTypeName (CustomAttributeData cad, out string typeNamespace, out string typeName);
154 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
157 var fa = fi.Attributes;
158 switch (fa & FieldAttributes.FieldAccessMask) {
159 case FieldAttributes.Public:
160 mod = Modifiers.PUBLIC;
162 case FieldAttributes.Assembly:
163 mod = Modifiers.INTERNAL;
165 case FieldAttributes.Family:
166 mod = Modifiers.PROTECTED;
168 case FieldAttributes.FamORAssem:
169 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
172 // Ignore private fields (even for error reporting) to not require extra dependencies
173 if (IgnorePrivateMembers || HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
176 mod = Modifiers.PRIVATE;
183 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
184 } catch (Exception e) {
185 // TODO: I should construct fake TypeSpec based on TypeRef signature
186 // but there is no way to do it with System.Reflection
187 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
188 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
191 var definition = new ImportedMemberDefinition (fi, field_type, this);
193 if ((fa & FieldAttributes.Literal) != 0) {
194 var c = Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
195 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
198 if ((fa & FieldAttributes.InitOnly) != 0) {
199 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
200 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
202 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
205 mod |= Modifiers.READONLY;
207 var req_mod = fi.GetRequiredCustomModifiers ();
208 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
209 mod |= Modifiers.VOLATILE;
212 if ((fa & FieldAttributes.Static) != 0) {
213 mod |= Modifiers.STATIC;
215 // Fixed buffers cannot be static
216 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
217 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
219 // TODO: Sanity check on field_type (only few types are allowed)
220 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
221 return new FixedFieldSpec (declaringType, definition, fi, element_field, mod);
225 return new FieldSpec (declaringType, definition, field_type, fi, mod);
228 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
230 add.IsAccessor = true;
231 remove.IsAccessor = true;
233 if (add.Modifiers != remove.Modifiers)
234 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
236 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
237 var definition = new ImportedMemberDefinition (ei, event_type, this);
238 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
241 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
243 var tparams = type.GetGenericArguments ();
245 int parent_owned_count;
247 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
250 // System.Reflection duplicates parent type parameters for each
251 // nested type with slightly modified properties (eg. different owner)
252 // This just makes things more complicated (think of cloned constraints)
253 // therefore we remap any nested type owned by parent using `type_cache'
254 // to the single TypeParameterSpec
256 if (declaringType != null && parent_owned_count > 0) {
258 while (read_count != parent_owned_count) {
259 var tparams_count = declaringType.Arity;
260 if (tparams_count != 0) {
261 var parent_tp = declaringType.MemberDefinition.TypeParameters;
262 read_count += tparams_count;
263 for (int i = 0; i < tparams_count; i++) {
264 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
268 declaringType = declaringType.DeclaringType;
272 parent_owned_count = 0;
275 if (tparams.Length - parent_owned_count == 0)
278 return CreateGenericParameters (parent_owned_count, tparams);
281 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
283 var tspec = new TypeParameterSpec[tparams.Length - first];
284 for (int pos = first; pos < tparams.Length; ++pos) {
285 var type = tparams[pos];
286 int index = pos - first;
288 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
294 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
298 var tspec = new TypeSpec [tparams.Length - first];
299 for (int pos = first; pos < tparams.Length; ++pos) {
300 var type = tparams[pos];
301 int index = pos - first;
304 if (type.HasElementType) {
305 var element = type.GetElementType ();
307 spec = ImportType (element, dtype);
310 throw new NotImplementedException ("Unknown element type " + type.ToString ());
313 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
315 spec = CreateType (type, dtype, true);
318 // We treat nested generic types as inflated internally where
319 // reflection uses type definition
322 // IFoo<A<T>> foo; // A<T> is definition in this case
325 // TODO: Is full logic from CreateType needed here as well?
327 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
328 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
329 spec = spec.MakeGenericType (module, targs);
340 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
342 Modifiers mod = ReadMethodModifiers (mb, declaringType);
343 TypeParameterSpec[] tparams;
345 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
347 if (mb.IsGenericMethod) {
348 if (!mb.IsGenericMethodDefinition)
349 throw new NotSupportedException ("assert");
351 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
358 if (mb.MemberType == MemberTypes.Constructor) {
359 kind = MemberKind.Constructor;
360 returnType = module.Compiler.BuiltinTypes.Void;
363 // Detect operators and destructors
365 string name = mb.Name;
366 kind = MemberKind.Method;
367 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
368 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
369 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
370 var op_type = Operator.GetType (name);
371 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
372 kind = MemberKind.Operator;
375 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
376 kind = MemberKind.Destructor;
377 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
378 mod &= ~Modifiers.OVERRIDE;
379 mod |= Modifiers.VIRTUAL;
384 var mi = (MethodInfo) mb;
385 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
387 // Cannot set to OVERRIDE without full hierarchy checks
388 // this flag indicates that the method could be override
389 // but further validation is needed
390 if ((mod & Modifiers.OVERRIDE) != 0) {
391 bool is_real_override = false;
392 if (kind == MemberKind.Method && declaringType.BaseType != null) {
393 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
394 var candidate = MemberCache.FindMember (declaringType.BaseType, filter, BindingRestriction.None);
397 // For imported class method do additional validation to be sure that metadata
398 // override flag was correct
400 // Difference between protected internal and protected is ok
402 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
403 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
404 is_real_override = true;
408 if (!is_real_override) {
409 mod &= ~Modifiers.OVERRIDE;
410 if ((mod & Modifiers.SEALED) != 0)
411 mod &= ~Modifiers.SEALED;
413 mod |= Modifiers.VIRTUAL;
418 IMemberDefinition definition;
419 if (tparams != null) {
420 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
421 foreach (var tp in gmd.TypeParameters) {
422 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
427 definition = new ImportedParameterMemberDefinition (mb, returnType, parameters, this);
430 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, mb, parameters, mod);
438 // Imports System.Reflection parameters
440 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
442 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
444 if (pi.Length == 0 && varargs == 0)
445 return ParametersCompiled.EmptyReadOnlyParameters;
447 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
448 IParameterData[] par = new IParameterData[pi.Length + varargs];
449 bool is_params = false;
450 for (int i = 0; i < pi.Length; i++) {
451 ParameterInfo p = pi[i];
452 Parameter.Modifier mod = 0;
453 Expression default_value = null;
454 if (p.ParameterType.IsByRef) {
455 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
456 mod = Parameter.Modifier.OUT;
458 mod = Parameter.Modifier.REF;
461 // Strip reference wrapping
463 var el = p.ParameterType.GetElementType ();
464 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
465 } else if (i == 0 && method.IsStatic && parent.IsStatic && parent.MemberDefinition.DeclaringAssembly.HasExtensionMethod &&
466 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
467 mod = Parameter.Modifier.This;
468 types[i] = ImportType (p.ParameterType);
470 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
472 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
473 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
474 mod = Parameter.Modifier.PARAMS;
479 if (!is_params && p.IsOptional) {
480 object value = p.RawDefaultValue;
481 var ptype = types[i];
482 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeManager.IsReferenceType (ptype))) {
484 default_value = Constant.CreateConstant (ptype, null, Location.Null);
486 default_value = ImportParameterConstant (value);
489 default_value = new EnumConstant ((Constant) default_value, ptype);
492 } else if (value == Missing.Value) {
493 default_value = EmptyExpression.MissingValue;
494 } else if (value == null) {
495 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
496 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
497 default_value = ImportParameterConstant (value);
502 par[i] = new ParameterData (p.Name, mod, default_value);
506 par[par.Length - 1] = new ArglistParameter (Location.Null);
507 types[types.Length - 1] = InternalType.Arglist;
510 return method != null ?
511 new ParametersImported (par, types, varargs != 0, is_params) :
512 new ParametersImported (par, types, is_params);
516 // Returns null when the property is not valid C# property
518 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
521 AParametersCollection param = null;
522 TypeSpec type = null;
525 param = get.Parameters;
526 type = get.ReturnType;
529 bool is_valid_property = true;
531 if (set.ReturnType.Kind != MemberKind.Void)
532 is_valid_property = false;
534 var set_param_count = set.Parameters.Count - 1;
536 if (set_param_count < 0) {
538 is_valid_property = false;
541 var set_type = set.Parameters.Types[set_param_count];
544 AParametersCollection set_based_param;
546 if (set_param_count == 0) {
547 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
550 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
552 var data = new IParameterData[set_param_count];
553 var types = new TypeSpec[set_param_count];
554 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
555 Array.Copy (set.Parameters.Types, types, set_param_count);
556 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
560 param = set_based_param;
563 if (set_param_count != get.Parameters.Count)
564 is_valid_property = false;
566 if (get.ReturnType != set_type)
567 is_valid_property = false;
569 // Possible custom accessor modifiers
570 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
571 var get_acc = mod & Modifiers.AccessibilityMask;
572 if (get_acc != Modifiers.PUBLIC) {
573 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
574 // If the accessor modifiers are not same, do extra restriction checks
575 if (get_acc != set_acc) {
576 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
577 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
578 if (get_restr && set_restr) {
579 is_valid_property = false; // Neither is more restrictive
583 mod &= ~Modifiers.AccessibilityMask;
592 PropertySpec spec = null;
593 if (!param.IsEmpty) {
594 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
595 if (index_name == null) {
596 is_valid_property = false;
600 is_valid_property = false;
601 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
602 is_valid_property = false;
606 is_valid_property = false;
607 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
608 is_valid_property = false;
612 if (is_valid_property)
613 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
617 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
619 if (!is_valid_property) {
620 spec.IsNotRealProperty = true;
632 public TypeSpec CreateType (MetaType type)
634 return CreateType (type, new DynamicTypeReader (), true);
637 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
639 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
642 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
644 TypeSpec declaring_type;
645 if (type.IsNested && !type.IsGenericParameter)
646 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
648 declaring_type = null;
650 return CreateType (type, declaring_type, dtype, canImportBaseType);
653 TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
656 if (import_cache.TryGetValue (type, out spec)) {
657 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
658 if (dtype.IsDynamicObject (this))
659 return module.Compiler.BuiltinTypes.Dynamic;
664 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
667 if (!dtype.HasDynamicAttribute (this))
670 // We've found same object in the cache but this one has a dynamic custom attribute
671 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
672 // Do type resolve process again in that case
674 // TODO: Handle cases where they still unify
677 if (IsMissingType (type)) {
678 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
679 spec.MemberCache = MemberCache.Empty;
680 import_cache.Add (type, spec);
684 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
685 var type_def = type.GetGenericTypeDefinition ();
686 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
687 if (declaringType == null) {
688 // Simple case, no nesting
689 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
690 spec = spec.MakeGenericType (module, targs);
693 // Nested type case, converting .NET types like
694 // A`1.B`1.C`1<int, long, string> to typespec like
695 // A<int>.B<long>.C<string>
697 var nested_hierarchy = new List<TypeSpec> ();
698 while (declaringType.IsNested) {
699 nested_hierarchy.Add (declaringType);
700 declaringType = declaringType.DeclaringType;
704 if (declaringType.Arity > 0) {
705 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
706 targs_pos = spec.Arity;
708 spec = declaringType;
711 for (int i = nested_hierarchy.Count; i != 0; --i) {
712 var t = nested_hierarchy [i - 1];
713 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
715 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
716 targs_pos += t.Arity;
720 string name = type.Name;
721 int index = name.IndexOf ('`');
723 name = name.Substring (0, index);
725 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
729 if (spec.Arity > 0) {
730 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
734 // Don't add generic type with dynamic arguments, they can interfere with same type
735 // using object type arguments
736 if (!spec.HasDynamicElement) {
738 // Add to reading cache to speed up reading
739 if (!import_cache.ContainsKey (type))
740 import_cache.Add (type, spec);
749 var ma = type.Attributes;
750 switch (ma & TypeAttributes.VisibilityMask) {
751 case TypeAttributes.Public:
752 case TypeAttributes.NestedPublic:
753 mod = Modifiers.PUBLIC;
755 case TypeAttributes.NestedPrivate:
756 mod = Modifiers.PRIVATE;
758 case TypeAttributes.NestedFamily:
759 mod = Modifiers.PROTECTED;
761 case TypeAttributes.NestedFamORAssem:
762 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
765 mod = Modifiers.INTERNAL;
769 if ((ma & TypeAttributes.Interface) != 0) {
770 kind = MemberKind.Interface;
771 } else if (type.IsGenericParameter) {
772 kind = MemberKind.TypeParameter;
774 var base_type = type.BaseType;
775 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
776 kind = MemberKind.Class;
778 kind = DetermineKindFromBaseType (base_type);
779 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
780 mod |= Modifiers.SEALED;
784 if (kind == MemberKind.Class) {
785 if ((ma & TypeAttributes.Sealed) != 0) {
786 mod |= Modifiers.SEALED;
787 if ((ma & TypeAttributes.Abstract) != 0)
788 mod |= Modifiers.STATIC;
789 } else if ((ma & TypeAttributes.Abstract) != 0) {
790 mod |= Modifiers.ABSTRACT;
795 var definition = new ImportedTypeDefinition (type, this);
798 if (kind == MemberKind.Enum) {
799 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
800 BindingFlags.Instance |
801 BindingFlags.Public | BindingFlags.NonPublic;
803 var type_members = type.GetFields (underlying_member);
804 foreach (var type_member in type_members) {
805 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
810 kind = MemberKind.Class;
812 } else if (kind == MemberKind.TypeParameter) {
813 spec = CreateTypeParameter (type, declaringType);
814 } else if (type.IsGenericTypeDefinition) {
815 definition.TypeParameters = CreateGenericParameters (type, declaringType);
816 } else if (compiled_types.TryGetValue (type, out pt)) {
818 // Same type was found in inside compiled types. It's
819 // either build-in type or forward referenced typed
820 // which point into just compiled assembly.
823 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
825 bts.SetDefinition (definition, type, mod);
829 spec = new TypeSpec (kind, declaringType, definition, type, mod);
831 import_cache.Add (type, spec);
834 // Two stage setup as the base type can be inflated declaring type or
835 // another nested type inside same declaring type which has not been
836 // loaded, therefore we can import a base type of nested types once
837 // the types have been imported
839 if (canImportBaseType)
840 ImportTypeBase (spec, type);
845 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
847 IAssemblyDefinition found;
848 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
850 // This can happen in dynamic context only
851 var def = new ImportedAssemblyDefinition (assembly, this);
852 assembly_2_definition.Add (assembly, def);
853 def.ReadAttributes ();
860 public void ImportTypeBase (MetaType type)
862 TypeSpec spec = import_cache[type];
864 ImportTypeBase (spec, type);
867 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
870 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
871 case GenericParameterAttributes.Covariant:
872 variance = Variance.Covariant;
874 case GenericParameterAttributes.Contravariant:
875 variance = Variance.Contravariant;
878 variance = Variance.None;
882 SpecialConstraint special = SpecialConstraint.None;
883 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
885 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
886 special |= SpecialConstraint.Struct;
887 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
888 special = SpecialConstraint.Constructor;
891 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
892 special |= SpecialConstraint.Class;
895 TypeParameterSpec spec;
896 var def = new ImportedTypeParameterDefinition (type, this);
897 if (type.DeclaringMethod != null) {
898 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
900 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
907 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
908 // they can be assembly specific therefore we do check based on names only
910 public bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
912 if (attributesData.Count == 0)
916 foreach (var attr in attributesData) {
917 GetCustomAttributeTypeName (attr, out ns, out name);
918 if (name == attrName && ns == attrNamespace)
925 void ImportTypeBase (TypeSpec spec, MetaType type)
927 if (spec.Kind == MemberKind.Interface)
928 spec.BaseType = module.Compiler.BuiltinTypes.Object;
929 else if (type.BaseType != null) {
931 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
932 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
934 base_type = CreateType (type.BaseType);
936 spec.BaseType = base_type;
941 ifaces = type.__GetDeclaredInterfaces ();
942 if (ifaces.Length != 0) {
943 foreach (var iface in ifaces) {
944 var it = CreateType (iface);
948 spec.AddInterface (it);
950 // Unfortunately not all languages expand inherited interfaces
951 var bifaces = it.Interfaces;
952 if (bifaces != null) {
953 foreach (var biface in bifaces) {
954 spec.AddInterface (biface);
960 if (spec.BaseType != null) {
961 var bifaces = spec.BaseType.Interfaces;
962 if (bifaces != null) {
963 foreach (var iface in bifaces)
964 spec.AddInterface (iface);
968 ifaces = type.GetInterfaces ();
970 if (ifaces.Length > 0) {
971 foreach (var iface in ifaces) {
972 spec.AddInterface (CreateType (iface));
977 if (spec.MemberDefinition.TypeParametersCount > 0) {
978 foreach (var tp in spec.MemberDefinition.TypeParameters) {
979 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
985 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
987 Namespace ns = targetNamespace;
988 string prev_namespace = null;
989 foreach (var t in types) {
993 // Be careful not to trigger full parent type loading
994 if (t.MemberType == MemberTypes.NestedType)
997 if (t.Name[0] == '<')
1000 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1004 if (prev_namespace != t.Namespace) {
1005 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1006 prev_namespace = t.Namespace;
1009 ns.AddType (module, it);
1011 if (it.IsStatic && hasExtensionTypes &&
1012 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1013 it.SetExtensionMethodContainer ();
1018 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1020 var constraints = type.GetGenericParameterConstraints ();
1021 List<TypeSpec> tparams = null;
1022 foreach (var ct in constraints) {
1023 if (ct.IsGenericParameter) {
1024 if (tparams == null)
1025 tparams = new List<TypeSpec> ();
1027 tparams.Add (CreateType (ct));
1031 if (!IsMissingType (ct) && ct.IsClass) {
1032 spec.BaseType = CreateType (ct);
1036 spec.AddInterface (CreateType (ct));
1039 if (spec.BaseType == null)
1040 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1042 if (tparams != null)
1043 spec.TypeArguments = tparams.ToArray ();
1046 Constant ImportParameterConstant (object value)
1049 // Get type of underlying value as int constant can be used for object
1050 // parameter type. This is not allowed in C# but other languages can do that
1052 var types = module.Compiler.BuiltinTypes;
1053 switch (System.Type.GetTypeCode (value.GetType ())) {
1054 case TypeCode.Boolean:
1055 return new BoolConstant (types, (bool) value, Location.Null);
1057 return new ByteConstant (types, (byte) value, Location.Null);
1059 return new CharConstant (types, (char) value, Location.Null);
1060 case TypeCode.Decimal:
1061 return new DecimalConstant (types, (decimal) value, Location.Null);
1062 case TypeCode.Double:
1063 return new DoubleConstant (types, (double) value, Location.Null);
1064 case TypeCode.Int16:
1065 return new ShortConstant (types, (short) value, Location.Null);
1066 case TypeCode.Int32:
1067 return new IntConstant (types, (int) value, Location.Null);
1068 case TypeCode.Int64:
1069 return new LongConstant (types, (long) value, Location.Null);
1070 case TypeCode.SByte:
1071 return new SByteConstant (types, (sbyte) value, Location.Null);
1072 case TypeCode.Single:
1073 return new FloatConstant (types, (float) value, Location.Null);
1074 case TypeCode.String:
1075 return new StringConstant (types, (string) value, Location.Null);
1076 case TypeCode.UInt16:
1077 return new UShortConstant (types, (ushort) value, Location.Null);
1078 case TypeCode.UInt32:
1079 return new UIntConstant (types, (uint) value, Location.Null);
1080 case TypeCode.UInt64:
1081 return new ULongConstant (types, (ulong) value, Location.Null);
1084 throw new NotImplementedException (value.GetType ().ToString ());
1087 public TypeSpec ImportType (MetaType type)
1089 return ImportType (type, new DynamicTypeReader (type));
1092 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1094 if (type.HasElementType) {
1095 var element = type.GetElementType ();
1097 var spec = ImportType (element, dtype);
1100 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1102 return ReferenceContainer.MakeType (module, spec);
1104 return PointerContainer.MakeType (module, spec);
1106 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1109 return CreateType (type, dtype, true);
1112 static bool IsMissingType (MetaType type)
1115 return type.__IsMissing;
1122 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1123 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1124 // DecimalConstantAttribute metadata.
1126 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1128 if (attrs.Count == 0)
1132 foreach (var ca in attrs) {
1133 GetCustomAttributeTypeName (ca, out ns, out name);
1134 if (name != "DecimalConstantAttribute" || ns != CompilerServicesNamespace)
1137 var value = new decimal (
1138 (int) (uint) ca.ConstructorArguments[4].Value,
1139 (int) (uint) ca.ConstructorArguments[3].Value,
1140 (int) (uint) ca.ConstructorArguments[2].Value,
1141 (byte) ca.ConstructorArguments[1].Value != 0,
1142 (byte) ca.ConstructorArguments[0].Value);
1144 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1150 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1153 var ma = mb.Attributes;
1154 switch (ma & MethodAttributes.MemberAccessMask) {
1155 case MethodAttributes.Public:
1156 mod = Modifiers.PUBLIC;
1158 case MethodAttributes.Assembly:
1159 mod = Modifiers.INTERNAL;
1161 case MethodAttributes.Family:
1162 mod = Modifiers.PROTECTED;
1164 case MethodAttributes.FamORAssem:
1165 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1168 mod = Modifiers.PRIVATE;
1172 if ((ma & MethodAttributes.Static) != 0) {
1173 mod |= Modifiers.STATIC;
1176 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1177 mod |= Modifiers.ABSTRACT;
1181 // It can be sealed and override
1182 if ((ma & MethodAttributes.Final) != 0)
1183 mod |= Modifiers.SEALED;
1185 if ((ma & MethodAttributes.Virtual) != 0) {
1186 // Not every member can be detected based on MethodAttribute, we
1187 // set virtual or non-virtual only when we are certain. Further checks
1188 // to really find out what `virtual' means for this member are done
1190 if ((ma & MethodAttributes.NewSlot) != 0) {
1191 if ((mod & Modifiers.SEALED) != 0) {
1192 mod &= ~Modifiers.SEALED;
1194 mod |= Modifiers.VIRTUAL;
1197 mod |= Modifiers.OVERRIDE;
1205 abstract class ImportedDefinition : IMemberDefinition
1207 protected class AttributesBag
1209 public static readonly AttributesBag Default = new AttributesBag ();
1211 public AttributeUsageAttribute AttributeUsage;
1212 public ObsoleteAttribute Obsolete;
1213 public string[] Conditionals;
1214 public string DefaultIndexerName;
1215 public bool? CLSAttributeValue;
1216 public TypeSpec CoClass;
1218 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1220 AttributesBag bag = null;
1221 List<string> conditionals = null;
1223 // It should not throw any loading exception
1224 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1227 foreach (var a in attrs) {
1228 importer.GetCustomAttributeTypeName (a, out ns, out name);
1229 if (name == "ObsoleteAttribute") {
1234 bag = new AttributesBag ();
1236 var args = a.ConstructorArguments;
1238 if (args.Count == 1) {
1239 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1240 } else if (args.Count == 2) {
1241 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1243 bag.Obsolete = new ObsoleteAttribute ();
1249 if (name == "ConditionalAttribute") {
1250 if (ns != "System.Diagnostics")
1254 bag = new AttributesBag ();
1256 if (conditionals == null)
1257 conditionals = new List<string> (2);
1259 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1263 if (name == "CLSCompliantAttribute") {
1268 bag = new AttributesBag ();
1270 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1274 // Type only attributes
1275 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1276 if (name == "DefaultMemberAttribute") {
1277 if (ns != "System.Reflection")
1281 bag = new AttributesBag ();
1283 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1287 if (name == "AttributeUsageAttribute") {
1292 bag = new AttributesBag ();
1294 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1295 foreach (var named in a.NamedArguments) {
1296 if (named.MemberInfo.Name == "AllowMultiple")
1297 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1298 else if (named.MemberInfo.Name == "Inherited")
1299 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1304 // Interface only attribute
1305 if (name == "CoClassAttribute") {
1306 if (ns != "System.Runtime.InteropServices")
1310 bag = new AttributesBag ();
1312 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1321 if (conditionals != null)
1322 bag.Conditionals = conditionals.ToArray ();
1328 protected readonly MemberInfo provider;
1329 protected AttributesBag cattrs;
1330 protected readonly MetadataImporter importer;
1332 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1334 this.provider = provider;
1335 this.importer = importer;
1340 public bool IsImported {
1346 public virtual string Name {
1348 return provider.Name;
1354 public string[] ConditionalConditions ()
1359 return cattrs.Conditionals;
1362 public ObsoleteAttribute GetAttributeObsolete ()
1367 return cattrs.Obsolete;
1370 public bool? CLSAttributeValue {
1375 return cattrs.CLSAttributeValue;
1379 protected void ReadAttributes ()
1381 cattrs = AttributesBag.Read (provider, importer);
1384 public void SetIsAssigned ()
1386 // Unused for imported members
1389 public void SetIsUsed ()
1391 // Unused for imported members
1395 public class ImportedModuleDefinition
1397 readonly Module module;
1399 readonly MetadataImporter importer;
1401 public ImportedModuleDefinition (Module module, MetadataImporter importer)
1403 this.module = module;
1404 this.importer = importer;
1409 public bool IsCLSCompliant {
1411 return cls_compliant;
1415 public string Name {
1423 public void ReadAttributes ()
1425 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1428 foreach (var a in attrs) {
1429 importer.GetCustomAttributeTypeName (a, out ns, out name);
1430 if (name == "CLSCompliantAttribute") {
1434 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1441 // Reads assembly attributes which where attached to a special type because
1442 // module does have assembly manifest
1444 public List<Attribute> ReadAssemblyAttributes ()
1446 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1450 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1454 // TODO: implement, the idea is to fabricate specil Attribute class and
1455 // add it to OptAttributes before resolving the source code attributes
1456 // Need to build module location as well for correct error reporting
1458 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1459 //var attrs = new List<Attribute> (assembly_attributes.Count);
1460 //foreach (var a in assembly_attributes)
1462 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1463 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1465 // foreach (var carg in a.ConstructorArguments) {
1469 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1476 public class ImportedAssemblyDefinition : IAssemblyDefinition
1478 readonly Assembly assembly;
1479 readonly AssemblyName aname;
1480 readonly MetadataImporter importer;
1482 bool contains_extension_methods;
1484 List<AssemblyName> internals_visible_to;
1485 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1487 public ImportedAssemblyDefinition (Assembly assembly, MetadataImporter importer)
1489 this.assembly = assembly;
1490 this.aname = assembly.GetName ();
1491 this.importer = importer;
1496 public Assembly Assembly {
1502 public string FullName {
1504 return aname.FullName;
1508 public bool HasExtensionMethod {
1510 return contains_extension_methods;
1514 public bool HasStrongName {
1516 return aname.GetPublicKey ().Length != 0;
1520 public bool IsMissing {
1523 return assembly.__IsMissing;
1530 public bool IsCLSCompliant {
1532 return cls_compliant;
1536 public string Location {
1538 return assembly.Location;
1542 public string Name {
1550 public byte[] GetPublicKeyToken ()
1552 return aname.GetPublicKeyToken ();
1555 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1557 return internals_visible_to_cache [assembly];
1560 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1562 if (internals_visible_to == null)
1565 AssemblyName is_visible = null;
1566 if (internals_visible_to_cache == null) {
1567 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1569 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1570 return is_visible != null;
1573 var token = assembly.GetPublicKeyToken ();
1574 if (token != null && token.Length == 0)
1577 foreach (var internals in internals_visible_to) {
1578 if (internals.Name != assembly.Name)
1581 if (token == null && assembly is AssemblyDefinition) {
1582 is_visible = internals;
1586 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1589 is_visible = internals;
1593 internals_visible_to_cache.Add (assembly, is_visible);
1594 return is_visible != null;
1597 public void ReadAttributes ()
1600 if (assembly.__IsMissing)
1604 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1607 foreach (var a in attrs) {
1608 importer.GetCustomAttributeTypeName (a, out ns, out name);
1610 if (name == "CLSCompliantAttribute") {
1611 if (ns == "System") {
1613 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1620 if (name == "InternalsVisibleToAttribute") {
1621 if (ns != MetadataImporter.CompilerServicesNamespace)
1626 s = a.ConstructorArguments[0].Value as string;
1634 var an = new AssemblyName (s);
1635 if (internals_visible_to == null)
1636 internals_visible_to = new List<AssemblyName> ();
1638 internals_visible_to.Add (an);
1642 if (name == "ExtensionAttribute") {
1643 if (ns == MetadataImporter.CompilerServicesNamespace)
1644 contains_extension_methods = true;
1651 public override string ToString ()
1657 class ImportedMemberDefinition : ImportedDefinition
1659 readonly TypeSpec type;
1661 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1662 : base (member, importer)
1669 public TypeSpec MemberType {
1678 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1680 readonly AParametersCollection parameters;
1682 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1683 : base (provider, type, importer)
1685 this.parameters = parameters;
1688 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1689 : base (provider, type, importer)
1691 this.parameters = parameters;
1696 public AParametersCollection Parameters {
1705 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1707 readonly TypeParameterSpec[] tparams;
1709 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1710 : base (provider, type, parameters, importer)
1712 this.tparams = tparams;
1717 public TypeParameterSpec[] TypeParameters {
1723 public int TypeParametersCount {
1725 return tparams.Length;
1732 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1734 TypeParameterSpec[] tparams;
1737 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1738 : base (type, importer)
1744 public IAssemblyDefinition DeclaringAssembly {
1746 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1750 public override string Name {
1754 if (tparams != null) {
1755 int arity_start = name.IndexOf ('`');
1756 if (arity_start > 0)
1757 name = name.Substring (0, arity_start);
1765 public string Namespace {
1767 return ((MetaType) provider).Namespace;
1771 public int TypeParametersCount {
1773 return tparams == null ? 0 : tparams.Length;
1777 public TypeParameterSpec[] TypeParameters {
1788 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1791 // Report details about missing type and most likely cause of the problem.
1792 // csc reports 1683, 1684 as warnings but we report them only when used
1793 // or referenced from the user core in which case compilation error has to
1794 // be reported because compiler cannot continue anyway
1796 foreach (var t in types) {
1797 string name = t.GetSignatureForError ();
1799 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1800 ctx.Module.Compiler.Report.Error (1683, loc,
1801 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1803 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1804 ctx.Module.Compiler.Report.Error (12, loc,
1805 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1806 name, t.MemberDefinition.DeclaringAssembly.FullName);
1808 ctx.Module.Compiler.Report.Error (1684, loc,
1809 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1810 name, t.MemberDefinition.DeclaringAssembly.FullName);
1815 public TypeSpec GetAttributeCoClass ()
1820 return cattrs.CoClass;
1823 public string GetAttributeDefaultMember ()
1828 return cattrs.DefaultIndexerName;
1831 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1836 return cattrs.AttributeUsage;
1839 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1841 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1842 return a == assembly || a.IsFriendAssemblyTo (assembly);
1845 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1848 // Not interested in members of nested private types unless the importer needs them
1850 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1851 cache = MemberCache.Empty;
1855 var loading_type = (MetaType) provider;
1856 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1857 BindingFlags.Static | BindingFlags.Instance |
1858 BindingFlags.Public | BindingFlags.NonPublic;
1860 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1861 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1862 MethodAttributes.Final;
1864 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1865 List<EventSpec> imported_events = null;
1866 EventSpec event_spec;
1867 MemberSpec imported;
1871 all = loading_type.GetMembers (all_members);
1872 } catch (Exception e) {
1873 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1874 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1877 if (cache == null) {
1878 cache = new MemberCache (all.Length);
1881 // Do the types first as they can be referenced by the members before
1882 // they are found or inflated
1884 foreach (var member in all) {
1885 if (member.MemberType != MemberTypes.NestedType)
1888 var t = (MetaType) member;
1890 // Ignore compiler generated types, mostly lambda containers
1891 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1894 imported = importer.CreateNestedType (t, declaringType);
1895 cache.AddMemberImported (imported);
1898 foreach (var member in all) {
1899 if (member.MemberType != MemberTypes.NestedType)
1902 var t = (MetaType) member;
1904 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1907 importer.ImportTypeBase (t);
1913 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1915 foreach (var member in all) {
1916 switch (member.MemberType) {
1917 case MemberTypes.Constructor:
1918 case MemberTypes.Method:
1919 MethodBase mb = (MethodBase) member;
1920 var attrs = mb.Attributes;
1922 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1923 if (importer.IgnorePrivateMembers)
1926 // Ignore explicitly implemented members
1927 if ((attrs & explicit_impl) == explicit_impl)
1930 // Ignore compiler generated methods
1931 if (importer.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1935 imported = importer.CreateMethod (mb, declaringType);
1936 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1937 if (possible_accessors == null)
1938 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1940 // There are no metadata rules for accessors, we have to consider any method as possible candidate
1941 possible_accessors.Add (mb, (MethodSpec) imported);
1945 case MemberTypes.Property:
1946 if (possible_accessors == null)
1949 var p = (PropertyInfo) member;
1951 // Links possible accessors with property
1953 MethodSpec get, set;
1954 m = p.GetGetMethod (true);
1955 if (m == null || !possible_accessors.TryGetValue (m, out get))
1958 m = p.GetSetMethod (true);
1959 if (m == null || !possible_accessors.TryGetValue (m, out set))
1962 // No accessors registered (e.g. explicit implementation)
1963 if (get == null && set == null)
1966 imported = importer.CreateProperty (p, declaringType, get, set);
1967 if (imported == null)
1971 case MemberTypes.Event:
1972 if (possible_accessors == null)
1975 var e = (EventInfo) member;
1977 // Links accessors with event
1979 MethodSpec add, remove;
1980 m = e.GetAddMethod (true);
1981 if (m == null || !possible_accessors.TryGetValue (m, out add))
1984 m = e.GetRemoveMethod (true);
1985 if (m == null || !possible_accessors.TryGetValue (m, out remove))
1988 // Both accessors are required
1989 if (add == null || remove == null)
1992 event_spec = importer.CreateEvent (e, declaringType, add, remove);
1993 if (!importer.IgnorePrivateMembers) {
1994 if (imported_events == null)
1995 imported_events = new List<EventSpec> ();
1997 imported_events.Add (event_spec);
2000 imported = event_spec;
2002 case MemberTypes.Field:
2003 var fi = (FieldInfo) member;
2005 imported = importer.CreateField (fi, declaringType);
2006 if (imported == null)
2010 // For dynamic binder event has to be fully restored to allow operations
2011 // within the type container to work correctly
2013 if (imported_events != null) {
2014 // The backing event field should be private but it may not
2016 for (i = 0; i < imported_events.Count; ++i) {
2017 var ev = imported_events[i];
2018 if (ev.Name == fi.Name) {
2019 ev.BackingField = (FieldSpec) imported;
2020 imported_events.RemoveAt (i);
2031 case MemberTypes.NestedType:
2032 // Already in the cache from the first pass
2035 throw new NotImplementedException (member.ToString ());
2038 cache.AddMemberImported (imported);
2042 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2043 foreach (var iface in declaringType.Interfaces) {
2044 cache.AddInterface (iface);
2050 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2052 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2053 : base (type, importer)
2059 public IAssemblyDefinition DeclaringAssembly {
2061 throw new NotImplementedException ();
2065 public string Namespace {
2071 public int TypeParametersCount {
2077 public TypeParameterSpec[] TypeParameters {
2085 public TypeSpec GetAttributeCoClass ()
2090 public string GetAttributeDefaultMember ()
2092 throw new NotSupportedException ();
2095 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2097 throw new NotSupportedException ();
2100 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2102 throw new NotImplementedException ();
2105 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2107 throw new NotImplementedException ();