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 Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
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 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
247 add.IsAccessor = true;
248 remove.IsAccessor = true;
250 if (add.Modifiers != remove.Modifiers)
251 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
253 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
254 var definition = new ImportedMemberDefinition (ei, event_type, this);
255 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
258 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
260 var tparams = type.GetGenericArguments ();
262 int parent_owned_count;
264 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
267 // System.Reflection duplicates parent type parameters for each
268 // nested type with slightly modified properties (eg. different owner)
269 // This just makes things more complicated (think of cloned constraints)
270 // therefore we remap any nested type owned by parent using `type_cache'
271 // to the single TypeParameterSpec
273 if (declaringType != null && parent_owned_count > 0) {
275 while (read_count != parent_owned_count) {
276 var tparams_count = declaringType.Arity;
277 if (tparams_count != 0) {
278 var parent_tp = declaringType.MemberDefinition.TypeParameters;
279 read_count += tparams_count;
280 for (int i = 0; i < tparams_count; i++) {
281 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
285 declaringType = declaringType.DeclaringType;
289 parent_owned_count = 0;
292 if (tparams.Length - parent_owned_count == 0)
295 return CreateGenericParameters (parent_owned_count, tparams);
298 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
300 var tspec = new TypeParameterSpec[tparams.Length - first];
301 for (int pos = first; pos < tparams.Length; ++pos) {
302 var type = tparams[pos];
303 int index = pos - first;
305 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
311 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
315 var tspec = new TypeSpec [tparams.Length - first];
316 for (int pos = first; pos < tparams.Length; ++pos) {
317 var type = tparams[pos];
318 int index = pos - first;
321 if (type.HasElementType) {
322 var element = type.GetElementType ();
324 spec = ImportType (element, dtype);
327 throw new NotImplementedException ("Unknown element type " + type.ToString ());
330 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
332 spec = CreateType (type, dtype, true);
335 // We treat nested generic types as inflated internally where
336 // reflection uses type definition
339 // IFoo<A<T>> foo; // A<T> is definition in this case
342 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
343 var start_pos = spec.DeclaringType == null ? 0 : spec.DeclaringType.MemberDefinition.TypeParametersCount;
344 var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype);
345 spec = spec.MakeGenericType (module, targs);
359 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
361 Modifiers mod = ReadMethodModifiers (mb, declaringType);
362 TypeParameterSpec[] tparams;
364 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
366 if (mb.IsGenericMethod) {
367 if (!mb.IsGenericMethodDefinition)
368 throw new NotSupportedException ("assert");
370 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
377 if (mb.MemberType == MemberTypes.Constructor) {
378 kind = MemberKind.Constructor;
379 returnType = module.Compiler.BuiltinTypes.Void;
382 // Detect operators and destructors
384 string name = mb.Name;
385 kind = MemberKind.Method;
386 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
387 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
388 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o' && (mb.Attributes & MethodAttributes.SpecialName) != 0) {
389 var op_type = Operator.GetType (name);
390 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
391 kind = MemberKind.Operator;
394 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
395 kind = MemberKind.Destructor;
396 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
397 mod &= ~Modifiers.OVERRIDE;
398 mod |= Modifiers.VIRTUAL;
403 var mi = (MethodInfo) mb;
404 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
406 // Cannot set to OVERRIDE without full hierarchy checks
407 // this flag indicates that the method could be override
408 // but further validation is needed
409 if ((mod & Modifiers.OVERRIDE) != 0) {
410 bool is_real_override = false;
411 if (kind == MemberKind.Method && declaringType.BaseType != null) {
412 var btype = declaringType.BaseType;
413 if (IsOverrideMethodBaseTypeAccessible (btype)) {
414 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
415 var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
418 // For imported class method do additional validation to be sure that metadata
419 // override flag was correct
421 // Difference between protected internal and protected is ok
423 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
424 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
425 is_real_override = true;
430 if (!is_real_override) {
431 mod &= ~Modifiers.OVERRIDE;
432 if ((mod & Modifiers.SEALED) != 0)
433 mod &= ~Modifiers.SEALED;
435 mod |= Modifiers.VIRTUAL;
440 IMethodDefinition definition;
441 if (tparams != null) {
442 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
443 foreach (var tp in gmd.TypeParameters) {
444 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
449 definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
452 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
459 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
461 switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
462 case Modifiers.PUBLIC:
464 case Modifiers.INTERNAL:
466 // Check whether imported method in base type is accessible from compiled
469 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
470 case Modifiers.PRIVATE:
474 // protected internal
476 // Method accessibility checks will be done later based on context
477 // where the method is called (CS0122 error will be reported for inaccessible)
484 // Imports System.Reflection parameters
486 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
488 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
490 if (pi.Length == 0 && varargs == 0)
491 return ParametersCompiled.EmptyReadOnlyParameters;
493 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
494 IParameterData[] par = new IParameterData[pi.Length + varargs];
495 bool is_params = false;
496 for (int i = 0; i < pi.Length; i++) {
497 ParameterInfo p = pi[i];
498 Parameter.Modifier mod = 0;
499 Expression default_value = null;
500 if (p.ParameterType.IsByRef) {
501 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
502 mod = Parameter.Modifier.OUT;
504 mod = Parameter.Modifier.REF;
507 // Strip reference wrapping
509 var el = p.ParameterType.GetElementType ();
510 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
511 } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
512 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
513 mod = Parameter.Modifier.This;
514 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
516 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
518 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
519 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
520 mod = Parameter.Modifier.PARAMS;
525 if (!is_params && p.IsOptional) {
526 object value = p.RawDefaultValue;
527 var ptype = types[i];
528 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
530 default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
532 default_value = ImportParameterConstant (value);
535 default_value = new EnumConstant ((Constant) default_value, ptype);
539 var attrs = CustomAttributeData.GetCustomAttributes (p);
540 for (int ii = 0; ii < attrs.Count; ++ii) {
541 var attr = attrs[ii];
542 var dt = attr.Constructor.DeclaringType;
543 if (dt.Namespace != CompilerServicesNamespace)
546 if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
547 mod |= Parameter.Modifier.CallerLineNumber;
548 else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
549 mod |= Parameter.Modifier.CallerFilePath;
550 else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
551 mod |= Parameter.Modifier.CallerMemberName;
553 } else if (value == Missing.Value) {
554 default_value = EmptyExpression.MissingValue;
555 } else if (value == null) {
556 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
557 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
558 default_value = ImportParameterConstant (value);
563 par[i] = new ParameterData (p.Name, mod, default_value);
567 par[par.Length - 1] = new ArglistParameter (Location.Null);
568 types[types.Length - 1] = InternalType.Arglist;
571 return method != null ?
572 new ParametersImported (par, types, varargs != 0, is_params) :
573 new ParametersImported (par, types, is_params);
577 // Returns null when the property is not valid C# property
579 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
582 AParametersCollection param = null;
583 TypeSpec type = null;
586 param = get.Parameters;
587 type = get.ReturnType;
590 bool is_valid_property = true;
592 if (set.ReturnType.Kind != MemberKind.Void)
593 is_valid_property = false;
595 var set_param_count = set.Parameters.Count - 1;
597 if (set_param_count < 0) {
599 is_valid_property = false;
602 var set_type = set.Parameters.Types[set_param_count];
605 AParametersCollection set_based_param;
607 if (set_param_count == 0) {
608 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
611 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
613 var data = new IParameterData[set_param_count];
614 var types = new TypeSpec[set_param_count];
615 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
616 Array.Copy (set.Parameters.Types, types, set_param_count);
617 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
621 param = set_based_param;
624 if (set_param_count != get.Parameters.Count)
625 is_valid_property = false;
627 if (get.ReturnType != set_type)
628 is_valid_property = false;
630 // Possible custom accessor modifiers
631 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
632 var get_acc = mod & Modifiers.AccessibilityMask;
633 if (get_acc != Modifiers.PUBLIC) {
634 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
635 // If the accessor modifiers are not same, do extra restriction checks
636 if (get_acc != set_acc) {
637 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
638 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
639 if (get_restr && set_restr) {
640 is_valid_property = false; // Neither is more restrictive
644 mod &= ~Modifiers.AccessibilityMask;
653 PropertySpec spec = null;
654 if (!param.IsEmpty) {
655 if (is_valid_property) {
656 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
657 if (index_name == null) {
658 is_valid_property = false;
662 is_valid_property = false;
663 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
664 is_valid_property = false;
668 is_valid_property = false;
669 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
670 is_valid_property = false;
674 if (is_valid_property) {
675 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
676 } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
678 // Enables support for properties with parameters (must have default value) of COM-imported types
680 is_valid_property = true;
682 for (int i = 0; i < param.FixedParameters.Length; ++i) {
683 if (!param.FixedParameters[i].HasDefaultValue) {
684 is_valid_property = false;
693 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
695 if (!is_valid_property) {
696 spec.IsNotCSharpCompatible = true;
708 public TypeSpec CreateType (MetaType type)
710 return CreateType (type, new DynamicTypeReader (), true);
713 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
715 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
718 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
720 TypeSpec declaring_type;
721 if (type.IsNested && !type.IsGenericParameter)
722 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
724 declaring_type = null;
726 return CreateType (type, declaring_type, dtype, canImportBaseType);
729 protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
732 if (import_cache.TryGetValue (type, out spec)) {
733 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
734 if (dtype.IsDynamicObject ())
735 return module.Compiler.BuiltinTypes.Dynamic;
740 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
743 if (!dtype.HasDynamicAttribute ())
746 // We've found same object in the cache but this one has a dynamic custom attribute
747 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
748 // Do type resolve process again in that case
750 // TODO: Handle cases where they still unify
753 if (IsMissingType (type)) {
754 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
755 spec.MemberCache = MemberCache.Empty;
756 import_cache.Add (type, spec);
760 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
761 var type_def = type.GetGenericTypeDefinition ();
763 // Generic type definition can also be forwarded
764 if (compiled_types.TryGetValue (type_def, out spec))
767 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
770 if (declaringType == null) {
771 // Simple case, no nesting
772 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
773 spec = spec.MakeGenericType (module, targs);
776 // Nested type case, converting .NET types like
777 // A`1.B`1.C`1<int, long, string> to typespec like
778 // A<int>.B<long>.C<string>
780 var nested_hierarchy = new List<TypeSpec> ();
781 while (declaringType.IsNested) {
782 nested_hierarchy.Add (declaringType);
783 declaringType = declaringType.DeclaringType;
787 if (declaringType.Arity > 0) {
788 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
789 targs_pos = spec.Arity;
791 spec = declaringType;
794 for (int i = nested_hierarchy.Count; i != 0; --i) {
795 var t = nested_hierarchy [i - 1];
796 if (t.Kind == MemberKind.MissingType)
799 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
802 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
803 targs_pos += t.Arity;
807 if (spec.Kind == MemberKind.MissingType) {
808 spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC);
809 spec.MemberCache = MemberCache.Empty;
811 if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
814 string name = type.Name;
815 int index = name.IndexOf ('`');
817 name = name.Substring (0, index);
819 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
821 if (spec.Arity > 0) {
822 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
827 // Don't add generic type with dynamic arguments, they can interfere with same type
828 // using object type arguments
829 if (!spec.HasDynamicElement) {
831 // Add to reading cache to speed up reading
832 if (!import_cache.ContainsKey (type))
833 import_cache.Add (type, spec);
842 var ma = type.Attributes;
843 switch (ma & TypeAttributes.VisibilityMask) {
844 case TypeAttributes.Public:
845 case TypeAttributes.NestedPublic:
846 mod = Modifiers.PUBLIC;
848 case TypeAttributes.NestedPrivate:
849 mod = Modifiers.PRIVATE;
851 case TypeAttributes.NestedFamily:
852 mod = Modifiers.PROTECTED;
854 case TypeAttributes.NestedFamORAssem:
855 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
858 mod = Modifiers.INTERNAL;
862 if ((ma & TypeAttributes.Interface) != 0) {
863 kind = MemberKind.Interface;
864 } else if (type.IsGenericParameter) {
865 kind = MemberKind.TypeParameter;
867 var base_type = type.BaseType;
868 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
869 kind = MemberKind.Class;
871 kind = DetermineKindFromBaseType (base_type);
872 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
873 mod |= Modifiers.SEALED;
877 if (kind == MemberKind.Class) {
878 if ((ma & TypeAttributes.Sealed) != 0) {
879 if ((ma & TypeAttributes.Abstract) != 0)
880 mod |= Modifiers.STATIC;
882 mod |= Modifiers.SEALED;
883 } else if ((ma & TypeAttributes.Abstract) != 0) {
884 mod |= Modifiers.ABSTRACT;
889 var definition = new ImportedTypeDefinition (type, this);
892 if (kind == MemberKind.Enum) {
893 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
894 BindingFlags.Instance |
895 BindingFlags.Public | BindingFlags.NonPublic;
897 var type_members = type.GetFields (underlying_member);
898 foreach (var type_member in type_members) {
899 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
904 kind = MemberKind.Class;
906 } else if (kind == MemberKind.TypeParameter) {
907 spec = CreateTypeParameter (type, declaringType);
908 } else if (type.IsGenericTypeDefinition) {
909 definition.TypeParameters = CreateGenericParameters (type, declaringType);
910 } else if (compiled_types.TryGetValue (type, out pt)) {
912 // Same type was found in inside compiled types. It's
913 // either build-in type or forward referenced typed
914 // which point into just compiled assembly.
917 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
919 bts.SetDefinition (definition, type, mod);
923 spec = new TypeSpec (kind, declaringType, definition, type, mod);
925 import_cache.Add (type, spec);
927 if (kind == MemberKind.TypeParameter) {
928 if (canImportBaseType)
929 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
935 // Two stage setup as the base type can be inflated declaring type or
936 // another nested type inside same declaring type which has not been
937 // loaded, therefore we can import a base type of nested types once
938 // the types have been imported
940 if (canImportBaseType)
941 ImportTypeBase (spec, type);
946 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
948 IAssemblyDefinition found;
949 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
951 // This can happen in dynamic context only
952 var def = new ImportedAssemblyDefinition (assembly);
953 assembly_2_definition.Add (assembly, def);
954 def.ReadAttributes ();
961 public void ImportTypeBase (MetaType type)
963 TypeSpec spec = import_cache[type];
965 ImportTypeBase (spec, type);
968 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
971 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
972 case GenericParameterAttributes.Covariant:
973 variance = Variance.Covariant;
975 case GenericParameterAttributes.Contravariant:
976 variance = Variance.Contravariant;
979 variance = Variance.None;
983 SpecialConstraint special = SpecialConstraint.None;
984 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
986 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
987 special |= SpecialConstraint.Struct;
988 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
989 special = SpecialConstraint.Constructor;
992 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
993 special |= SpecialConstraint.Class;
996 TypeParameterSpec spec;
997 var def = new ImportedTypeParameterDefinition (type, this);
998 if (type.DeclaringMethod != null) {
999 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
1001 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
1008 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
1009 // they can be assembly specific therefore we do check based on names only
1011 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
1013 if (attributesData.Count == 0)
1016 foreach (var attr in attributesData) {
1017 var dt = attr.Constructor.DeclaringType;
1018 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1025 void ImportTypeBase (TypeSpec spec, MetaType type)
1027 if (spec.Kind == MemberKind.Interface)
1028 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1029 else if (type.BaseType != null) {
1031 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1032 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1034 base_type = CreateType (type.BaseType);
1036 spec.BaseType = base_type;
1039 if (spec.MemberDefinition.TypeParametersCount > 0) {
1040 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1041 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1046 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1048 Namespace ns = targetNamespace;
1049 string prev_namespace = null;
1050 foreach (var t in types) {
1054 // Be careful not to trigger full parent type loading
1055 if (t.MemberType == MemberTypes.NestedType)
1058 if (t.Name[0] == '<')
1061 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1065 if (prev_namespace != t.Namespace) {
1066 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1067 prev_namespace = t.Namespace;
1070 // Cannot rely on assembly level Extension attribute or static modifier because they
1071 // are not followed by other compilers (e.g. F#).
1072 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1073 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1074 it.SetExtensionMethodContainer ();
1077 ns.AddType (module, it);
1081 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1083 var constraints = type.GetGenericParameterConstraints ();
1084 List<TypeSpec> tparams = null;
1085 foreach (var ct in constraints) {
1086 if (ct.IsGenericParameter) {
1087 if (tparams == null)
1088 tparams = new List<TypeSpec> ();
1090 tparams.Add (CreateType (ct));
1094 var constraint_type = CreateType (ct);
1095 if (constraint_type.IsClass) {
1096 spec.BaseType = constraint_type;
1100 spec.AddInterface (constraint_type);
1103 if (spec.BaseType == null)
1104 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1106 if (tparams != null)
1107 spec.TypeArguments = tparams.ToArray ();
1110 Constant ImportParameterConstant (object value)
1113 // Get type of underlying value as int constant can be used for object
1114 // parameter type. This is not allowed in C# but other languages can do that
1116 var types = module.Compiler.BuiltinTypes;
1117 switch (System.Type.GetTypeCode (value.GetType ())) {
1118 case TypeCode.Boolean:
1119 return new BoolConstant (types, (bool) value, Location.Null);
1121 return new ByteConstant (types, (byte) value, Location.Null);
1123 return new CharConstant (types, (char) value, Location.Null);
1124 case TypeCode.Decimal:
1125 return new DecimalConstant (types, (decimal) value, Location.Null);
1126 case TypeCode.Double:
1127 return new DoubleConstant (types, (double) value, Location.Null);
1128 case TypeCode.Int16:
1129 return new ShortConstant (types, (short) value, Location.Null);
1130 case TypeCode.Int32:
1131 return new IntConstant (types, (int) value, Location.Null);
1132 case TypeCode.Int64:
1133 return new LongConstant (types, (long) value, Location.Null);
1134 case TypeCode.SByte:
1135 return new SByteConstant (types, (sbyte) value, Location.Null);
1136 case TypeCode.Single:
1137 return new FloatConstant (types, (float) value, Location.Null);
1138 case TypeCode.String:
1139 return new StringConstant (types, (string) value, Location.Null);
1140 case TypeCode.UInt16:
1141 return new UShortConstant (types, (ushort) value, Location.Null);
1142 case TypeCode.UInt32:
1143 return new UIntConstant (types, (uint) value, Location.Null);
1144 case TypeCode.UInt64:
1145 return new ULongConstant (types, (ulong) value, Location.Null);
1148 throw new NotImplementedException (value.GetType ().ToString ());
1151 public TypeSpec ImportType (MetaType type)
1153 return ImportType (type, new DynamicTypeReader (type));
1156 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1158 if (type.HasElementType) {
1159 var element = type.GetElementType ();
1161 var spec = ImportType (element, dtype);
1164 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1166 return ReferenceContainer.MakeType (module, spec);
1168 return PointerContainer.MakeType (module, spec);
1170 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1173 TypeSpec compiled_type;
1174 if (compiled_types.TryGetValue (type, out compiled_type)) {
1175 if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
1176 return module.Compiler.BuiltinTypes.Dynamic;
1178 return compiled_type;
1181 return CreateType (type, dtype, true);
1184 static bool IsMissingType (MetaType type)
1187 return type.__IsMissing;
1194 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1195 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1196 // DecimalConstantAttribute metadata.
1198 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1200 if (attrs.Count == 0)
1203 foreach (var ca in attrs) {
1204 var dt = ca.Constructor.DeclaringType;
1205 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1208 var value = new decimal (
1209 (int) (uint) ca.ConstructorArguments[4].Value,
1210 (int) (uint) ca.ConstructorArguments[3].Value,
1211 (int) (uint) ca.ConstructorArguments[2].Value,
1212 (byte) ca.ConstructorArguments[1].Value != 0,
1213 (byte) ca.ConstructorArguments[0].Value);
1215 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1221 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1224 var ma = mb.Attributes;
1225 switch (ma & MethodAttributes.MemberAccessMask) {
1226 case MethodAttributes.Public:
1227 mod = Modifiers.PUBLIC;
1229 case MethodAttributes.Assembly:
1230 mod = Modifiers.INTERNAL;
1232 case MethodAttributes.Family:
1233 mod = Modifiers.PROTECTED;
1235 case MethodAttributes.FamORAssem:
1236 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1239 mod = Modifiers.PRIVATE;
1243 if ((ma & MethodAttributes.Static) != 0) {
1244 mod |= Modifiers.STATIC;
1247 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1248 mod |= Modifiers.ABSTRACT;
1252 // It can be sealed and override
1253 if ((ma & MethodAttributes.Final) != 0)
1254 mod |= Modifiers.SEALED;
1256 if ((ma & MethodAttributes.Virtual) != 0) {
1257 // Not every member can be detected based on MethodAttribute, we
1258 // set virtual or non-virtual only when we are certain. Further checks
1259 // to really find out what `virtual' means for this member are done
1261 if ((ma & MethodAttributes.NewSlot) != 0) {
1262 if ((mod & Modifiers.SEALED) != 0) {
1263 mod &= ~Modifiers.SEALED;
1265 mod |= Modifiers.VIRTUAL;
1268 mod |= Modifiers.OVERRIDE;
1276 abstract class ImportedDefinition : IMemberDefinition
1278 protected class AttributesBag
1280 public static readonly AttributesBag Default = new AttributesBag ();
1282 public AttributeUsageAttribute AttributeUsage;
1283 public ObsoleteAttribute Obsolete;
1284 public string[] Conditionals;
1285 public string DefaultIndexerName;
1286 public bool? CLSAttributeValue;
1287 public TypeSpec CoClass;
1289 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1291 AttributesBag bag = null;
1292 List<string> conditionals = null;
1294 // It should not throw any loading exception
1295 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1297 foreach (var a in attrs) {
1298 var dt = a.Constructor.DeclaringType;
1299 string name = dt.Name;
1300 if (name == "ObsoleteAttribute") {
1301 if (dt.Namespace != "System")
1305 bag = new AttributesBag ();
1307 var args = a.ConstructorArguments;
1309 if (args.Count == 1) {
1310 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1311 } else if (args.Count == 2) {
1312 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1314 bag.Obsolete = new ObsoleteAttribute ();
1320 if (name == "ConditionalAttribute") {
1321 if (dt.Namespace != "System.Diagnostics")
1325 bag = new AttributesBag ();
1327 if (conditionals == null)
1328 conditionals = new List<string> (2);
1330 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1334 if (name == "CLSCompliantAttribute") {
1335 if (dt.Namespace != "System")
1339 bag = new AttributesBag ();
1341 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1345 // Type only attributes
1346 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1347 if (name == "DefaultMemberAttribute") {
1348 if (dt.Namespace != "System.Reflection")
1352 bag = new AttributesBag ();
1354 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1358 if (name == "AttributeUsageAttribute") {
1359 if (dt.Namespace != "System")
1363 bag = new AttributesBag ();
1365 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1366 foreach (var named in a.NamedArguments) {
1367 if (named.MemberInfo.Name == "AllowMultiple")
1368 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1369 else if (named.MemberInfo.Name == "Inherited")
1370 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1375 // Interface only attribute
1376 if (name == "CoClassAttribute") {
1377 if (dt.Namespace != "System.Runtime.InteropServices")
1381 bag = new AttributesBag ();
1383 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1392 if (conditionals != null)
1393 bag.Conditionals = conditionals.ToArray ();
1399 protected readonly MemberInfo provider;
1400 protected AttributesBag cattrs;
1401 protected readonly MetadataImporter importer;
1403 protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1405 this.provider = provider;
1406 this.importer = importer;
1411 public bool IsImported {
1417 public virtual string Name {
1419 return provider.Name;
1425 public string[] ConditionalConditions ()
1430 return cattrs.Conditionals;
1433 public ObsoleteAttribute GetAttributeObsolete ()
1438 return cattrs.Obsolete;
1441 public bool? CLSAttributeValue {
1446 return cattrs.CLSAttributeValue;
1450 protected void ReadAttributes ()
1452 cattrs = AttributesBag.Read (provider, importer);
1455 public void SetIsAssigned ()
1457 // Unused for imported members
1460 public void SetIsUsed ()
1462 // Unused for imported members
1466 public class ImportedModuleDefinition
1468 readonly Module module;
1471 public ImportedModuleDefinition (Module module)
1473 this.module = module;
1478 public bool IsCLSCompliant {
1480 return cls_compliant;
1484 public string Name {
1492 public void ReadAttributes ()
1494 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1496 foreach (var a in attrs) {
1497 var dt = a.Constructor.DeclaringType;
1498 if (dt.Name == "CLSCompliantAttribute") {
1499 if (dt.Namespace != "System")
1502 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1509 // Reads assembly attributes which where attached to a special type because
1510 // module does have assembly manifest
1512 public List<Attribute> ReadAssemblyAttributes ()
1514 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1518 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1522 // TODO: implement, the idea is to fabricate specil Attribute class and
1523 // add it to OptAttributes before resolving the source code attributes
1524 // Need to build module location as well for correct error reporting
1526 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1527 //var attrs = new List<Attribute> (assembly_attributes.Count);
1528 //foreach (var a in assembly_attributes)
1530 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1531 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1533 // foreach (var carg in a.ConstructorArguments) {
1537 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1544 public class ImportedAssemblyDefinition : IAssemblyDefinition
1546 readonly Assembly assembly;
1547 readonly AssemblyName aname;
1550 List<AssemblyName> internals_visible_to;
1551 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1553 public ImportedAssemblyDefinition (Assembly assembly)
1555 this.assembly = assembly;
1556 this.aname = assembly.GetName ();
1561 public Assembly Assembly {
1567 public string FullName {
1569 return aname.FullName;
1573 public bool HasStrongName {
1575 return aname.GetPublicKey ().Length != 0;
1579 public bool IsMissing {
1582 return assembly.__IsMissing;
1589 public bool IsCLSCompliant {
1591 return cls_compliant;
1595 public string Location {
1597 return assembly.Location;
1601 public string Name {
1609 public byte[] GetPublicKeyToken ()
1611 return aname.GetPublicKeyToken ();
1614 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1616 return internals_visible_to_cache [assembly];
1619 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1621 if (internals_visible_to == null)
1624 AssemblyName is_visible = null;
1625 if (internals_visible_to_cache == null) {
1626 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1628 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1629 return is_visible != null;
1632 var token = assembly.GetPublicKeyToken ();
1633 if (token != null && token.Length == 0)
1636 foreach (var internals in internals_visible_to) {
1637 if (internals.Name != assembly.Name)
1640 if (token == null && assembly is AssemblyDefinition) {
1641 is_visible = internals;
1645 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1648 is_visible = internals;
1652 internals_visible_to_cache.Add (assembly, is_visible);
1653 return is_visible != null;
1656 public void ReadAttributes ()
1659 if (assembly.__IsMissing)
1663 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1665 foreach (var a in attrs) {
1666 var dt = a.Constructor.DeclaringType;
1668 if (name == "CLSCompliantAttribute") {
1669 if (dt.Namespace == "System") {
1670 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1675 if (name == "InternalsVisibleToAttribute") {
1676 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1679 string s = a.ConstructorArguments[0].Value as string;
1683 var an = new AssemblyName (s);
1684 if (internals_visible_to == null)
1685 internals_visible_to = new List<AssemblyName> ();
1687 internals_visible_to.Add (an);
1693 public override string ToString ()
1699 class ImportedMemberDefinition : ImportedDefinition
1701 readonly TypeSpec type;
1703 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1704 : base (member, importer)
1711 public TypeSpec MemberType {
1720 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1722 readonly AParametersCollection parameters;
1724 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1725 : base (provider, type, importer)
1727 this.parameters = parameters;
1730 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1731 : base (provider, type, importer)
1733 this.parameters = parameters;
1738 public AParametersCollection Parameters {
1747 class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1749 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1750 : base (provider, type, parameters, importer)
1754 MethodBase IMethodDefinition.Metadata {
1756 return (MethodBase) provider;
1761 class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1763 readonly TypeParameterSpec[] tparams;
1765 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1766 : base (provider, type, parameters, importer)
1768 this.tparams = tparams;
1773 public TypeParameterSpec[] TypeParameters {
1779 public int TypeParametersCount {
1781 return tparams.Length;
1788 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1790 TypeParameterSpec[] tparams;
1793 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1794 : base (type, importer)
1800 public IAssemblyDefinition DeclaringAssembly {
1802 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1806 bool ITypeDefinition.IsComImport {
1808 return ((MetaType) provider).IsImport;
1813 bool ITypeDefinition.IsPartial {
1819 bool ITypeDefinition.IsTypeForwarder {
1822 return ((MetaType) provider).__IsTypeForwarder;
1829 bool ITypeDefinition.IsCyclicTypeForwarder {
1832 return ((MetaType) provider).__IsCyclicTypeForwarder;
1839 public override string Name {
1843 if (tparams != null) {
1844 int arity_start = name.IndexOf ('`');
1845 if (arity_start > 0)
1846 name = name.Substring (0, arity_start);
1854 public string Namespace {
1856 return ((MetaType) provider).Namespace;
1860 public int TypeParametersCount {
1862 return tparams == null ? 0 : tparams.Length;
1866 public TypeParameterSpec[] TypeParameters {
1877 public void DefineInterfaces (TypeSpec spec)
1879 var type = (MetaType) provider;
1882 ifaces = type.__GetDeclaredInterfaces ();
1883 if (ifaces.Length != 0) {
1884 foreach (var iface in ifaces) {
1885 var it = importer.CreateType (iface);
1889 spec.AddInterfaceDefined (it);
1891 // Unfortunately not all languages expand inherited interfaces
1892 var bifaces = it.Interfaces;
1893 if (bifaces != null) {
1894 foreach (var biface in bifaces) {
1895 spec.AddInterfaceDefined (biface);
1902 // It's impossible to get declared interfaces only using System.Reflection
1903 // hence we need to mimic the behavior with ikvm-reflection too to keep
1904 // our type look-up logic same
1906 if (spec.BaseType != null) {
1907 var bifaces = spec.BaseType.Interfaces;
1908 if (bifaces != null) {
1910 // Before adding base class interfaces close defined interfaces
1911 // on type parameter
1913 var tp = spec as TypeParameterSpec;
1914 if (tp != null && tp.InterfacesDefined == null) {
1915 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1918 foreach (var iface in bifaces)
1919 spec.AddInterfaceDefined (iface);
1923 ifaces = type.GetInterfaces ();
1925 if (ifaces.Length > 0) {
1926 foreach (var iface in ifaces) {
1927 spec.AddInterface (importer.CreateType (iface));
1934 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
1937 // Report details about missing type and most likely cause of the problem.
1938 // csc reports 1683, 1684 as warnings but we report them only when used
1939 // or referenced from the user core in which case compilation error has to
1940 // be reported because compiler cannot continue anyway
1943 var report = ctx.Module.Compiler.Report;
1945 for (int i = 0; i < missing.Count; ++i) {
1946 var t = missing [i].Type;
1949 // Report missing types only once
1951 if (report.Printer.MissingTypeReported (t.MemberDefinition))
1954 string name = t.GetSignatureForError ();
1956 var caller = missing[i].Caller;
1957 if (caller.Kind != MemberKind.MissingType)
1958 report.SymbolRelatedToPreviousError (caller);
1960 var definition = t.MemberDefinition;
1961 if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1962 report.Error (1683, loc,
1963 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1965 } else if (definition.DeclaringAssembly.IsMissing) {
1966 if (definition.IsTypeForwarder) {
1967 report.Error (1070, loc,
1968 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1969 name, definition.DeclaringAssembly.FullName);
1971 report.Error (12, loc,
1972 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1973 name, definition.DeclaringAssembly.FullName);
1975 } else if (definition.IsTypeForwarder) {
1976 report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
1977 name, definition.DeclaringAssembly.FullName);
1979 report.Error (1684, loc,
1980 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1981 name, t.MemberDefinition.DeclaringAssembly.FullName);
1986 public TypeSpec GetAttributeCoClass ()
1991 return cattrs.CoClass;
1994 public string GetAttributeDefaultMember ()
1999 return cattrs.DefaultIndexerName;
2002 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2007 return cattrs.AttributeUsage;
2010 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2012 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
2013 return a == assembly || a.IsFriendAssemblyTo (assembly);
2016 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2019 // Not interested in members of nested private types unless the importer needs them
2021 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
2022 cache = MemberCache.Empty;
2026 var loading_type = (MetaType) provider;
2027 const BindingFlags all_members = BindingFlags.DeclaredOnly |
2028 BindingFlags.Static | BindingFlags.Instance |
2029 BindingFlags.Public | BindingFlags.NonPublic;
2031 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
2032 MethodAttributes.Virtual | MethodAttributes.HideBySig |
2033 MethodAttributes.Final;
2035 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
2036 List<EventSpec> imported_events = null;
2037 EventSpec event_spec;
2038 MemberSpec imported;
2042 all = loading_type.GetMembers (all_members);
2043 } catch (Exception e) {
2044 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2045 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2048 if (cache == null) {
2049 cache = new MemberCache (all.Length);
2052 // Do the types first as they can be referenced by the members before
2053 // they are found or inflated
2055 foreach (var member in all) {
2056 if (member.MemberType != MemberTypes.NestedType)
2059 var t = (MetaType) member;
2061 // Ignore compiler generated types, mostly lambda containers
2062 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2066 imported = importer.CreateNestedType (t, declaringType);
2067 } catch (Exception e) {
2068 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2069 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2072 cache.AddMemberImported (imported);
2075 foreach (var member in all) {
2076 if (member.MemberType != MemberTypes.NestedType)
2079 var t = (MetaType) member;
2081 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2084 importer.ImportTypeBase (t);
2089 // Load base interfaces first to minic behaviour of compiled members
2091 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2092 foreach (var iface in declaringType.Interfaces) {
2093 cache.AddInterface (iface);
2099 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2101 foreach (var member in all) {
2102 switch (member.MemberType) {
2103 case MemberTypes.Constructor:
2104 if (declaringType.IsInterface)
2107 goto case MemberTypes.Method;
2108 case MemberTypes.Method:
2109 MethodBase mb = (MethodBase) member;
2110 var attrs = mb.Attributes;
2112 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2113 if (importer.IgnorePrivateMembers)
2116 // Ignore explicitly implemented members
2117 if ((attrs & explicit_impl) == explicit_impl)
2120 // Ignore compiler generated methods
2121 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2125 imported = importer.CreateMethod (mb, declaringType);
2126 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2127 if (possible_accessors == null)
2128 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2130 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2131 possible_accessors.Add (mb, (MethodSpec) imported);
2135 case MemberTypes.Property:
2136 if (possible_accessors == null)
2139 var p = (PropertyInfo) member;
2141 // Links possible accessors with property
2143 MethodSpec get, set;
2144 m = p.GetGetMethod (true);
2145 if (m == null || !possible_accessors.TryGetValue (m, out get))
2148 m = p.GetSetMethod (true);
2149 if (m == null || !possible_accessors.TryGetValue (m, out set))
2152 // No accessors registered (e.g. explicit implementation)
2153 if (get == null && set == null)
2157 imported = importer.CreateProperty (p, declaringType, get, set);
2158 } catch (Exception ex) {
2159 throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2160 p.Name, declaringType.GetSignatureForError ());
2163 if (imported == null)
2167 case MemberTypes.Event:
2168 if (possible_accessors == null)
2171 var e = (EventInfo) member;
2173 // Links accessors with event
2175 MethodSpec add, remove;
2176 m = e.GetAddMethod (true);
2177 if (m == null || !possible_accessors.TryGetValue (m, out add))
2180 m = e.GetRemoveMethod (true);
2181 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2184 // Both accessors are required
2185 if (add == null || remove == null)
2188 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2189 if (!importer.IgnorePrivateMembers) {
2190 if (imported_events == null)
2191 imported_events = new List<EventSpec> ();
2193 imported_events.Add (event_spec);
2196 imported = event_spec;
2198 case MemberTypes.Field:
2199 var fi = (FieldInfo) member;
2201 imported = importer.CreateField (fi, declaringType);
2202 if (imported == null)
2206 // For dynamic binder event has to be fully restored to allow operations
2207 // within the type container to work correctly
2209 if (imported_events != null) {
2210 // The backing event field should be private but it may not
2212 for (i = 0; i < imported_events.Count; ++i) {
2213 var ev = imported_events[i];
2214 if (ev.Name == fi.Name) {
2215 ev.BackingField = (FieldSpec) imported;
2216 imported_events.RemoveAt (i);
2227 case MemberTypes.NestedType:
2228 // Already in the cache from the first pass
2231 throw new NotImplementedException (member.ToString ());
2234 if (imported.IsStatic && declaringType.IsInterface)
2237 cache.AddMemberImported (imported);
2243 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2245 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2246 : base (type, importer)
2252 public IAssemblyDefinition DeclaringAssembly {
2254 throw new NotImplementedException ();
2258 bool ITypeDefinition.IsComImport {
2264 bool ITypeDefinition.IsPartial {
2270 bool ITypeDefinition.IsTypeForwarder {
2276 bool ITypeDefinition.IsCyclicTypeForwarder {
2282 public string Namespace {
2288 public int TypeParametersCount {
2294 public TypeParameterSpec[] TypeParameters {
2302 public TypeSpec GetAttributeCoClass ()
2307 public string GetAttributeDefaultMember ()
2309 throw new NotSupportedException ();
2312 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2314 throw new NotSupportedException ();
2317 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2319 throw new NotImplementedException ();
2322 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2324 throw new NotImplementedException ();