2 // import.cs: System.Reflection conversions
4 // Authors: Marek Safar (marek.safar@gmail.com)
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 // Copyright 2009, 2010 Novell, Inc
12 using System.Runtime.CompilerServices;
14 using System.Collections.Generic;
17 using MetaType = IKVM.Reflection.Type;
18 using IKVM.Reflection;
19 using IKVM.Reflection.Emit;
21 using MetaType = System.Type;
22 using System.Reflection;
23 using System.Reflection.Emit;
28 public abstract class MetadataImporter
31 // Dynamic types reader with additional logic to reconstruct a dynamic
32 // type using DynamicAttribute values
34 struct DynamicTypeReader
36 static readonly bool[] single_attribute = { true };
41 // There is no common type for CustomAttributeData and we cannot
42 // use ICustomAttributeProvider
46 // A member provider which can be used to get CustomAttributeData
48 public DynamicTypeReader (object provider)
52 this.provider = provider;
56 // Returns true when object at local position has dynamic attribute flag
58 public bool IsDynamicObject (MetadataImporter importer)
61 ReadAttribute (importer);
63 return flags != null && Position < flags.Length && flags[Position];
67 // Returns true when DynamicAttribute exists
69 public bool HasDynamicAttribute (MetadataImporter importer)
72 ReadAttribute (importer);
77 void ReadAttribute (MetadataImporter importer)
79 IList<CustomAttributeData> cad;
80 if (provider is MemberInfo) {
81 cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
82 } else if (provider is ParameterInfo) {
83 cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
91 foreach (var ca in cad) {
92 importer.GetCustomAttributeTypeName (ca, out ns, out name);
93 if (name != "DynamicAttribute" && ns != CompilerServicesNamespace)
96 if (ca.ConstructorArguments.Count == 0) {
97 flags = single_attribute;
101 var arg_type = ca.ConstructorArguments[0].ArgumentType;
103 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
104 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
105 flags = new bool[carg.Count];
106 for (int i = 0; i < flags.Length; ++i) {
107 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
108 flags[i] = (bool) carg[i].Value;
120 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
121 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
122 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
124 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
126 protected MetadataImporter ()
128 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
129 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
130 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
131 IgnorePrivateMembers = true;
136 public ICollection<IAssemblyDefinition> Assemblies {
138 return assembly_2_definition.Values;
142 public bool IgnorePrivateMembers { get; set; }
146 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
147 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
148 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
149 public abstract void GetCustomAttributeTypeName (CustomAttributeData cad, out string typeNamespace, out string typeName);
151 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
154 var fa = fi.Attributes;
155 switch (fa & FieldAttributes.FieldAccessMask) {
156 case FieldAttributes.Public:
157 mod = Modifiers.PUBLIC;
159 case FieldAttributes.Assembly:
160 mod = Modifiers.INTERNAL;
162 case FieldAttributes.Family:
163 mod = Modifiers.PROTECTED;
165 case FieldAttributes.FamORAssem:
166 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
169 // Ignore private fields (even for error reporting) to not require extra dependencies
170 if (IgnorePrivateMembers || HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
173 mod = Modifiers.PRIVATE;
180 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
181 } catch (Exception e) {
182 // TODO: I should construct fake TypeSpec based on TypeRef signature
183 // but there is no way to do it with System.Reflection
184 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
185 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
188 var definition = new ImportedMemberDefinition (fi, field_type, this);
190 if ((fa & FieldAttributes.Literal) != 0) {
191 var c = Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
192 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
195 if ((fa & FieldAttributes.InitOnly) != 0) {
196 if (field_type == TypeManager.decimal_type) {
197 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
199 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
202 mod |= Modifiers.READONLY;
204 var req_mod = fi.GetRequiredCustomModifiers ();
205 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
206 mod |= Modifiers.VOLATILE;
209 if ((fa & FieldAttributes.Static) != 0) {
210 mod |= Modifiers.STATIC;
212 // Fixed buffers cannot be static
213 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
214 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
216 // TODO: Sanity check on field_type (only few type are allowed)
217 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
218 return new FixedFieldSpec (declaringType, definition, fi, element_field, mod);
222 return new FieldSpec (declaringType, definition, field_type, fi, mod);
225 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
227 add.IsAccessor = true;
228 remove.IsAccessor = true;
230 if (add.Modifiers != remove.Modifiers)
231 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
233 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
234 var definition = new ImportedMemberDefinition (ei, event_type, this);
235 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
238 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
240 var tparams = type.GetGenericArguments ();
242 int parent_owned_count;
244 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
247 // System.Reflection duplicates parent type parameters for each
248 // nested type with slightly modified properties (eg. different owner)
249 // This just makes things more complicated (think of cloned constraints)
250 // therefore we remap any nested type owned by parent using `type_cache'
251 // to the single TypeParameterSpec
253 if (declaringType != null && parent_owned_count > 0) {
255 while (read_count != parent_owned_count) {
256 var tparams_count = declaringType.Arity;
257 if (tparams_count != 0) {
258 var parent_tp = declaringType.MemberDefinition.TypeParameters;
259 read_count += tparams_count;
260 for (int i = 0; i < tparams_count; i++) {
261 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
265 declaringType = declaringType.DeclaringType;
269 parent_owned_count = 0;
272 if (tparams.Length - parent_owned_count == 0)
275 return CreateGenericParameters (parent_owned_count, tparams);
278 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
280 var tspec = new TypeParameterSpec[tparams.Length - first];
281 for (int pos = first; pos < tparams.Length; ++pos) {
282 var type = tparams[pos];
283 int index = pos - first;
285 tspec [index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
291 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
295 var tspec = new TypeSpec [tparams.Length - first];
296 for (int pos = first; pos < tparams.Length; ++pos) {
297 var type = tparams[pos];
298 int index = pos - first;
301 if (type.HasElementType) {
302 var element = type.GetElementType ();
304 spec = ImportType (element, dtype);
307 throw new NotImplementedException ("Unknown element type " + type.ToString ());
310 spec = ArrayContainer.MakeType (spec, type.GetArrayRank ());
312 spec = CreateType (type, dtype, true);
315 // We treat nested generic types as inflated internally where
316 // reflection uses type definition
319 // IFoo<A<T>> foo; // A<T> is definition in this case
322 // TODO: Is full logic from CreateType needed here as well?
324 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
325 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
326 spec = spec.MakeGenericType (targs);
337 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
339 Modifiers mod = ReadMethodModifiers (mb, declaringType);
340 TypeParameterSpec[] tparams;
342 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
344 if (mb.IsGenericMethod) {
345 if (!mb.IsGenericMethodDefinition)
346 throw new NotSupportedException ("assert");
348 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
355 if (mb.MemberType == MemberTypes.Constructor) {
356 kind = MemberKind.Constructor;
357 returnType = TypeManager.void_type;
360 // Detect operators and destructors
362 string name = mb.Name;
363 kind = MemberKind.Method;
364 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
365 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
366 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
367 var op_type = Operator.GetType (name);
368 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
369 kind = MemberKind.Operator;
372 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
373 kind = MemberKind.Destructor;
374 if (declaringType == TypeManager.object_type) {
375 mod &= ~Modifiers.OVERRIDE;
376 mod |= Modifiers.VIRTUAL;
381 var mi = (MethodInfo) mb;
382 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
384 // Cannot set to OVERRIDE without full hierarchy checks
385 // this flag indicates that the method could be override
386 // but further validation is needed
387 if ((mod & Modifiers.OVERRIDE) != 0 && kind == MemberKind.Method && declaringType.BaseType != null) {
388 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
389 var candidate = MemberCache.FindMember (declaringType.BaseType, filter, BindingRestriction.None);
392 // For imported class method do additional validation to be sure that metadata
393 // override flag was correct
395 // Difference between protected internal and protected is ok
397 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
398 if (candidate == null || (candidate.Modifiers & conflict_mask) != (mod & conflict_mask) || candidate.IsStatic) {
399 mod &= ~Modifiers.OVERRIDE;
404 IMemberDefinition definition;
405 if (tparams != null) {
406 definition = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
408 definition = new ImportedParameterMemberDefinition (mb, returnType, parameters, this);
411 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, mb, parameters, mod);
419 // Imports System.Reflection parameters
421 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
423 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
425 if (pi.Length == 0 && varargs == 0)
426 return ParametersCompiled.EmptyReadOnlyParameters;
428 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
429 IParameterData[] par = new IParameterData[pi.Length + varargs];
430 bool is_params = false;
431 for (int i = 0; i < pi.Length; i++) {
432 ParameterInfo p = pi[i];
433 Parameter.Modifier mod = 0;
434 Expression default_value = null;
435 if (p.ParameterType.IsByRef) {
436 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
437 mod = Parameter.Modifier.OUT;
439 mod = Parameter.Modifier.REF;
442 // Strip reference wrapping
444 var el = p.ParameterType.GetElementType ();
445 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
446 } else if (i == 0 && method.IsStatic && parent.IsStatic && parent.MemberDefinition.DeclaringAssembly.HasExtensionMethod &&
447 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
448 mod = Parameter.Modifier.This;
449 types[i] = ImportType (p.ParameterType);
451 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
453 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
454 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
455 mod = Parameter.Modifier.PARAMS;
460 if (!is_params && p.IsOptional) {
461 object value = p.RawDefaultValue;
462 var ptype = types[i];
463 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeManager.IsReferenceType (ptype))) {
465 default_value = Constant.CreateConstant (null, ptype, null, Location.Null);
467 default_value = ImportParameterConstant (value).Resolve (null);
470 default_value = new EnumConstant ((Constant) default_value, ptype).Resolve (null);
473 } else if (value == Missing.Value) {
474 default_value = EmptyExpression.MissingValue;
475 } else if (value == null) {
476 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
477 } else if (ptype == TypeManager.decimal_type) {
478 default_value = ImportParameterConstant (value).Resolve (null);
483 par[i] = new ParameterData (p.Name, mod, default_value);
487 par[par.Length - 1] = new ArglistParameter (Location.Null);
488 types[types.Length - 1] = InternalType.Arglist;
491 return method != null ?
492 new ParametersImported (par, types, varargs != 0, is_params) :
493 new ParametersImported (par, types, is_params);
497 // Returns null when the property is not valid C# property
499 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
502 AParametersCollection param = null;
503 TypeSpec type = null;
506 param = get.Parameters;
507 type = get.ReturnType;
510 bool is_valid_property = true;
512 if (set.ReturnType != TypeManager.void_type)
513 is_valid_property = false;
515 var set_param_count = set.Parameters.Count - 1;
517 if (set_param_count < 0) {
519 is_valid_property = false;
522 var set_type = set.Parameters.Types[set_param_count];
525 AParametersCollection set_based_param;
527 if (set_param_count == 0) {
528 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
531 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
533 var data = new IParameterData[set_param_count];
534 var types = new TypeSpec[set_param_count];
535 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
536 Array.Copy (set.Parameters.Types, types, set_param_count);
537 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
541 param = set_based_param;
544 if (set_param_count != get.Parameters.Count)
545 is_valid_property = false;
547 if (get.ReturnType != set_type)
548 is_valid_property = false;
550 // Possible custom accessor modifiers
551 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
552 var get_acc = mod & Modifiers.AccessibilityMask;
553 if (get_acc != Modifiers.PUBLIC) {
554 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
555 // If the accessor modifiers are not same, do extra restriction checks
556 if (get_acc != set_acc) {
557 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
558 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
559 if (get_restr && set_restr) {
560 is_valid_property = false; // Neither is more restrictive
564 mod &= ~Modifiers.AccessibilityMask;
573 PropertySpec spec = null;
574 if (!param.IsEmpty) {
575 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
576 if (index_name == null) {
577 is_valid_property = false;
581 is_valid_property = false;
582 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
583 is_valid_property = false;
587 is_valid_property = false;
588 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
589 is_valid_property = false;
593 if (is_valid_property)
594 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
598 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
600 if (!is_valid_property) {
601 spec.IsNotRealProperty = true;
613 public TypeSpec CreateType (MetaType type)
615 return CreateType (type, new DynamicTypeReader (), true);
618 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
620 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
623 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
625 TypeSpec declaring_type;
626 if (type.IsNested && !type.IsGenericParameter)
627 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
629 declaring_type = null;
631 return CreateType (type, declaring_type, dtype, canImportBaseType);
634 TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
637 if (import_cache.TryGetValue (type, out spec)) {
638 if (spec == TypeManager.object_type) {
639 if (dtype.IsDynamicObject (this))
640 return InternalType.Dynamic;
645 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
648 if (!dtype.HasDynamicAttribute (this))
651 // We've found same object in the cache but this one has a dynamic custom attribute
652 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
653 // Do type resolve process again in that case
655 // TODO: Handle cases where they still unify
658 if (IsMissingType (type)) {
659 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
660 spec.MemberCache = MemberCache.Empty;
661 import_cache.Add (type, spec);
665 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
666 var type_def = type.GetGenericTypeDefinition ();
667 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
668 if (declaringType == null) {
669 // Simple case, no nesting
670 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
671 spec = spec.MakeGenericType (targs);
674 // Nested type case, converting .NET types like
675 // A`1.B`1.C`1<int, long, string> to typespec like
676 // A<int>.B<long>.C<string>
678 var nested_hierarchy = new List<TypeSpec> ();
679 while (declaringType.IsNested) {
680 nested_hierarchy.Add (declaringType);
681 declaringType = declaringType.DeclaringType;
685 if (declaringType.Arity > 0) {
686 spec = declaringType.MakeGenericType (targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
687 targs_pos = spec.Arity;
689 spec = declaringType;
692 for (int i = nested_hierarchy.Count; i != 0; --i) {
693 var t = nested_hierarchy [i - 1];
694 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
696 spec = spec.MakeGenericType (targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
697 targs_pos += t.Arity;
701 string name = type.Name;
702 int index = name.IndexOf ('`');
704 name = name.Substring (0, index);
706 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
707 if (spec.Arity > 0) {
708 spec = spec.MakeGenericType (targs.Skip (targs_pos).ToArray ());
712 // Don't add generic type with dynamic arguments, they can interfere with same type
713 // using object type arguments
714 if (!spec.HasDynamicElement) {
716 // Add to reading cache to speed up reading
717 if (!import_cache.ContainsKey (type))
718 import_cache.Add (type, spec);
727 var ma = type.Attributes;
728 switch (ma & TypeAttributes.VisibilityMask) {
729 case TypeAttributes.Public:
730 case TypeAttributes.NestedPublic:
731 mod = Modifiers.PUBLIC;
733 case TypeAttributes.NestedPrivate:
734 mod = Modifiers.PRIVATE;
736 case TypeAttributes.NestedFamily:
737 mod = Modifiers.PROTECTED;
739 case TypeAttributes.NestedFamORAssem:
740 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
743 mod = Modifiers.INTERNAL;
747 if ((ma & TypeAttributes.Interface) != 0) {
748 kind = MemberKind.Interface;
749 } else if (type.IsGenericParameter) {
750 kind = MemberKind.TypeParameter;
752 var base_type = type.BaseType;
753 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
754 kind = MemberKind.Class;
756 kind = DetermineKindFromBaseType (base_type);
757 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
758 mod |= Modifiers.SEALED;
762 if (kind == MemberKind.Class) {
763 if ((ma & TypeAttributes.Sealed) != 0) {
764 mod |= Modifiers.SEALED;
765 if ((ma & TypeAttributes.Abstract) != 0)
766 mod |= Modifiers.STATIC;
767 } else if ((ma & TypeAttributes.Abstract) != 0) {
768 mod |= Modifiers.ABSTRACT;
773 var definition = new ImportedTypeDefinition (type, this);
776 if (kind == MemberKind.Enum) {
777 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
778 BindingFlags.Instance |
779 BindingFlags.Public | BindingFlags.NonPublic;
781 var type_members = type.GetFields (underlying_member);
782 foreach (var type_member in type_members) {
783 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
788 kind = MemberKind.Class;
790 } else if (kind == MemberKind.TypeParameter) {
791 // Return as type_cache was updated
792 return CreateTypeParameter (type, declaringType);
793 } else if (type.IsGenericTypeDefinition) {
794 definition.TypeParameters = CreateGenericParameters (type, declaringType);
796 // Constraints are not loaded on demand and can reference this type
797 if (import_cache.TryGetValue (type, out spec))
800 } else if (compiled_types.TryGetValue (type, out pt)) {
802 // Same type was found in inside compiled types. It's
803 // either build-in type or forward referenced typed
804 // which point into just compiled assembly.
807 BuildinTypeSpec bts = pt as BuildinTypeSpec;
809 bts.SetDefinition (definition, type, mod);
813 spec = new TypeSpec (kind, declaringType, definition, type, mod);
815 import_cache.Add (type, spec);
818 // Two stage setup as the base type can be inflated declaring type or
819 // another nested type inside same declaring type which has not been
820 // loaded, therefore we can import a base type of nested types once
821 // the types have been imported
823 if (canImportBaseType)
824 ImportTypeBase (spec, type);
829 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
831 IAssemblyDefinition found;
832 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
834 // This can happen in dynamic context only
835 var def = new ImportedAssemblyDefinition (assembly, this);
836 assembly_2_definition.Add (assembly, def);
837 def.ReadAttributes ();
844 public void ImportTypeBase (MetaType type)
846 TypeSpec spec = import_cache[type];
848 ImportTypeBase (spec, type);
851 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
854 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
855 case GenericParameterAttributes.Covariant:
856 variance = Variance.Covariant;
858 case GenericParameterAttributes.Contravariant:
859 variance = Variance.Contravariant;
862 variance = Variance.None;
866 SpecialConstraint special = SpecialConstraint.None;
867 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
869 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
870 special |= SpecialConstraint.Struct;
871 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
872 special = SpecialConstraint.Constructor;
875 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
876 special |= SpecialConstraint.Class;
879 TypeParameterSpec spec;
880 var def = new ImportedTypeParameterDefinition (type, this);
881 if (type.DeclaringMethod != null)
882 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
884 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
886 // Add it now, so any constraint can reference it and get same instance
887 import_cache.Add (type, spec);
889 var constraints = type.GetGenericParameterConstraints ();
890 List<TypeSpec> tparams = null;
891 foreach (var ct in constraints) {
892 if (ct.IsGenericParameter) {
894 tparams = new List<TypeSpec> ();
896 tparams.Add (CreateType (ct));
900 if (!IsMissingType (ct) && ct.IsClass) {
901 spec.BaseType = CreateType (ct);
905 spec.AddInterface (CreateType (ct));
908 if (spec.BaseType == null)
909 spec.BaseType = TypeManager.object_type;
912 spec.TypeArguments = tparams.ToArray ();
918 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
919 // they can be assembly specific therefore we do check based on names only
921 public bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
923 if (attributesData.Count == 0)
927 foreach (var attr in attributesData) {
928 GetCustomAttributeTypeName (attr, out ns, out name);
929 if (name == attrName && ns == attrNamespace)
936 void ImportTypeBase (TypeSpec spec, MetaType type)
938 if (spec.Kind == MemberKind.Interface)
939 spec.BaseType = TypeManager.object_type;
940 else if (type.BaseType != null) {
942 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
943 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
945 base_type = CreateType (type.BaseType);
947 spec.BaseType = base_type;
952 ifaces = type.__GetDeclaredInterfaces ();
953 if (ifaces.Length != 0) {
954 foreach (var iface in ifaces)
955 spec.AddInterface (CreateType (iface));
958 if (spec.BaseType != null) {
959 var bifaces = spec.BaseType.Interfaces;
960 if (bifaces != null) {
961 foreach (var iface in bifaces)
962 spec.AddInterface (iface);
966 ifaces = type.GetInterfaces ();
968 if (ifaces.Length > 0) {
969 foreach (var iface in ifaces) {
970 spec.AddInterface (CreateType (iface));
976 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
978 Namespace ns = targetNamespace;
979 string prev_namespace = null;
980 foreach (var t in types) {
984 // Be careful not to trigger full parent type loading
985 if (t.MemberType == MemberTypes.NestedType)
988 if (t.Name[0] == '<')
991 var it = CreateType (t, null, new DynamicTypeReader (t), true);
995 if (prev_namespace != t.Namespace) {
996 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
997 prev_namespace = t.Namespace;
1002 if (it.IsStatic && hasExtensionTypes &&
1003 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1004 it.SetExtensionMethodContainer ();
1009 static Constant ImportParameterConstant (object value)
1012 // Get type of underlying value as int constant can be used for object
1013 // parameter type. This is not allowed in C# but other languages can do that
1015 switch (System.Type.GetTypeCode (value.GetType ())) {
1016 case TypeCode.Boolean:
1017 return new BoolConstant ((bool) value, Location.Null);
1019 return new ByteConstant ((byte) value, Location.Null);
1021 return new CharConstant ((char) value, Location.Null);
1022 case TypeCode.Decimal:
1023 return new DecimalConstant ((decimal) value, Location.Null);
1024 case TypeCode.Double:
1025 return new DoubleConstant ((double) value, Location.Null);
1026 case TypeCode.Int16:
1027 return new ShortConstant ((short) value, Location.Null);
1028 case TypeCode.Int32:
1029 return new IntConstant ((int) value, Location.Null);
1030 case TypeCode.Int64:
1031 return new LongConstant ((long) value, Location.Null);
1032 case TypeCode.SByte:
1033 return new SByteConstant ((sbyte) value, Location.Null);
1034 case TypeCode.Single:
1035 return new FloatConstant ((float) value, Location.Null);
1036 case TypeCode.String:
1037 return new StringConstant ((string) value, Location.Null);
1038 case TypeCode.UInt16:
1039 return new UShortConstant ((ushort) value, Location.Null);
1040 case TypeCode.UInt32:
1041 return new UIntConstant ((uint) value, Location.Null);
1042 case TypeCode.UInt64:
1043 return new ULongConstant ((ulong) value, Location.Null);
1046 throw new NotImplementedException (value.GetType ().ToString ());
1049 public TypeSpec ImportType (MetaType type)
1051 return ImportType (type, new DynamicTypeReader (type));
1054 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1056 if (type.HasElementType) {
1057 var element = type.GetElementType ();
1059 var spec = ImportType (element, dtype);
1062 return ArrayContainer.MakeType (spec, type.GetArrayRank ());
1064 return ReferenceContainer.MakeType (spec);
1066 return PointerContainer.MakeType (spec);
1068 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1071 return CreateType (type, dtype, true);
1074 static bool IsMissingType (MetaType type)
1077 return type.__IsMissing;
1084 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1085 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1086 // DecimalConstantAttribute metadata.
1088 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1090 if (attrs.Count == 0)
1094 foreach (var ca in attrs) {
1095 GetCustomAttributeTypeName (ca, out ns, out name);
1096 if (name != "DecimalConstantAttribute" || ns != CompilerServicesNamespace)
1099 var value = new decimal (
1100 (int) (uint) ca.ConstructorArguments[4].Value,
1101 (int) (uint) ca.ConstructorArguments[3].Value,
1102 (int) (uint) ca.ConstructorArguments[2].Value,
1103 (byte) ca.ConstructorArguments[1].Value != 0,
1104 (byte) ca.ConstructorArguments[0].Value);
1106 return new DecimalConstant (value, Location.Null).Resolve (null);
1112 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1115 var ma = mb.Attributes;
1116 switch (ma & MethodAttributes.MemberAccessMask) {
1117 case MethodAttributes.Public:
1118 mod = Modifiers.PUBLIC;
1120 case MethodAttributes.Assembly:
1121 mod = Modifiers.INTERNAL;
1123 case MethodAttributes.Family:
1124 mod = Modifiers.PROTECTED;
1126 case MethodAttributes.FamORAssem:
1127 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1130 mod = Modifiers.PRIVATE;
1134 if ((ma & MethodAttributes.Static) != 0) {
1135 mod |= Modifiers.STATIC;
1138 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1139 mod |= Modifiers.ABSTRACT;
1143 if ((ma & MethodAttributes.Final) != 0)
1144 mod |= Modifiers.SEALED;
1146 // It can be sealed and override
1147 if ((ma & MethodAttributes.Virtual) != 0) {
1148 if ((ma & MethodAttributes.NewSlot) != 0 || !declaringType.IsClass) {
1149 // No private virtual or sealed virtual
1150 if ((mod & (Modifiers.PRIVATE | Modifiers.SEALED)) == 0)
1151 mod |= Modifiers.VIRTUAL;
1153 mod |= Modifiers.OVERRIDE;
1161 abstract class ImportedDefinition : IMemberDefinition
1163 protected class AttributesBag
1165 public static readonly AttributesBag Default = new AttributesBag ();
1167 public AttributeUsageAttribute AttributeUsage;
1168 public ObsoleteAttribute Obsolete;
1169 public string[] Conditionals;
1170 public string DefaultIndexerName;
1171 public bool IsNotCLSCompliant;
1172 public TypeSpec CoClass;
1174 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1176 AttributesBag bag = null;
1177 List<string> conditionals = null;
1179 // It should not throw any loading exception
1180 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1183 foreach (var a in attrs) {
1184 importer.GetCustomAttributeTypeName (a, out ns, out name);
1185 if (name == "ObsoleteAttribute") {
1190 bag = new AttributesBag ();
1192 var args = a.ConstructorArguments;
1194 if (args.Count == 1) {
1195 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1196 } else if (args.Count == 2) {
1197 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1199 bag.Obsolete = new ObsoleteAttribute ();
1205 if (name == "ConditionalAttribute") {
1206 if (ns != "System.Diagnostics")
1210 bag = new AttributesBag ();
1212 if (conditionals == null)
1213 conditionals = new List<string> (2);
1215 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1219 if (name == "CLSCompliantAttribute") {
1224 bag = new AttributesBag ();
1226 bag.IsNotCLSCompliant = !(bool) a.ConstructorArguments[0].Value;
1230 // Type only attributes
1231 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1232 if (name == "DefaultMemberAttribute") {
1233 if (ns != "System.Reflection")
1237 bag = new AttributesBag ();
1239 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1243 if (name == "AttributeUsageAttribute") {
1248 bag = new AttributesBag ();
1250 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1251 foreach (var named in a.NamedArguments) {
1252 if (named.MemberInfo.Name == "AllowMultiple")
1253 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1254 else if (named.MemberInfo.Name == "Inherited")
1255 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1260 // Interface only attribute
1261 if (name == "CoClassAttribute") {
1262 if (ns != "System.Runtime.InteropServices")
1266 bag = new AttributesBag ();
1268 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1277 if (conditionals != null)
1278 bag.Conditionals = conditionals.ToArray ();
1284 protected readonly MemberInfo provider;
1285 protected AttributesBag cattrs;
1286 protected readonly MetadataImporter importer;
1288 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1290 this.provider = provider;
1291 this.importer = importer;
1296 public bool IsImported {
1302 public virtual string Name {
1304 return provider.Name;
1310 public string[] ConditionalConditions ()
1315 return cattrs.Conditionals;
1318 public ObsoleteAttribute GetAttributeObsolete ()
1323 return cattrs.Obsolete;
1326 public bool IsNotCLSCompliant ()
1331 return cattrs.IsNotCLSCompliant;
1334 protected void ReadAttributes ()
1336 cattrs = AttributesBag.Read (provider, importer);
1339 public void SetIsAssigned ()
1341 // Unused for imported members
1344 public void SetIsUsed ()
1346 // Unused for imported members
1350 public class ImportedModuleDefinition
1352 readonly Module module;
1354 readonly MetadataImporter importer;
1356 public ImportedModuleDefinition (Module module, MetadataImporter importer)
1358 this.module = module;
1359 this.importer = importer;
1364 public bool IsCLSCompliant {
1366 return cls_compliant;
1370 public string Name {
1378 public void ReadAttributes ()
1380 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1383 foreach (var a in attrs) {
1384 importer.GetCustomAttributeTypeName (a, out ns, out name);
1385 if (name == "CLSCompliantAttribute") {
1389 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1396 // Reads assembly attributes which where attached to a special type because
1397 // module does have assembly manifest
1399 public List<Attribute> ReadAssemblyAttributes ()
1401 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1405 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1409 // TODO: implement, the idea is to fabricate specil Attribute class and
1410 // add it to OptAttributes before resolving the source code attributes
1411 // Need to build module location as well for correct error reporting
1413 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1414 //var attrs = new List<Attribute> (assembly_attributes.Count);
1415 //foreach (var a in assembly_attributes)
1417 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1418 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1420 // foreach (var carg in a.ConstructorArguments) {
1424 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1431 public class ImportedAssemblyDefinition : IAssemblyDefinition
1433 readonly Assembly assembly;
1434 readonly AssemblyName aname;
1435 readonly MetadataImporter importer;
1437 bool contains_extension_methods;
1439 List<AssemblyName> internals_visible_to;
1440 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1442 public ImportedAssemblyDefinition (Assembly assembly, MetadataImporter importer)
1444 this.assembly = assembly;
1445 this.aname = assembly.GetName ();
1446 this.importer = importer;
1451 public Assembly Assembly {
1457 public string FullName {
1459 return aname.FullName;
1463 public bool HasExtensionMethod {
1465 return contains_extension_methods;
1469 public bool HasStrongName {
1471 return aname.GetPublicKey ().Length != 0;
1475 public bool IsMissing {
1478 return assembly.__IsMissing;
1485 public bool IsCLSCompliant {
1487 return cls_compliant;
1491 public string Location {
1493 return assembly.Location;
1497 public string Name {
1505 public byte[] GetPublicKeyToken ()
1507 return aname.GetPublicKeyToken ();
1510 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1512 return internals_visible_to_cache [assembly];
1515 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1517 if (internals_visible_to == null)
1520 AssemblyName is_visible = null;
1521 if (internals_visible_to_cache == null) {
1522 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1524 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1525 return is_visible != null;
1528 var token = assembly.GetPublicKeyToken ();
1529 if (token != null && token.Length == 0)
1532 foreach (var internals in internals_visible_to) {
1533 if (internals.Name != assembly.Name)
1536 if (token == null && assembly is AssemblyDefinition) {
1537 is_visible = internals;
1541 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1544 is_visible = internals;
1548 internals_visible_to_cache.Add (assembly, is_visible);
1549 return is_visible != null;
1552 public void ReadAttributes ()
1555 if (assembly.__IsMissing)
1559 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1562 foreach (var a in attrs) {
1563 importer.GetCustomAttributeTypeName (a, out ns, out name);
1565 if (name == "CLSCompliantAttribute") {
1566 if (ns == "System") {
1568 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1575 if (name == "InternalsVisibleToAttribute") {
1576 if (ns != MetadataImporter.CompilerServicesNamespace)
1581 s = a.ConstructorArguments[0].Value as string;
1589 var an = new AssemblyName (s);
1590 if (internals_visible_to == null)
1591 internals_visible_to = new List<AssemblyName> ();
1593 internals_visible_to.Add (an);
1597 if (name == "ExtensionAttribute") {
1598 if (ns == MetadataImporter.CompilerServicesNamespace)
1599 contains_extension_methods = true;
1606 public override string ToString ()
1612 class ImportedMemberDefinition : ImportedDefinition
1614 readonly TypeSpec type;
1616 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1617 : base (member, importer)
1624 public TypeSpec MemberType {
1633 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1635 readonly AParametersCollection parameters;
1637 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1638 : base (provider, type, importer)
1640 this.parameters = parameters;
1643 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1644 : base (provider, type, importer)
1646 this.parameters = parameters;
1651 public AParametersCollection Parameters {
1660 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1662 readonly TypeParameterSpec[] tparams;
1664 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1665 : base (provider, type, parameters, importer)
1667 this.tparams = tparams;
1672 public TypeParameterSpec[] TypeParameters {
1678 public int TypeParametersCount {
1680 return tparams.Length;
1687 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1689 TypeParameterSpec[] tparams;
1692 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1693 : base (type, importer)
1699 public IAssemblyDefinition DeclaringAssembly {
1701 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1705 public override string Name {
1709 if (tparams != null) {
1710 int arity_start = name.IndexOf ('`');
1711 if (arity_start > 0)
1712 name = name.Substring (0, arity_start);
1720 public string Namespace {
1722 return ((MetaType) provider).Namespace;
1726 public int TypeParametersCount {
1728 return tparams == null ? 0 : tparams.Length;
1732 public TypeParameterSpec[] TypeParameters {
1743 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1746 // Report details about missing type and most likely cause of the problem.
1747 // csc reports 1683, 1684 as warnings but we report them only when used
1748 // or referenced from the user core in which case compilation error has to
1749 // be reported because compiler cannot continue anyway
1751 foreach (var t in types) {
1752 string name = t.GetSignatureForError ();
1754 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1755 ctx.Compiler.Report.Error (1683, loc,
1756 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1758 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1759 ctx.Compiler.Report.Error (12, loc,
1760 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1761 name, t.MemberDefinition.DeclaringAssembly.FullName);
1763 ctx.Compiler.Report.Error (1684, loc,
1764 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1765 name, t.MemberDefinition.DeclaringAssembly.FullName);
1770 public TypeSpec GetAttributeCoClass ()
1775 return cattrs.CoClass;
1778 public string GetAttributeDefaultMember ()
1783 return cattrs.DefaultIndexerName;
1786 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1791 return cattrs.AttributeUsage;
1794 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1796 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1797 return a == assembly || a.IsFriendAssemblyTo (assembly);
1800 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1803 // Not interested in members of nested private types unless the importer needs them
1805 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1806 cache = MemberCache.Empty;
1810 var loading_type = (MetaType) provider;
1811 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1812 BindingFlags.Static | BindingFlags.Instance |
1813 BindingFlags.Public | BindingFlags.NonPublic;
1815 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1816 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1817 MethodAttributes.Final;
1819 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1820 List<EventSpec> imported_events = null;
1821 EventSpec event_spec;
1822 MemberSpec imported;
1826 all = loading_type.GetMembers (all_members);
1827 } catch (Exception e) {
1828 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1829 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1832 if (cache == null) {
1833 cache = new MemberCache (all.Length);
1836 // Do the types first as they can be referenced by the members before
1837 // they are found or inflated
1839 foreach (var member in all) {
1840 if (member.MemberType != MemberTypes.NestedType)
1843 var t = (MetaType) member;
1845 // Ignore compiler generated types, mostly lambda containers
1846 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate)
1849 imported = importer.CreateNestedType (t, declaringType);
1850 cache.AddMemberImported (imported);
1853 foreach (var member in all) {
1854 if (member.MemberType != MemberTypes.NestedType)
1857 var t = (MetaType) member;
1859 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate)
1862 importer.ImportTypeBase (t);
1868 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1870 foreach (var member in all) {
1871 switch (member.MemberType) {
1872 case MemberTypes.Constructor:
1873 case MemberTypes.Method:
1874 MethodBase mb = (MethodBase) member;
1875 var attrs = mb.Attributes;
1877 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1878 if (importer.IgnorePrivateMembers)
1881 // Ignore explicitly implemented members
1882 if ((attrs & explicit_impl) == explicit_impl)
1885 // Ignore compiler generated methods
1886 if (importer.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1890 imported = importer.CreateMethod (mb, declaringType);
1891 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1892 if (possible_accessors == null)
1893 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1895 // There are no metadata rules for accessors, we have to consider any method as possible candidate
1896 possible_accessors.Add (mb, (MethodSpec) imported);
1900 case MemberTypes.Property:
1901 if (possible_accessors == null)
1904 var p = (PropertyInfo) member;
1906 // Links possible accessors with property
1908 MethodSpec get, set;
1909 m = p.GetGetMethod (true);
1910 if (m == null || !possible_accessors.TryGetValue (m, out get))
1913 m = p.GetSetMethod (true);
1914 if (m == null || !possible_accessors.TryGetValue (m, out set))
1917 // No accessors registered (e.g. explicit implementation)
1918 if (get == null && set == null)
1921 imported = importer.CreateProperty (p, declaringType, get, set);
1922 if (imported == null)
1926 case MemberTypes.Event:
1927 if (possible_accessors == null)
1930 var e = (EventInfo) member;
1932 // Links accessors with event
1934 MethodSpec add, remove;
1935 m = e.GetAddMethod (true);
1936 if (m == null || !possible_accessors.TryGetValue (m, out add))
1939 m = e.GetRemoveMethod (true);
1940 if (m == null || !possible_accessors.TryGetValue (m, out remove))
1943 // Both accessors are required
1944 if (add == null || remove == null)
1947 event_spec = importer.CreateEvent (e, declaringType, add, remove);
1948 if (!importer.IgnorePrivateMembers) {
1949 if (imported_events == null)
1950 imported_events = new List<EventSpec> ();
1952 imported_events.Add (event_spec);
1955 imported = event_spec;
1957 case MemberTypes.Field:
1958 var fi = (FieldInfo) member;
1960 imported = importer.CreateField (fi, declaringType);
1961 if (imported == null)
1965 // For dynamic binder event has to be fully restored to allow operations
1966 // within the type container to work correctly
1968 if (imported_events != null) {
1969 // The backing event field should be private but it may not
1970 int index = imported_events.FindIndex (l => l.Name == fi.Name);
1972 event_spec = imported_events[index];
1973 event_spec.BackingField = (FieldSpec) imported;
1974 imported_events.RemoveAt (index);
1980 case MemberTypes.NestedType:
1981 // Already in the cache from the first pass
1984 throw new NotImplementedException (member.ToString ());
1987 cache.AddMemberImported (imported);
1991 if (declaringType.IsInterface && declaringType.Interfaces != null) {
1992 foreach (var iface in declaringType.Interfaces) {
1993 cache.AddInterface (iface);
1999 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2001 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2002 : base (type, importer)
2008 public IAssemblyDefinition DeclaringAssembly {
2010 throw new NotImplementedException ();
2014 public string Namespace {
2020 public int TypeParametersCount {
2026 public TypeParameterSpec[] TypeParameters {
2034 public TypeSpec GetAttributeCoClass ()
2039 public string GetAttributeDefaultMember ()
2041 throw new NotSupportedException ();
2044 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2046 throw new NotSupportedException ();
2049 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2051 throw new NotImplementedException ();
2054 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2056 throw new NotImplementedException ();