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);
838 if (kind == MemberKind.TypeParameter) {
839 if (canImportBaseType)
840 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
846 // Two stage setup as the base type can be inflated declaring type or
847 // another nested type inside same declaring type which has not been
848 // loaded, therefore we can import a base type of nested types once
849 // the types have been imported
851 if (canImportBaseType)
852 ImportTypeBase (spec, type);
857 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
859 IAssemblyDefinition found;
860 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
862 // This can happen in dynamic context only
863 var def = new ImportedAssemblyDefinition (assembly);
864 assembly_2_definition.Add (assembly, def);
865 def.ReadAttributes ();
872 public void ImportTypeBase (MetaType type)
874 TypeSpec spec = import_cache[type];
876 ImportTypeBase (spec, type);
879 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
882 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
883 case GenericParameterAttributes.Covariant:
884 variance = Variance.Covariant;
886 case GenericParameterAttributes.Contravariant:
887 variance = Variance.Contravariant;
890 variance = Variance.None;
894 SpecialConstraint special = SpecialConstraint.None;
895 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
897 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
898 special |= SpecialConstraint.Struct;
899 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
900 special = SpecialConstraint.Constructor;
903 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
904 special |= SpecialConstraint.Class;
907 TypeParameterSpec spec;
908 var def = new ImportedTypeParameterDefinition (type, this);
909 if (type.DeclaringMethod != null) {
910 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
912 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
919 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
920 // they can be assembly specific therefore we do check based on names only
922 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
924 if (attributesData.Count == 0)
927 foreach (var attr in attributesData) {
928 var dt = attr.Constructor.DeclaringType;
929 if (dt.Name == attrName && dt.Namespace == attrNamespace)
936 void ImportTypeBase (TypeSpec spec, MetaType type)
938 if (spec.Kind == MemberKind.Interface)
939 spec.BaseType = module.Compiler.BuiltinTypes.Object;
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 var it = CreateType (iface);
959 spec.AddInterface (it);
961 // Unfortunately not all languages expand inherited interfaces
962 var bifaces = it.Interfaces;
963 if (bifaces != null) {
964 foreach (var biface in bifaces) {
965 spec.AddInterface (biface);
971 if (spec.BaseType != null) {
972 var bifaces = spec.BaseType.Interfaces;
973 if (bifaces != null) {
975 // Before adding base class interfaces close defined interfaces
978 var tp = spec as TypeParameterSpec;
979 if (tp != null && tp.InterfacesDefined == null) {
980 tp.InterfacesDefined = TypeSpec.EmptyTypes;
983 foreach (var iface in bifaces)
984 spec.AddInterface (iface);
988 ifaces = type.GetInterfaces ();
990 if (ifaces.Length > 0) {
991 foreach (var iface in ifaces) {
992 spec.AddInterface (CreateType (iface));
997 if (spec.MemberDefinition.TypeParametersCount > 0) {
998 foreach (var tp in spec.MemberDefinition.TypeParameters) {
999 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1004 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
1006 Namespace ns = targetNamespace;
1007 string prev_namespace = null;
1008 foreach (var t in types) {
1012 // Be careful not to trigger full parent type loading
1013 if (t.MemberType == MemberTypes.NestedType)
1016 if (t.Name[0] == '<')
1019 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1023 if (prev_namespace != t.Namespace) {
1024 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1025 prev_namespace = t.Namespace;
1028 ns.AddType (module, it);
1030 if (it.IsStatic && hasExtensionTypes &&
1031 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1032 it.SetExtensionMethodContainer ();
1037 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1039 var constraints = type.GetGenericParameterConstraints ();
1040 List<TypeSpec> tparams = null;
1041 foreach (var ct in constraints) {
1042 if (ct.IsGenericParameter) {
1043 if (tparams == null)
1044 tparams = new List<TypeSpec> ();
1046 tparams.Add (CreateType (ct));
1050 if (!IsMissingType (ct) && ct.IsClass) {
1051 spec.BaseType = CreateType (ct);
1055 spec.AddInterface (CreateType (ct));
1058 if (spec.BaseType == null)
1059 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1061 if (tparams != null)
1062 spec.TypeArguments = tparams.ToArray ();
1065 Constant ImportParameterConstant (object value)
1068 // Get type of underlying value as int constant can be used for object
1069 // parameter type. This is not allowed in C# but other languages can do that
1071 var types = module.Compiler.BuiltinTypes;
1072 switch (System.Type.GetTypeCode (value.GetType ())) {
1073 case TypeCode.Boolean:
1074 return new BoolConstant (types, (bool) value, Location.Null);
1076 return new ByteConstant (types, (byte) value, Location.Null);
1078 return new CharConstant (types, (char) value, Location.Null);
1079 case TypeCode.Decimal:
1080 return new DecimalConstant (types, (decimal) value, Location.Null);
1081 case TypeCode.Double:
1082 return new DoubleConstant (types, (double) value, Location.Null);
1083 case TypeCode.Int16:
1084 return new ShortConstant (types, (short) value, Location.Null);
1085 case TypeCode.Int32:
1086 return new IntConstant (types, (int) value, Location.Null);
1087 case TypeCode.Int64:
1088 return new LongConstant (types, (long) value, Location.Null);
1089 case TypeCode.SByte:
1090 return new SByteConstant (types, (sbyte) value, Location.Null);
1091 case TypeCode.Single:
1092 return new FloatConstant (types, (float) value, Location.Null);
1093 case TypeCode.String:
1094 return new StringConstant (types, (string) value, Location.Null);
1095 case TypeCode.UInt16:
1096 return new UShortConstant (types, (ushort) value, Location.Null);
1097 case TypeCode.UInt32:
1098 return new UIntConstant (types, (uint) value, Location.Null);
1099 case TypeCode.UInt64:
1100 return new ULongConstant (types, (ulong) value, Location.Null);
1103 throw new NotImplementedException (value.GetType ().ToString ());
1106 public TypeSpec ImportType (MetaType type)
1108 return ImportType (type, new DynamicTypeReader (type));
1111 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1113 if (type.HasElementType) {
1114 var element = type.GetElementType ();
1116 var spec = ImportType (element, dtype);
1119 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1121 return ReferenceContainer.MakeType (module, spec);
1123 return PointerContainer.MakeType (module, spec);
1125 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1128 return CreateType (type, dtype, true);
1131 static bool IsMissingType (MetaType type)
1134 return type.__IsMissing;
1141 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1142 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1143 // DecimalConstantAttribute metadata.
1145 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1147 if (attrs.Count == 0)
1150 foreach (var ca in attrs) {
1151 var dt = ca.Constructor.DeclaringType;
1152 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1155 var value = new decimal (
1156 (int) (uint) ca.ConstructorArguments[4].Value,
1157 (int) (uint) ca.ConstructorArguments[3].Value,
1158 (int) (uint) ca.ConstructorArguments[2].Value,
1159 (byte) ca.ConstructorArguments[1].Value != 0,
1160 (byte) ca.ConstructorArguments[0].Value);
1162 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1168 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1171 var ma = mb.Attributes;
1172 switch (ma & MethodAttributes.MemberAccessMask) {
1173 case MethodAttributes.Public:
1174 mod = Modifiers.PUBLIC;
1176 case MethodAttributes.Assembly:
1177 mod = Modifiers.INTERNAL;
1179 case MethodAttributes.Family:
1180 mod = Modifiers.PROTECTED;
1182 case MethodAttributes.FamORAssem:
1183 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1186 mod = Modifiers.PRIVATE;
1190 if ((ma & MethodAttributes.Static) != 0) {
1191 mod |= Modifiers.STATIC;
1194 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1195 mod |= Modifiers.ABSTRACT;
1199 // It can be sealed and override
1200 if ((ma & MethodAttributes.Final) != 0)
1201 mod |= Modifiers.SEALED;
1203 if ((ma & MethodAttributes.Virtual) != 0) {
1204 // Not every member can be detected based on MethodAttribute, we
1205 // set virtual or non-virtual only when we are certain. Further checks
1206 // to really find out what `virtual' means for this member are done
1208 if ((ma & MethodAttributes.NewSlot) != 0) {
1209 if ((mod & Modifiers.SEALED) != 0) {
1210 mod &= ~Modifiers.SEALED;
1212 mod |= Modifiers.VIRTUAL;
1215 mod |= Modifiers.OVERRIDE;
1223 abstract class ImportedDefinition : IMemberDefinition
1225 protected class AttributesBag
1227 public static readonly AttributesBag Default = new AttributesBag ();
1229 public AttributeUsageAttribute AttributeUsage;
1230 public ObsoleteAttribute Obsolete;
1231 public string[] Conditionals;
1232 public string DefaultIndexerName;
1233 public bool? CLSAttributeValue;
1234 public TypeSpec CoClass;
1236 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1238 AttributesBag bag = null;
1239 List<string> conditionals = null;
1241 // It should not throw any loading exception
1242 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1244 foreach (var a in attrs) {
1245 var dt = a.Constructor.DeclaringType;
1246 string name = dt.Name;
1247 if (name == "ObsoleteAttribute") {
1248 if (dt.Namespace != "System")
1252 bag = new AttributesBag ();
1254 var args = a.ConstructorArguments;
1256 if (args.Count == 1) {
1257 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1258 } else if (args.Count == 2) {
1259 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1261 bag.Obsolete = new ObsoleteAttribute ();
1267 if (name == "ConditionalAttribute") {
1268 if (dt.Namespace != "System.Diagnostics")
1272 bag = new AttributesBag ();
1274 if (conditionals == null)
1275 conditionals = new List<string> (2);
1277 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1281 if (name == "CLSCompliantAttribute") {
1282 if (dt.Namespace != "System")
1286 bag = new AttributesBag ();
1288 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1292 // Type only attributes
1293 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1294 if (name == "DefaultMemberAttribute") {
1295 if (dt.Namespace != "System.Reflection")
1299 bag = new AttributesBag ();
1301 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1305 if (name == "AttributeUsageAttribute") {
1306 if (dt.Namespace != "System")
1310 bag = new AttributesBag ();
1312 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1313 foreach (var named in a.NamedArguments) {
1314 if (named.MemberInfo.Name == "AllowMultiple")
1315 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1316 else if (named.MemberInfo.Name == "Inherited")
1317 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1322 // Interface only attribute
1323 if (name == "CoClassAttribute") {
1324 if (dt.Namespace != "System.Runtime.InteropServices")
1328 bag = new AttributesBag ();
1330 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1339 if (conditionals != null)
1340 bag.Conditionals = conditionals.ToArray ();
1346 protected readonly MemberInfo provider;
1347 protected AttributesBag cattrs;
1348 protected readonly MetadataImporter importer;
1350 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1352 this.provider = provider;
1353 this.importer = importer;
1358 public bool IsImported {
1364 public virtual string Name {
1366 return provider.Name;
1372 public string[] ConditionalConditions ()
1377 return cattrs.Conditionals;
1380 public ObsoleteAttribute GetAttributeObsolete ()
1385 return cattrs.Obsolete;
1388 public bool? CLSAttributeValue {
1393 return cattrs.CLSAttributeValue;
1397 protected void ReadAttributes ()
1399 cattrs = AttributesBag.Read (provider, importer);
1402 public void SetIsAssigned ()
1404 // Unused for imported members
1407 public void SetIsUsed ()
1409 // Unused for imported members
1413 public class ImportedModuleDefinition
1415 readonly Module module;
1418 public ImportedModuleDefinition (Module module)
1420 this.module = module;
1425 public bool IsCLSCompliant {
1427 return cls_compliant;
1431 public string Name {
1439 public void ReadAttributes ()
1441 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1443 foreach (var a in attrs) {
1444 var dt = a.Constructor.DeclaringType;
1445 if (dt.Name == "CLSCompliantAttribute") {
1446 if (dt.Namespace != "System")
1449 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1456 // Reads assembly attributes which where attached to a special type because
1457 // module does have assembly manifest
1459 public List<Attribute> ReadAssemblyAttributes ()
1461 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1465 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1469 // TODO: implement, the idea is to fabricate specil Attribute class and
1470 // add it to OptAttributes before resolving the source code attributes
1471 // Need to build module location as well for correct error reporting
1473 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1474 //var attrs = new List<Attribute> (assembly_attributes.Count);
1475 //foreach (var a in assembly_attributes)
1477 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1478 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1480 // foreach (var carg in a.ConstructorArguments) {
1484 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1491 public class ImportedAssemblyDefinition : IAssemblyDefinition
1493 readonly Assembly assembly;
1494 readonly AssemblyName aname;
1496 bool contains_extension_methods;
1498 List<AssemblyName> internals_visible_to;
1499 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1501 public ImportedAssemblyDefinition (Assembly assembly)
1503 this.assembly = assembly;
1504 this.aname = assembly.GetName ();
1509 public Assembly Assembly {
1515 public string FullName {
1517 return aname.FullName;
1521 public bool HasExtensionMethod {
1523 return contains_extension_methods;
1527 public bool HasStrongName {
1529 return aname.GetPublicKey ().Length != 0;
1533 public bool IsMissing {
1536 return assembly.__IsMissing;
1543 public bool IsCLSCompliant {
1545 return cls_compliant;
1549 public string Location {
1551 return assembly.Location;
1555 public string Name {
1563 public byte[] GetPublicKeyToken ()
1565 return aname.GetPublicKeyToken ();
1568 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1570 return internals_visible_to_cache [assembly];
1573 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1575 if (internals_visible_to == null)
1578 AssemblyName is_visible = null;
1579 if (internals_visible_to_cache == null) {
1580 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1582 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1583 return is_visible != null;
1586 var token = assembly.GetPublicKeyToken ();
1587 if (token != null && token.Length == 0)
1590 foreach (var internals in internals_visible_to) {
1591 if (internals.Name != assembly.Name)
1594 if (token == null && assembly is AssemblyDefinition) {
1595 is_visible = internals;
1599 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1602 is_visible = internals;
1606 internals_visible_to_cache.Add (assembly, is_visible);
1607 return is_visible != null;
1610 public void ReadAttributes ()
1613 if (assembly.__IsMissing)
1617 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1619 foreach (var a in attrs) {
1620 var dt = a.Constructor.DeclaringType;
1622 if (name == "CLSCompliantAttribute") {
1623 if (dt.Namespace == "System") {
1624 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1629 if (name == "InternalsVisibleToAttribute") {
1630 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1633 string s = a.ConstructorArguments[0].Value as string;
1637 var an = new AssemblyName (s);
1638 if (internals_visible_to == null)
1639 internals_visible_to = new List<AssemblyName> ();
1641 internals_visible_to.Add (an);
1645 if (name == "ExtensionAttribute") {
1646 if (dt.Namespace == MetadataImporter.CompilerServicesNamespace)
1647 contains_extension_methods = true;
1654 public override string ToString ()
1660 class ImportedMemberDefinition : ImportedDefinition
1662 readonly TypeSpec type;
1664 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1665 : base (member, importer)
1672 public TypeSpec MemberType {
1681 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1683 readonly AParametersCollection parameters;
1685 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1686 : base (provider, type, importer)
1688 this.parameters = parameters;
1691 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1692 : base (provider, type, importer)
1694 this.parameters = parameters;
1699 public AParametersCollection Parameters {
1708 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1710 readonly TypeParameterSpec[] tparams;
1712 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1713 : base (provider, type, parameters, importer)
1715 this.tparams = tparams;
1720 public TypeParameterSpec[] TypeParameters {
1726 public int TypeParametersCount {
1728 return tparams.Length;
1735 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1737 TypeParameterSpec[] tparams;
1740 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1741 : base (type, importer)
1747 public IAssemblyDefinition DeclaringAssembly {
1749 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1753 bool ITypeDefinition.IsPartial {
1759 public override string Name {
1763 if (tparams != null) {
1764 int arity_start = name.IndexOf ('`');
1765 if (arity_start > 0)
1766 name = name.Substring (0, arity_start);
1774 public string Namespace {
1776 return ((MetaType) provider).Namespace;
1780 public int TypeParametersCount {
1782 return tparams == null ? 0 : tparams.Length;
1786 public TypeParameterSpec[] TypeParameters {
1797 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1800 // Report details about missing type and most likely cause of the problem.
1801 // csc reports 1683, 1684 as warnings but we report them only when used
1802 // or referenced from the user core in which case compilation error has to
1803 // be reported because compiler cannot continue anyway
1805 for (int i = 0; i < types.Count; ++i) {
1809 // Report missing types only once per type
1811 if (i > 0 && types.IndexOf (t) < i)
1814 string name = t.GetSignatureForError ();
1816 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1817 ctx.Module.Compiler.Report.Error (1683, loc,
1818 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1820 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1821 ctx.Module.Compiler.Report.Error (12, loc,
1822 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1823 name, t.MemberDefinition.DeclaringAssembly.FullName);
1825 ctx.Module.Compiler.Report.Error (1684, loc,
1826 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1827 name, t.MemberDefinition.DeclaringAssembly.FullName);
1832 public TypeSpec GetAttributeCoClass ()
1837 return cattrs.CoClass;
1840 public string GetAttributeDefaultMember ()
1845 return cattrs.DefaultIndexerName;
1848 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1853 return cattrs.AttributeUsage;
1856 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1858 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1859 return a == assembly || a.IsFriendAssemblyTo (assembly);
1862 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1865 // Not interested in members of nested private types unless the importer needs them
1867 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1868 cache = MemberCache.Empty;
1872 var loading_type = (MetaType) provider;
1873 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1874 BindingFlags.Static | BindingFlags.Instance |
1875 BindingFlags.Public | BindingFlags.NonPublic;
1877 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1878 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1879 MethodAttributes.Final;
1881 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1882 List<EventSpec> imported_events = null;
1883 EventSpec event_spec;
1884 MemberSpec imported;
1888 all = loading_type.GetMembers (all_members);
1889 } catch (Exception e) {
1890 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1891 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1894 if (cache == null) {
1895 cache = new MemberCache (all.Length);
1898 // Do the types first as they can be referenced by the members before
1899 // they are found or inflated
1901 foreach (var member in all) {
1902 if (member.MemberType != MemberTypes.NestedType)
1905 var t = (MetaType) member;
1907 // Ignore compiler generated types, mostly lambda containers
1908 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1912 imported = importer.CreateNestedType (t, declaringType);
1913 } catch (Exception e) {
1914 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
1915 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
1918 cache.AddMemberImported (imported);
1921 foreach (var member in all) {
1922 if (member.MemberType != MemberTypes.NestedType)
1925 var t = (MetaType) member;
1927 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1930 importer.ImportTypeBase (t);
1935 // Load base interfaces first to minic behaviour of compiled members
1937 if (declaringType.IsInterface && declaringType.Interfaces != null) {
1938 foreach (var iface in declaringType.Interfaces) {
1939 cache.AddInterface (iface);
1945 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1947 foreach (var member in all) {
1948 switch (member.MemberType) {
1949 case MemberTypes.Constructor:
1950 case MemberTypes.Method:
1951 MethodBase mb = (MethodBase) member;
1952 var attrs = mb.Attributes;
1954 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1955 if (importer.IgnorePrivateMembers)
1958 // Ignore explicitly implemented members
1959 if ((attrs & explicit_impl) == explicit_impl)
1962 // Ignore compiler generated methods
1963 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1967 imported = importer.CreateMethod (mb, declaringType);
1968 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1969 if (possible_accessors == null)
1970 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1972 // There are no metadata rules for accessors, we have to consider any method as possible candidate
1973 possible_accessors.Add (mb, (MethodSpec) imported);
1977 case MemberTypes.Property:
1978 if (possible_accessors == null)
1981 var p = (PropertyInfo) member;
1983 // Links possible accessors with property
1985 MethodSpec get, set;
1986 m = p.GetGetMethod (true);
1987 if (m == null || !possible_accessors.TryGetValue (m, out get))
1990 m = p.GetSetMethod (true);
1991 if (m == null || !possible_accessors.TryGetValue (m, out set))
1994 // No accessors registered (e.g. explicit implementation)
1995 if (get == null && set == null)
1998 imported = importer.CreateProperty (p, declaringType, get, set);
1999 if (imported == null)
2003 case MemberTypes.Event:
2004 if (possible_accessors == null)
2007 var e = (EventInfo) member;
2009 // Links accessors with event
2011 MethodSpec add, remove;
2012 m = e.GetAddMethod (true);
2013 if (m == null || !possible_accessors.TryGetValue (m, out add))
2016 m = e.GetRemoveMethod (true);
2017 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2020 // Both accessors are required
2021 if (add == null || remove == null)
2024 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2025 if (!importer.IgnorePrivateMembers) {
2026 if (imported_events == null)
2027 imported_events = new List<EventSpec> ();
2029 imported_events.Add (event_spec);
2032 imported = event_spec;
2034 case MemberTypes.Field:
2035 var fi = (FieldInfo) member;
2037 imported = importer.CreateField (fi, declaringType);
2038 if (imported == null)
2042 // For dynamic binder event has to be fully restored to allow operations
2043 // within the type container to work correctly
2045 if (imported_events != null) {
2046 // The backing event field should be private but it may not
2048 for (i = 0; i < imported_events.Count; ++i) {
2049 var ev = imported_events[i];
2050 if (ev.Name == fi.Name) {
2051 ev.BackingField = (FieldSpec) imported;
2052 imported_events.RemoveAt (i);
2063 case MemberTypes.NestedType:
2064 // Already in the cache from the first pass
2067 throw new NotImplementedException (member.ToString ());
2070 cache.AddMemberImported (imported);
2076 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2078 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2079 : base (type, importer)
2085 public IAssemblyDefinition DeclaringAssembly {
2087 throw new NotImplementedException ();
2091 bool ITypeDefinition.IsPartial {
2097 public string Namespace {
2103 public int TypeParametersCount {
2109 public TypeParameterSpec[] TypeParameters {
2117 public TypeSpec GetAttributeCoClass ()
2122 public string GetAttributeDefaultMember ()
2124 throw new NotSupportedException ();
2127 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2129 throw new NotSupportedException ();
2132 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2134 throw new NotImplementedException ();
2137 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2139 throw new NotImplementedException ();