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;
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
29 public abstract class MetadataImporter
32 // Dynamic types reader with additional logic to reconstruct a dynamic
33 // type using DynamicAttribute values
35 protected struct DynamicTypeReader
37 static readonly bool[] single_attribute = { true };
42 // There is no common type for CustomAttributeData and we cannot
43 // use ICustomAttributeProvider
47 // A member provider which can be used to get CustomAttributeData
49 public DynamicTypeReader (object provider)
53 this.provider = provider;
57 // Returns true when object at local position has dynamic attribute flag
59 public bool IsDynamicObject ()
64 return flags != null && Position < flags.Length && flags[Position];
68 // Returns true when DynamicAttribute exists
70 public bool HasDynamicAttribute ()
78 IList<CustomAttributeData> GetCustomAttributes ()
80 var mi = provider as MemberInfo;
82 return CustomAttributeData.GetCustomAttributes (mi);
84 var pi = provider as ParameterInfo;
86 return CustomAttributeData.GetCustomAttributes (pi);
94 var cad = GetCustomAttributes ();
100 foreach (var ca in cad) {
101 var dt = ca.Constructor.DeclaringType;
102 if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace)
105 if (ca.ConstructorArguments.Count == 0) {
106 flags = single_attribute;
110 var arg_type = ca.ConstructorArguments[0].ArgumentType;
112 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
113 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
114 flags = new bool[carg.Count];
115 for (int i = 0; i < flags.Length; ++i) {
116 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
117 flags[i] = (bool) carg[i].Value;
129 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
130 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
131 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
132 protected readonly ModuleContainer module;
134 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
136 protected MetadataImporter (ModuleContainer module)
138 this.module = module;
140 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
141 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
142 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
143 IgnorePrivateMembers = true;
148 public ICollection<IAssemblyDefinition> Assemblies {
150 return assembly_2_definition.Values;
154 public bool IgnorePrivateMembers { get; set; }
158 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
159 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
160 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
162 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
165 var fa = fi.Attributes;
166 switch (fa & FieldAttributes.FieldAccessMask) {
167 case FieldAttributes.Public:
168 mod = Modifiers.PUBLIC;
170 case FieldAttributes.Assembly:
171 mod = Modifiers.INTERNAL;
173 case FieldAttributes.Family:
174 mod = Modifiers.PROTECTED;
176 case FieldAttributes.FamORAssem:
177 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
180 // Ignore private fields (even for error reporting) to not require extra dependencies
181 if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
182 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
185 mod = Modifiers.PRIVATE;
192 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
195 // Private field has private type which is not fixed buffer
197 if (field_type == null)
199 } catch (Exception e) {
200 // TODO: I should construct fake TypeSpec based on TypeRef signature
201 // but there is no way to do it with System.Reflection
202 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
203 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
206 var definition = new ImportedMemberDefinition (fi, field_type, this);
208 if ((fa & FieldAttributes.Literal) != 0) {
209 Constant c = field_type.Kind == MemberKind.MissingType ?
210 new NullConstant (InternalType.ErrorType, Location.Null) :
211 CreateConstantFromValue (field_type, fi);
212 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
215 if ((fa & FieldAttributes.InitOnly) != 0) {
216 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
217 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
219 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
222 mod |= Modifiers.READONLY;
224 var req_mod = fi.GetRequiredCustomModifiers ();
225 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
226 mod |= Modifiers.VOLATILE;
229 if ((fa & FieldAttributes.Static) != 0) {
230 mod |= Modifiers.STATIC;
232 // Fixed buffers cannot be static
233 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
234 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
236 // TODO: Sanity check on field_type (only few types are allowed)
237 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
238 return new FixedFieldSpec (module, declaringType, definition, fi, element_field, mod);
242 return new FieldSpec (declaringType, definition, field_type, fi, mod);
245 Constant CreateConstantFromValue (TypeSpec fieldType, FieldInfo fi)
247 var value = fi.GetRawConstantValue ();
249 // Metadata value can be encoded using different constant value type
250 // than is actual field type
252 // e.g. unsigned int16 CONSTANT = int16 (0x0000ffff)
254 if (value != null && !fieldType.IsEnum) {
255 var c = ImportConstant (value);
257 return fieldType == c.Type ? c : c.ConvertExplicitly (false, fieldType);
261 return Constant.CreateConstantFromValue (fieldType, value, Location.Null);
264 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
266 add.IsAccessor = true;
267 remove.IsAccessor = true;
269 if (add.Modifiers != remove.Modifiers)
270 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
272 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
273 var definition = new ImportedMemberDefinition (ei, event_type, this);
274 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
277 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
279 var tparams = type.GetGenericArguments ();
281 int parent_owned_count;
283 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
286 // System.Reflection duplicates parent type parameters for each
287 // nested type with slightly modified properties (eg. different owner)
288 // This just makes things more complicated (think of cloned constraints)
289 // therefore we remap any nested type owned by parent using `type_cache'
290 // to the single TypeParameterSpec
292 if (declaringType != null && parent_owned_count > 0) {
294 while (read_count != parent_owned_count) {
295 var tparams_count = declaringType.Arity;
296 if (tparams_count != 0) {
297 var parent_tp = declaringType.MemberDefinition.TypeParameters;
298 read_count += tparams_count;
299 for (int i = 0; i < tparams_count; i++) {
300 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
304 declaringType = declaringType.DeclaringType;
308 parent_owned_count = 0;
311 if (tparams.Length - parent_owned_count == 0)
314 return CreateGenericParameters (parent_owned_count, tparams);
317 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
319 var tspec = new TypeParameterSpec[tparams.Length - first];
320 for (int pos = first; pos < tparams.Length; ++pos) {
321 var type = tparams[pos];
322 int index = pos - first;
324 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
330 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
334 var tspec = new TypeSpec [tparams.Length - first];
335 for (int pos = first; pos < tparams.Length; ++pos) {
336 var type = tparams[pos];
337 int index = pos - first;
340 if (type.HasElementType) {
341 var element = type.GetElementType ();
343 spec = ImportType (element, dtype);
346 throw new NotImplementedException ("Unknown element type " + type.ToString ());
349 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
351 spec = CreateType (type, dtype, true);
354 // We treat nested generic types as inflated internally where
355 // reflection uses type definition
358 // IFoo<A<T>> foo; // A<T> is definition in this case
361 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
362 var start_pos = spec.DeclaringType == null ? 0 : spec.DeclaringType.MemberDefinition.TypeParametersCount;
363 var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype);
364 spec = spec.MakeGenericType (module, targs);
378 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
380 Modifiers mod = ReadMethodModifiers (mb, declaringType);
381 TypeParameterSpec[] tparams;
383 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
385 if (mb.IsGenericMethod) {
386 if (!mb.IsGenericMethodDefinition)
387 throw new NotSupportedException ("assert");
389 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
396 if (mb.MemberType == MemberTypes.Constructor) {
397 kind = MemberKind.Constructor;
398 returnType = module.Compiler.BuiltinTypes.Void;
401 // Detect operators and destructors
403 string name = mb.Name;
404 kind = MemberKind.Method;
405 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
406 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
407 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o' && (mb.Attributes & MethodAttributes.SpecialName) != 0) {
408 var op_type = Operator.GetType (name);
409 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
410 kind = MemberKind.Operator;
413 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
414 kind = MemberKind.Destructor;
415 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
416 mod &= ~Modifiers.OVERRIDE;
417 mod |= Modifiers.VIRTUAL;
422 var mi = (MethodInfo) mb;
423 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
425 // Cannot set to OVERRIDE without full hierarchy checks
426 // this flag indicates that the method could be override
427 // but further validation is needed
428 if ((mod & Modifiers.OVERRIDE) != 0) {
429 bool is_real_override = false;
430 if (kind == MemberKind.Method && declaringType.BaseType != null) {
431 var btype = declaringType.BaseType;
432 if (IsOverrideMethodBaseTypeAccessible (btype)) {
433 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
434 var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
437 // For imported class method do additional validation to be sure that metadata
438 // override flag was correct
440 // Difference between protected internal and protected is ok
442 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
443 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
444 is_real_override = true;
449 if (!is_real_override) {
450 mod &= ~Modifiers.OVERRIDE;
451 if ((mod & Modifiers.SEALED) != 0)
452 mod &= ~Modifiers.SEALED;
454 mod |= Modifiers.VIRTUAL;
456 } else if (parameters.HasExtensionMethodType) {
457 mod |= Modifiers.METHOD_EXTENSION;
461 IMethodDefinition definition;
462 if (tparams != null) {
463 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
464 foreach (var tp in gmd.TypeParameters) {
465 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
470 definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
473 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
480 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
482 switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
483 case Modifiers.PUBLIC:
485 case Modifiers.INTERNAL:
487 // Check whether imported method in base type is accessible from compiled
490 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
491 case Modifiers.PRIVATE:
495 // protected internal
497 // Method accessibility checks will be done later based on context
498 // where the method is called (CS0122 error will be reported for inaccessible)
505 // Imports System.Reflection parameters
507 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
509 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
511 if (pi.Length == 0 && varargs == 0)
512 return ParametersCompiled.EmptyReadOnlyParameters;
514 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
515 IParameterData[] par = new IParameterData[pi.Length + varargs];
516 bool is_params = false;
517 for (int i = 0; i < pi.Length; i++) {
518 ParameterInfo p = pi[i];
519 Parameter.Modifier mod = 0;
520 Expression default_value = null;
521 if (p.ParameterType.IsByRef) {
522 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
523 mod = Parameter.Modifier.OUT;
525 mod = Parameter.Modifier.REF;
528 // Strip reference wrapping
530 var el = p.ParameterType.GetElementType ();
531 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
532 } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
533 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
534 mod = Parameter.Modifier.This;
535 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
537 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
539 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
540 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
541 mod = Parameter.Modifier.PARAMS;
546 if (!is_params && p.IsOptional) {
547 object value = p.RawDefaultValue;
548 var ptype = types[i];
549 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
551 default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
553 default_value = ImportConstant (value);
556 default_value = new EnumConstant ((Constant) default_value, ptype);
560 var attrs = CustomAttributeData.GetCustomAttributes (p);
561 for (int ii = 0; ii < attrs.Count; ++ii) {
562 var attr = attrs[ii];
563 var dt = attr.Constructor.DeclaringType;
564 if (dt.Namespace != CompilerServicesNamespace)
567 if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
568 mod |= Parameter.Modifier.CallerLineNumber;
569 else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
570 mod |= Parameter.Modifier.CallerFilePath;
571 else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
572 mod |= Parameter.Modifier.CallerMemberName;
574 } else if (value == Missing.Value) {
575 default_value = EmptyExpression.MissingValue;
576 } else if (value == null) {
577 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
578 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
579 default_value = ImportConstant (value);
584 par[i] = new ParameterData (p.Name, mod, default_value);
588 par[par.Length - 1] = new ArglistParameter (Location.Null);
589 types[types.Length - 1] = InternalType.Arglist;
592 return method != null ?
593 new ParametersImported (par, types, varargs != 0, is_params) :
594 new ParametersImported (par, types, is_params);
598 // Returns null when the property is not valid C# property
600 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
603 AParametersCollection param = null;
604 TypeSpec type = null;
607 param = get.Parameters;
608 type = get.ReturnType;
611 bool is_valid_property = true;
613 if (set.ReturnType.Kind != MemberKind.Void)
614 is_valid_property = false;
616 var set_param_count = set.Parameters.Count - 1;
618 if (set_param_count < 0) {
620 is_valid_property = false;
623 var set_type = set.Parameters.Types[set_param_count];
626 AParametersCollection set_based_param;
628 if (set_param_count == 0) {
629 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
632 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
634 var data = new IParameterData[set_param_count];
635 var types = new TypeSpec[set_param_count];
636 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
637 Array.Copy (set.Parameters.Types, types, set_param_count);
638 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
642 param = set_based_param;
645 if (set_param_count != get.Parameters.Count)
646 is_valid_property = false;
648 if (get.ReturnType != set_type)
649 is_valid_property = false;
651 // Possible custom accessor modifiers
652 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
653 var get_acc = mod & Modifiers.AccessibilityMask;
654 if (get_acc != Modifiers.PUBLIC) {
655 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
656 // If the accessor modifiers are not same, do extra restriction checks
657 if (get_acc != set_acc) {
658 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
659 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
660 if (get_restr && set_restr) {
661 is_valid_property = false; // Neither is more restrictive
665 mod &= ~Modifiers.AccessibilityMask;
674 PropertySpec spec = null;
675 if (!param.IsEmpty) {
676 if (is_valid_property) {
677 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
678 if (index_name == null) {
679 is_valid_property = false;
683 is_valid_property = false;
684 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
685 is_valid_property = false;
689 is_valid_property = false;
690 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
691 is_valid_property = false;
695 if (is_valid_property) {
696 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
697 } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
699 // Enables support for properties with parameters (must have default value) of COM-imported types
701 is_valid_property = true;
703 for (int i = 0; i < param.FixedParameters.Length; ++i) {
704 if (!param.FixedParameters[i].HasDefaultValue) {
705 is_valid_property = false;
714 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
716 if (!is_valid_property) {
717 spec.IsNotCSharpCompatible = true;
729 public TypeSpec CreateType (MetaType type)
731 return CreateType (type, new DynamicTypeReader (), true);
734 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
736 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
739 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
741 TypeSpec declaring_type;
742 if (type.IsNested && !type.IsGenericParameter)
743 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
745 declaring_type = null;
747 return CreateType (type, declaring_type, dtype, canImportBaseType);
750 protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
753 if (import_cache.TryGetValue (type, out spec)) {
754 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
755 if (dtype.IsDynamicObject ())
756 return module.Compiler.BuiltinTypes.Dynamic;
761 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
764 if (!dtype.HasDynamicAttribute ())
767 // We've found same object in the cache but this one has a dynamic custom attribute
768 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
769 // Do type resolve process again in that case
771 // TODO: Handle cases where they still unify
774 if (IsMissingType (type)) {
775 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
776 spec.MemberCache = MemberCache.Empty;
777 import_cache.Add (type, spec);
781 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
782 var type_def = type.GetGenericTypeDefinition ();
784 // Generic type definition can also be forwarded
785 if (compiled_types.TryGetValue (type_def, out spec))
788 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
791 if (declaringType == null) {
792 // Simple case, no nesting
793 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
794 spec = spec.MakeGenericType (module, targs);
797 // Nested type case, converting .NET types like
798 // A`1.B`1.C`1<int, long, string> to typespec like
799 // A<int>.B<long>.C<string>
801 var nested_hierarchy = new List<TypeSpec> ();
802 while (declaringType.IsNested) {
803 nested_hierarchy.Add (declaringType);
804 declaringType = declaringType.DeclaringType;
808 if (declaringType.Arity > 0) {
809 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
810 targs_pos = spec.Arity;
812 spec = declaringType;
815 for (int i = nested_hierarchy.Count; i != 0; --i) {
816 var t = nested_hierarchy [i - 1];
817 if (t.Kind == MemberKind.MissingType)
820 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
823 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
824 targs_pos += t.Arity;
828 if (spec.Kind == MemberKind.MissingType) {
829 spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC);
830 spec.MemberCache = MemberCache.Empty;
832 if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
835 string name = type.Name;
836 int index = name.IndexOf ('`');
838 name = name.Substring (0, index);
840 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
842 if (spec.Arity > 0) {
843 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
848 // Don't add generic type with dynamic arguments, they can interfere with same type
849 // using object type arguments
850 if (!spec.HasDynamicElement) {
852 // Add to reading cache to speed up reading
853 if (!import_cache.ContainsKey (type))
854 import_cache.Add (type, spec);
863 var ma = type.Attributes;
864 switch (ma & TypeAttributes.VisibilityMask) {
865 case TypeAttributes.Public:
866 case TypeAttributes.NestedPublic:
867 mod = Modifiers.PUBLIC;
869 case TypeAttributes.NestedPrivate:
870 mod = Modifiers.PRIVATE;
872 case TypeAttributes.NestedFamily:
873 mod = Modifiers.PROTECTED;
875 case TypeAttributes.NestedFamORAssem:
876 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
879 mod = Modifiers.INTERNAL;
883 if ((ma & TypeAttributes.Interface) != 0) {
884 kind = MemberKind.Interface;
885 } else if (type.IsGenericParameter) {
886 kind = MemberKind.TypeParameter;
888 var base_type = type.BaseType;
889 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
890 kind = MemberKind.Class;
892 kind = DetermineKindFromBaseType (base_type);
893 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
894 mod |= Modifiers.SEALED;
898 if (kind == MemberKind.Class) {
899 if ((ma & TypeAttributes.Sealed) != 0) {
900 if ((ma & TypeAttributes.Abstract) != 0)
901 mod |= Modifiers.STATIC;
903 mod |= Modifiers.SEALED;
904 } else if ((ma & TypeAttributes.Abstract) != 0) {
905 mod |= Modifiers.ABSTRACT;
910 var definition = new ImportedTypeDefinition (type, this);
913 if (kind == MemberKind.Enum) {
914 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
915 BindingFlags.Instance |
916 BindingFlags.Public | BindingFlags.NonPublic;
918 var type_members = type.GetFields (underlying_member);
919 foreach (var type_member in type_members) {
920 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
925 kind = MemberKind.Class;
927 } else if (kind == MemberKind.TypeParameter) {
928 spec = CreateTypeParameter (type, declaringType);
929 } else if (type.IsGenericTypeDefinition) {
930 definition.TypeParameters = CreateGenericParameters (type, declaringType);
931 } else if (compiled_types.TryGetValue (type, out pt)) {
933 // Same type was found in inside compiled types. It's
934 // either build-in type or forward referenced typed
935 // which point into just compiled assembly.
938 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
940 bts.SetDefinition (definition, type, mod);
944 spec = new TypeSpec (kind, declaringType, definition, type, mod);
946 import_cache.Add (type, spec);
948 if (kind == MemberKind.TypeParameter) {
949 if (canImportBaseType)
950 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
956 // Two stage setup as the base type can be inflated declaring type or
957 // another nested type inside same declaring type which has not been
958 // loaded, therefore we can import a base type of nested types once
959 // the types have been imported
961 if (canImportBaseType)
962 ImportTypeBase (spec, type);
967 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
969 IAssemblyDefinition found;
970 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
972 // This can happen in dynamic context only
973 var def = new ImportedAssemblyDefinition (assembly);
974 assembly_2_definition.Add (assembly, def);
975 def.ReadAttributes ();
982 public void ImportTypeBase (MetaType type)
984 TypeSpec spec = import_cache[type];
986 ImportTypeBase (spec, type);
989 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
992 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
993 case GenericParameterAttributes.Covariant:
994 variance = Variance.Covariant;
996 case GenericParameterAttributes.Contravariant:
997 variance = Variance.Contravariant;
1000 variance = Variance.None;
1004 SpecialConstraint special = SpecialConstraint.None;
1005 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
1007 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
1008 special |= SpecialConstraint.Struct;
1009 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
1010 special = SpecialConstraint.Constructor;
1013 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
1014 special |= SpecialConstraint.Class;
1017 TypeParameterSpec spec;
1018 var def = new ImportedTypeParameterDefinition (type, this);
1019 if (type.DeclaringMethod != null) {
1020 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
1022 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
1029 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
1030 // they can be assembly specific therefore we do check based on names only
1032 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
1034 if (attributesData.Count == 0)
1037 foreach (var attr in attributesData) {
1038 var dt = attr.Constructor.DeclaringType;
1039 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1046 void ImportTypeBase (TypeSpec spec, MetaType type)
1048 if (spec.Kind == MemberKind.Interface)
1049 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1050 else if (type.BaseType != null) {
1052 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1053 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1055 base_type = CreateType (type.BaseType);
1057 spec.BaseType = base_type;
1060 if (spec.MemberDefinition.TypeParametersCount > 0) {
1061 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1062 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1067 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1069 Namespace ns = targetNamespace;
1070 string prev_namespace = null;
1071 foreach (var t in types) {
1075 // Be careful not to trigger full parent type loading
1076 if (t.MemberType == MemberTypes.NestedType)
1079 if (t.Name[0] == '<')
1082 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1086 if (prev_namespace != t.Namespace) {
1087 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1088 prev_namespace = t.Namespace;
1091 // Cannot rely on assembly level Extension attribute or static modifier because they
1092 // are not followed by other compilers (e.g. F#).
1093 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1094 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1095 it.SetExtensionMethodContainer ();
1098 ns.AddType (module, it);
1102 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1104 var constraints = type.GetGenericParameterConstraints ();
1105 List<TypeSpec> tparams = null;
1106 foreach (var ct in constraints) {
1107 if (ct.IsGenericParameter) {
1108 if (tparams == null)
1109 tparams = new List<TypeSpec> ();
1111 tparams.Add (CreateType (ct));
1115 var constraint_type = CreateType (ct);
1116 if (constraint_type.IsClass) {
1117 spec.BaseType = constraint_type;
1121 spec.AddInterface (constraint_type);
1124 if (spec.BaseType == null)
1125 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1127 if (tparams != null)
1128 spec.TypeArguments = tparams.ToArray ();
1131 Constant ImportConstant (object value)
1134 // Get type of underlying value as int constant can be used for object
1135 // parameter type. This is not allowed in C# but other languages can do that
1137 var types = module.Compiler.BuiltinTypes;
1138 switch (System.Type.GetTypeCode (value.GetType ())) {
1139 case TypeCode.Boolean:
1140 return new BoolConstant (types, (bool) value, Location.Null);
1142 return new ByteConstant (types, (byte) value, Location.Null);
1144 return new CharConstant (types, (char) value, Location.Null);
1145 case TypeCode.Decimal:
1146 return new DecimalConstant (types, (decimal) value, Location.Null);
1147 case TypeCode.Double:
1148 return new DoubleConstant (types, (double) value, Location.Null);
1149 case TypeCode.Int16:
1150 return new ShortConstant (types, (short) value, Location.Null);
1151 case TypeCode.Int32:
1152 return new IntConstant (types, (int) value, Location.Null);
1153 case TypeCode.Int64:
1154 return new LongConstant (types, (long) value, Location.Null);
1155 case TypeCode.SByte:
1156 return new SByteConstant (types, (sbyte) value, Location.Null);
1157 case TypeCode.Single:
1158 return new FloatConstant (types, (float) value, Location.Null);
1159 case TypeCode.String:
1160 return new StringConstant (types, (string) value, Location.Null);
1161 case TypeCode.UInt16:
1162 return new UShortConstant (types, (ushort) value, Location.Null);
1163 case TypeCode.UInt32:
1164 return new UIntConstant (types, (uint) value, Location.Null);
1165 case TypeCode.UInt64:
1166 return new ULongConstant (types, (ulong) value, Location.Null);
1169 throw new NotImplementedException (value.GetType ().ToString ());
1172 public TypeSpec ImportType (MetaType type)
1174 return ImportType (type, new DynamicTypeReader (type));
1177 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1179 if (type.HasElementType) {
1180 var element = type.GetElementType ();
1182 var spec = ImportType (element, dtype);
1185 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1187 return ReferenceContainer.MakeType (module, spec);
1189 return PointerContainer.MakeType (module, spec);
1191 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1194 TypeSpec compiled_type;
1195 if (compiled_types.TryGetValue (type, out compiled_type)) {
1196 if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
1197 return module.Compiler.BuiltinTypes.Dynamic;
1199 return compiled_type;
1202 return CreateType (type, dtype, true);
1205 static bool IsMissingType (MetaType type)
1208 return type.__IsMissing;
1215 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1216 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1217 // DecimalConstantAttribute metadata.
1219 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1221 if (attrs.Count == 0)
1224 foreach (var ca in attrs) {
1225 var dt = ca.Constructor.DeclaringType;
1226 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1229 var value = new decimal (
1230 (int) (uint) ca.ConstructorArguments[4].Value,
1231 (int) (uint) ca.ConstructorArguments[3].Value,
1232 (int) (uint) ca.ConstructorArguments[2].Value,
1233 (byte) ca.ConstructorArguments[1].Value != 0,
1234 (byte) ca.ConstructorArguments[0].Value);
1236 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1242 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1245 var ma = mb.Attributes;
1246 switch (ma & MethodAttributes.MemberAccessMask) {
1247 case MethodAttributes.Public:
1248 mod = Modifiers.PUBLIC;
1250 case MethodAttributes.Assembly:
1251 mod = Modifiers.INTERNAL;
1253 case MethodAttributes.Family:
1254 mod = Modifiers.PROTECTED;
1256 case MethodAttributes.FamORAssem:
1257 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1260 mod = Modifiers.PRIVATE;
1264 if ((ma & MethodAttributes.Static) != 0) {
1265 mod |= Modifiers.STATIC;
1268 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1269 mod |= Modifiers.ABSTRACT;
1273 // It can be sealed and override
1274 if ((ma & MethodAttributes.Final) != 0)
1275 mod |= Modifiers.SEALED;
1277 if ((ma & MethodAttributes.Virtual) != 0) {
1278 // Not every member can be detected based on MethodAttribute, we
1279 // set virtual or non-virtual only when we are certain. Further checks
1280 // to really find out what `virtual' means for this member are done
1282 if ((ma & MethodAttributes.NewSlot) != 0) {
1283 if ((mod & Modifiers.SEALED) != 0) {
1284 mod &= ~Modifiers.SEALED;
1286 mod |= Modifiers.VIRTUAL;
1289 mod |= Modifiers.OVERRIDE;
1297 abstract class ImportedDefinition : IMemberDefinition
1299 protected class AttributesBag
1301 public static readonly AttributesBag Default = new AttributesBag ();
1303 public AttributeUsageAttribute AttributeUsage;
1304 public ObsoleteAttribute Obsolete;
1305 public string[] Conditionals;
1306 public string DefaultIndexerName;
1307 public bool? CLSAttributeValue;
1308 public TypeSpec CoClass;
1310 static bool HasMissingType (ConstructorInfo ctor)
1314 // Mimic odd csc behaviour where missing type on predefined
1315 // attributes means the attribute is silently ignored. This can
1316 // happen with PCL facades
1318 foreach (var p in ctor.GetParameters ()) {
1319 if (p.ParameterType.__ContainsMissingType)
1327 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1329 AttributesBag bag = null;
1330 List<string> conditionals = null;
1332 // It should not throw any loading exception
1333 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1335 foreach (var a in attrs) {
1336 var dt = a.Constructor.DeclaringType;
1337 string name = dt.Name;
1338 if (name == "ObsoleteAttribute") {
1339 if (dt.Namespace != "System")
1343 bag = new AttributesBag ();
1345 var args = a.ConstructorArguments;
1347 if (args.Count == 1) {
1348 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1349 } else if (args.Count == 2) {
1350 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1352 bag.Obsolete = new ObsoleteAttribute ();
1358 if (name == "ConditionalAttribute") {
1359 if (dt.Namespace != "System.Diagnostics")
1363 bag = new AttributesBag ();
1365 if (conditionals == null)
1366 conditionals = new List<string> (2);
1368 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1372 if (name == "CLSCompliantAttribute") {
1373 if (dt.Namespace != "System")
1377 bag = new AttributesBag ();
1379 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1383 // Type only attributes
1384 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1385 if (name == "DefaultMemberAttribute") {
1386 if (dt.Namespace != "System.Reflection")
1390 bag = new AttributesBag ();
1392 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1396 if (name == "AttributeUsageAttribute") {
1397 if (dt.Namespace != "System")
1400 if (HasMissingType (a.Constructor))
1404 bag = new AttributesBag ();
1406 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1407 foreach (var named in a.NamedArguments) {
1408 if (named.MemberInfo.Name == "AllowMultiple")
1409 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1410 else if (named.MemberInfo.Name == "Inherited")
1411 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1416 // Interface only attribute
1417 if (name == "CoClassAttribute") {
1418 if (dt.Namespace != "System.Runtime.InteropServices")
1421 if (HasMissingType (a.Constructor))
1425 bag = new AttributesBag ();
1427 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1436 if (conditionals != null)
1437 bag.Conditionals = conditionals.ToArray ();
1443 protected readonly MemberInfo provider;
1444 protected AttributesBag cattrs;
1445 protected readonly MetadataImporter importer;
1447 protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1449 this.provider = provider;
1450 this.importer = importer;
1455 public bool IsImported {
1461 public virtual string Name {
1463 return provider.Name;
1469 public string[] ConditionalConditions ()
1474 return cattrs.Conditionals;
1477 public ObsoleteAttribute GetAttributeObsolete ()
1482 return cattrs.Obsolete;
1485 public bool? CLSAttributeValue {
1490 return cattrs.CLSAttributeValue;
1494 protected void ReadAttributes ()
1496 cattrs = AttributesBag.Read (provider, importer);
1499 public void SetIsAssigned ()
1501 // Unused for imported members
1504 public void SetIsUsed ()
1506 // Unused for imported members
1510 public class ImportedModuleDefinition
1512 readonly Module module;
1515 public ImportedModuleDefinition (Module module)
1517 this.module = module;
1522 public bool IsCLSCompliant {
1524 return cls_compliant;
1528 public string Name {
1536 public void ReadAttributes ()
1538 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1540 foreach (var a in attrs) {
1541 var dt = a.Constructor.DeclaringType;
1542 if (dt.Name == "CLSCompliantAttribute") {
1543 if (dt.Namespace != "System")
1546 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1553 // Reads assembly attributes which where attached to a special type because
1554 // module does have assembly manifest
1556 public List<Attribute> ReadAssemblyAttributes ()
1558 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1562 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1566 // TODO: implement, the idea is to fabricate specil Attribute class and
1567 // add it to OptAttributes before resolving the source code attributes
1568 // Need to build module location as well for correct error reporting
1570 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1571 //var attrs = new List<Attribute> (assembly_attributes.Count);
1572 //foreach (var a in assembly_attributes)
1574 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1575 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1577 // foreach (var carg in a.ConstructorArguments) {
1581 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1588 public class ImportedAssemblyDefinition : IAssemblyDefinition
1590 readonly Assembly assembly;
1591 readonly AssemblyName aname;
1594 List<AssemblyName> internals_visible_to;
1595 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1597 public ImportedAssemblyDefinition (Assembly assembly)
1599 this.assembly = assembly;
1600 this.aname = assembly.GetName ();
1605 public Assembly Assembly {
1611 public string FullName {
1613 return aname.FullName;
1617 public bool HasStrongName {
1619 return aname.GetPublicKey ().Length != 0;
1623 public bool IsMissing {
1626 return assembly.__IsMissing;
1633 public bool IsCLSCompliant {
1635 return cls_compliant;
1639 public string Location {
1641 return assembly.Location;
1645 public string Name {
1653 public byte[] GetPublicKeyToken ()
1655 return aname.GetPublicKeyToken ();
1658 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1660 return internals_visible_to_cache [assembly];
1663 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1665 if (internals_visible_to == null)
1668 AssemblyName is_visible = null;
1669 if (internals_visible_to_cache == null) {
1670 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1672 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1673 return is_visible != null;
1676 var token = assembly.GetPublicKeyToken ();
1677 if (token != null && token.Length == 0)
1680 foreach (var internals in internals_visible_to) {
1681 if (internals.Name != assembly.Name)
1684 if (token == null && assembly is AssemblyDefinition) {
1685 is_visible = internals;
1689 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1692 is_visible = internals;
1696 internals_visible_to_cache.Add (assembly, is_visible);
1697 return is_visible != null;
1700 public void ReadAttributes ()
1703 if (assembly.__IsMissing)
1707 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1709 foreach (var a in attrs) {
1710 var dt = a.Constructor.DeclaringType;
1712 if (name == "CLSCompliantAttribute") {
1713 if (dt.Namespace == "System") {
1714 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1719 if (name == "InternalsVisibleToAttribute") {
1720 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1723 string s = a.ConstructorArguments[0].Value as string;
1727 var an = new AssemblyName (s);
1728 if (internals_visible_to == null)
1729 internals_visible_to = new List<AssemblyName> ();
1731 internals_visible_to.Add (an);
1737 public override string ToString ()
1743 class ImportedMemberDefinition : ImportedDefinition
1745 readonly TypeSpec type;
1747 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1748 : base (member, importer)
1755 public TypeSpec MemberType {
1764 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1766 readonly AParametersCollection parameters;
1768 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1769 : base (provider, type, importer)
1771 this.parameters = parameters;
1774 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1775 : base (provider, type, importer)
1777 this.parameters = parameters;
1782 public AParametersCollection Parameters {
1791 class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1793 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1794 : base (provider, type, parameters, importer)
1798 MethodBase IMethodDefinition.Metadata {
1800 return (MethodBase) provider;
1805 class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1807 readonly TypeParameterSpec[] tparams;
1809 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1810 : base (provider, type, parameters, importer)
1812 this.tparams = tparams;
1817 public TypeParameterSpec[] TypeParameters {
1823 public int TypeParametersCount {
1825 return tparams.Length;
1832 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1834 TypeParameterSpec[] tparams;
1837 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1838 : base (type, importer)
1844 public IAssemblyDefinition DeclaringAssembly {
1846 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1850 bool ITypeDefinition.IsComImport {
1852 return ((MetaType) provider).IsImport;
1857 bool ITypeDefinition.IsPartial {
1863 bool ITypeDefinition.IsTypeForwarder {
1866 return ((MetaType) provider).__IsTypeForwarder;
1873 bool ITypeDefinition.IsCyclicTypeForwarder {
1876 return ((MetaType) provider).__IsCyclicTypeForwarder;
1883 public override string Name {
1887 if (tparams != null) {
1888 int arity_start = name.IndexOf ('`');
1889 if (arity_start > 0)
1890 name = name.Substring (0, arity_start);
1898 public string Namespace {
1900 return ((MetaType) provider).Namespace;
1904 public int TypeParametersCount {
1906 return tparams == null ? 0 : tparams.Length;
1910 public TypeParameterSpec[] TypeParameters {
1921 public void DefineInterfaces (TypeSpec spec)
1923 var type = (MetaType) provider;
1926 ifaces = type.__GetDeclaredInterfaces ();
1927 if (ifaces.Length != 0) {
1928 foreach (var iface in ifaces) {
1929 var it = importer.CreateType (iface);
1933 spec.AddInterfaceDefined (it);
1935 // Unfortunately not all languages expand inherited interfaces
1936 var bifaces = it.Interfaces;
1937 if (bifaces != null) {
1938 foreach (var biface in bifaces) {
1939 spec.AddInterfaceDefined (biface);
1946 // It's impossible to get declared interfaces only using System.Reflection
1947 // hence we need to mimic the behavior with ikvm-reflection too to keep
1948 // our type look-up logic same
1950 if (spec.BaseType != null) {
1951 var bifaces = spec.BaseType.Interfaces;
1952 if (bifaces != null) {
1954 // Before adding base class interfaces close defined interfaces
1955 // on type parameter
1957 var tp = spec as TypeParameterSpec;
1958 if (tp != null && tp.InterfacesDefined == null) {
1959 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1962 foreach (var iface in bifaces)
1963 spec.AddInterfaceDefined (iface);
1967 ifaces = type.GetInterfaces ();
1969 if (ifaces.Length > 0) {
1970 foreach (var iface in ifaces) {
1971 spec.AddInterface (importer.CreateType (iface));
1978 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
1981 // Report details about missing type and most likely cause of the problem.
1982 // csc used to reports 1683, 1684 (now 7069) as warnings but we report them only when used
1983 // or referenced from the user core in which case compilation error has to
1984 // be reported because compiler cannot continue anyway
1987 var report = ctx.Module.Compiler.Report;
1989 for (int i = 0; i < missing.Count; ++i) {
1990 var t = missing [i].Type;
1993 // Report missing types only once
1995 if (report.Printer.MissingTypeReported (t.MemberDefinition))
1998 string name = t.GetSignatureForError ();
2000 var caller = missing[i].Caller;
2001 if (caller.Kind != MemberKind.MissingType)
2002 report.SymbolRelatedToPreviousError (caller);
2004 var definition = t.MemberDefinition;
2005 if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
2006 report.Error (1683, loc,
2007 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
2009 } else if (definition.DeclaringAssembly.IsMissing) {
2010 if (definition.IsTypeForwarder) {
2011 report.Error (1070, loc,
2012 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2013 name, definition.DeclaringAssembly.FullName);
2015 report.Error (12, loc,
2016 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2017 name, definition.DeclaringAssembly.FullName);
2019 } else if (definition.IsTypeForwarder) {
2020 report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
2021 name, definition.DeclaringAssembly.FullName);
2023 report.Error (7069, loc,
2024 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
2025 name, t.MemberDefinition.DeclaringAssembly.FullName);
2030 public TypeSpec GetAttributeCoClass ()
2035 return cattrs.CoClass;
2038 public string GetAttributeDefaultMember ()
2043 return cattrs.DefaultIndexerName;
2046 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2051 return cattrs.AttributeUsage;
2054 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2056 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
2057 return a == assembly || a.IsFriendAssemblyTo (assembly);
2060 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2063 // Not interested in members of nested private types unless the importer needs them
2065 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
2066 cache = MemberCache.Empty;
2070 var loading_type = (MetaType) provider;
2071 const BindingFlags all_members = BindingFlags.DeclaredOnly |
2072 BindingFlags.Static | BindingFlags.Instance |
2073 BindingFlags.Public | BindingFlags.NonPublic;
2075 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
2076 MethodAttributes.Virtual | MethodAttributes.HideBySig |
2077 MethodAttributes.Final;
2079 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
2080 List<EventSpec> imported_events = null;
2081 EventSpec event_spec;
2082 MemberSpec imported;
2086 all = loading_type.GetMembers (all_members);
2087 } catch (Exception e) {
2088 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2089 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2092 if (cache == null) {
2093 cache = new MemberCache (all.Length);
2096 // Do the types first as they can be referenced by the members before
2097 // they are found or inflated
2099 foreach (var member in all) {
2100 if (member.MemberType != MemberTypes.NestedType)
2103 var t = (MetaType) member;
2105 // Ignore compiler generated types, mostly lambda containers
2106 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2110 imported = importer.CreateNestedType (t, declaringType);
2111 } catch (Exception e) {
2112 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2113 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2116 cache.AddMemberImported (imported);
2119 foreach (var member in all) {
2120 if (member.MemberType != MemberTypes.NestedType)
2123 var t = (MetaType) member;
2125 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2128 importer.ImportTypeBase (t);
2133 // Load base interfaces first to minic behaviour of compiled members
2135 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2136 foreach (var iface in declaringType.Interfaces) {
2137 cache.AddInterface (iface);
2143 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2145 foreach (var member in all) {
2146 switch (member.MemberType) {
2147 case MemberTypes.Constructor:
2148 if (declaringType.IsInterface)
2151 goto case MemberTypes.Method;
2152 case MemberTypes.Method:
2153 MethodBase mb = (MethodBase) member;
2154 var attrs = mb.Attributes;
2156 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2157 if (importer.IgnorePrivateMembers)
2160 // Ignore explicitly implemented members
2161 if ((attrs & explicit_impl) == explicit_impl)
2164 // Ignore compiler generated methods
2165 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2169 imported = importer.CreateMethod (mb, declaringType);
2170 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2171 if (possible_accessors == null)
2172 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2174 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2175 possible_accessors.Add (mb, (MethodSpec) imported);
2179 case MemberTypes.Property:
2180 if (possible_accessors == null)
2183 var p = (PropertyInfo) member;
2185 // Links possible accessors with property
2187 MethodSpec get, set;
2188 m = p.GetGetMethod (true);
2189 if (m == null || !possible_accessors.TryGetValue (m, out get))
2192 m = p.GetSetMethod (true);
2193 if (m == null || !possible_accessors.TryGetValue (m, out set))
2196 // No accessors registered (e.g. explicit implementation)
2197 if (get == null && set == null)
2201 imported = importer.CreateProperty (p, declaringType, get, set);
2202 } catch (Exception ex) {
2203 throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2204 p.Name, declaringType.GetSignatureForError ());
2207 if (imported == null)
2211 case MemberTypes.Event:
2212 if (possible_accessors == null)
2215 var e = (EventInfo) member;
2217 // Links accessors with event
2219 MethodSpec add, remove;
2220 m = e.GetAddMethod (true);
2221 if (m == null || !possible_accessors.TryGetValue (m, out add))
2224 m = e.GetRemoveMethod (true);
2225 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2228 // Both accessors are required
2229 if (add == null || remove == null)
2232 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2233 if (!importer.IgnorePrivateMembers) {
2234 if (imported_events == null)
2235 imported_events = new List<EventSpec> ();
2237 imported_events.Add (event_spec);
2240 imported = event_spec;
2242 case MemberTypes.Field:
2243 var fi = (FieldInfo) member;
2245 imported = importer.CreateField (fi, declaringType);
2246 if (imported == null)
2250 // For dynamic binder event has to be fully restored to allow operations
2251 // within the type container to work correctly
2253 if (imported_events != null) {
2254 // The backing event field should be private but it may not
2256 for (i = 0; i < imported_events.Count; ++i) {
2257 var ev = imported_events[i];
2258 if (ev.Name == fi.Name) {
2259 ev.BackingField = (FieldSpec) imported;
2260 imported_events.RemoveAt (i);
2271 case MemberTypes.NestedType:
2272 // Already in the cache from the first pass
2275 throw new NotImplementedException (member.ToString ());
2278 if (imported.IsStatic && declaringType.IsInterface)
2281 cache.AddMemberImported (imported);
2287 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2289 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2290 : base (type, importer)
2296 public IAssemblyDefinition DeclaringAssembly {
2298 throw new NotImplementedException ();
2302 bool ITypeDefinition.IsComImport {
2308 bool ITypeDefinition.IsPartial {
2314 bool ITypeDefinition.IsTypeForwarder {
2320 bool ITypeDefinition.IsCyclicTypeForwarder {
2326 public string Namespace {
2332 public int TypeParametersCount {
2338 public TypeParameterSpec[] TypeParameters {
2346 public TypeSpec GetAttributeCoClass ()
2351 public string GetAttributeDefaultMember ()
2353 throw new NotSupportedException ();
2356 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2358 throw new NotSupportedException ();
2361 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2363 throw new NotImplementedException ();
2366 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2368 throw new NotImplementedException ();