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;
149 public ICollection<IAssemblyDefinition> Assemblies {
151 return assembly_2_definition.Values;
155 public bool IgnorePrivateMembers { get; set; }
159 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
160 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
161 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
163 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
166 var fa = fi.Attributes;
167 switch (fa & FieldAttributes.FieldAccessMask) {
168 case FieldAttributes.Public:
169 mod = Modifiers.PUBLIC;
171 case FieldAttributes.Assembly:
172 mod = Modifiers.INTERNAL;
174 case FieldAttributes.Family:
175 mod = Modifiers.PROTECTED;
177 case FieldAttributes.FamORAssem:
178 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
181 // Ignore private fields (even for error reporting) to not require extra dependencies
182 if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
183 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
186 mod = Modifiers.PRIVATE;
193 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
196 // Private field has private type which is not fixed buffer
198 if (field_type == null)
200 } catch (Exception e) {
201 // TODO: I should construct fake TypeSpec based on TypeRef signature
202 // but there is no way to do it with System.Reflection
203 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
204 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
207 var definition = new ImportedMemberDefinition (fi, field_type, this);
209 if ((fa & FieldAttributes.Literal) != 0) {
210 Constant c = field_type.Kind == MemberKind.MissingType ?
211 new NullConstant (InternalType.ErrorType, Location.Null) :
212 CreateConstantFromValue (field_type, fi);
213 return new ConstSpec (declaringType, definition, field_type, fi, mod | Modifiers.STATIC, c);
216 if ((fa & FieldAttributes.InitOnly) != 0) {
217 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
218 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
220 return new ConstSpec (declaringType, definition, field_type, fi, mod | Modifiers.STATIC, dc);
223 mod |= Modifiers.READONLY;
225 var req_mod = fi.GetRequiredCustomModifiers ();
226 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
227 mod |= Modifiers.VOLATILE;
230 if ((fa & FieldAttributes.Static) != 0) {
231 mod |= Modifiers.STATIC;
233 // Fixed buffers cannot be static
234 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
235 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
237 // TODO: Sanity check on field_type (only few types are allowed)
238 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
239 return new FixedFieldSpec (module, declaringType, definition, fi, element_field, mod);
243 return new FieldSpec (declaringType, definition, field_type, fi, mod);
246 Constant CreateConstantFromValue (TypeSpec fieldType, FieldInfo fi)
248 var value = fi.GetRawConstantValue ();
250 // Metadata value can be encoded using different constant value type
251 // than is actual field type
253 // e.g. unsigned int16 CONSTANT = int16 (0x0000ffff)
255 if (value != null && !fieldType.IsEnum) {
256 var c = ImportConstant (value);
258 return fieldType == c.Type ? c : c.ConvertExplicitly (false, fieldType);
262 return Constant.CreateConstantFromValue (fieldType, value, Location.Null);
265 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
267 add.IsAccessor = true;
268 remove.IsAccessor = true;
270 if (add.Modifiers != remove.Modifiers)
271 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
273 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
274 var definition = new ImportedMemberDefinition (ei, event_type, this);
275 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
278 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
280 var tparams = type.GetGenericArguments ();
282 int parent_owned_count;
284 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
287 // System.Reflection duplicates parent type parameters for each
288 // nested type with slightly modified properties (eg. different owner)
289 // This just makes things more complicated (think of cloned constraints)
290 // therefore we remap any nested type owned by parent using `type_cache'
291 // to the single TypeParameterSpec
293 if (declaringType != null && parent_owned_count > 0) {
295 while (read_count != parent_owned_count) {
296 var tparams_count = declaringType.Arity;
297 if (tparams_count != 0) {
298 var parent_tp = declaringType.MemberDefinition.TypeParameters;
299 read_count += tparams_count;
300 for (int i = 0; i < tparams_count; i++) {
301 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
305 declaringType = declaringType.DeclaringType;
309 parent_owned_count = 0;
312 if (tparams.Length - parent_owned_count == 0)
315 return CreateGenericParameters (parent_owned_count, tparams);
318 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
320 var tspec = new TypeParameterSpec[tparams.Length - first];
321 for (int pos = first; pos < tparams.Length; ++pos) {
322 var type = tparams[pos];
323 int index = pos - first;
325 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
331 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
335 var tspec = new TypeSpec [tparams.Length - first];
336 for (int pos = first; pos < tparams.Length; ++pos) {
337 var type = tparams[pos];
338 int index = pos - first;
341 if (type.HasElementType) {
342 var element = type.GetElementType ();
344 spec = ImportType (element, dtype);
347 throw new NotImplementedException ("Unknown element type " + type.ToString ());
350 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
352 spec = CreateType (type, dtype, true);
355 // We treat nested generic types as inflated internally where
356 // reflection uses type definition
359 // IFoo<A<T>> foo; // A<T> is definition in this case
362 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
363 var start_pos = spec.DeclaringType == null ? 0 : spec.DeclaringType.MemberDefinition.TypeParametersCount;
364 var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype);
365 spec = spec.MakeGenericType (module, targs);
379 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
381 Modifiers mod = ReadMethodModifiers (mb, declaringType);
382 TypeParameterSpec[] tparams;
384 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
386 if (mb.IsGenericMethod) {
387 if (!mb.IsGenericMethodDefinition)
388 throw new NotSupportedException ("assert");
390 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
397 if (mb.MemberType == MemberTypes.Constructor) {
398 kind = MemberKind.Constructor;
399 returnType = module.Compiler.BuiltinTypes.Void;
402 // Detect operators and destructors
404 string name = mb.Name;
405 kind = MemberKind.Method;
406 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
407 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
408 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o' && (mb.Attributes & MethodAttributes.SpecialName) != 0) {
409 var op_type = Operator.GetType (name);
410 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
411 kind = MemberKind.Operator;
414 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
415 kind = MemberKind.Destructor;
416 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
417 mod &= ~Modifiers.OVERRIDE;
418 mod |= Modifiers.VIRTUAL;
423 var mi = (MethodInfo) mb;
424 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
426 // Cannot set to OVERRIDE without full hierarchy checks
427 // this flag indicates that the method could be override
428 // but further validation is needed
429 if ((mod & Modifiers.OVERRIDE) != 0) {
430 bool is_real_override = false;
431 if (kind == MemberKind.Method && declaringType.BaseType != null) {
432 var btype = declaringType.BaseType;
433 if (IsOverrideMethodBaseTypeAccessible (btype)) {
434 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
435 var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
438 // For imported class method do additional validation to be sure that metadata
439 // override flag was correct
441 // Difference between protected internal and protected is ok
443 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
444 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
445 is_real_override = true;
450 if (!is_real_override) {
451 mod &= ~Modifiers.OVERRIDE;
452 if ((mod & Modifiers.SEALED) != 0)
453 mod &= ~Modifiers.SEALED;
455 mod |= Modifiers.VIRTUAL;
457 } else if (parameters.HasExtensionMethodType) {
458 mod |= Modifiers.METHOD_EXTENSION;
462 IMethodDefinition definition;
463 if (tparams != null) {
464 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
465 foreach (var tp in gmd.TypeParameters) {
466 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
471 definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
474 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
481 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
483 switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
484 case Modifiers.PUBLIC:
486 case Modifiers.INTERNAL:
488 // Check whether imported method in base type is accessible from compiled
491 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
492 case Modifiers.PRIVATE:
496 // protected internal
498 // Method accessibility checks will be done later based on context
499 // where the method is called (CS0122 error will be reported for inaccessible)
506 // Imports System.Reflection parameters
508 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
510 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
512 if (pi.Length == 0 && varargs == 0)
513 return ParametersCompiled.EmptyReadOnlyParameters;
515 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
516 IParameterData[] par = new IParameterData[pi.Length + varargs];
517 bool is_params = false;
518 for (int i = 0; i < pi.Length; i++) {
519 ParameterInfo p = pi[i];
520 Parameter.Modifier mod = 0;
521 Expression default_value = null;
522 if (p.ParameterType.IsByRef) {
523 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
524 mod = Parameter.Modifier.OUT;
526 mod = Parameter.Modifier.REF;
529 // Strip reference wrapping
531 var el = p.ParameterType.GetElementType ();
532 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
533 } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
534 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
535 mod = Parameter.Modifier.This;
536 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
538 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
540 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
541 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
542 mod = Parameter.Modifier.PARAMS;
547 if (!is_params && p.IsOptional) {
548 object value = p.RawDefaultValue;
549 var ptype = types[i];
550 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
552 default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
554 default_value = ImportConstant (value);
557 default_value = new EnumConstant ((Constant) default_value, ptype);
561 var attrs = CustomAttributeData.GetCustomAttributes (p);
562 for (int ii = 0; ii < attrs.Count; ++ii) {
563 var attr = attrs[ii];
564 var dt = attr.Constructor.DeclaringType;
565 if (dt.Namespace != CompilerServicesNamespace)
568 if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
569 mod |= Parameter.Modifier.CallerLineNumber;
570 else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
571 mod |= Parameter.Modifier.CallerFilePath;
572 else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
573 mod |= Parameter.Modifier.CallerMemberName;
575 } else if (value == Missing.Value) {
576 default_value = EmptyExpression.MissingValue;
577 } else if (value == null) {
578 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
579 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
580 default_value = ImportConstant (value);
585 par[i] = new ParameterData (p.Name, mod, default_value);
589 par[par.Length - 1] = new ArglistParameter (Location.Null);
590 types[types.Length - 1] = InternalType.Arglist;
593 return method != null ?
594 new ParametersImported (par, types, varargs != 0, is_params) :
595 new ParametersImported (par, types, is_params);
599 // Returns null when the property is not valid C# property
601 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
604 AParametersCollection param = null;
605 TypeSpec type = null;
608 param = get.Parameters;
609 type = get.ReturnType;
612 bool is_valid_property = true;
614 if (set.ReturnType.Kind != MemberKind.Void)
615 is_valid_property = false;
617 var set_param_count = set.Parameters.Count - 1;
619 if (set_param_count < 0) {
621 is_valid_property = false;
624 var set_type = set.Parameters.Types[set_param_count];
627 AParametersCollection set_based_param;
629 if (set_param_count == 0) {
630 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
633 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
635 var data = new IParameterData[set_param_count];
636 var types = new TypeSpec[set_param_count];
637 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
638 Array.Copy (set.Parameters.Types, types, set_param_count);
639 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
643 param = set_based_param;
646 if (set_param_count != get.Parameters.Count)
647 is_valid_property = false;
649 if (get.ReturnType != set_type)
650 is_valid_property = false;
652 // Possible custom accessor modifiers
653 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
654 var get_acc = mod & Modifiers.AccessibilityMask;
655 if (get_acc != Modifiers.PUBLIC) {
656 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
657 // If the accessor modifiers are not same, do extra restriction checks
658 if (get_acc != set_acc) {
659 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
660 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
661 if (get_restr && set_restr) {
662 is_valid_property = false; // Neither is more restrictive
666 mod &= ~Modifiers.AccessibilityMask;
675 PropertySpec spec = null;
676 if (!param.IsEmpty) {
677 if (is_valid_property) {
678 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
679 if (index_name == null) {
680 is_valid_property = false;
684 is_valid_property = false;
685 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
686 is_valid_property = false;
690 is_valid_property = false;
691 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
692 is_valid_property = false;
696 if (is_valid_property) {
697 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
698 } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
700 // Enables support for properties with parameters (must have default value) of COM-imported types
702 is_valid_property = true;
704 for (int i = 0; i < param.FixedParameters.Length; ++i) {
705 if (!param.FixedParameters[i].HasDefaultValue) {
706 is_valid_property = false;
715 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
717 if (!is_valid_property) {
718 spec.IsNotCSharpCompatible = true;
730 public TypeSpec CreateType (MetaType type)
732 return CreateType (type, new DynamicTypeReader (), true);
735 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
737 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
740 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
742 TypeSpec declaring_type;
743 if (type.IsNested && !type.IsGenericParameter)
744 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
746 declaring_type = null;
748 return CreateType (type, declaring_type, dtype, canImportBaseType);
751 protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
754 if (import_cache.TryGetValue (type, out spec)) {
755 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
756 if (dtype.IsDynamicObject ())
757 return module.Compiler.BuiltinTypes.Dynamic;
762 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
765 if (!dtype.HasDynamicAttribute ())
768 // We've found same object in the cache but this one has a dynamic custom attribute
769 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
770 // Do type resolve process again in that case
772 // TODO: Handle cases where they still unify
775 if (IsMissingType (type)) {
776 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
777 spec.MemberCache = MemberCache.Empty;
778 import_cache.Add (type, spec);
782 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
783 var type_def = type.GetGenericTypeDefinition ();
785 // Generic type definition can also be forwarded
786 if (compiled_types.TryGetValue (type_def, out spec))
789 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
792 if (declaringType == null) {
793 // Simple case, no nesting
794 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
795 spec = spec.MakeGenericType (module, targs);
798 // Nested type case, converting .NET types like
799 // A`1.B`1.C`1<int, long, string> to typespec like
800 // A<int>.B<long>.C<string>
802 var nested_hierarchy = new List<TypeSpec> ();
803 while (declaringType.IsNested) {
804 nested_hierarchy.Add (declaringType);
805 declaringType = declaringType.DeclaringType;
809 if (declaringType.Arity > 0) {
810 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
811 targs_pos = spec.Arity;
813 spec = declaringType;
816 for (int i = nested_hierarchy.Count; i != 0; --i) {
817 var t = nested_hierarchy [i - 1];
818 if (t.Kind == MemberKind.MissingType)
821 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
824 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
825 targs_pos += t.Arity;
829 if (spec.Kind == MemberKind.MissingType) {
830 spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC);
831 spec.MemberCache = MemberCache.Empty;
833 if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
836 string name = type.Name;
837 int index = name.IndexOf ('`');
839 name = name.Substring (0, index);
841 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
843 if (spec.Arity > 0) {
844 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
849 // Don't add generic type with dynamic arguments, they can interfere with same type
850 // using object type arguments
851 if (!spec.HasDynamicElement) {
853 // Add to reading cache to speed up reading
854 if (!import_cache.ContainsKey (type))
855 import_cache.Add (type, spec);
864 var ma = type.Attributes;
865 switch (ma & TypeAttributes.VisibilityMask) {
866 case TypeAttributes.Public:
867 case TypeAttributes.NestedPublic:
868 mod = Modifiers.PUBLIC;
870 case TypeAttributes.NestedPrivate:
871 mod = Modifiers.PRIVATE;
873 case TypeAttributes.NestedFamily:
874 mod = Modifiers.PROTECTED;
876 case TypeAttributes.NestedFamORAssem:
877 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
880 mod = Modifiers.INTERNAL;
884 if ((ma & TypeAttributes.Interface) != 0) {
885 kind = MemberKind.Interface;
886 } else if (type.IsGenericParameter) {
887 kind = MemberKind.TypeParameter;
889 var base_type = type.BaseType;
890 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
891 kind = MemberKind.Class;
893 kind = DetermineKindFromBaseType (base_type);
894 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
895 mod |= Modifiers.SEALED;
899 if (kind == MemberKind.Class) {
900 if ((ma & TypeAttributes.Sealed) != 0) {
901 if ((ma & TypeAttributes.Abstract) != 0)
902 mod |= Modifiers.STATIC;
904 mod |= Modifiers.SEALED;
905 } else if ((ma & TypeAttributes.Abstract) != 0) {
906 mod |= Modifiers.ABSTRACT;
911 var definition = new ImportedTypeDefinition (type, this);
914 if (kind == MemberKind.Enum) {
915 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
916 BindingFlags.Instance |
917 BindingFlags.Public | BindingFlags.NonPublic;
919 var type_members = type.GetFields (underlying_member);
920 foreach (var type_member in type_members) {
921 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
926 kind = MemberKind.Class;
928 } else if (kind == MemberKind.TypeParameter) {
929 spec = CreateTypeParameter (type, declaringType);
930 } else if (type.IsGenericTypeDefinition) {
931 definition.TypeParameters = CreateGenericParameters (type, declaringType);
932 } else if (compiled_types.TryGetValue (type, out pt)) {
934 // Same type was found in inside compiled types. It's
935 // either build-in type or forward referenced typed
936 // which point into just compiled assembly.
939 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
941 bts.SetDefinition (definition, type, mod);
945 spec = new TypeSpec (kind, declaringType, definition, type, mod);
947 import_cache.Add (type, spec);
949 if (kind == MemberKind.TypeParameter) {
950 if (canImportBaseType)
951 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
957 // Two stage setup as the base type can be inflated declaring type or
958 // another nested type inside same declaring type which has not been
959 // loaded, therefore we can import a base type of nested types once
960 // the types have been imported
962 if (canImportBaseType)
963 ImportTypeBase (spec, type);
968 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
970 IAssemblyDefinition found;
971 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
973 // This can happen in dynamic context only
974 var def = new ImportedAssemblyDefinition (assembly);
975 assembly_2_definition.Add (assembly, def);
976 def.ReadAttributes ();
983 public ImportedAssemblyDefinition GetImportedAssemblyDefinition (AssemblyName assemblyName)
985 foreach (var a in Assemblies) {
986 var ia = a as ImportedAssemblyDefinition;
990 if (a.Name == assemblyName.Name)
998 public void ImportTypeBase (MetaType type)
1000 TypeSpec spec = import_cache[type];
1002 ImportTypeBase (spec, type);
1005 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
1008 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
1009 case GenericParameterAttributes.Covariant:
1010 variance = Variance.Covariant;
1012 case GenericParameterAttributes.Contravariant:
1013 variance = Variance.Contravariant;
1016 variance = Variance.None;
1020 SpecialConstraint special = SpecialConstraint.None;
1021 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
1023 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
1024 special |= SpecialConstraint.Struct;
1025 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
1026 special = SpecialConstraint.Constructor;
1029 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
1030 special |= SpecialConstraint.Class;
1033 TypeParameterSpec spec;
1034 var def = new ImportedTypeParameterDefinition (type, this);
1035 if (type.DeclaringMethod != null) {
1036 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
1038 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
1045 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
1046 // they can be assembly specific therefore we do check based on names only
1048 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
1050 if (attributesData.Count == 0)
1053 foreach (var attr in attributesData) {
1054 var dt = attr.Constructor.DeclaringType;
1055 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1062 void ImportTypeBase (TypeSpec spec, MetaType type)
1064 if (spec.Kind == MemberKind.Interface)
1065 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1066 else if (type.BaseType != null) {
1068 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1069 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1071 base_type = CreateType (type.BaseType);
1073 spec.BaseType = base_type;
1076 if (spec.MemberDefinition.TypeParametersCount > 0) {
1077 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1078 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1083 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1085 Namespace ns = targetNamespace;
1086 string prev_namespace = null;
1087 foreach (var t in types) {
1091 // Be careful not to trigger full parent type loading
1092 if (t.MemberType == MemberTypes.NestedType)
1095 if (t.Name[0] == '<')
1098 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1102 if (prev_namespace != t.Namespace) {
1103 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1104 prev_namespace = t.Namespace;
1107 // Cannot rely on assembly level Extension attribute or static modifier because they
1108 // are not followed by other compilers (e.g. F#).
1109 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1110 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1111 it.SetExtensionMethodContainer ();
1114 ns.AddType (module, it);
1118 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1120 var constraints = type.GetGenericParameterConstraints ();
1121 List<TypeSpec> tparams = null;
1122 foreach (var ct in constraints) {
1123 if (ct.IsGenericParameter) {
1124 if (tparams == null)
1125 tparams = new List<TypeSpec> ();
1127 tparams.Add (CreateType (ct));
1131 var constraint_type = CreateType (ct);
1132 if (constraint_type.IsClass) {
1133 spec.BaseType = constraint_type;
1137 spec.AddInterface (constraint_type);
1140 if (spec.BaseType == null)
1141 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1143 if (tparams != null)
1144 spec.TypeArguments = tparams.ToArray ();
1147 Constant ImportConstant (object value)
1150 // Get type of underlying value as int constant can be used for object
1151 // parameter type. This is not allowed in C# but other languages can do that
1153 var types = module.Compiler.BuiltinTypes;
1154 switch (System.Type.GetTypeCode (value.GetType ())) {
1155 case TypeCode.Boolean:
1156 return new BoolConstant (types, (bool) value, Location.Null);
1158 return new ByteConstant (types, (byte) value, Location.Null);
1160 return new CharConstant (types, (char) value, Location.Null);
1161 case TypeCode.Decimal:
1162 return new DecimalConstant (types, (decimal) value, Location.Null);
1163 case TypeCode.Double:
1164 return new DoubleConstant (types, (double) value, Location.Null);
1165 case TypeCode.Int16:
1166 return new ShortConstant (types, (short) value, Location.Null);
1167 case TypeCode.Int32:
1168 return new IntConstant (types, (int) value, Location.Null);
1169 case TypeCode.Int64:
1170 return new LongConstant (types, (long) value, Location.Null);
1171 case TypeCode.SByte:
1172 return new SByteConstant (types, (sbyte) value, Location.Null);
1173 case TypeCode.Single:
1174 return new FloatConstant (types, (float) value, Location.Null);
1175 case TypeCode.String:
1176 return new StringConstant (types, (string) value, Location.Null);
1177 case TypeCode.UInt16:
1178 return new UShortConstant (types, (ushort) value, Location.Null);
1179 case TypeCode.UInt32:
1180 return new UIntConstant (types, (uint) value, Location.Null);
1181 case TypeCode.UInt64:
1182 return new ULongConstant (types, (ulong) value, Location.Null);
1185 throw new NotImplementedException (value.GetType ().ToString ());
1188 public TypeSpec ImportType (MetaType type)
1190 return ImportType (type, new DynamicTypeReader (type));
1193 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1195 if (type.HasElementType) {
1196 var element = type.GetElementType ();
1198 var spec = ImportType (element, dtype);
1201 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1203 return ReferenceContainer.MakeType (module, spec);
1205 return PointerContainer.MakeType (module, spec);
1207 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1210 TypeSpec compiled_type;
1211 if (compiled_types.TryGetValue (type, out compiled_type)) {
1212 if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
1213 return module.Compiler.BuiltinTypes.Dynamic;
1215 return compiled_type;
1218 return CreateType (type, dtype, true);
1221 static bool IsMissingType (MetaType type)
1224 return type.__IsMissing;
1231 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1232 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1233 // DecimalConstantAttribute metadata.
1235 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1237 if (attrs.Count == 0)
1240 foreach (var ca in attrs) {
1241 var dt = ca.Constructor.DeclaringType;
1242 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1245 var value = new decimal (
1246 (int) (uint) ca.ConstructorArguments[4].Value,
1247 (int) (uint) ca.ConstructorArguments[3].Value,
1248 (int) (uint) ca.ConstructorArguments[2].Value,
1249 (byte) ca.ConstructorArguments[1].Value != 0,
1250 (byte) ca.ConstructorArguments[0].Value);
1252 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1258 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1261 var ma = mb.Attributes;
1262 switch (ma & MethodAttributes.MemberAccessMask) {
1263 case MethodAttributes.Public:
1264 mod = Modifiers.PUBLIC;
1266 case MethodAttributes.Assembly:
1267 mod = Modifiers.INTERNAL;
1269 case MethodAttributes.Family:
1270 mod = Modifiers.PROTECTED;
1272 case MethodAttributes.FamORAssem:
1273 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1276 mod = Modifiers.PRIVATE;
1280 if ((ma & MethodAttributes.Static) != 0) {
1281 mod |= Modifiers.STATIC;
1284 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1285 mod |= Modifiers.ABSTRACT;
1289 // It can be sealed and override
1290 if ((ma & MethodAttributes.Final) != 0)
1291 mod |= Modifiers.SEALED;
1293 if ((ma & MethodAttributes.Virtual) != 0) {
1294 // Not every member can be detected based on MethodAttribute, we
1295 // set virtual or non-virtual only when we are certain. Further checks
1296 // to really find out what `virtual' means for this member are done
1298 if ((ma & MethodAttributes.NewSlot) != 0) {
1299 if ((mod & Modifiers.SEALED) != 0) {
1300 mod &= ~Modifiers.SEALED;
1302 mod |= Modifiers.VIRTUAL;
1305 mod |= Modifiers.OVERRIDE;
1313 abstract class ImportedDefinition : IMemberDefinition
1315 protected class AttributesBag
1317 public static readonly AttributesBag Default = new AttributesBag ();
1319 public AttributeUsageAttribute AttributeUsage;
1320 public ObsoleteAttribute Obsolete;
1321 public string[] Conditionals;
1322 public string DefaultIndexerName;
1323 public bool? CLSAttributeValue;
1324 public TypeSpec CoClass;
1326 static bool HasMissingType (ConstructorInfo ctor)
1330 // Mimic odd csc behaviour where missing type on predefined
1331 // attributes means the attribute is silently ignored. This can
1332 // happen with PCL facades
1334 foreach (var p in ctor.GetParameters ()) {
1335 if (p.ParameterType.__ContainsMissingType)
1343 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1345 AttributesBag bag = null;
1346 List<string> conditionals = null;
1348 // It should not throw any loading exception
1349 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1351 foreach (var a in attrs) {
1352 var dt = a.Constructor.DeclaringType;
1353 string name = dt.Name;
1354 if (name == "ObsoleteAttribute") {
1355 if (dt.Namespace != "System")
1359 bag = new AttributesBag ();
1361 var args = a.ConstructorArguments;
1363 if (args.Count == 1) {
1364 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1365 } else if (args.Count == 2) {
1366 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1368 bag.Obsolete = new ObsoleteAttribute ();
1374 if (name == "ConditionalAttribute") {
1375 if (dt.Namespace != "System.Diagnostics")
1379 bag = new AttributesBag ();
1381 if (conditionals == null)
1382 conditionals = new List<string> (2);
1384 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1388 if (name == "CLSCompliantAttribute") {
1389 if (dt.Namespace != "System")
1393 bag = new AttributesBag ();
1395 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1399 // Type only attributes
1400 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1401 if (name == "DefaultMemberAttribute") {
1402 if (dt.Namespace != "System.Reflection")
1406 bag = new AttributesBag ();
1408 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1412 if (name == "AttributeUsageAttribute") {
1413 if (dt.Namespace != "System")
1416 if (HasMissingType (a.Constructor))
1420 bag = new AttributesBag ();
1422 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1423 foreach (var named in a.NamedArguments) {
1424 if (named.MemberInfo.Name == "AllowMultiple")
1425 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1426 else if (named.MemberInfo.Name == "Inherited")
1427 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1432 // Interface only attribute
1433 if (name == "CoClassAttribute") {
1434 if (dt.Namespace != "System.Runtime.InteropServices")
1437 if (HasMissingType (a.Constructor))
1441 bag = new AttributesBag ();
1443 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1452 if (conditionals != null)
1453 bag.Conditionals = conditionals.ToArray ();
1459 protected readonly MemberInfo provider;
1460 protected AttributesBag cattrs;
1461 protected readonly MetadataImporter importer;
1463 protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1465 this.provider = provider;
1466 this.importer = importer;
1471 public bool IsImported {
1477 public virtual string Name {
1479 return provider.Name;
1485 public string[] ConditionalConditions ()
1490 return cattrs.Conditionals;
1493 public ObsoleteAttribute GetAttributeObsolete ()
1498 return cattrs.Obsolete;
1501 public bool? CLSAttributeValue {
1506 return cattrs.CLSAttributeValue;
1510 protected void ReadAttributes ()
1512 cattrs = AttributesBag.Read (provider, importer);
1515 public void SetIsAssigned ()
1517 // Unused for imported members
1520 public void SetIsUsed ()
1522 // Unused for imported members
1526 public class ImportedModuleDefinition
1528 readonly Module module;
1531 public ImportedModuleDefinition (Module module)
1533 this.module = module;
1538 public bool IsCLSCompliant {
1540 return cls_compliant;
1544 public string Name {
1552 public void ReadAttributes ()
1554 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1556 foreach (var a in attrs) {
1557 var dt = a.Constructor.DeclaringType;
1558 if (dt.Name == "CLSCompliantAttribute") {
1559 if (dt.Namespace != "System")
1562 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1569 // Reads assembly attributes which where attached to a special type because
1570 // module does have assembly manifest
1572 public List<Attribute> ReadAssemblyAttributes ()
1574 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1578 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1582 // TODO: implement, the idea is to fabricate specil Attribute class and
1583 // add it to OptAttributes before resolving the source code attributes
1584 // Need to build module location as well for correct error reporting
1586 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1587 //var attrs = new List<Attribute> (assembly_attributes.Count);
1588 //foreach (var a in assembly_attributes)
1590 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1591 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1593 // foreach (var carg in a.ConstructorArguments) {
1597 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1604 public class ImportedAssemblyDefinition : IAssemblyDefinition
1606 readonly Assembly assembly;
1607 readonly AssemblyName aname;
1610 List<AssemblyName> internals_visible_to;
1611 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1613 public ImportedAssemblyDefinition (Assembly assembly)
1615 this.assembly = assembly;
1616 this.aname = assembly.GetName ();
1621 public Assembly Assembly {
1627 public string FullName {
1629 return aname.FullName;
1633 public bool HasStrongName {
1635 return aname.GetPublicKey ().Length != 0;
1639 public bool IsMissing {
1642 return assembly.__IsMissing;
1649 public bool IsCLSCompliant {
1651 return cls_compliant;
1655 public string Location {
1657 return assembly.Location;
1661 public string Name {
1669 public byte[] GetPublicKeyToken ()
1671 return aname.GetPublicKeyToken ();
1674 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1676 return internals_visible_to_cache [assembly];
1679 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1681 if (internals_visible_to == null)
1684 AssemblyName is_visible = null;
1685 if (internals_visible_to_cache == null) {
1686 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1688 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1689 return is_visible != null;
1692 var token = assembly.GetPublicKeyToken ();
1693 if (token != null && token.Length == 0)
1696 foreach (var internals in internals_visible_to) {
1697 if (internals.Name != assembly.Name)
1700 if (token == null && assembly is AssemblyDefinition) {
1701 is_visible = internals;
1705 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1708 is_visible = internals;
1712 internals_visible_to_cache.Add (assembly, is_visible);
1713 return is_visible != null;
1716 public void ReadAttributes ()
1719 if (assembly.__IsMissing)
1723 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1725 foreach (var a in attrs) {
1726 var dt = a.Constructor.DeclaringType;
1728 if (name == "CLSCompliantAttribute") {
1729 if (dt.Namespace == "System") {
1730 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1735 if (name == "InternalsVisibleToAttribute") {
1736 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1739 string s = a.ConstructorArguments[0].Value as string;
1745 an = new AssemblyName (s);
1746 } catch (FileLoadException) {
1747 // Invalid assembly name reuses FileLoadException
1751 if (internals_visible_to == null)
1752 internals_visible_to = new List<AssemblyName> ();
1754 internals_visible_to.Add (an);
1760 public override string ToString ()
1766 class ImportedMemberDefinition : ImportedDefinition
1768 readonly TypeSpec type;
1770 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1771 : base (member, importer)
1778 public TypeSpec MemberType {
1787 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1789 readonly AParametersCollection parameters;
1791 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1792 : base (provider, type, importer)
1794 this.parameters = parameters;
1797 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1798 : base (provider, type, importer)
1800 this.parameters = parameters;
1805 public AParametersCollection Parameters {
1814 class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1816 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1817 : base (provider, type, parameters, importer)
1821 MethodBase IMethodDefinition.Metadata {
1823 return (MethodBase) provider;
1828 class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1830 readonly TypeParameterSpec[] tparams;
1832 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1833 : base (provider, type, parameters, importer)
1835 this.tparams = tparams;
1840 public TypeParameterSpec[] TypeParameters {
1846 public int TypeParametersCount {
1848 return tparams.Length;
1855 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1857 TypeParameterSpec[] tparams;
1860 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1861 : base (type, importer)
1867 public IAssemblyDefinition DeclaringAssembly {
1869 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1873 bool ITypeDefinition.IsComImport {
1875 return ((MetaType) provider).IsImport;
1880 bool ITypeDefinition.IsPartial {
1886 bool ITypeDefinition.IsTypeForwarder {
1889 return ((MetaType) provider).__IsTypeForwarder;
1896 bool ITypeDefinition.IsCyclicTypeForwarder {
1899 return ((MetaType) provider).__IsCyclicTypeForwarder;
1906 public override string Name {
1910 if (tparams != null) {
1911 int arity_start = name.IndexOf ('`');
1912 if (arity_start > 0)
1913 name = name.Substring (0, arity_start);
1921 public string Namespace {
1923 return ((MetaType) provider).Namespace;
1927 public int TypeParametersCount {
1929 return tparams == null ? 0 : tparams.Length;
1933 public TypeParameterSpec[] TypeParameters {
1944 public void DefineInterfaces (TypeSpec spec)
1946 var type = (MetaType) provider;
1949 ifaces = type.__GetDeclaredInterfaces ();
1950 if (ifaces.Length != 0) {
1951 foreach (var iface in ifaces) {
1952 var it = importer.CreateType (iface);
1956 spec.AddInterfaceDefined (it);
1958 // Unfortunately not all languages expand inherited interfaces
1959 var bifaces = it.Interfaces;
1960 if (bifaces != null) {
1961 foreach (var biface in bifaces) {
1962 spec.AddInterfaceDefined (biface);
1969 // It's impossible to get declared interfaces only using System.Reflection
1970 // hence we need to mimic the behavior with ikvm-reflection too to keep
1971 // our type look-up logic same
1973 if (spec.BaseType != null) {
1974 var bifaces = spec.BaseType.Interfaces;
1975 if (bifaces != null) {
1977 // Before adding base class interfaces close defined interfaces
1978 // on type parameter
1980 var tp = spec as TypeParameterSpec;
1981 if (tp != null && tp.InterfacesDefined == null) {
1982 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1985 foreach (var iface in bifaces)
1986 spec.AddInterfaceDefined (iface);
1990 ifaces = type.GetInterfaces ();
1992 if (ifaces.Length > 0) {
1993 foreach (var iface in ifaces) {
1994 spec.AddInterface (importer.CreateType (iface));
2001 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
2004 // Report details about missing type and most likely cause of the problem.
2005 // csc used to reports 1683, 1684 (now 7069) as warnings but we report them only when used
2006 // or referenced from the user core in which case compilation error has to
2007 // be reported because compiler cannot continue anyway
2010 var report = ctx.Module.Compiler.Report;
2012 for (int i = 0; i < missing.Count; ++i) {
2013 var t = missing [i].Type;
2016 // Report missing types only once
2018 if (report.Printer.MissingTypeReported (t.MemberDefinition))
2021 string name = t.GetSignatureForError ();
2023 var caller = missing[i].Caller;
2024 if (caller.Kind != MemberKind.MissingType)
2025 report.SymbolRelatedToPreviousError (caller);
2027 var definition = t.MemberDefinition;
2028 if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
2029 report.Error (1683, loc,
2030 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
2032 } else if (definition.DeclaringAssembly.IsMissing) {
2033 if (definition.IsTypeForwarder) {
2034 report.Error (1070, loc,
2035 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2036 name, definition.DeclaringAssembly.FullName);
2038 report.Error (12, loc,
2039 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2040 name, definition.DeclaringAssembly.FullName);
2042 } else if (definition.IsTypeForwarder) {
2043 report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
2044 name, definition.DeclaringAssembly.FullName);
2046 report.Error (7069, loc,
2047 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
2048 name, t.MemberDefinition.DeclaringAssembly.FullName);
2053 public TypeSpec GetAttributeCoClass ()
2058 return cattrs.CoClass;
2061 public string GetAttributeDefaultMember ()
2066 return cattrs.DefaultIndexerName;
2069 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2074 return cattrs.AttributeUsage;
2077 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2079 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
2080 return a == assembly || a.IsFriendAssemblyTo (assembly);
2083 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2086 // Not interested in members of nested private types unless the importer needs them
2088 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
2089 cache = MemberCache.Empty;
2093 var loading_type = (MetaType) provider;
2094 const BindingFlags all_members = BindingFlags.DeclaredOnly |
2095 BindingFlags.Static | BindingFlags.Instance |
2096 BindingFlags.Public | BindingFlags.NonPublic;
2098 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
2099 MethodAttributes.Virtual | MethodAttributes.HideBySig |
2100 MethodAttributes.Final;
2102 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
2103 List<EventSpec> imported_events = null;
2104 EventSpec event_spec;
2105 MemberSpec imported;
2109 all = loading_type.GetMembers (all_members);
2110 } catch (Exception e) {
2111 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2112 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2115 if (cache == null) {
2116 cache = new MemberCache (all.Length);
2119 // Do the types first as they can be referenced by the members before
2120 // they are found or inflated
2122 foreach (var member in all) {
2123 if (member.MemberType != MemberTypes.NestedType)
2126 var t = (MetaType) member;
2128 // Ignore compiler generated types, mostly lambda containers
2129 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2133 imported = importer.CreateNestedType (t, declaringType);
2134 } catch (Exception e) {
2135 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2136 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2139 cache.AddMemberImported (imported);
2142 foreach (var member in all) {
2143 if (member.MemberType != MemberTypes.NestedType)
2146 var t = (MetaType) member;
2148 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2151 importer.ImportTypeBase (t);
2156 // Load base interfaces first to minic behaviour of compiled members
2158 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2159 foreach (var iface in declaringType.Interfaces) {
2160 cache.AddInterface (iface);
2166 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2168 foreach (var member in all) {
2169 switch (member.MemberType) {
2170 case MemberTypes.Constructor:
2171 if (declaringType.IsInterface)
2174 goto case MemberTypes.Method;
2175 case MemberTypes.Method:
2176 MethodBase mb = (MethodBase) member;
2177 var attrs = mb.Attributes;
2179 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2180 if (importer.IgnorePrivateMembers)
2183 // Ignore explicitly implemented members
2184 if ((attrs & explicit_impl) == explicit_impl)
2187 // Ignore compiler generated methods
2188 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2192 imported = importer.CreateMethod (mb, declaringType);
2193 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2194 if (possible_accessors == null)
2195 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2197 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2198 possible_accessors.Add (mb, (MethodSpec) imported);
2202 case MemberTypes.Property:
2203 if (possible_accessors == null)
2206 var p = (PropertyInfo) member;
2208 // Links possible accessors with property
2210 MethodSpec get, set;
2211 m = p.GetGetMethod (true);
2212 if (m == null || !possible_accessors.TryGetValue (m, out get))
2215 m = p.GetSetMethod (true);
2216 if (m == null || !possible_accessors.TryGetValue (m, out set))
2219 // No accessors registered (e.g. explicit implementation)
2220 if (get == null && set == null)
2224 imported = importer.CreateProperty (p, declaringType, get, set);
2225 } catch (Exception ex) {
2226 throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2227 p.Name, declaringType.GetSignatureForError ());
2230 if (imported == null)
2234 case MemberTypes.Event:
2235 if (possible_accessors == null)
2238 var e = (EventInfo) member;
2240 // Links accessors with event
2242 MethodSpec add, remove;
2243 m = e.GetAddMethod (true);
2244 if (m == null || !possible_accessors.TryGetValue (m, out add))
2247 m = e.GetRemoveMethod (true);
2248 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2251 // Both accessors are required
2252 if (add == null || remove == null)
2255 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2256 if (!importer.IgnorePrivateMembers) {
2257 if (imported_events == null)
2258 imported_events = new List<EventSpec> ();
2260 imported_events.Add (event_spec);
2263 imported = event_spec;
2265 case MemberTypes.Field:
2266 var fi = (FieldInfo) member;
2268 imported = importer.CreateField (fi, declaringType);
2269 if (imported == null)
2273 // For dynamic binder event has to be fully restored to allow operations
2274 // within the type container to work correctly
2276 if (imported_events != null) {
2277 // The backing event field should be private but it may not
2279 for (i = 0; i < imported_events.Count; ++i) {
2280 var ev = imported_events[i];
2281 if (ev.Name == fi.Name) {
2282 ev.BackingField = (FieldSpec) imported;
2283 imported_events.RemoveAt (i);
2294 case MemberTypes.NestedType:
2295 // Already in the cache from the first pass
2298 throw new NotImplementedException (member.ToString ());
2301 if (imported.IsStatic && declaringType.IsInterface)
2304 cache.AddMemberImported (imported);
2310 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2312 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2313 : base (type, importer)
2319 public IAssemblyDefinition DeclaringAssembly {
2321 throw new NotImplementedException ();
2325 bool ITypeDefinition.IsComImport {
2331 bool ITypeDefinition.IsPartial {
2337 bool ITypeDefinition.IsTypeForwarder {
2343 bool ITypeDefinition.IsCyclicTypeForwarder {
2349 public string Namespace {
2355 public int TypeParametersCount {
2361 public TypeParameterSpec[] TypeParameters {
2369 public TypeSpec GetAttributeCoClass ()
2374 public string GetAttributeDefaultMember ()
2376 throw new NotSupportedException ();
2379 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2381 throw new NotSupportedException ();
2384 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2386 throw new NotImplementedException ();
2389 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2391 throw new NotImplementedException ();