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));
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));
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);
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 = spec.DeclaringType == null ? 0 : spec.DeclaringType.MemberDefinition.TypeParametersCount;
369 var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype);
370 spec = spec.MakeGenericType (module, targs);
384 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
386 Modifiers mod = ReadMethodModifiers (mb, declaringType);
387 TypeParameterSpec[] tparams;
389 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
391 if (mb.IsGenericMethod) {
392 if (!mb.IsGenericMethodDefinition)
393 throw new NotSupportedException ("assert");
395 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
402 if (mb.MemberType == MemberTypes.Constructor) {
403 kind = MemberKind.Constructor;
404 returnType = module.Compiler.BuiltinTypes.Void;
407 // Detect operators and destructors
409 string name = mb.Name;
410 kind = MemberKind.Method;
411 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
412 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
413 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o' && (mb.Attributes & MethodAttributes.SpecialName) != 0) {
414 var op_type = Operator.GetType (name);
415 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
416 kind = MemberKind.Operator;
419 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
420 kind = MemberKind.Destructor;
421 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
422 mod &= ~Modifiers.OVERRIDE;
423 mod |= Modifiers.VIRTUAL;
428 var mi = (MethodInfo) mb;
429 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
431 // Cannot set to OVERRIDE without full hierarchy checks
432 // this flag indicates that the method could be override
433 // but further validation is needed
434 if ((mod & Modifiers.OVERRIDE) != 0) {
435 bool is_real_override = false;
436 if (kind == MemberKind.Method && declaringType.BaseType != null) {
437 var btype = declaringType.BaseType;
438 if (IsOverrideMethodBaseTypeAccessible (btype)) {
439 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
440 var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
443 // For imported class method do additional validation to be sure that metadata
444 // override flag was correct
446 // Difference between protected internal and protected is ok
448 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
449 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
450 is_real_override = true;
455 if (!is_real_override) {
456 mod &= ~Modifiers.OVERRIDE;
457 if ((mod & Modifiers.SEALED) != 0)
458 mod &= ~Modifiers.SEALED;
460 mod |= Modifiers.VIRTUAL;
462 } else if (parameters.HasExtensionMethodType) {
463 mod |= Modifiers.METHOD_EXTENSION;
467 IMethodDefinition definition;
468 if (tparams != null) {
469 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
470 foreach (var tp in gmd.TypeParameters) {
471 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
476 definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
479 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
486 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
488 switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
489 case Modifiers.PUBLIC:
491 case Modifiers.INTERNAL:
493 // Check whether imported method in base type is accessible from compiled
496 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
497 case Modifiers.PRIVATE:
501 // protected internal
503 // Method accessibility checks will be done later based on context
504 // where the method is called (CS0122 error will be reported for inaccessible)
511 // Imports System.Reflection parameters
513 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
515 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
517 if (pi.Length == 0 && varargs == 0)
518 return ParametersCompiled.EmptyReadOnlyParameters;
520 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
521 IParameterData[] par = new IParameterData[pi.Length + varargs];
522 bool is_params = false;
523 for (int i = 0; i < pi.Length; i++) {
524 ParameterInfo p = pi[i];
525 Parameter.Modifier mod = 0;
526 Expression default_value = null;
527 if (p.ParameterType.IsByRef) {
528 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
529 mod = Parameter.Modifier.OUT;
531 mod = Parameter.Modifier.REF;
534 // Strip reference wrapping
536 var el = p.ParameterType.GetElementType ();
537 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
538 } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
539 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
540 mod = Parameter.Modifier.This;
541 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
543 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
545 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
546 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
547 mod = Parameter.Modifier.PARAMS;
552 if (!is_params && p.IsOptional) {
553 object value = p.RawDefaultValue;
554 var ptype = types[i];
555 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
557 default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
559 default_value = ImportConstant (value);
562 default_value = new EnumConstant ((Constant) default_value, ptype);
566 var attrs = CustomAttributeData.GetCustomAttributes (p);
567 for (int ii = 0; ii < attrs.Count; ++ii) {
568 var attr = attrs[ii];
569 var dt = attr.Constructor.DeclaringType;
570 if (dt.Namespace != CompilerServicesNamespace)
573 if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
574 mod |= Parameter.Modifier.CallerLineNumber;
575 else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
576 mod |= Parameter.Modifier.CallerFilePath;
577 else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
578 mod |= Parameter.Modifier.CallerMemberName;
580 } else if (value == Missing.Value) {
581 default_value = EmptyExpression.MissingValue;
582 } else if (value == null) {
583 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
584 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
585 default_value = ImportConstant (value);
590 par[i] = new ParameterData (p.Name, mod, default_value);
594 par[par.Length - 1] = new ArglistParameter (Location.Null);
595 types[types.Length - 1] = InternalType.Arglist;
598 return method != null ?
599 new ParametersImported (par, types, varargs != 0, is_params) :
600 new ParametersImported (par, types, is_params);
604 // Returns null when the property is not valid C# property
606 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
609 AParametersCollection param = null;
610 TypeSpec type = null;
613 param = get.Parameters;
614 type = get.ReturnType;
617 bool is_valid_property = true;
619 if (set.ReturnType.Kind != MemberKind.Void)
620 is_valid_property = false;
622 var set_param_count = set.Parameters.Count - 1;
624 if (set_param_count < 0) {
626 is_valid_property = false;
629 var set_type = set.Parameters.Types[set_param_count];
632 AParametersCollection set_based_param;
634 if (set_param_count == 0) {
635 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
638 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
640 var data = new IParameterData[set_param_count];
641 var types = new TypeSpec[set_param_count];
642 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
643 Array.Copy (set.Parameters.Types, types, set_param_count);
644 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
648 param = set_based_param;
651 if (set_param_count != get.Parameters.Count)
652 is_valid_property = false;
654 if (get.ReturnType != set_type)
655 is_valid_property = false;
657 // Possible custom accessor modifiers
658 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
659 var get_acc = mod & Modifiers.AccessibilityMask;
660 if (get_acc != Modifiers.PUBLIC) {
661 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
662 // If the accessor modifiers are not same, do extra restriction checks
663 if (get_acc != set_acc) {
664 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
665 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
666 if (get_restr && set_restr) {
667 is_valid_property = false; // Neither is more restrictive
671 mod &= ~Modifiers.AccessibilityMask;
680 PropertySpec spec = null;
681 if (!param.IsEmpty) {
682 if (is_valid_property) {
683 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
684 if (index_name == null || index_name != pi.Name) {
685 is_valid_property = false;
689 is_valid_property = false;
693 is_valid_property = false;
697 if (is_valid_property) {
698 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
699 } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
701 // Enables support for properties with parameters (must have default value) of COM-imported types
703 is_valid_property = true;
705 for (int i = 0; i < param.FixedParameters.Length; ++i) {
706 if (!param.FixedParameters[i].HasDefaultValue) {
707 is_valid_property = false;
716 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
718 if (!is_valid_property) {
719 spec.IsNotCSharpCompatible = true;
731 public TypeSpec CreateType (MetaType type)
733 return CreateType (type, new DynamicTypeReader (), true);
736 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
738 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
741 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
743 TypeSpec declaring_type;
744 if (type.IsNested && !type.IsGenericParameter)
745 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
747 declaring_type = null;
749 return CreateType (type, declaring_type, dtype, canImportBaseType);
752 protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
755 if (import_cache.TryGetValue (type, out spec)) {
756 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
757 if (dtype.IsDynamicObject ())
758 return module.Compiler.BuiltinTypes.Dynamic;
763 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
766 if (!dtype.HasDynamicAttribute ())
769 // We've found same object in the cache but this one has a dynamic custom attribute
770 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
771 // Do type resolve process again in that case
773 // TODO: Handle cases where they still unify
776 if (IsMissingType (type)) {
777 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
778 spec.MemberCache = MemberCache.Empty;
779 import_cache.Add (type, spec);
783 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
784 var type_def = type.GetGenericTypeDefinition ();
786 // Generic type definition can also be forwarded
787 if (compiled_types.TryGetValue (type_def, out spec))
790 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
793 if (declaringType == null) {
794 // Simple case, no nesting
795 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
796 spec = spec.MakeGenericType (module, targs);
799 // Nested type case, converting .NET types like
800 // A`1.B`1.C`1<int, long, string> to typespec like
801 // A<int>.B<long>.C<string>
803 var nested_hierarchy = new List<TypeSpec> ();
804 while (declaringType.IsNested) {
805 nested_hierarchy.Add (declaringType);
806 declaringType = declaringType.DeclaringType;
810 if (declaringType.Arity > 0) {
811 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
812 targs_pos = spec.Arity;
814 spec = declaringType;
817 for (int i = nested_hierarchy.Count; i != 0; --i) {
818 var t = nested_hierarchy [i - 1];
819 if (t.Kind == MemberKind.MissingType)
822 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity, false);
825 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
826 targs_pos += t.Arity;
830 if (spec.Kind == MemberKind.MissingType) {
831 spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC);
832 spec.MemberCache = MemberCache.Empty;
834 if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
837 string name = type.Name;
838 int index = name.IndexOf ('`');
840 name = name.Substring (0, index);
842 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos, false);
844 if (spec.Arity > 0) {
845 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
850 // Don't add generic type with dynamic arguments, they can interfere with same type
851 // using object type arguments
852 if (!spec.HasDynamicElement) {
854 // Add to reading cache to speed up reading
855 if (!import_cache.ContainsKey (type))
856 import_cache.Add (type, spec);
865 var ma = type.Attributes;
866 switch (ma & TypeAttributes.VisibilityMask) {
867 case TypeAttributes.Public:
868 case TypeAttributes.NestedPublic:
869 mod = Modifiers.PUBLIC;
871 case TypeAttributes.NestedPrivate:
872 mod = Modifiers.PRIVATE;
874 case TypeAttributes.NestedFamily:
875 mod = Modifiers.PROTECTED;
877 case TypeAttributes.NestedFamORAssem:
878 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
881 mod = Modifiers.INTERNAL;
885 if ((ma & TypeAttributes.Interface) != 0) {
886 kind = MemberKind.Interface;
887 } else if (type.IsGenericParameter) {
888 kind = MemberKind.TypeParameter;
890 var base_type = type.BaseType;
891 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
892 kind = MemberKind.Class;
894 kind = DetermineKindFromBaseType (base_type);
895 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
896 mod |= Modifiers.SEALED;
900 if (kind == MemberKind.Class) {
901 if ((ma & TypeAttributes.Sealed) != 0) {
902 if ((ma & TypeAttributes.Abstract) != 0)
903 mod |= Modifiers.STATIC;
905 mod |= Modifiers.SEALED;
906 } else if ((ma & TypeAttributes.Abstract) != 0) {
907 mod |= Modifiers.ABSTRACT;
912 var definition = new ImportedTypeDefinition (type, this);
915 if (kind == MemberKind.Enum) {
916 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
917 BindingFlags.Instance |
918 BindingFlags.Public | BindingFlags.NonPublic;
920 var type_members = type.GetFields (underlying_member);
921 foreach (var type_member in type_members) {
922 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
927 kind = MemberKind.Class;
929 } else if (kind == MemberKind.TypeParameter) {
930 spec = CreateTypeParameter (type, declaringType);
931 } else if (type.IsGenericTypeDefinition) {
932 definition.TypeParameters = CreateGenericParameters (type, declaringType);
933 } else if (compiled_types.TryGetValue (type, out pt)) {
935 // Same type was found in inside compiled types. It's
936 // either build-in type or forward referenced typed
937 // which point into just compiled assembly.
940 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
942 bts.SetDefinition (definition, type, mod);
946 spec = new TypeSpec (kind, declaringType, definition, type, mod);
948 import_cache.Add (type, spec);
950 if (kind == MemberKind.TypeParameter) {
951 if (canImportBaseType)
952 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
958 // Two stage setup as the base type can be inflated declaring type or
959 // another nested type inside same declaring type which has not been
960 // loaded, therefore we can import a base type of nested types once
961 // the types have been imported
963 if (canImportBaseType)
964 ImportTypeBase (spec, type);
969 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
971 IAssemblyDefinition found;
972 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
974 // This can happen in dynamic context only
975 var def = new ImportedAssemblyDefinition (assembly);
976 assembly_2_definition.Add (assembly, def);
977 def.ReadAttributes ();
984 public ImportedAssemblyDefinition GetImportedAssemblyDefinition (AssemblyName assemblyName)
986 foreach (var a in Assemblies) {
987 var ia = a as ImportedAssemblyDefinition;
991 if (a.Name == assemblyName.Name)
999 public void ImportTypeBase (MetaType type)
1001 TypeSpec spec = import_cache[type];
1003 ImportTypeBase (spec, type);
1006 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
1009 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
1010 case GenericParameterAttributes.Covariant:
1011 variance = Variance.Covariant;
1013 case GenericParameterAttributes.Contravariant:
1014 variance = Variance.Contravariant;
1017 variance = Variance.None;
1021 SpecialConstraint special = SpecialConstraint.None;
1022 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
1024 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
1025 special |= SpecialConstraint.Struct;
1026 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
1027 special = SpecialConstraint.Constructor;
1030 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
1031 special |= SpecialConstraint.Class;
1034 TypeParameterSpec spec;
1035 var def = new ImportedTypeParameterDefinition (type, this);
1036 if (type.DeclaringMethod != null) {
1037 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
1039 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
1046 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
1047 // they can be assembly specific therefore we do check based on names only
1049 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
1051 if (attributesData.Count == 0)
1054 foreach (var attr in attributesData) {
1055 var dt = attr.Constructor.DeclaringType;
1056 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1063 void ImportTypeBase (TypeSpec spec, MetaType type)
1065 if (spec.Kind == MemberKind.Interface)
1066 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1067 else if (type.BaseType != null) {
1069 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1070 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1072 base_type = CreateType (type.BaseType);
1074 spec.BaseType = base_type;
1077 if (spec.MemberDefinition.TypeParametersCount > 0) {
1078 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1079 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1084 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1086 Namespace ns = targetNamespace;
1087 string prev_namespace = null;
1088 foreach (var t in types) {
1092 // Be careful not to trigger full parent type loading
1093 if (t.MemberType == MemberTypes.NestedType)
1096 if (t.Name[0] == '<')
1099 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1103 if (prev_namespace != t.Namespace) {
1104 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1105 prev_namespace = t.Namespace;
1108 // Cannot rely on assembly level Extension attribute or static modifier because they
1109 // are not followed by other compilers (e.g. F#).
1110 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1111 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1112 it.SetExtensionMethodContainer ();
1115 ns.AddType (module, it);
1119 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1121 var constraints = type.GetGenericParameterConstraints ();
1122 List<TypeSpec> tparams = null;
1123 foreach (var ct in constraints) {
1124 if (ct.IsGenericParameter) {
1125 if (tparams == null)
1126 tparams = new List<TypeSpec> ();
1128 tparams.Add (CreateType (ct));
1132 var constraint_type = CreateType (ct);
1133 if (constraint_type.IsClass) {
1134 spec.BaseType = constraint_type;
1138 spec.AddInterface (constraint_type);
1141 if (spec.BaseType == null)
1142 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1144 if (tparams != null)
1145 spec.TypeArguments = tparams.ToArray ();
1148 Constant ImportConstant (object value)
1151 // Get type of underlying value as int constant can be used for object
1152 // parameter type. This is not allowed in C# but other languages can do that
1154 var types = module.Compiler.BuiltinTypes;
1155 switch (System.Type.GetTypeCode (value.GetType ())) {
1156 case TypeCode.Boolean:
1157 return new BoolConstant (types, (bool) value, Location.Null);
1159 return new ByteConstant (types, (byte) value, Location.Null);
1161 return new CharConstant (types, (char) value, Location.Null);
1162 case TypeCode.Decimal:
1163 return new DecimalConstant (types, (decimal) value, Location.Null);
1164 case TypeCode.Double:
1165 return new DoubleConstant (types, (double) value, Location.Null);
1166 case TypeCode.Int16:
1167 return new ShortConstant (types, (short) value, Location.Null);
1168 case TypeCode.Int32:
1169 return new IntConstant (types, (int) value, Location.Null);
1170 case TypeCode.Int64:
1171 return new LongConstant (types, (long) value, Location.Null);
1172 case TypeCode.SByte:
1173 return new SByteConstant (types, (sbyte) value, Location.Null);
1174 case TypeCode.Single:
1175 return new FloatConstant (types, (float) value, Location.Null);
1176 case TypeCode.String:
1177 return new StringConstant (types, (string) value, Location.Null);
1178 case TypeCode.UInt16:
1179 return new UShortConstant (types, (ushort) value, Location.Null);
1180 case TypeCode.UInt32:
1181 return new UIntConstant (types, (uint) value, Location.Null);
1182 case TypeCode.UInt64:
1183 return new ULongConstant (types, (ulong) value, Location.Null);
1186 throw new NotImplementedException (value.GetType ().ToString ());
1189 public TypeSpec ImportType (MetaType type)
1191 return ImportType (type, new DynamicTypeReader (type));
1194 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1196 if (type.HasElementType) {
1197 var element = type.GetElementType ();
1199 var spec = ImportType (element, dtype);
1202 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1204 return ReferenceContainer.MakeType (module, spec);
1206 return PointerContainer.MakeType (module, spec);
1208 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1211 TypeSpec compiled_type;
1212 if (compiled_types.TryGetValue (type, out compiled_type)) {
1213 if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
1214 return module.Compiler.BuiltinTypes.Dynamic;
1216 return compiled_type;
1219 return CreateType (type, dtype, true);
1222 static bool IsMissingType (MetaType type)
1225 return type.__IsMissing;
1232 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1233 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1234 // DecimalConstantAttribute metadata.
1236 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1238 if (attrs.Count == 0)
1241 foreach (var ca in attrs) {
1242 var dt = ca.Constructor.DeclaringType;
1243 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1246 var value = new decimal (
1247 (int) (uint) ca.ConstructorArguments[4].Value,
1248 (int) (uint) ca.ConstructorArguments[3].Value,
1249 (int) (uint) ca.ConstructorArguments[2].Value,
1250 (byte) ca.ConstructorArguments[1].Value != 0,
1251 (byte) ca.ConstructorArguments[0].Value);
1253 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1259 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1262 var ma = mb.Attributes;
1263 switch (ma & MethodAttributes.MemberAccessMask) {
1264 case MethodAttributes.Public:
1265 mod = Modifiers.PUBLIC;
1267 case MethodAttributes.Assembly:
1268 mod = Modifiers.INTERNAL;
1270 case MethodAttributes.Family:
1271 mod = Modifiers.PROTECTED;
1273 case MethodAttributes.FamORAssem:
1274 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1277 mod = Modifiers.PRIVATE;
1281 if ((ma & MethodAttributes.Static) != 0) {
1282 mod |= Modifiers.STATIC;
1285 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1286 mod |= Modifiers.ABSTRACT;
1290 // It can be sealed and override
1291 if ((ma & MethodAttributes.Final) != 0)
1292 mod |= Modifiers.SEALED;
1294 if ((ma & MethodAttributes.Virtual) != 0) {
1295 // Not every member can be detected based on MethodAttribute, we
1296 // set virtual or non-virtual only when we are certain. Further checks
1297 // to really find out what `virtual' means for this member are done
1299 if ((ma & MethodAttributes.NewSlot) != 0) {
1300 if ((mod & Modifiers.SEALED) != 0) {
1301 mod &= ~Modifiers.SEALED;
1303 mod |= Modifiers.VIRTUAL;
1306 mod |= Modifiers.OVERRIDE;
1314 abstract class ImportedDefinition : IMemberDefinition
1316 protected class AttributesBag
1318 public static readonly AttributesBag Default = new AttributesBag ();
1320 public AttributeUsageAttribute AttributeUsage;
1321 public ObsoleteAttribute Obsolete;
1322 public string[] Conditionals;
1323 public string DefaultIndexerName;
1324 public bool? CLSAttributeValue;
1325 public TypeSpec CoClass;
1327 static bool HasMissingType (ConstructorInfo ctor)
1331 // Mimic odd csc behaviour where missing type on predefined
1332 // attributes means the attribute is silently ignored. This can
1333 // happen with PCL facades
1335 foreach (var p in ctor.GetParameters ()) {
1336 if (p.ParameterType.__ContainsMissingType)
1344 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1346 AttributesBag bag = null;
1347 List<string> conditionals = null;
1349 // It should not throw any loading exception
1350 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1352 foreach (var a in attrs) {
1353 var dt = a.Constructor.DeclaringType;
1354 string name = dt.Name;
1355 if (name == "ObsoleteAttribute") {
1356 if (dt.Namespace != "System")
1360 bag = new AttributesBag ();
1362 var args = a.ConstructorArguments;
1364 if (args.Count == 1) {
1365 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1366 } else if (args.Count == 2) {
1367 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1369 bag.Obsolete = new ObsoleteAttribute ();
1375 if (name == "ConditionalAttribute") {
1376 if (dt.Namespace != "System.Diagnostics")
1380 bag = new AttributesBag ();
1382 if (conditionals == null)
1383 conditionals = new List<string> (2);
1385 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1389 if (name == "CLSCompliantAttribute") {
1390 if (dt.Namespace != "System")
1394 bag = new AttributesBag ();
1396 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1400 // Type only attributes
1401 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1402 if (name == "DefaultMemberAttribute") {
1403 if (dt.Namespace != "System.Reflection")
1407 bag = new AttributesBag ();
1409 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1413 if (name == "AttributeUsageAttribute") {
1414 if (dt.Namespace != "System")
1417 if (HasMissingType (a.Constructor))
1421 bag = new AttributesBag ();
1423 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1424 foreach (var named in a.NamedArguments) {
1425 if (named.MemberInfo.Name == "AllowMultiple")
1426 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1427 else if (named.MemberInfo.Name == "Inherited")
1428 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1433 // Interface only attribute
1434 if (name == "CoClassAttribute") {
1435 if (dt.Namespace != "System.Runtime.InteropServices")
1438 if (HasMissingType (a.Constructor))
1442 bag = new AttributesBag ();
1444 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1453 if (conditionals != null)
1454 bag.Conditionals = conditionals.ToArray ();
1460 protected readonly MemberInfo provider;
1461 protected AttributesBag cattrs;
1462 protected readonly MetadataImporter importer;
1464 protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1466 this.provider = provider;
1467 this.importer = importer;
1472 public bool IsImported {
1478 public virtual string Name {
1480 return provider.Name;
1486 public string[] ConditionalConditions ()
1491 return cattrs.Conditionals;
1494 public ObsoleteAttribute GetAttributeObsolete ()
1499 return cattrs.Obsolete;
1502 public bool? CLSAttributeValue {
1507 return cattrs.CLSAttributeValue;
1511 protected void ReadAttributes ()
1513 cattrs = AttributesBag.Read (provider, importer);
1516 public void SetIsAssigned ()
1518 // Unused for imported members
1521 public void SetIsUsed ()
1523 // Unused for imported members
1527 public class ImportedModuleDefinition
1529 readonly Module module;
1532 public ImportedModuleDefinition (Module module)
1534 this.module = module;
1539 public bool IsCLSCompliant {
1541 return cls_compliant;
1545 public string Name {
1553 public void ReadAttributes ()
1555 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1557 foreach (var a in attrs) {
1558 var dt = a.Constructor.DeclaringType;
1559 if (dt.Name == "CLSCompliantAttribute") {
1560 if (dt.Namespace != "System")
1563 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1570 // Reads assembly attributes which where attached to a special type because
1571 // module does have assembly manifest
1573 public List<Attribute> ReadAssemblyAttributes ()
1575 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1579 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1583 // TODO: implement, the idea is to fabricate specil Attribute class and
1584 // add it to OptAttributes before resolving the source code attributes
1585 // Need to build module location as well for correct error reporting
1587 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1588 //var attrs = new List<Attribute> (assembly_attributes.Count);
1589 //foreach (var a in assembly_attributes)
1591 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1592 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1594 // foreach (var carg in a.ConstructorArguments) {
1598 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1605 public class ImportedAssemblyDefinition : IAssemblyDefinition
1607 readonly Assembly assembly;
1608 readonly AssemblyName aname;
1611 List<AssemblyName> internals_visible_to;
1612 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1614 public ImportedAssemblyDefinition (Assembly assembly)
1616 this.assembly = assembly;
1617 this.aname = assembly.GetName ();
1622 public Assembly Assembly {
1628 public string FullName {
1630 return aname.FullName;
1634 public bool HasStrongName {
1636 return aname.GetPublicKey ().Length != 0;
1640 public bool IsMissing {
1643 return assembly.__IsMissing;
1650 public bool IsCLSCompliant {
1652 return cls_compliant;
1656 public string Location {
1658 return assembly.Location;
1662 public string Name {
1670 public byte[] GetPublicKeyToken ()
1672 return aname.GetPublicKeyToken ();
1675 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1677 return internals_visible_to_cache [assembly];
1680 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1682 if (internals_visible_to == null)
1685 AssemblyName is_visible = null;
1686 if (internals_visible_to_cache == null) {
1687 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1689 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1690 return is_visible != null;
1693 var token = assembly.GetPublicKeyToken ();
1694 if (token != null && token.Length == 0)
1697 foreach (var internals in internals_visible_to) {
1698 if (internals.Name != assembly.Name)
1701 if (token == null && assembly is AssemblyDefinition) {
1702 is_visible = internals;
1706 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1709 is_visible = internals;
1713 internals_visible_to_cache.Add (assembly, is_visible);
1714 return is_visible != null;
1717 public void ReadAttributes ()
1720 if (assembly.__IsMissing)
1724 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1726 foreach (var a in attrs) {
1727 var dt = a.Constructor.DeclaringType;
1729 if (name == "CLSCompliantAttribute") {
1730 if (dt.Namespace == "System") {
1731 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1736 if (name == "InternalsVisibleToAttribute") {
1737 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1740 string s = a.ConstructorArguments[0].Value as string;
1746 an = new AssemblyName (s);
1747 } catch (FileLoadException) {
1748 // Invalid assembly name reuses FileLoadException
1752 if (internals_visible_to == null)
1753 internals_visible_to = new List<AssemblyName> ();
1755 internals_visible_to.Add (an);
1761 public override string ToString ()
1767 class ImportedMemberDefinition : ImportedDefinition
1769 readonly TypeSpec type;
1771 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1772 : base (member, importer)
1779 public TypeSpec MemberType {
1788 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1790 readonly AParametersCollection parameters;
1792 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1793 : base (provider, type, importer)
1795 this.parameters = parameters;
1798 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1799 : base (provider, type, importer)
1801 this.parameters = parameters;
1806 public AParametersCollection Parameters {
1815 class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1817 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1818 : base (provider, type, parameters, importer)
1822 MethodBase IMethodDefinition.Metadata {
1824 return (MethodBase) provider;
1829 class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1831 readonly TypeParameterSpec[] tparams;
1833 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1834 : base (provider, type, parameters, importer)
1836 this.tparams = tparams;
1841 public TypeParameterSpec[] TypeParameters {
1847 public int TypeParametersCount {
1849 return tparams.Length;
1856 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1858 TypeParameterSpec[] tparams;
1861 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1862 : base (type, importer)
1868 public IAssemblyDefinition DeclaringAssembly {
1870 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1874 bool ITypeDefinition.IsComImport {
1876 return ((MetaType) provider).IsImport;
1881 bool ITypeDefinition.IsPartial {
1887 bool ITypeDefinition.IsTypeForwarder {
1890 return ((MetaType) provider).__IsTypeForwarder;
1897 bool ITypeDefinition.IsCyclicTypeForwarder {
1900 return ((MetaType) provider).__IsCyclicTypeForwarder;
1907 public override string Name {
1911 if (tparams != null) {
1912 int arity_start = name.IndexOf ('`');
1913 if (arity_start > 0)
1914 name = name.Substring (0, arity_start);
1922 public string Namespace {
1924 return ((MetaType) provider).Namespace;
1928 public int TypeParametersCount {
1930 return tparams == null ? 0 : tparams.Length;
1934 public TypeParameterSpec[] TypeParameters {
1945 public void DefineInterfaces (TypeSpec spec)
1947 var type = (MetaType) provider;
1950 ifaces = type.__GetDeclaredInterfaces ();
1951 if (ifaces.Length != 0) {
1952 foreach (var iface in ifaces) {
1953 var it = importer.CreateType (iface);
1957 spec.AddInterfaceDefined (it);
1959 // Unfortunately not all languages expand inherited interfaces
1960 var bifaces = it.Interfaces;
1961 if (bifaces != null) {
1962 foreach (var biface in bifaces) {
1963 spec.AddInterfaceDefined (biface);
1970 // It's impossible to get declared interfaces only using System.Reflection
1971 // hence we need to mimic the behavior with ikvm-reflection too to keep
1972 // our type look-up logic same
1974 if (spec.BaseType != null) {
1975 var bifaces = spec.BaseType.Interfaces;
1976 if (bifaces != null) {
1978 // Before adding base class interfaces close defined interfaces
1979 // on type parameter
1981 var tp = spec as TypeParameterSpec;
1982 if (tp != null && tp.InterfacesDefined == null) {
1983 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1986 foreach (var iface in bifaces)
1987 spec.AddInterfaceDefined (iface);
1991 ifaces = type.GetInterfaces ();
1993 if (ifaces.Length > 0) {
1994 foreach (var iface in ifaces) {
1995 spec.AddInterface (importer.CreateType (iface));
2002 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
2005 // Report details about missing type and most likely cause of the problem.
2006 // csc used to reports 1683, 1684 (now 7069) as warnings but we report them only when used
2007 // or referenced from the user core in which case compilation error has to
2008 // be reported because compiler cannot continue anyway
2011 var report = ctx.Module.Compiler.Report;
2013 for (int i = 0; i < missing.Count; ++i) {
2014 var t = missing [i].Type;
2017 // Report missing types only once
2019 if (report.Printer.MissingTypeReported (t.MemberDefinition))
2022 string name = t.GetSignatureForError ();
2024 var caller = missing[i].Caller;
2025 if (caller.Kind != MemberKind.MissingType)
2026 report.SymbolRelatedToPreviousError (caller);
2028 var definition = t.MemberDefinition;
2029 if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
2030 report.Error (1683, loc,
2031 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
2033 } else if (definition.DeclaringAssembly.IsMissing) {
2034 if (definition.IsTypeForwarder) {
2035 report.Error (1070, loc,
2036 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2037 name, definition.DeclaringAssembly.FullName);
2039 report.Error (12, loc,
2040 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2041 name, definition.DeclaringAssembly.FullName);
2043 } else if (definition.IsTypeForwarder) {
2044 report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
2045 name, definition.DeclaringAssembly.FullName);
2047 report.Error (7069, loc,
2048 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
2049 name, t.MemberDefinition.DeclaringAssembly.FullName);
2054 public TypeSpec GetAttributeCoClass ()
2059 return cattrs.CoClass;
2062 public string GetAttributeDefaultMember ()
2067 return cattrs.DefaultIndexerName;
2070 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2075 return cattrs.AttributeUsage;
2078 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2080 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
2081 return a == assembly || a.IsFriendAssemblyTo (assembly);
2084 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2087 // Not interested in members of nested private types unless the importer needs them
2089 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
2090 cache = MemberCache.Empty;
2094 var loading_type = (MetaType) provider;
2095 const BindingFlags all_members = BindingFlags.DeclaredOnly |
2096 BindingFlags.Static | BindingFlags.Instance |
2097 BindingFlags.Public | BindingFlags.NonPublic;
2099 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
2100 MethodAttributes.Virtual | MethodAttributes.HideBySig |
2101 MethodAttributes.Final;
2103 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
2104 List<EventSpec> imported_events = null;
2105 EventSpec event_spec;
2106 MemberSpec imported;
2110 all = loading_type.GetMembers (all_members);
2111 } catch (Exception e) {
2112 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2113 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2116 if (cache == null) {
2117 cache = new MemberCache (all.Length);
2120 // Do the types first as they can be referenced by the members before
2121 // they are found or inflated
2123 foreach (var member in all) {
2124 if (member.MemberType != MemberTypes.NestedType)
2127 var t = (MetaType) member;
2129 // Ignore compiler generated types, mostly lambda containers
2130 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2134 imported = importer.CreateNestedType (t, declaringType);
2135 } catch (Exception e) {
2136 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2137 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2140 cache.AddMemberImported (imported);
2143 foreach (var member in all) {
2144 if (member.MemberType != MemberTypes.NestedType)
2147 var t = (MetaType) member;
2149 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2152 importer.ImportTypeBase (t);
2157 // Load base interfaces first to minic behaviour of compiled members
2159 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2160 foreach (var iface in declaringType.Interfaces) {
2161 cache.AddInterface (iface);
2167 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2169 foreach (var member in all) {
2170 switch (member.MemberType) {
2171 case MemberTypes.Constructor:
2172 if (declaringType.IsInterface)
2175 goto case MemberTypes.Method;
2176 case MemberTypes.Method:
2177 MethodBase mb = (MethodBase) member;
2178 var attrs = mb.Attributes;
2180 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2181 if (importer.IgnorePrivateMembers)
2184 // Ignore explicitly implemented members
2185 if ((attrs & explicit_impl) == explicit_impl)
2188 // Ignore compiler generated methods
2189 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2193 imported = importer.CreateMethod (mb, declaringType);
2194 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2195 if (possible_accessors == null)
2196 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2198 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2199 possible_accessors.Add (mb, (MethodSpec) imported);
2203 case MemberTypes.Property:
2204 if (possible_accessors == null)
2207 var p = (PropertyInfo) member;
2209 // Links possible accessors with property
2211 MethodSpec get, set;
2212 m = p.GetGetMethod (true);
2213 if (m == null || !possible_accessors.TryGetValue (m, out get))
2216 m = p.GetSetMethod (true);
2217 if (m == null || !possible_accessors.TryGetValue (m, out set))
2220 // No accessors registered (e.g. explicit implementation)
2221 if (get == null && set == null)
2225 imported = importer.CreateProperty (p, declaringType, get, set);
2226 } catch (Exception ex) {
2227 throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2228 p.Name, declaringType.GetSignatureForError ());
2231 if (imported == null)
2235 case MemberTypes.Event:
2236 if (possible_accessors == null)
2239 var e = (EventInfo) member;
2241 // Links accessors with event
2243 MethodSpec add, remove;
2244 m = e.GetAddMethod (true);
2245 if (m == null || !possible_accessors.TryGetValue (m, out add))
2248 m = e.GetRemoveMethod (true);
2249 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2252 // Both accessors are required
2253 if (add == null || remove == null)
2256 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2257 if (!importer.IgnorePrivateMembers) {
2258 if (imported_events == null)
2259 imported_events = new List<EventSpec> ();
2261 imported_events.Add (event_spec);
2264 imported = event_spec;
2266 case MemberTypes.Field:
2267 var fi = (FieldInfo) member;
2269 imported = importer.CreateField (fi, declaringType);
2270 if (imported == null)
2274 // For dynamic binder event has to be fully restored to allow operations
2275 // within the type container to work correctly
2277 if (imported_events != null) {
2278 // The backing event field should be private but it may not
2280 for (i = 0; i < imported_events.Count; ++i) {
2281 var ev = imported_events[i];
2282 if (ev.Name == fi.Name) {
2283 ev.BackingField = (FieldSpec) imported;
2284 imported_events.RemoveAt (i);
2295 case MemberTypes.NestedType:
2296 // Already in the cache from the first pass
2299 throw new NotImplementedException (member.ToString ());
2302 if (imported.IsStatic && declaringType.IsInterface)
2305 cache.AddMemberImported (imported);
2311 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2313 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2314 : base (type, importer)
2320 public IAssemblyDefinition DeclaringAssembly {
2322 throw new NotImplementedException ();
2326 bool ITypeDefinition.IsComImport {
2332 bool ITypeDefinition.IsPartial {
2338 bool ITypeDefinition.IsTypeForwarder {
2344 bool ITypeDefinition.IsCyclicTypeForwarder {
2350 public string Namespace {
2356 public int TypeParametersCount {
2362 public TypeParameterSpec[] TypeParameters {
2370 public TypeSpec GetAttributeCoClass ()
2375 public string GetAttributeDefaultMember ()
2377 throw new NotSupportedException ();
2380 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2382 throw new NotSupportedException ();
2385 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2387 throw new NotImplementedException ();
2390 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2392 throw new NotImplementedException ();