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-2012 Xamarin, Inc (http://www.xamarin.com)
13 using System.Runtime.CompilerServices;
15 using System.Collections.Generic;
19 using MetaType = IKVM.Reflection.Type;
20 using IKVM.Reflection;
21 using IKVM.Reflection.Emit;
23 using MetaType = System.Type;
24 using System.Reflection;
25 using System.Reflection.Emit;
30 public abstract class MetadataImporter
33 // Dynamic types reader with additional logic to reconstruct a dynamic
34 // type using DynamicAttribute values
36 protected struct DynamicTypeReader
38 static readonly bool[] single_attribute = { true };
43 // There is no common type for CustomAttributeData and we cannot
44 // use ICustomAttributeProvider
48 // A member provider which can be used to get CustomAttributeData
50 public DynamicTypeReader (object provider)
54 this.provider = provider;
58 // Returns true when object at local position has dynamic attribute flag
60 public bool IsDynamicObject ()
65 return flags != null && Position < flags.Length && flags[Position];
69 // Returns true when DynamicAttribute exists
71 public bool HasDynamicAttribute ()
79 IList<CustomAttributeData> GetCustomAttributes ()
81 var mi = provider as MemberInfo;
83 return CustomAttributeData.GetCustomAttributes (mi);
85 var pi = provider as ParameterInfo;
87 return CustomAttributeData.GetCustomAttributes (pi);
95 var cad = GetCustomAttributes ();
101 foreach (var ca in cad) {
102 var dt = ca.Constructor.DeclaringType;
103 if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace)
106 if (ca.ConstructorArguments.Count == 0) {
107 flags = single_attribute;
111 var arg_type = ca.ConstructorArguments[0].ArgumentType;
113 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
114 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
115 flags = new bool[carg.Count];
116 for (int i = 0; i < flags.Length; ++i) {
117 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
118 flags[i] = (bool) carg[i].Value;
130 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
131 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
132 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
133 protected readonly ModuleContainer module;
135 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
137 protected MetadataImporter (ModuleContainer module)
139 this.module = module;
141 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
142 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
143 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
144 IgnorePrivateMembers = true;
145 IgnoreCompilerGeneratedField = true;
150 public ICollection<IAssemblyDefinition> Assemblies {
152 return assembly_2_definition.Values;
156 public bool IgnorePrivateMembers { get; set; }
158 public bool IgnoreCompilerGeneratedField { get; set; }
162 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
163 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
164 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
166 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
169 var fa = fi.Attributes;
170 switch (fa & FieldAttributes.FieldAccessMask) {
171 case FieldAttributes.Public:
172 mod = Modifiers.PUBLIC;
174 case FieldAttributes.Assembly:
175 mod = Modifiers.INTERNAL;
177 case FieldAttributes.Family:
178 mod = Modifiers.PROTECTED;
180 case FieldAttributes.FamORAssem:
181 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
184 // Ignore private fields (even for error reporting) to not require extra dependencies
185 if (IgnorePrivateMembers && !declaringType.IsStruct)
188 if (IgnoreCompilerGeneratedField && HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
191 mod = Modifiers.PRIVATE;
198 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi), declaringType);
201 // Private field has private type which is not fixed buffer
203 if (field_type == null)
205 } catch (Exception e) {
206 // TODO: I should construct fake TypeSpec based on TypeRef signature
207 // but there is no way to do it with System.Reflection
208 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
209 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
212 var definition = new ImportedMemberDefinition (fi, field_type, this);
214 if ((fa & FieldAttributes.Literal) != 0) {
215 Constant c = field_type.Kind == MemberKind.MissingType ?
216 new NullConstant (InternalType.ErrorType, Location.Null) :
217 CreateConstantFromValue (field_type, fi);
218 return new ConstSpec (declaringType, definition, field_type, fi, mod | Modifiers.STATIC, c);
221 if ((fa & FieldAttributes.InitOnly) != 0) {
222 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
223 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
225 return new ConstSpec (declaringType, definition, field_type, fi, mod | Modifiers.STATIC, dc);
228 mod |= Modifiers.READONLY;
230 var req_mod = fi.GetRequiredCustomModifiers ();
231 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
232 mod |= Modifiers.VOLATILE;
235 if ((fa & FieldAttributes.Static) != 0) {
236 mod |= Modifiers.STATIC;
238 // Fixed buffers cannot be static
239 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
240 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
242 // TODO: Sanity check on field_type (only few types are allowed)
243 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
244 return new FixedFieldSpec (module, declaringType, definition, fi, element_field, mod);
248 return new FieldSpec (declaringType, definition, field_type, fi, mod);
251 Constant CreateConstantFromValue (TypeSpec fieldType, FieldInfo fi)
253 var value = fi.GetRawConstantValue ();
255 // Metadata value can be encoded using different constant value type
256 // than is actual field type
258 // e.g. unsigned int16 CONSTANT = int16 (0x0000ffff)
260 if (value != null && !fieldType.IsEnum) {
261 var c = ImportConstant (value);
263 return fieldType == c.Type ? c : c.ConvertExplicitly (false, fieldType);
267 return Constant.CreateConstantFromValue (fieldType, value, Location.Null);
270 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
272 add.IsAccessor = true;
273 remove.IsAccessor = true;
275 if (add.Modifiers != remove.Modifiers)
276 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
278 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei), declaringType);
279 var definition = new ImportedMemberDefinition (ei, event_type, this);
280 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
283 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
285 var tparams = type.GetGenericArguments ();
287 int parent_owned_count;
289 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
292 // System.Reflection duplicates parent type parameters for each
293 // nested type with slightly modified properties (eg. different owner)
294 // This just makes things more complicated (think of cloned constraints)
295 // therefore we remap any nested type owned by parent using `type_cache'
296 // to the single TypeParameterSpec
298 if (declaringType != null && parent_owned_count > 0) {
300 while (read_count != parent_owned_count) {
301 var tparams_count = declaringType.Arity;
302 if (tparams_count != 0) {
303 var parent_tp = declaringType.MemberDefinition.TypeParameters;
304 read_count += tparams_count;
305 for (int i = 0; i < tparams_count; i++) {
306 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
310 declaringType = declaringType.DeclaringType;
314 parent_owned_count = 0;
317 if (tparams.Length - parent_owned_count == 0)
320 return CreateGenericParameters (parent_owned_count, tparams);
323 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
325 var tspec = new TypeParameterSpec[tparams.Length - first];
326 for (int pos = first; pos < tparams.Length; ++pos) {
327 var type = tparams[pos];
328 int index = pos - first;
330 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
336 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
340 var tspec = new TypeSpec [tparams.Length - first];
341 for (int pos = first; pos < tparams.Length; ++pos) {
342 var type = tparams[pos];
343 int index = pos - first;
346 if (type.HasElementType) {
347 var element = type.GetElementType ();
349 spec = ImportType (element, dtype, null);
352 throw new NotImplementedException ("Unknown element type " + type.ToString ());
355 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
357 spec = CreateType (type, dtype, true);
360 // We treat nested generic types as inflated internally where
361 // reflection uses type definition
364 // IFoo<A<T>> foo; // A<T> is definition in this case
367 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
368 var start_pos = GetDeclaringTypesTypeParametersCount (spec);
369 var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype);
370 spec = spec.MakeGenericType (module, targs);
384 static int GetDeclaringTypesTypeParametersCount (TypeSpec spec)
387 while (spec.DeclaringType != null) {
388 total += spec.DeclaringType.MemberDefinition.TypeParametersCount;
389 spec = spec.DeclaringType;
395 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
397 Modifiers mod = ReadMethodModifiers (mb, declaringType);
398 TypeParameterSpec[] tparams;
400 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
402 if (mb.IsGenericMethod) {
403 if (!mb.IsGenericMethodDefinition)
404 throw new NotSupportedException ("assert");
406 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
413 if (mb.MemberType == MemberTypes.Constructor) {
414 kind = MemberKind.Constructor;
415 returnType = module.Compiler.BuiltinTypes.Void;
417 var mi = (MethodInfo)mb;
418 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter), declaringType);
421 // Detect operators and destructors
423 string name = mb.Name;
424 kind = MemberKind.Method;
425 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
426 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
427 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o' && (mb.Attributes & MethodAttributes.SpecialName) != 0) {
428 var op_type = Operator.GetType (name);
429 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
430 kind = MemberKind.Operator;
433 } else if (parameters.IsEmpty && name == Destructor.MetadataName && returnType.Kind == MemberKind.Void) {
434 kind = MemberKind.Destructor;
435 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
436 mod &= ~Modifiers.OVERRIDE;
437 mod |= Modifiers.VIRTUAL;
442 // Cannot set to OVERRIDE without full hierarchy checks
443 // this flag indicates that the method could be override
444 // but further validation is needed
445 if ((mod & Modifiers.OVERRIDE) != 0) {
446 bool is_real_override = false;
447 if (kind == MemberKind.Method && declaringType.BaseType != null) {
448 var btype = declaringType.BaseType;
449 if (IsOverrideMethodBaseTypeAccessible (btype)) {
450 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
451 var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
454 // For imported class method do additional validation to be sure that metadata
455 // override flag was correct
457 // Difference between protected internal and protected is ok
459 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
460 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
461 is_real_override = true;
466 if (!is_real_override) {
467 mod &= ~Modifiers.OVERRIDE;
468 if ((mod & Modifiers.SEALED) != 0)
469 mod &= ~Modifiers.SEALED;
471 mod |= Modifiers.VIRTUAL;
473 } else if (parameters.HasExtensionMethodType) {
474 mod |= Modifiers.METHOD_EXTENSION;
478 IMethodDefinition definition;
479 if (tparams != null) {
480 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
481 foreach (var tp in gmd.TypeParameters) {
482 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
487 definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
490 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
497 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
499 switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
500 case Modifiers.PUBLIC:
502 case Modifiers.INTERNAL:
504 // Check whether imported method in base type is accessible from compiled
507 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
508 case Modifiers.PRIVATE:
512 // protected internal
514 // Method accessibility checks will be done later based on context
515 // where the method is called (CS0122 error will be reported for inaccessible)
522 // Imports System.Reflection parameters
524 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
526 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
528 if (pi.Length == 0 && varargs == 0)
529 return ParametersCompiled.EmptyReadOnlyParameters;
531 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
532 IParameterData[] par = new IParameterData[pi.Length + varargs];
533 bool is_params = false;
534 for (int i = 0; i < pi.Length; i++) {
535 ParameterInfo p = pi[i];
536 Parameter.Modifier mod = 0;
537 Expression default_value = null;
538 if (p.ParameterType.IsByRef) {
539 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
540 mod = Parameter.Modifier.OUT;
542 mod = Parameter.Modifier.REF;
545 // Strip reference wrapping
547 var el = p.ParameterType.GetElementType ();
548 types[i] = ImportType (el, new DynamicTypeReader (p), parent); // TODO: 1-based positio to be csc compatible
549 } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
550 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
551 mod = Parameter.Modifier.This;
552 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p), parent);
554 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p), parent);
556 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
557 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
558 mod = Parameter.Modifier.PARAMS;
563 if (!is_params && p.IsOptional) {
564 object value = p.RawDefaultValue;
565 var ptype = types[i];
566 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
568 default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
570 default_value = ImportConstant (value);
573 default_value = new EnumConstant ((Constant) default_value, ptype);
577 var attrs = CustomAttributeData.GetCustomAttributes (p);
578 for (int ii = 0; ii < attrs.Count; ++ii) {
579 var attr = attrs[ii];
580 var dt = attr.Constructor.DeclaringType;
581 if (dt.Namespace != CompilerServicesNamespace)
584 if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
585 mod |= Parameter.Modifier.CallerLineNumber;
586 else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
587 mod |= Parameter.Modifier.CallerFilePath;
588 else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
589 mod |= Parameter.Modifier.CallerMemberName;
591 } else if (value == Missing.Value) {
592 default_value = EmptyExpression.MissingValue;
593 } else if (value == null) {
594 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
595 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
596 default_value = ImportConstant (value);
601 par[i] = new ParameterData (p.Name, mod, default_value);
605 par[par.Length - 1] = new ArglistParameter (Location.Null);
606 types[types.Length - 1] = InternalType.Arglist;
609 return method != null ?
610 new ParametersImported (par, types, varargs != 0, is_params) :
611 new ParametersImported (par, types, is_params);
615 // Returns null when the property is not valid C# property
617 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
620 AParametersCollection param = null;
621 TypeSpec type = null;
624 param = get.Parameters;
625 type = get.ReturnType;
628 bool is_valid_property = true;
630 if (set.ReturnType.Kind != MemberKind.Void)
631 is_valid_property = false;
633 var set_param_count = set.Parameters.Count - 1;
635 if (set_param_count < 0) {
637 is_valid_property = false;
640 var set_type = set.Parameters.Types[set_param_count];
643 AParametersCollection set_based_param;
645 if (set_param_count == 0) {
646 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
648 set_based_param = IndexerSpec.CreateParametersFromSetter (set, set_param_count);
652 param = set_based_param;
655 if (set_param_count != get.Parameters.Count)
656 is_valid_property = false;
658 if (get.ReturnType != set_type)
659 is_valid_property = false;
661 // Possible custom accessor modifiers
662 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
663 var get_acc = mod & Modifiers.AccessibilityMask;
664 if (get_acc != Modifiers.PUBLIC) {
665 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
666 // If the accessor modifiers are not same, do extra restriction checks
667 if (get_acc != set_acc) {
668 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
669 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
670 if (get_restr && set_restr) {
671 is_valid_property = false; // Neither is more restrictive
675 mod &= ~Modifiers.AccessibilityMask;
684 PropertySpec spec = null;
685 if (!param.IsEmpty) {
686 if (is_valid_property) {
687 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
688 if (index_name == null || index_name != pi.Name) {
689 is_valid_property = false;
693 is_valid_property = false;
697 is_valid_property = false;
701 if (is_valid_property) {
702 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
703 } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
705 // Enables support for properties with parameters (must have default value) of COM-imported types
707 is_valid_property = true;
709 for (int i = 0; i < param.FixedParameters.Length; ++i) {
710 if (!param.FixedParameters[i].HasDefaultValue) {
711 is_valid_property = false;
720 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
722 if (!is_valid_property) {
723 spec.IsNotCSharpCompatible = true;
735 public TypeSpec CreateType (MetaType type)
737 return CreateType (type, new DynamicTypeReader (), true);
740 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
742 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
745 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
747 TypeSpec declaring_type;
748 if (type.IsNested && !type.IsGenericParameter)
749 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
751 declaring_type = null;
753 return CreateType (type, declaring_type, dtype, canImportBaseType);
756 protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
759 if (import_cache.TryGetValue (type, out spec)) {
760 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
761 if (dtype.IsDynamicObject ())
762 return module.Compiler.BuiltinTypes.Dynamic;
767 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
770 if (!dtype.HasDynamicAttribute ())
773 // We've found same object in the cache but this one has a dynamic custom attribute
774 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
775 // Do type resolve process again in that case
777 // TODO: Handle cases where they still unify
780 if (IsMissingType (type)) {
781 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
782 spec.MemberCache = MemberCache.Empty;
783 import_cache.Add (type, spec);
787 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
788 var type_def = type.GetGenericTypeDefinition ();
790 // Generic type definition can also be forwarded
791 if (compiled_types.TryGetValue (type_def, out spec))
794 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
797 if (declaringType == null) {
798 // Simple case, no nesting
799 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
800 spec = spec.MakeGenericType (module, targs);
803 // Nested type case, converting .NET types like
804 // A`1.B`1.C`1<int, long, string> to typespec like
805 // A<int>.B<long>.C<string>
807 var nested_hierarchy = new List<TypeSpec> ();
808 while (declaringType.IsNested) {
809 nested_hierarchy.Add (declaringType);
810 declaringType = declaringType.DeclaringType;
814 if (declaringType.Arity > 0) {
815 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
816 targs_pos = spec.Arity;
818 spec = declaringType;
821 for (int i = nested_hierarchy.Count; i != 0; --i) {
822 var t = nested_hierarchy [i - 1];
823 if (t.Kind == MemberKind.MissingType)
826 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity, false);
829 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
830 targs_pos += t.Arity;
834 if (spec.Kind == MemberKind.MissingType) {
835 spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC);
836 spec.MemberCache = MemberCache.Empty;
838 if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
841 string name = type.Name;
842 int index = name.IndexOf ('`');
844 name = name.Substring (0, index);
846 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos, false);
848 if (spec.Arity > 0) {
849 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
854 // Don't add generic type with dynamic arguments, they can interfere with same type
855 // using object type arguments
856 if (!spec.HasDynamicElement) {
858 // Add to reading cache to speed up reading
859 if (!import_cache.ContainsKey (type))
860 import_cache.Add (type, spec);
869 var ma = type.Attributes;
870 switch (ma & TypeAttributes.VisibilityMask) {
871 case TypeAttributes.Public:
872 case TypeAttributes.NestedPublic:
873 mod = Modifiers.PUBLIC;
875 case TypeAttributes.NestedPrivate:
876 mod = Modifiers.PRIVATE;
878 case TypeAttributes.NestedFamily:
879 mod = Modifiers.PROTECTED;
881 case TypeAttributes.NestedFamORAssem:
882 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
885 mod = Modifiers.INTERNAL;
889 if ((ma & TypeAttributes.Interface) != 0) {
890 kind = MemberKind.Interface;
891 } else if (type.IsGenericParameter) {
892 kind = MemberKind.TypeParameter;
894 var base_type = type.BaseType;
895 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
896 kind = MemberKind.Class;
898 kind = DetermineKindFromBaseType (base_type);
899 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
900 mod |= Modifiers.SEALED;
904 if (kind == MemberKind.Class) {
905 if ((ma & TypeAttributes.Sealed) != 0) {
906 if ((ma & TypeAttributes.Abstract) != 0)
907 mod |= Modifiers.STATIC;
909 mod |= Modifiers.SEALED;
910 } else if ((ma & TypeAttributes.Abstract) != 0) {
911 mod |= Modifiers.ABSTRACT;
916 var definition = new ImportedTypeDefinition (type, this);
919 if (kind == MemberKind.Enum) {
920 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
921 BindingFlags.Instance |
922 BindingFlags.Public | BindingFlags.NonPublic;
924 var type_members = type.GetFields (underlying_member);
925 foreach (var type_member in type_members) {
926 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
931 kind = MemberKind.Class;
933 } else if (kind == MemberKind.TypeParameter) {
934 spec = CreateTypeParameter (type, declaringType);
935 } else if (type.IsGenericTypeDefinition) {
936 definition.TypeParameters = CreateGenericParameters (type, declaringType);
937 } else if (compiled_types.TryGetValue (type, out pt)) {
939 // Same type was found in inside compiled types. It's
940 // either build-in type or forward referenced typed
941 // which point into just compiled assembly.
944 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
946 bts.SetDefinition (definition, type, mod);
950 spec = new TypeSpec (kind, declaringType, definition, type, mod);
952 import_cache.Add (type, spec);
954 if (kind == MemberKind.TypeParameter) {
955 if (canImportBaseType)
956 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
962 // Two stage setup as the base type can be inflated declaring type or
963 // another nested type inside same declaring type which has not been
964 // loaded, therefore we can import a base type of nested types once
965 // the types have been imported
967 if (canImportBaseType)
968 ImportTypeBase (spec, type);
973 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
975 IAssemblyDefinition found;
976 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
978 // This can happen in dynamic context only
979 var def = new ImportedAssemblyDefinition (assembly);
980 assembly_2_definition.Add (assembly, def);
981 def.ReadAttributes ();
988 public ImportedAssemblyDefinition GetImportedAssemblyDefinition (AssemblyName assemblyName)
990 foreach (var a in Assemblies) {
991 var ia = a as ImportedAssemblyDefinition;
995 if (a.Name == assemblyName.Name)
1003 public void ImportTypeBase (MetaType type)
1005 TypeSpec spec = import_cache[type];
1007 ImportTypeBase (spec, type);
1010 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
1013 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
1014 case GenericParameterAttributes.Covariant:
1015 variance = Variance.Covariant;
1017 case GenericParameterAttributes.Contravariant:
1018 variance = Variance.Contravariant;
1021 variance = Variance.None;
1025 SpecialConstraint special = SpecialConstraint.None;
1026 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
1028 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
1029 special |= SpecialConstraint.Struct;
1030 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
1031 special = SpecialConstraint.Constructor;
1034 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
1035 special |= SpecialConstraint.Class;
1038 TypeParameterSpec spec;
1039 var def = new ImportedTypeParameterDefinition (type, this);
1040 if (type.DeclaringMethod != null) {
1041 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
1043 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
1050 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
1051 // they can be assembly specific therefore we do check based on names only
1053 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
1055 if (attributesData.Count == 0)
1058 foreach (var attr in attributesData) {
1059 var dt = attr.Constructor.DeclaringType;
1060 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1067 void ImportTypeBase (TypeSpec spec, MetaType type)
1069 if (spec.Kind == MemberKind.Interface)
1070 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1071 else if (type.BaseType != null) {
1073 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1074 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1076 base_type = CreateType (type.BaseType);
1078 spec.BaseType = base_type;
1081 if (spec.MemberDefinition.TypeParametersCount > 0) {
1082 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1083 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1088 public void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1090 Namespace ns = targetNamespace;
1091 string prev_namespace = null;
1092 foreach (var t in types) {
1096 // Be careful not to trigger full parent type loading
1097 if (t.MemberType == MemberTypes.NestedType)
1100 if (t.Name[0] == '<')
1103 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1107 if (prev_namespace != t.Namespace) {
1108 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1109 prev_namespace = t.Namespace;
1112 // Cannot rely on assembly level Extension attribute or static modifier because they
1113 // are not followed by other compilers (e.g. F#).
1114 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1115 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1116 it.SetExtensionMethodContainer ();
1119 ns.AddType (module, it);
1123 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1125 var constraints = type.GetGenericParameterConstraints ();
1126 List<TypeSpec> tparams = null;
1127 foreach (var ct in constraints) {
1128 if (ct.IsGenericParameter) {
1129 if (tparams == null)
1130 tparams = new List<TypeSpec> ();
1132 tparams.Add (CreateType (ct));
1136 var constraint_type = CreateType (ct);
1137 if (constraint_type.IsClass) {
1138 spec.BaseType = constraint_type;
1142 spec.AddInterface (constraint_type);
1145 if (spec.BaseType == null)
1146 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1148 if (tparams != null)
1149 spec.TypeArguments = tparams.ToArray ();
1152 Constant ImportConstant (object value)
1155 // Get type of underlying value as int constant can be used for object
1156 // parameter type. This is not allowed in C# but other languages can do that
1158 var types = module.Compiler.BuiltinTypes;
1159 switch (System.Type.GetTypeCode (value.GetType ())) {
1160 case TypeCode.Boolean:
1161 return new BoolConstant (types, (bool) value, Location.Null);
1163 return new ByteConstant (types, (byte) value, Location.Null);
1165 return new CharConstant (types, (char) value, Location.Null);
1166 case TypeCode.Decimal:
1167 return new DecimalConstant (types, (decimal) value, Location.Null);
1168 case TypeCode.Double:
1169 return new DoubleConstant (types, (double) value, Location.Null);
1170 case TypeCode.Int16:
1171 return new ShortConstant (types, (short) value, Location.Null);
1172 case TypeCode.Int32:
1173 return new IntConstant (types, (int) value, Location.Null);
1174 case TypeCode.Int64:
1175 return new LongConstant (types, (long) value, Location.Null);
1176 case TypeCode.SByte:
1177 return new SByteConstant (types, (sbyte) value, Location.Null);
1178 case TypeCode.Single:
1179 return new FloatConstant (types, (float) value, Location.Null);
1180 case TypeCode.String:
1181 return new StringConstant (types, (string) value, Location.Null);
1182 case TypeCode.UInt16:
1183 return new UShortConstant (types, (ushort) value, Location.Null);
1184 case TypeCode.UInt32:
1185 return new UIntConstant (types, (uint) value, Location.Null);
1186 case TypeCode.UInt64:
1187 return new ULongConstant (types, (ulong) value, Location.Null);
1190 throw new NotImplementedException (value.GetType ().ToString ());
1193 public TypeSpec ImportType (MetaType type)
1195 return ImportType (type, new DynamicTypeReader (type), null);
1198 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype, TypeSpec currentType)
1200 if (type.HasElementType) {
1201 var element = type.GetElementType ();
1203 var spec = ImportType (element, dtype, currentType);
1206 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1208 return ReferenceContainer.MakeType (module, spec);
1210 return PointerContainer.MakeType (module, spec);
1212 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1215 TypeSpec compiled_type;
1216 if (compiled_types.TryGetValue (type, out compiled_type)) {
1217 if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
1218 return module.Compiler.BuiltinTypes.Dynamic;
1220 compiled_type = CreateType (type, dtype, true);
1223 if (currentType == compiled_type && currentType?.IsGeneric == true) {
1225 // Inflates current type to match behaviour of TypeDefinition::CurrentType used by compiled types
1227 var targs = compiled_type.MemberDefinition.TypeParameters;
1228 compiled_type = compiled_type.MakeGenericType (module, targs);
1231 return compiled_type;
1234 static bool IsMissingType (MetaType type)
1237 return type.__IsMissing;
1244 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1245 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1246 // DecimalConstantAttribute metadata.
1248 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1250 if (attrs.Count == 0)
1253 foreach (var ca in attrs) {
1254 var dt = ca.Constructor.DeclaringType;
1255 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1258 var value = new decimal (
1259 (int) (uint) ca.ConstructorArguments[4].Value,
1260 (int) (uint) ca.ConstructorArguments[3].Value,
1261 (int) (uint) ca.ConstructorArguments[2].Value,
1262 (byte) ca.ConstructorArguments[1].Value != 0,
1263 (byte) ca.ConstructorArguments[0].Value);
1265 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1271 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1274 var ma = mb.Attributes;
1275 switch (ma & MethodAttributes.MemberAccessMask) {
1276 case MethodAttributes.Public:
1277 mod = Modifiers.PUBLIC;
1279 case MethodAttributes.Assembly:
1280 mod = Modifiers.INTERNAL;
1282 case MethodAttributes.Family:
1283 mod = Modifiers.PROTECTED;
1285 case MethodAttributes.FamORAssem:
1286 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1289 mod = Modifiers.PRIVATE;
1293 if ((ma & MethodAttributes.Static) != 0) {
1294 mod |= Modifiers.STATIC;
1297 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1298 mod |= Modifiers.ABSTRACT;
1302 // It can be sealed and override
1303 if ((ma & MethodAttributes.Final) != 0)
1304 mod |= Modifiers.SEALED;
1306 if ((ma & MethodAttributes.Virtual) != 0) {
1307 // Not every member can be detected based on MethodAttribute, we
1308 // set virtual or non-virtual only when we are certain. Further checks
1309 // to really find out what `virtual' means for this member are done
1311 if ((ma & MethodAttributes.NewSlot) != 0) {
1312 if ((mod & Modifiers.SEALED) != 0) {
1313 mod &= ~Modifiers.SEALED;
1315 mod |= Modifiers.VIRTUAL;
1318 mod |= Modifiers.OVERRIDE;
1326 abstract class ImportedDefinition : IMemberDefinition
1328 protected class AttributesBag
1330 public static readonly AttributesBag Default = new AttributesBag ();
1332 public AttributeUsageAttribute AttributeUsage;
1333 public ObsoleteAttribute Obsolete;
1334 public string[] Conditionals;
1335 public string DefaultIndexerName;
1336 public bool? CLSAttributeValue;
1337 public TypeSpec CoClass;
1339 static bool HasMissingType (ConstructorInfo ctor)
1343 // Mimic odd csc behaviour where missing type on predefined
1344 // attributes means the attribute is silently ignored. This can
1345 // happen with PCL facades
1347 foreach (var p in ctor.GetParameters ()) {
1348 if (p.ParameterType.__ContainsMissingType)
1356 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1358 AttributesBag bag = null;
1359 List<string> conditionals = null;
1361 // It should not throw any loading exception
1362 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1364 foreach (var a in attrs) {
1365 var dt = a.Constructor.DeclaringType;
1366 string name = dt.Name;
1367 if (name == "ObsoleteAttribute") {
1368 if (dt.Namespace != "System")
1372 bag = new AttributesBag ();
1374 var args = a.ConstructorArguments;
1376 if (args.Count == 1) {
1377 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1378 } else if (args.Count == 2) {
1379 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1381 bag.Obsolete = new ObsoleteAttribute ();
1387 if (name == "ConditionalAttribute") {
1388 if (dt.Namespace != "System.Diagnostics")
1392 bag = new AttributesBag ();
1394 if (conditionals == null)
1395 conditionals = new List<string> (2);
1397 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1401 if (name == "CLSCompliantAttribute") {
1402 if (dt.Namespace != "System")
1406 bag = new AttributesBag ();
1408 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1412 // Type only attributes
1413 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1414 if (name == "DefaultMemberAttribute") {
1415 if (dt.Namespace != "System.Reflection")
1419 bag = new AttributesBag ();
1421 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1425 if (name == "AttributeUsageAttribute") {
1426 if (dt.Namespace != "System")
1429 if (HasMissingType (a.Constructor))
1433 bag = new AttributesBag ();
1435 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1436 foreach (var named in a.NamedArguments) {
1437 if (named.MemberInfo.Name == "AllowMultiple")
1438 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1439 else if (named.MemberInfo.Name == "Inherited")
1440 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1445 // Interface only attribute
1446 if (name == "CoClassAttribute") {
1447 if (dt.Namespace != "System.Runtime.InteropServices")
1450 if (HasMissingType (a.Constructor))
1454 bag = new AttributesBag ();
1456 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1465 if (conditionals != null)
1466 bag.Conditionals = conditionals.ToArray ();
1472 protected readonly MemberInfo provider;
1473 protected AttributesBag cattrs;
1474 protected readonly MetadataImporter importer;
1476 protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1478 this.provider = provider;
1479 this.importer = importer;
1484 public bool IsImported {
1490 public virtual string Name {
1492 return provider.Name;
1498 public string[] ConditionalConditions ()
1503 return cattrs.Conditionals;
1506 public ObsoleteAttribute GetAttributeObsolete ()
1511 return cattrs.Obsolete;
1514 public bool? CLSAttributeValue {
1519 return cattrs.CLSAttributeValue;
1523 protected void ReadAttributes ()
1525 cattrs = AttributesBag.Read (provider, importer);
1528 public void SetIsAssigned ()
1530 // Unused for imported members
1533 public void SetIsUsed ()
1535 // Unused for imported members
1539 public class ImportedModuleDefinition
1541 readonly Module module;
1544 public ImportedModuleDefinition (Module module)
1546 this.module = module;
1551 public bool IsCLSCompliant {
1553 return cls_compliant;
1557 public string Name {
1565 public void ReadAttributes ()
1567 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1569 foreach (var a in attrs) {
1570 var dt = a.Constructor.DeclaringType;
1571 if (dt.Name == "CLSCompliantAttribute") {
1572 if (dt.Namespace != "System")
1575 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1582 // Reads assembly attributes which where attached to a special type because
1583 // module does have assembly manifest
1585 public List<Attribute> ReadAssemblyAttributes ()
1587 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1591 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1595 // TODO: implement, the idea is to fabricate specil Attribute class and
1596 // add it to OptAttributes before resolving the source code attributes
1597 // Need to build module location as well for correct error reporting
1599 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1600 //var attrs = new List<Attribute> (assembly_attributes.Count);
1601 //foreach (var a in assembly_attributes)
1603 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1604 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1606 // foreach (var carg in a.ConstructorArguments) {
1610 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1617 public class ImportedAssemblyDefinition : IAssemblyDefinition
1619 readonly Assembly assembly;
1620 readonly AssemblyName aname;
1623 List<AssemblyName> internals_visible_to;
1624 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1626 public ImportedAssemblyDefinition (Assembly assembly)
1628 this.assembly = assembly;
1629 this.aname = assembly.GetName ();
1634 public Assembly Assembly {
1640 public string FullName {
1642 return aname.FullName;
1646 public bool HasStrongName {
1648 return aname.GetPublicKey ().Length != 0;
1652 public bool IsMissing {
1655 return assembly.__IsMissing;
1662 public bool IsCLSCompliant {
1664 return cls_compliant;
1668 public string Location {
1670 return assembly.Location;
1674 public string Name {
1682 public byte[] GetPublicKeyToken ()
1684 return aname.GetPublicKeyToken ();
1687 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1689 return internals_visible_to_cache [assembly];
1692 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1694 if (internals_visible_to == null)
1697 AssemblyName is_visible = null;
1698 if (internals_visible_to_cache == null) {
1699 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1701 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1702 return is_visible != null;
1705 var token = assembly.GetPublicKeyToken ();
1706 if (token != null && token.Length == 0)
1709 foreach (var internals in internals_visible_to) {
1710 if (!String.Equals(internals.Name, assembly.Name, StringComparison.OrdinalIgnoreCase))
1713 if (token == null && assembly is AssemblyDefinition) {
1714 is_visible = internals;
1718 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1721 is_visible = internals;
1725 internals_visible_to_cache.Add (assembly, is_visible);
1726 return is_visible != null;
1729 public void ReadAttributes ()
1732 if (assembly.__IsMissing)
1736 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1738 foreach (var a in attrs) {
1739 var dt = a.Constructor.DeclaringType;
1741 if (name == "CLSCompliantAttribute") {
1742 if (dt.Namespace == "System") {
1743 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1748 if (name == "InternalsVisibleToAttribute") {
1749 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1752 string s = a.ConstructorArguments[0].Value as string;
1758 an = new AssemblyName (s);
1759 } catch (FileLoadException) {
1760 // Invalid assembly name reuses FileLoadException
1764 if (internals_visible_to == null)
1765 internals_visible_to = new List<AssemblyName> ();
1767 internals_visible_to.Add (an);
1773 public override string ToString ()
1779 class ImportedMemberDefinition : ImportedDefinition
1781 readonly TypeSpec type;
1783 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1784 : base (member, importer)
1791 public TypeSpec MemberType {
1800 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1802 readonly AParametersCollection parameters;
1804 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1805 : base (provider, type, importer)
1807 this.parameters = parameters;
1810 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1811 : base (provider, type, importer)
1813 this.parameters = parameters;
1818 public AParametersCollection Parameters {
1827 class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1829 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1830 : base (provider, type, parameters, importer)
1834 MethodBase IMethodDefinition.Metadata {
1836 return (MethodBase) provider;
1841 class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1843 readonly TypeParameterSpec[] tparams;
1845 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1846 : base (provider, type, parameters, importer)
1848 this.tparams = tparams;
1853 public TypeParameterSpec[] TypeParameters {
1859 public int TypeParametersCount {
1861 return tparams.Length;
1868 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1870 TypeParameterSpec[] tparams;
1873 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1874 : base (type, importer)
1880 public IAssemblyDefinition DeclaringAssembly {
1882 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1886 bool ITypeDefinition.IsComImport {
1888 return ((MetaType) provider).IsImport;
1893 bool ITypeDefinition.IsPartial {
1899 bool ITypeDefinition.IsTypeForwarder {
1902 return ((MetaType) provider).__IsTypeForwarder;
1909 bool ITypeDefinition.IsCyclicTypeForwarder {
1912 return ((MetaType) provider).__IsCyclicTypeForwarder;
1919 public override string Name {
1923 if (tparams != null) {
1924 int arity_start = name.IndexOf ('`');
1925 if (arity_start > 0)
1926 name = name.Substring (0, arity_start);
1934 public string Namespace {
1936 return ((MetaType) provider).Namespace;
1940 public int TypeParametersCount {
1942 return tparams == null ? 0 : tparams.Length;
1946 public TypeParameterSpec[] TypeParameters {
1957 public void DefineInterfaces (TypeSpec spec)
1959 var type = (MetaType) provider;
1962 ifaces = type.__GetDeclaredInterfaces ();
1963 if (ifaces.Length != 0) {
1964 foreach (var iface in ifaces) {
1965 var it = importer.CreateType (iface);
1969 spec.AddInterfaceDefined (it);
1971 // Unfortunately not all languages expand inherited interfaces
1972 var bifaces = it.Interfaces;
1973 if (bifaces != null) {
1974 foreach (var biface in bifaces) {
1975 spec.AddInterfaceDefined (biface);
1982 // It's impossible to get declared interfaces only using System.Reflection
1983 // hence we need to mimic the behavior with ikvm-reflection too to keep
1984 // our type look-up logic same
1986 if (spec.BaseType != null) {
1987 var bifaces = spec.BaseType.Interfaces;
1988 if (bifaces != null) {
1990 // Before adding base class interfaces close defined interfaces
1991 // on type parameter
1993 var tp = spec as TypeParameterSpec;
1994 if (tp != null && tp.InterfacesDefined == null) {
1995 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1998 foreach (var iface in bifaces)
1999 spec.AddInterfaceDefined (iface);
2003 ifaces = type.GetInterfaces ();
2005 if (ifaces.Length > 0) {
2006 foreach (var iface in ifaces) {
2007 spec.AddInterface (importer.CreateType (iface));
2014 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
2017 // Report details about missing type and most likely cause of the problem.
2018 // csc used to reports 1683, 1684 (now 7069) as warnings but we report them only when used
2019 // or referenced from the user core in which case compilation error has to
2020 // be reported because compiler cannot continue anyway
2023 var report = ctx.Module.Compiler.Report;
2025 for (int i = 0; i < missing.Count; ++i) {
2026 var t = missing [i].Type;
2029 // Report missing types only once
2031 if (report.Printer.MissingTypeReported (t.MemberDefinition))
2034 string name = t.GetSignatureForError ();
2036 var caller = missing[i].Caller;
2037 if (caller.Kind != MemberKind.MissingType)
2038 report.SymbolRelatedToPreviousError (caller);
2040 var definition = t.MemberDefinition;
2041 if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
2042 report.Error (1683, loc,
2043 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
2045 } else if (definition.DeclaringAssembly.IsMissing) {
2046 if (definition.IsTypeForwarder) {
2047 report.Error (1070, loc,
2048 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2049 name, definition.DeclaringAssembly.FullName);
2051 report.Error (12, loc,
2052 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2053 name, definition.DeclaringAssembly.FullName);
2055 } else if (definition.IsTypeForwarder) {
2056 report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
2057 name, definition.DeclaringAssembly.FullName);
2059 report.Error (7069, loc,
2060 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
2061 name, t.MemberDefinition.DeclaringAssembly.FullName);
2066 public TypeSpec GetAttributeCoClass ()
2071 return cattrs.CoClass;
2074 public string GetAttributeDefaultMember ()
2079 return cattrs.DefaultIndexerName;
2082 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2087 return cattrs.AttributeUsage;
2090 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2092 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
2093 return a == assembly || a.IsFriendAssemblyTo (assembly);
2096 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2099 // Not interested in members of nested private types unless the importer needs them
2101 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
2102 cache = MemberCache.Empty;
2106 var loading_type = (MetaType) provider;
2107 const BindingFlags all_members = BindingFlags.DeclaredOnly |
2108 BindingFlags.Static | BindingFlags.Instance |
2109 BindingFlags.Public | BindingFlags.NonPublic;
2111 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
2112 MethodAttributes.Virtual | MethodAttributes.HideBySig |
2113 MethodAttributes.Final;
2115 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
2116 List<EventSpec> imported_events = null;
2117 EventSpec event_spec;
2118 MemberSpec imported;
2122 all = loading_type.GetMembers (all_members);
2123 } catch (Exception e) {
2124 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2125 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2128 if (cache == null) {
2129 cache = new MemberCache (all.Length);
2132 // Do the types first as they can be referenced by the members before
2133 // they are found or inflated
2135 foreach (var member in all) {
2136 if (member.MemberType != MemberTypes.NestedType)
2139 var t = (MetaType) member;
2141 // Ignore compiler generated types, mostly lambda containers
2142 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2146 imported = importer.CreateNestedType (t, declaringType);
2147 } catch (Exception e) {
2148 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2149 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2152 cache.AddMemberImported (imported);
2155 foreach (var member in all) {
2156 if (member.MemberType != MemberTypes.NestedType)
2159 var t = (MetaType) member;
2161 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2164 importer.ImportTypeBase (t);
2169 // Load base interfaces first to minic behaviour of compiled members
2171 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2172 foreach (var iface in declaringType.Interfaces) {
2173 cache.AddInterface (iface);
2179 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2181 foreach (var member in all) {
2182 switch (member.MemberType) {
2183 case MemberTypes.Constructor:
2184 if (declaringType.IsInterface)
2187 goto case MemberTypes.Method;
2188 case MemberTypes.Method:
2189 MethodBase mb = (MethodBase) member;
2190 var attrs = mb.Attributes;
2192 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2193 if (importer.IgnorePrivateMembers)
2196 // Ignore explicitly implemented members
2197 if ((attrs & explicit_impl) == explicit_impl)
2200 // Ignore compiler generated methods
2201 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2205 imported = importer.CreateMethod (mb, declaringType);
2206 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2207 if (possible_accessors == null)
2208 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2210 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2211 possible_accessors.Add (mb, (MethodSpec) imported);
2215 case MemberTypes.Property:
2216 if (possible_accessors == null)
2219 var p = (PropertyInfo) member;
2221 // Links possible accessors with property
2223 MethodSpec get, set;
2224 m = p.GetGetMethod (true);
2225 if (m == null || !possible_accessors.TryGetValue (m, out get))
2228 m = p.GetSetMethod (true);
2229 if (m == null || !possible_accessors.TryGetValue (m, out set))
2232 // No accessors registered (e.g. explicit implementation)
2233 if (get == null && set == null)
2237 imported = importer.CreateProperty (p, declaringType, get, set);
2238 } catch (Exception ex) {
2239 throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2240 p.Name, declaringType.GetSignatureForError ());
2243 if (imported == null)
2247 case MemberTypes.Event:
2248 if (possible_accessors == null)
2251 var e = (EventInfo) member;
2253 // Links accessors with event
2255 MethodSpec add, remove;
2256 m = e.GetAddMethod (true);
2257 if (m == null || !possible_accessors.TryGetValue (m, out add))
2260 m = e.GetRemoveMethod (true);
2261 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2264 // Both accessors are required
2265 if (add == null || remove == null)
2268 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2269 if (!importer.IgnorePrivateMembers) {
2270 if (imported_events == null)
2271 imported_events = new List<EventSpec> ();
2273 imported_events.Add (event_spec);
2276 imported = event_spec;
2278 case MemberTypes.Field:
2279 var fi = (FieldInfo) member;
2281 imported = importer.CreateField (fi, declaringType);
2282 if (imported == null)
2286 // For dynamic binder event has to be fully restored to allow operations
2287 // within the type container to work correctly
2289 if (imported_events != null) {
2290 // The backing event field should be private but it may not
2292 for (i = 0; i < imported_events.Count; ++i) {
2293 var ev = imported_events[i];
2294 if (ev.Name == fi.Name) {
2295 ev.BackingField = (FieldSpec) imported;
2296 imported_events.RemoveAt (i);
2307 case MemberTypes.NestedType:
2308 // Already in the cache from the first pass
2311 throw new NotImplementedException (member.ToString ());
2314 if (imported.IsStatic && declaringType.IsInterface)
2317 cache.AddMemberImported (imported);
2323 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2325 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2326 : base (type, importer)
2332 public IAssemblyDefinition DeclaringAssembly {
2334 throw new NotImplementedException ();
2338 bool ITypeDefinition.IsComImport {
2344 bool ITypeDefinition.IsPartial {
2350 bool ITypeDefinition.IsTypeForwarder {
2356 bool ITypeDefinition.IsCyclicTypeForwarder {
2362 public string Namespace {
2368 public int TypeParametersCount {
2374 public TypeParameterSpec[] TypeParameters {
2382 public TypeSpec GetAttributeCoClass ()
2387 public string GetAttributeDefaultMember ()
2389 throw new NotSupportedException ();
2392 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2394 throw new NotSupportedException ();
2397 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2399 throw new NotImplementedException ();
2402 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2404 throw new NotImplementedException ();