2 // import.cs: System.Reflection conversions
4 // Authors: Marek Safar (marek.safar@gmail.com)
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 // Copyright 2009-2011 Novell, Inc
9 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 using System.Runtime.CompilerServices;
15 using System.Collections.Generic;
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
29 public abstract class MetadataImporter
32 // Dynamic types reader with additional logic to reconstruct a dynamic
33 // type using DynamicAttribute values
35 struct DynamicTypeReader
37 static readonly bool[] single_attribute = { true };
42 // There is no common type for CustomAttributeData and we cannot
43 // use ICustomAttributeProvider
47 // A member provider which can be used to get CustomAttributeData
49 public DynamicTypeReader (object provider)
53 this.provider = provider;
57 // Returns true when object at local position has dynamic attribute flag
59 public bool IsDynamicObject (MetadataImporter importer)
62 ReadAttribute (importer);
64 return flags != null && Position < flags.Length && flags[Position];
68 // Returns true when DynamicAttribute exists
70 public bool HasDynamicAttribute (MetadataImporter importer)
73 ReadAttribute (importer);
78 void ReadAttribute (MetadataImporter importer)
80 IList<CustomAttributeData> cad;
81 if (provider is MemberInfo) {
82 cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
83 } else if (provider is ParameterInfo) {
84 cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
91 foreach (var ca in cad) {
92 var dt = ca.Constructor.DeclaringType;
93 if (dt.Name != "DynamicAttribute" && dt.Namespace != CompilerServicesNamespace)
96 if (ca.ConstructorArguments.Count == 0) {
97 flags = single_attribute;
101 var arg_type = ca.ConstructorArguments[0].ArgumentType;
103 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
104 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
105 flags = new bool[carg.Count];
106 for (int i = 0; i < flags.Length; ++i) {
107 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
108 flags[i] = (bool) carg[i].Value;
120 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
121 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
122 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
123 readonly ModuleContainer module;
125 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
127 protected MetadataImporter (ModuleContainer module)
129 this.module = module;
131 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
132 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
133 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
134 IgnorePrivateMembers = true;
139 public ICollection<IAssemblyDefinition> Assemblies {
141 return assembly_2_definition.Values;
145 public bool IgnorePrivateMembers { get; set; }
149 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
150 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
151 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
153 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
156 var fa = fi.Attributes;
157 switch (fa & FieldAttributes.FieldAccessMask) {
158 case FieldAttributes.Public:
159 mod = Modifiers.PUBLIC;
161 case FieldAttributes.Assembly:
162 mod = Modifiers.INTERNAL;
164 case FieldAttributes.Family:
165 mod = Modifiers.PROTECTED;
167 case FieldAttributes.FamORAssem:
168 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
171 // Ignore private fields (even for error reporting) to not require extra dependencies
172 if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
173 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 || TypeSpec.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.IsNotCSharpCompatible = 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 ();
687 // Generic type definition can also be forwarded
688 if (compiled_types.TryGetValue (type_def, out spec))
691 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
692 if (declaringType == null) {
693 // Simple case, no nesting
694 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
695 spec = spec.MakeGenericType (module, targs);
698 // Nested type case, converting .NET types like
699 // A`1.B`1.C`1<int, long, string> to typespec like
700 // A<int>.B<long>.C<string>
702 var nested_hierarchy = new List<TypeSpec> ();
703 while (declaringType.IsNested) {
704 nested_hierarchy.Add (declaringType);
705 declaringType = declaringType.DeclaringType;
709 if (declaringType.Arity > 0) {
710 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
711 targs_pos = spec.Arity;
713 spec = declaringType;
716 for (int i = nested_hierarchy.Count; i != 0; --i) {
717 var t = nested_hierarchy [i - 1];
718 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
720 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
721 targs_pos += t.Arity;
725 string name = type.Name;
726 int index = name.IndexOf ('`');
728 name = name.Substring (0, index);
730 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
734 if (spec.Arity > 0) {
735 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
739 // Don't add generic type with dynamic arguments, they can interfere with same type
740 // using object type arguments
741 if (!spec.HasDynamicElement) {
743 // Add to reading cache to speed up reading
744 if (!import_cache.ContainsKey (type))
745 import_cache.Add (type, spec);
754 var ma = type.Attributes;
755 switch (ma & TypeAttributes.VisibilityMask) {
756 case TypeAttributes.Public:
757 case TypeAttributes.NestedPublic:
758 mod = Modifiers.PUBLIC;
760 case TypeAttributes.NestedPrivate:
761 mod = Modifiers.PRIVATE;
763 case TypeAttributes.NestedFamily:
764 mod = Modifiers.PROTECTED;
766 case TypeAttributes.NestedFamORAssem:
767 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
770 mod = Modifiers.INTERNAL;
774 if ((ma & TypeAttributes.Interface) != 0) {
775 kind = MemberKind.Interface;
776 } else if (type.IsGenericParameter) {
777 kind = MemberKind.TypeParameter;
779 var base_type = type.BaseType;
780 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
781 kind = MemberKind.Class;
783 kind = DetermineKindFromBaseType (base_type);
784 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
785 mod |= Modifiers.SEALED;
789 if (kind == MemberKind.Class) {
790 if ((ma & TypeAttributes.Sealed) != 0) {
791 mod |= Modifiers.SEALED;
792 if ((ma & TypeAttributes.Abstract) != 0)
793 mod |= Modifiers.STATIC;
794 } else if ((ma & TypeAttributes.Abstract) != 0) {
795 mod |= Modifiers.ABSTRACT;
800 var definition = new ImportedTypeDefinition (type, this);
803 if (kind == MemberKind.Enum) {
804 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
805 BindingFlags.Instance |
806 BindingFlags.Public | BindingFlags.NonPublic;
808 var type_members = type.GetFields (underlying_member);
809 foreach (var type_member in type_members) {
810 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
815 kind = MemberKind.Class;
817 } else if (kind == MemberKind.TypeParameter) {
818 spec = CreateTypeParameter (type, declaringType);
819 } else if (type.IsGenericTypeDefinition) {
820 definition.TypeParameters = CreateGenericParameters (type, declaringType);
821 } else if (compiled_types.TryGetValue (type, out pt)) {
823 // Same type was found in inside compiled types. It's
824 // either build-in type or forward referenced typed
825 // which point into just compiled assembly.
828 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
830 bts.SetDefinition (definition, type, mod);
834 spec = new TypeSpec (kind, declaringType, definition, type, mod);
836 import_cache.Add (type, spec);
839 // Two stage setup as the base type can be inflated declaring type or
840 // another nested type inside same declaring type which has not been
841 // loaded, therefore we can import a base type of nested types once
842 // the types have been imported
844 if (canImportBaseType)
845 ImportTypeBase (spec, type);
850 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
852 IAssemblyDefinition found;
853 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
855 // This can happen in dynamic context only
856 var def = new ImportedAssemblyDefinition (assembly);
857 assembly_2_definition.Add (assembly, def);
858 def.ReadAttributes ();
865 public void ImportTypeBase (MetaType type)
867 TypeSpec spec = import_cache[type];
869 ImportTypeBase (spec, type);
872 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
875 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
876 case GenericParameterAttributes.Covariant:
877 variance = Variance.Covariant;
879 case GenericParameterAttributes.Contravariant:
880 variance = Variance.Contravariant;
883 variance = Variance.None;
887 SpecialConstraint special = SpecialConstraint.None;
888 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
890 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
891 special |= SpecialConstraint.Struct;
892 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
893 special = SpecialConstraint.Constructor;
896 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
897 special |= SpecialConstraint.Class;
900 TypeParameterSpec spec;
901 var def = new ImportedTypeParameterDefinition (type, this);
902 if (type.DeclaringMethod != null) {
903 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
905 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
912 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
913 // they can be assembly specific therefore we do check based on names only
915 public bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
917 if (attributesData.Count == 0)
920 foreach (var attr in attributesData) {
921 var dt = attr.Constructor.DeclaringType;
922 if (dt.Name == attrName && dt.Namespace == attrNamespace)
929 void ImportTypeBase (TypeSpec spec, MetaType type)
931 if (spec.Kind == MemberKind.Interface)
932 spec.BaseType = module.Compiler.BuiltinTypes.Object;
933 else if (type.BaseType != null) {
935 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
936 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
938 base_type = CreateType (type.BaseType);
940 spec.BaseType = base_type;
945 ifaces = type.__GetDeclaredInterfaces ();
946 if (ifaces.Length != 0) {
947 foreach (var iface in ifaces) {
948 var it = CreateType (iface);
952 spec.AddInterface (it);
954 // Unfortunately not all languages expand inherited interfaces
955 var bifaces = it.Interfaces;
956 if (bifaces != null) {
957 foreach (var biface in bifaces) {
958 spec.AddInterface (biface);
964 if (spec.BaseType != null) {
965 var bifaces = spec.BaseType.Interfaces;
966 if (bifaces != null) {
968 // Before adding base class interfaces close defined interfaces
971 var tp = spec as TypeParameterSpec;
972 if (tp != null && tp.InterfacesDefined == null) {
973 tp.InterfacesDefined = TypeSpec.EmptyTypes;
976 foreach (var iface in bifaces)
977 spec.AddInterface (iface);
981 ifaces = type.GetInterfaces ();
983 if (ifaces.Length > 0) {
984 foreach (var iface in ifaces) {
985 spec.AddInterface (CreateType (iface));
990 if (spec.MemberDefinition.TypeParametersCount > 0) {
991 foreach (var tp in spec.MemberDefinition.TypeParameters) {
992 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
998 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
1000 Namespace ns = targetNamespace;
1001 string prev_namespace = null;
1002 foreach (var t in types) {
1006 // Be careful not to trigger full parent type loading
1007 if (t.MemberType == MemberTypes.NestedType)
1010 if (t.Name[0] == '<')
1013 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1017 if (prev_namespace != t.Namespace) {
1018 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1019 prev_namespace = t.Namespace;
1022 ns.AddType (module, it);
1024 if (it.IsStatic && hasExtensionTypes &&
1025 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1026 it.SetExtensionMethodContainer ();
1031 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1033 var constraints = type.GetGenericParameterConstraints ();
1034 List<TypeSpec> tparams = null;
1035 foreach (var ct in constraints) {
1036 if (ct.IsGenericParameter) {
1037 if (tparams == null)
1038 tparams = new List<TypeSpec> ();
1040 tparams.Add (CreateType (ct));
1044 if (!IsMissingType (ct) && ct.IsClass) {
1045 spec.BaseType = CreateType (ct);
1049 spec.AddInterface (CreateType (ct));
1052 if (spec.BaseType == null)
1053 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1055 if (tparams != null)
1056 spec.TypeArguments = tparams.ToArray ();
1059 Constant ImportParameterConstant (object value)
1062 // Get type of underlying value as int constant can be used for object
1063 // parameter type. This is not allowed in C# but other languages can do that
1065 var types = module.Compiler.BuiltinTypes;
1066 switch (System.Type.GetTypeCode (value.GetType ())) {
1067 case TypeCode.Boolean:
1068 return new BoolConstant (types, (bool) value, Location.Null);
1070 return new ByteConstant (types, (byte) value, Location.Null);
1072 return new CharConstant (types, (char) value, Location.Null);
1073 case TypeCode.Decimal:
1074 return new DecimalConstant (types, (decimal) value, Location.Null);
1075 case TypeCode.Double:
1076 return new DoubleConstant (types, (double) value, Location.Null);
1077 case TypeCode.Int16:
1078 return new ShortConstant (types, (short) value, Location.Null);
1079 case TypeCode.Int32:
1080 return new IntConstant (types, (int) value, Location.Null);
1081 case TypeCode.Int64:
1082 return new LongConstant (types, (long) value, Location.Null);
1083 case TypeCode.SByte:
1084 return new SByteConstant (types, (sbyte) value, Location.Null);
1085 case TypeCode.Single:
1086 return new FloatConstant (types, (float) value, Location.Null);
1087 case TypeCode.String:
1088 return new StringConstant (types, (string) value, Location.Null);
1089 case TypeCode.UInt16:
1090 return new UShortConstant (types, (ushort) value, Location.Null);
1091 case TypeCode.UInt32:
1092 return new UIntConstant (types, (uint) value, Location.Null);
1093 case TypeCode.UInt64:
1094 return new ULongConstant (types, (ulong) value, Location.Null);
1097 throw new NotImplementedException (value.GetType ().ToString ());
1100 public TypeSpec ImportType (MetaType type)
1102 return ImportType (type, new DynamicTypeReader (type));
1105 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1107 if (type.HasElementType) {
1108 var element = type.GetElementType ();
1110 var spec = ImportType (element, dtype);
1113 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1115 return ReferenceContainer.MakeType (module, spec);
1117 return PointerContainer.MakeType (module, spec);
1119 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1122 return CreateType (type, dtype, true);
1125 static bool IsMissingType (MetaType type)
1128 return type.__IsMissing;
1135 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1136 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1137 // DecimalConstantAttribute metadata.
1139 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1141 if (attrs.Count == 0)
1144 foreach (var ca in attrs) {
1145 var dt = ca.Constructor.DeclaringType;
1146 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1149 var value = new decimal (
1150 (int) (uint) ca.ConstructorArguments[4].Value,
1151 (int) (uint) ca.ConstructorArguments[3].Value,
1152 (int) (uint) ca.ConstructorArguments[2].Value,
1153 (byte) ca.ConstructorArguments[1].Value != 0,
1154 (byte) ca.ConstructorArguments[0].Value);
1156 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1162 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1165 var ma = mb.Attributes;
1166 switch (ma & MethodAttributes.MemberAccessMask) {
1167 case MethodAttributes.Public:
1168 mod = Modifiers.PUBLIC;
1170 case MethodAttributes.Assembly:
1171 mod = Modifiers.INTERNAL;
1173 case MethodAttributes.Family:
1174 mod = Modifiers.PROTECTED;
1176 case MethodAttributes.FamORAssem:
1177 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1180 mod = Modifiers.PRIVATE;
1184 if ((ma & MethodAttributes.Static) != 0) {
1185 mod |= Modifiers.STATIC;
1188 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1189 mod |= Modifiers.ABSTRACT;
1193 // It can be sealed and override
1194 if ((ma & MethodAttributes.Final) != 0)
1195 mod |= Modifiers.SEALED;
1197 if ((ma & MethodAttributes.Virtual) != 0) {
1198 // Not every member can be detected based on MethodAttribute, we
1199 // set virtual or non-virtual only when we are certain. Further checks
1200 // to really find out what `virtual' means for this member are done
1202 if ((ma & MethodAttributes.NewSlot) != 0) {
1203 if ((mod & Modifiers.SEALED) != 0) {
1204 mod &= ~Modifiers.SEALED;
1206 mod |= Modifiers.VIRTUAL;
1209 mod |= Modifiers.OVERRIDE;
1217 abstract class ImportedDefinition : IMemberDefinition
1219 protected class AttributesBag
1221 public static readonly AttributesBag Default = new AttributesBag ();
1223 public AttributeUsageAttribute AttributeUsage;
1224 public ObsoleteAttribute Obsolete;
1225 public string[] Conditionals;
1226 public string DefaultIndexerName;
1227 public bool? CLSAttributeValue;
1228 public TypeSpec CoClass;
1230 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1232 AttributesBag bag = null;
1233 List<string> conditionals = null;
1235 // It should not throw any loading exception
1236 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1238 foreach (var a in attrs) {
1239 var dt = a.Constructor.DeclaringType;
1240 string name = dt.Name;
1241 if (name == "ObsoleteAttribute") {
1242 if (dt.Namespace != "System")
1246 bag = new AttributesBag ();
1248 var args = a.ConstructorArguments;
1250 if (args.Count == 1) {
1251 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1252 } else if (args.Count == 2) {
1253 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1255 bag.Obsolete = new ObsoleteAttribute ();
1261 if (name == "ConditionalAttribute") {
1262 if (dt.Namespace != "System.Diagnostics")
1266 bag = new AttributesBag ();
1268 if (conditionals == null)
1269 conditionals = new List<string> (2);
1271 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1275 if (name == "CLSCompliantAttribute") {
1276 if (dt.Namespace != "System")
1280 bag = new AttributesBag ();
1282 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1286 // Type only attributes
1287 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1288 if (name == "DefaultMemberAttribute") {
1289 if (dt.Namespace != "System.Reflection")
1293 bag = new AttributesBag ();
1295 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1299 if (name == "AttributeUsageAttribute") {
1300 if (dt.Namespace != "System")
1304 bag = new AttributesBag ();
1306 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1307 foreach (var named in a.NamedArguments) {
1308 if (named.MemberInfo.Name == "AllowMultiple")
1309 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1310 else if (named.MemberInfo.Name == "Inherited")
1311 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1316 // Interface only attribute
1317 if (name == "CoClassAttribute") {
1318 if (dt.Namespace != "System.Runtime.InteropServices")
1322 bag = new AttributesBag ();
1324 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1333 if (conditionals != null)
1334 bag.Conditionals = conditionals.ToArray ();
1340 protected readonly MemberInfo provider;
1341 protected AttributesBag cattrs;
1342 protected readonly MetadataImporter importer;
1344 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1346 this.provider = provider;
1347 this.importer = importer;
1352 public bool IsImported {
1358 public virtual string Name {
1360 return provider.Name;
1366 public string[] ConditionalConditions ()
1371 return cattrs.Conditionals;
1374 public ObsoleteAttribute GetAttributeObsolete ()
1379 return cattrs.Obsolete;
1382 public bool? CLSAttributeValue {
1387 return cattrs.CLSAttributeValue;
1391 protected void ReadAttributes ()
1393 cattrs = AttributesBag.Read (provider, importer);
1396 public void SetIsAssigned ()
1398 // Unused for imported members
1401 public void SetIsUsed ()
1403 // Unused for imported members
1407 public class ImportedModuleDefinition
1409 readonly Module module;
1412 public ImportedModuleDefinition (Module module)
1414 this.module = module;
1419 public bool IsCLSCompliant {
1421 return cls_compliant;
1425 public string Name {
1433 public void ReadAttributes ()
1435 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1437 foreach (var a in attrs) {
1438 var dt = a.Constructor.DeclaringType;
1439 if (dt.Name == "CLSCompliantAttribute") {
1440 if (dt.Namespace != "System")
1443 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1450 // Reads assembly attributes which where attached to a special type because
1451 // module does have assembly manifest
1453 public List<Attribute> ReadAssemblyAttributes ()
1455 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1459 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1463 // TODO: implement, the idea is to fabricate specil Attribute class and
1464 // add it to OptAttributes before resolving the source code attributes
1465 // Need to build module location as well for correct error reporting
1467 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1468 //var attrs = new List<Attribute> (assembly_attributes.Count);
1469 //foreach (var a in assembly_attributes)
1471 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1472 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1474 // foreach (var carg in a.ConstructorArguments) {
1478 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1485 public class ImportedAssemblyDefinition : IAssemblyDefinition
1487 readonly Assembly assembly;
1488 readonly AssemblyName aname;
1490 bool contains_extension_methods;
1492 List<AssemblyName> internals_visible_to;
1493 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1495 public ImportedAssemblyDefinition (Assembly assembly)
1497 this.assembly = assembly;
1498 this.aname = assembly.GetName ();
1503 public Assembly Assembly {
1509 public string FullName {
1511 return aname.FullName;
1515 public bool HasExtensionMethod {
1517 return contains_extension_methods;
1521 public bool HasStrongName {
1523 return aname.GetPublicKey ().Length != 0;
1527 public bool IsMissing {
1530 return assembly.__IsMissing;
1537 public bool IsCLSCompliant {
1539 return cls_compliant;
1543 public string Location {
1545 return assembly.Location;
1549 public string Name {
1557 public byte[] GetPublicKeyToken ()
1559 return aname.GetPublicKeyToken ();
1562 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1564 return internals_visible_to_cache [assembly];
1567 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1569 if (internals_visible_to == null)
1572 AssemblyName is_visible = null;
1573 if (internals_visible_to_cache == null) {
1574 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1576 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1577 return is_visible != null;
1580 var token = assembly.GetPublicKeyToken ();
1581 if (token != null && token.Length == 0)
1584 foreach (var internals in internals_visible_to) {
1585 if (internals.Name != assembly.Name)
1588 if (token == null && assembly is AssemblyDefinition) {
1589 is_visible = internals;
1593 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1596 is_visible = internals;
1600 internals_visible_to_cache.Add (assembly, is_visible);
1601 return is_visible != null;
1604 public void ReadAttributes ()
1607 if (assembly.__IsMissing)
1611 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1613 foreach (var a in attrs) {
1614 var dt = a.Constructor.DeclaringType;
1616 if (name == "CLSCompliantAttribute") {
1617 if (dt.Namespace == "System") {
1618 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1623 if (name == "InternalsVisibleToAttribute") {
1624 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1627 string s = a.ConstructorArguments[0].Value as string;
1631 var an = new AssemblyName (s);
1632 if (internals_visible_to == null)
1633 internals_visible_to = new List<AssemblyName> ();
1635 internals_visible_to.Add (an);
1639 if (name == "ExtensionAttribute") {
1640 if (dt.Namespace == MetadataImporter.CompilerServicesNamespace)
1641 contains_extension_methods = true;
1648 public override string ToString ()
1654 class ImportedMemberDefinition : ImportedDefinition
1656 readonly TypeSpec type;
1658 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1659 : base (member, importer)
1666 public TypeSpec MemberType {
1675 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1677 readonly AParametersCollection parameters;
1679 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1680 : base (provider, type, importer)
1682 this.parameters = parameters;
1685 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1686 : base (provider, type, importer)
1688 this.parameters = parameters;
1693 public AParametersCollection Parameters {
1702 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1704 readonly TypeParameterSpec[] tparams;
1706 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1707 : base (provider, type, parameters, importer)
1709 this.tparams = tparams;
1714 public TypeParameterSpec[] TypeParameters {
1720 public int TypeParametersCount {
1722 return tparams.Length;
1729 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1731 TypeParameterSpec[] tparams;
1734 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1735 : base (type, importer)
1741 public IAssemblyDefinition DeclaringAssembly {
1743 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1747 public override string Name {
1751 if (tparams != null) {
1752 int arity_start = name.IndexOf ('`');
1753 if (arity_start > 0)
1754 name = name.Substring (0, arity_start);
1762 public string Namespace {
1764 return ((MetaType) provider).Namespace;
1768 public int TypeParametersCount {
1770 return tparams == null ? 0 : tparams.Length;
1774 public TypeParameterSpec[] TypeParameters {
1785 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1788 // Report details about missing type and most likely cause of the problem.
1789 // csc reports 1683, 1684 as warnings but we report them only when used
1790 // or referenced from the user core in which case compilation error has to
1791 // be reported because compiler cannot continue anyway
1793 foreach (var t in types) {
1794 string name = t.GetSignatureForError ();
1796 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1797 ctx.Module.Compiler.Report.Error (1683, loc,
1798 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1800 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1801 ctx.Module.Compiler.Report.Error (12, loc,
1802 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1803 name, t.MemberDefinition.DeclaringAssembly.FullName);
1805 ctx.Module.Compiler.Report.Error (1684, loc,
1806 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1807 name, t.MemberDefinition.DeclaringAssembly.FullName);
1812 public TypeSpec GetAttributeCoClass ()
1817 return cattrs.CoClass;
1820 public string GetAttributeDefaultMember ()
1825 return cattrs.DefaultIndexerName;
1828 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1833 return cattrs.AttributeUsage;
1836 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1838 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1839 return a == assembly || a.IsFriendAssemblyTo (assembly);
1842 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1845 // Not interested in members of nested private types unless the importer needs them
1847 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1848 cache = MemberCache.Empty;
1852 var loading_type = (MetaType) provider;
1853 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1854 BindingFlags.Static | BindingFlags.Instance |
1855 BindingFlags.Public | BindingFlags.NonPublic;
1857 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1858 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1859 MethodAttributes.Final;
1861 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1862 List<EventSpec> imported_events = null;
1863 EventSpec event_spec;
1864 MemberSpec imported;
1868 all = loading_type.GetMembers (all_members);
1869 } catch (Exception e) {
1870 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1871 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1874 if (cache == null) {
1875 cache = new MemberCache (all.Length);
1878 // Do the types first as they can be referenced by the members before
1879 // they are found or inflated
1881 foreach (var member in all) {
1882 if (member.MemberType != MemberTypes.NestedType)
1885 var t = (MetaType) member;
1887 // Ignore compiler generated types, mostly lambda containers
1888 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1891 imported = importer.CreateNestedType (t, declaringType);
1892 cache.AddMemberImported (imported);
1895 foreach (var member in all) {
1896 if (member.MemberType != MemberTypes.NestedType)
1899 var t = (MetaType) member;
1901 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1904 importer.ImportTypeBase (t);
1909 // Load base interfaces first to minic behaviour of compiled members
1911 if (declaringType.IsInterface && declaringType.Interfaces != null) {
1912 foreach (var iface in declaringType.Interfaces) {
1913 cache.AddInterface (iface);
1919 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1921 foreach (var member in all) {
1922 switch (member.MemberType) {
1923 case MemberTypes.Constructor:
1924 case MemberTypes.Method:
1925 MethodBase mb = (MethodBase) member;
1926 var attrs = mb.Attributes;
1928 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1929 if (importer.IgnorePrivateMembers)
1932 // Ignore explicitly implemented members
1933 if ((attrs & explicit_impl) == explicit_impl)
1936 // Ignore compiler generated methods
1937 if (importer.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1941 imported = importer.CreateMethod (mb, declaringType);
1942 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1943 if (possible_accessors == null)
1944 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1946 // There are no metadata rules for accessors, we have to consider any method as possible candidate
1947 possible_accessors.Add (mb, (MethodSpec) imported);
1951 case MemberTypes.Property:
1952 if (possible_accessors == null)
1955 var p = (PropertyInfo) member;
1957 // Links possible accessors with property
1959 MethodSpec get, set;
1960 m = p.GetGetMethod (true);
1961 if (m == null || !possible_accessors.TryGetValue (m, out get))
1964 m = p.GetSetMethod (true);
1965 if (m == null || !possible_accessors.TryGetValue (m, out set))
1968 // No accessors registered (e.g. explicit implementation)
1969 if (get == null && set == null)
1972 imported = importer.CreateProperty (p, declaringType, get, set);
1973 if (imported == null)
1977 case MemberTypes.Event:
1978 if (possible_accessors == null)
1981 var e = (EventInfo) member;
1983 // Links accessors with event
1985 MethodSpec add, remove;
1986 m = e.GetAddMethod (true);
1987 if (m == null || !possible_accessors.TryGetValue (m, out add))
1990 m = e.GetRemoveMethod (true);
1991 if (m == null || !possible_accessors.TryGetValue (m, out remove))
1994 // Both accessors are required
1995 if (add == null || remove == null)
1998 event_spec = importer.CreateEvent (e, declaringType, add, remove);
1999 if (!importer.IgnorePrivateMembers) {
2000 if (imported_events == null)
2001 imported_events = new List<EventSpec> ();
2003 imported_events.Add (event_spec);
2006 imported = event_spec;
2008 case MemberTypes.Field:
2009 var fi = (FieldInfo) member;
2011 imported = importer.CreateField (fi, declaringType);
2012 if (imported == null)
2016 // For dynamic binder event has to be fully restored to allow operations
2017 // within the type container to work correctly
2019 if (imported_events != null) {
2020 // The backing event field should be private but it may not
2022 for (i = 0; i < imported_events.Count; ++i) {
2023 var ev = imported_events[i];
2024 if (ev.Name == fi.Name) {
2025 ev.BackingField = (FieldSpec) imported;
2026 imported_events.RemoveAt (i);
2037 case MemberTypes.NestedType:
2038 // Already in the cache from the first pass
2041 throw new NotImplementedException (member.ToString ());
2044 cache.AddMemberImported (imported);
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 ();