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));
193 } catch (Exception e) {
194 // TODO: I should construct fake TypeSpec based on TypeRef signature
195 // but there is no way to do it with System.Reflection
196 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
197 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
200 var definition = new ImportedMemberDefinition (fi, field_type, this);
202 if ((fa & FieldAttributes.Literal) != 0) {
203 Constant c = field_type.Kind == MemberKind.MissingType ?
204 new NullConstant (InternalType.ErrorType, Location.Null) :
205 Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
206 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
209 if ((fa & FieldAttributes.InitOnly) != 0) {
210 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
211 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
213 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
216 mod |= Modifiers.READONLY;
218 var req_mod = fi.GetRequiredCustomModifiers ();
219 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
220 mod |= Modifiers.VOLATILE;
223 if ((fa & FieldAttributes.Static) != 0) {
224 mod |= Modifiers.STATIC;
226 // Fixed buffers cannot be static
227 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
228 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
230 // TODO: Sanity check on field_type (only few types are allowed)
231 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
232 return new FixedFieldSpec (module, declaringType, definition, fi, element_field, mod);
236 return new FieldSpec (declaringType, definition, field_type, fi, mod);
239 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
241 add.IsAccessor = true;
242 remove.IsAccessor = true;
244 if (add.Modifiers != remove.Modifiers)
245 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
247 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
248 var definition = new ImportedMemberDefinition (ei, event_type, this);
249 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
252 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
254 var tparams = type.GetGenericArguments ();
256 int parent_owned_count;
258 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
261 // System.Reflection duplicates parent type parameters for each
262 // nested type with slightly modified properties (eg. different owner)
263 // This just makes things more complicated (think of cloned constraints)
264 // therefore we remap any nested type owned by parent using `type_cache'
265 // to the single TypeParameterSpec
267 if (declaringType != null && parent_owned_count > 0) {
269 while (read_count != parent_owned_count) {
270 var tparams_count = declaringType.Arity;
271 if (tparams_count != 0) {
272 var parent_tp = declaringType.MemberDefinition.TypeParameters;
273 read_count += tparams_count;
274 for (int i = 0; i < tparams_count; i++) {
275 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
279 declaringType = declaringType.DeclaringType;
283 parent_owned_count = 0;
286 if (tparams.Length - parent_owned_count == 0)
289 return CreateGenericParameters (parent_owned_count, tparams);
292 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
294 var tspec = new TypeParameterSpec[tparams.Length - first];
295 for (int pos = first; pos < tparams.Length; ++pos) {
296 var type = tparams[pos];
297 int index = pos - first;
299 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
305 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
309 var tspec = new TypeSpec [tparams.Length - first];
310 for (int pos = first; pos < tparams.Length; ++pos) {
311 var type = tparams[pos];
312 int index = pos - first;
315 if (type.HasElementType) {
316 var element = type.GetElementType ();
318 spec = ImportType (element, dtype);
321 throw new NotImplementedException ("Unknown element type " + type.ToString ());
324 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
326 spec = CreateType (type, dtype, true);
329 // We treat nested generic types as inflated internally where
330 // reflection uses type definition
333 // IFoo<A<T>> foo; // A<T> is definition in this case
336 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
337 var start_pos = spec.DeclaringType == null ? 0 : spec.DeclaringType.MemberDefinition.TypeParametersCount;
338 var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype);
339 spec = spec.MakeGenericType (module, targs);
350 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
352 Modifiers mod = ReadMethodModifiers (mb, declaringType);
353 TypeParameterSpec[] tparams;
355 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
357 if (mb.IsGenericMethod) {
358 if (!mb.IsGenericMethodDefinition)
359 throw new NotSupportedException ("assert");
361 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
368 if (mb.MemberType == MemberTypes.Constructor) {
369 kind = MemberKind.Constructor;
370 returnType = module.Compiler.BuiltinTypes.Void;
373 // Detect operators and destructors
375 string name = mb.Name;
376 kind = MemberKind.Method;
377 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
378 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
379 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
380 var op_type = Operator.GetType (name);
381 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
382 kind = MemberKind.Operator;
385 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
386 kind = MemberKind.Destructor;
387 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
388 mod &= ~Modifiers.OVERRIDE;
389 mod |= Modifiers.VIRTUAL;
394 var mi = (MethodInfo) mb;
395 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
397 // Cannot set to OVERRIDE without full hierarchy checks
398 // this flag indicates that the method could be override
399 // but further validation is needed
400 if ((mod & Modifiers.OVERRIDE) != 0) {
401 bool is_real_override = false;
402 if (kind == MemberKind.Method && declaringType.BaseType != null) {
403 var btype = declaringType.BaseType;
404 if (IsOverrideMethodBaseTypeAccessible (btype)) {
405 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
406 var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
409 // For imported class method do additional validation to be sure that metadata
410 // override flag was correct
412 // Difference between protected internal and protected is ok
414 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
415 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
416 is_real_override = true;
421 if (!is_real_override) {
422 mod &= ~Modifiers.OVERRIDE;
423 if ((mod & Modifiers.SEALED) != 0)
424 mod &= ~Modifiers.SEALED;
426 mod |= Modifiers.VIRTUAL;
431 IMethodDefinition definition;
432 if (tparams != null) {
433 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
434 foreach (var tp in gmd.TypeParameters) {
435 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
440 definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
443 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
450 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
452 switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
453 case Modifiers.PUBLIC:
455 case Modifiers.INTERNAL:
457 // Check whether imported method in base type is accessible from compiled
460 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
461 case Modifiers.PRIVATE:
465 // protected internal
467 // Method accessibility checks will be done later based on context
468 // where the method is called (CS0122 error will be reported for inaccessible)
475 // Imports System.Reflection parameters
477 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
479 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
481 if (pi.Length == 0 && varargs == 0)
482 return ParametersCompiled.EmptyReadOnlyParameters;
484 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
485 IParameterData[] par = new IParameterData[pi.Length + varargs];
486 bool is_params = false;
487 for (int i = 0; i < pi.Length; i++) {
488 ParameterInfo p = pi[i];
489 Parameter.Modifier mod = 0;
490 Expression default_value = null;
491 if (p.ParameterType.IsByRef) {
492 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
493 mod = Parameter.Modifier.OUT;
495 mod = Parameter.Modifier.REF;
498 // Strip reference wrapping
500 var el = p.ParameterType.GetElementType ();
501 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
502 } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
503 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
504 mod = Parameter.Modifier.This;
505 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
507 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
509 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
510 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
511 mod = Parameter.Modifier.PARAMS;
516 if (!is_params && p.IsOptional) {
517 object value = p.RawDefaultValue;
518 var ptype = types[i];
519 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
521 default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
523 default_value = ImportParameterConstant (value);
526 default_value = new EnumConstant ((Constant) default_value, ptype);
530 var attrs = CustomAttributeData.GetCustomAttributes (p);
531 for (int ii = 0; ii < attrs.Count; ++ii) {
532 var attr = attrs[ii];
533 var dt = attr.Constructor.DeclaringType;
534 if (dt.Namespace != CompilerServicesNamespace)
537 if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
538 mod |= Parameter.Modifier.CallerLineNumber;
539 else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
540 mod |= Parameter.Modifier.CallerFilePath;
541 else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
542 mod |= Parameter.Modifier.CallerMemberName;
544 } else if (value == Missing.Value) {
545 default_value = EmptyExpression.MissingValue;
546 } else if (value == null) {
547 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
548 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
549 default_value = ImportParameterConstant (value);
554 par[i] = new ParameterData (p.Name, mod, default_value);
558 par[par.Length - 1] = new ArglistParameter (Location.Null);
559 types[types.Length - 1] = InternalType.Arglist;
562 return method != null ?
563 new ParametersImported (par, types, varargs != 0, is_params) :
564 new ParametersImported (par, types, is_params);
568 // Returns null when the property is not valid C# property
570 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
573 AParametersCollection param = null;
574 TypeSpec type = null;
577 param = get.Parameters;
578 type = get.ReturnType;
581 bool is_valid_property = true;
583 if (set.ReturnType.Kind != MemberKind.Void)
584 is_valid_property = false;
586 var set_param_count = set.Parameters.Count - 1;
588 if (set_param_count < 0) {
590 is_valid_property = false;
593 var set_type = set.Parameters.Types[set_param_count];
596 AParametersCollection set_based_param;
598 if (set_param_count == 0) {
599 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
602 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
604 var data = new IParameterData[set_param_count];
605 var types = new TypeSpec[set_param_count];
606 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
607 Array.Copy (set.Parameters.Types, types, set_param_count);
608 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
612 param = set_based_param;
615 if (set_param_count != get.Parameters.Count)
616 is_valid_property = false;
618 if (get.ReturnType != set_type)
619 is_valid_property = false;
621 // Possible custom accessor modifiers
622 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
623 var get_acc = mod & Modifiers.AccessibilityMask;
624 if (get_acc != Modifiers.PUBLIC) {
625 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
626 // If the accessor modifiers are not same, do extra restriction checks
627 if (get_acc != set_acc) {
628 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
629 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
630 if (get_restr && set_restr) {
631 is_valid_property = false; // Neither is more restrictive
635 mod &= ~Modifiers.AccessibilityMask;
644 PropertySpec spec = null;
645 if (!param.IsEmpty) {
646 if (is_valid_property) {
647 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
648 if (index_name == null) {
649 is_valid_property = false;
653 is_valid_property = false;
654 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
655 is_valid_property = false;
659 is_valid_property = false;
660 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
661 is_valid_property = false;
665 if (is_valid_property) {
666 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
667 } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
669 // Enables support for properties with parameters (must have default value) of COM-imported types
671 is_valid_property = true;
673 for (int i = 0; i < param.FixedParameters.Length; ++i) {
674 if (!param.FixedParameters[i].HasDefaultValue) {
675 is_valid_property = false;
684 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
686 if (!is_valid_property) {
687 spec.IsNotCSharpCompatible = true;
699 public TypeSpec CreateType (MetaType type)
701 return CreateType (type, new DynamicTypeReader (), true);
704 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
706 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
709 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
711 TypeSpec declaring_type;
712 if (type.IsNested && !type.IsGenericParameter)
713 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
715 declaring_type = null;
717 return CreateType (type, declaring_type, dtype, canImportBaseType);
720 protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
723 if (import_cache.TryGetValue (type, out spec)) {
724 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
725 if (dtype.IsDynamicObject ())
726 return module.Compiler.BuiltinTypes.Dynamic;
731 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
734 if (!dtype.HasDynamicAttribute ())
737 // We've found same object in the cache but this one has a dynamic custom attribute
738 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
739 // Do type resolve process again in that case
741 // TODO: Handle cases where they still unify
744 if (IsMissingType (type)) {
745 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
746 spec.MemberCache = MemberCache.Empty;
747 import_cache.Add (type, spec);
751 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
752 var type_def = type.GetGenericTypeDefinition ();
754 // Generic type definition can also be forwarded
755 if (compiled_types.TryGetValue (type_def, out spec))
758 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
759 if (declaringType == null) {
760 // Simple case, no nesting
761 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
762 spec = spec.MakeGenericType (module, targs);
765 // Nested type case, converting .NET types like
766 // A`1.B`1.C`1<int, long, string> to typespec like
767 // A<int>.B<long>.C<string>
769 var nested_hierarchy = new List<TypeSpec> ();
770 while (declaringType.IsNested) {
771 nested_hierarchy.Add (declaringType);
772 declaringType = declaringType.DeclaringType;
776 if (declaringType.Arity > 0) {
777 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
778 targs_pos = spec.Arity;
780 spec = declaringType;
783 for (int i = nested_hierarchy.Count; i != 0; --i) {
784 var t = nested_hierarchy [i - 1];
785 if (t.Kind == MemberKind.MissingType)
788 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
791 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
792 targs_pos += t.Arity;
796 if (spec.Kind == MemberKind.MissingType) {
797 spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC);
798 spec.MemberCache = MemberCache.Empty;
800 if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
803 string name = type.Name;
804 int index = name.IndexOf ('`');
806 name = name.Substring (0, index);
808 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
810 if (spec.Arity > 0) {
811 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
816 // Don't add generic type with dynamic arguments, they can interfere with same type
817 // using object type arguments
818 if (!spec.HasDynamicElement) {
820 // Add to reading cache to speed up reading
821 if (!import_cache.ContainsKey (type))
822 import_cache.Add (type, spec);
831 var ma = type.Attributes;
832 switch (ma & TypeAttributes.VisibilityMask) {
833 case TypeAttributes.Public:
834 case TypeAttributes.NestedPublic:
835 mod = Modifiers.PUBLIC;
837 case TypeAttributes.NestedPrivate:
838 mod = Modifiers.PRIVATE;
840 case TypeAttributes.NestedFamily:
841 mod = Modifiers.PROTECTED;
843 case TypeAttributes.NestedFamORAssem:
844 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
847 mod = Modifiers.INTERNAL;
851 if ((ma & TypeAttributes.Interface) != 0) {
852 kind = MemberKind.Interface;
853 } else if (type.IsGenericParameter) {
854 kind = MemberKind.TypeParameter;
856 var base_type = type.BaseType;
857 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
858 kind = MemberKind.Class;
860 kind = DetermineKindFromBaseType (base_type);
861 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
862 mod |= Modifiers.SEALED;
866 if (kind == MemberKind.Class) {
867 if ((ma & TypeAttributes.Sealed) != 0) {
868 if ((ma & TypeAttributes.Abstract) != 0)
869 mod |= Modifiers.STATIC;
871 mod |= Modifiers.SEALED;
872 } else if ((ma & TypeAttributes.Abstract) != 0) {
873 mod |= Modifiers.ABSTRACT;
878 var definition = new ImportedTypeDefinition (type, this);
881 if (kind == MemberKind.Enum) {
882 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
883 BindingFlags.Instance |
884 BindingFlags.Public | BindingFlags.NonPublic;
886 var type_members = type.GetFields (underlying_member);
887 foreach (var type_member in type_members) {
888 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
893 kind = MemberKind.Class;
895 } else if (kind == MemberKind.TypeParameter) {
896 spec = CreateTypeParameter (type, declaringType);
897 } else if (type.IsGenericTypeDefinition) {
898 definition.TypeParameters = CreateGenericParameters (type, declaringType);
899 } else if (compiled_types.TryGetValue (type, out pt)) {
901 // Same type was found in inside compiled types. It's
902 // either build-in type or forward referenced typed
903 // which point into just compiled assembly.
906 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
908 bts.SetDefinition (definition, type, mod);
912 spec = new TypeSpec (kind, declaringType, definition, type, mod);
914 import_cache.Add (type, spec);
916 if (kind == MemberKind.TypeParameter) {
917 if (canImportBaseType)
918 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
924 // Two stage setup as the base type can be inflated declaring type or
925 // another nested type inside same declaring type which has not been
926 // loaded, therefore we can import a base type of nested types once
927 // the types have been imported
929 if (canImportBaseType)
930 ImportTypeBase (spec, type);
935 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
937 IAssemblyDefinition found;
938 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
940 // This can happen in dynamic context only
941 var def = new ImportedAssemblyDefinition (assembly);
942 assembly_2_definition.Add (assembly, def);
943 def.ReadAttributes ();
950 public void ImportTypeBase (MetaType type)
952 TypeSpec spec = import_cache[type];
954 ImportTypeBase (spec, type);
957 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
960 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
961 case GenericParameterAttributes.Covariant:
962 variance = Variance.Covariant;
964 case GenericParameterAttributes.Contravariant:
965 variance = Variance.Contravariant;
968 variance = Variance.None;
972 SpecialConstraint special = SpecialConstraint.None;
973 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
975 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
976 special |= SpecialConstraint.Struct;
977 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
978 special = SpecialConstraint.Constructor;
981 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
982 special |= SpecialConstraint.Class;
985 TypeParameterSpec spec;
986 var def = new ImportedTypeParameterDefinition (type, this);
987 if (type.DeclaringMethod != null) {
988 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
990 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
997 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
998 // they can be assembly specific therefore we do check based on names only
1000 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
1002 if (attributesData.Count == 0)
1005 foreach (var attr in attributesData) {
1006 var dt = attr.Constructor.DeclaringType;
1007 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1014 void ImportTypeBase (TypeSpec spec, MetaType type)
1016 if (spec.Kind == MemberKind.Interface)
1017 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1018 else if (type.BaseType != null) {
1020 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1021 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1023 base_type = CreateType (type.BaseType);
1025 spec.BaseType = base_type;
1028 if (spec.MemberDefinition.TypeParametersCount > 0) {
1029 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1030 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1035 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1037 Namespace ns = targetNamespace;
1038 string prev_namespace = null;
1039 foreach (var t in types) {
1043 // Be careful not to trigger full parent type loading
1044 if (t.MemberType == MemberTypes.NestedType)
1047 if (t.Name[0] == '<')
1050 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1054 if (prev_namespace != t.Namespace) {
1055 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1056 prev_namespace = t.Namespace;
1059 // Cannot rely on assembly level Extension attribute or static modifier because they
1060 // are not followed by other compilers (e.g. F#).
1061 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1062 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1063 it.SetExtensionMethodContainer ();
1066 ns.AddType (module, it);
1070 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1072 var constraints = type.GetGenericParameterConstraints ();
1073 List<TypeSpec> tparams = null;
1074 foreach (var ct in constraints) {
1075 if (ct.IsGenericParameter) {
1076 if (tparams == null)
1077 tparams = new List<TypeSpec> ();
1079 tparams.Add (CreateType (ct));
1083 var constraint_type = CreateType (ct);
1084 if (constraint_type.IsClass) {
1085 spec.BaseType = constraint_type;
1089 spec.AddInterface (constraint_type);
1092 if (spec.BaseType == null)
1093 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1095 if (tparams != null)
1096 spec.TypeArguments = tparams.ToArray ();
1099 Constant ImportParameterConstant (object value)
1102 // Get type of underlying value as int constant can be used for object
1103 // parameter type. This is not allowed in C# but other languages can do that
1105 var types = module.Compiler.BuiltinTypes;
1106 switch (System.Type.GetTypeCode (value.GetType ())) {
1107 case TypeCode.Boolean:
1108 return new BoolConstant (types, (bool) value, Location.Null);
1110 return new ByteConstant (types, (byte) value, Location.Null);
1112 return new CharConstant (types, (char) value, Location.Null);
1113 case TypeCode.Decimal:
1114 return new DecimalConstant (types, (decimal) value, Location.Null);
1115 case TypeCode.Double:
1116 return new DoubleConstant (types, (double) value, Location.Null);
1117 case TypeCode.Int16:
1118 return new ShortConstant (types, (short) value, Location.Null);
1119 case TypeCode.Int32:
1120 return new IntConstant (types, (int) value, Location.Null);
1121 case TypeCode.Int64:
1122 return new LongConstant (types, (long) value, Location.Null);
1123 case TypeCode.SByte:
1124 return new SByteConstant (types, (sbyte) value, Location.Null);
1125 case TypeCode.Single:
1126 return new FloatConstant (types, (float) value, Location.Null);
1127 case TypeCode.String:
1128 return new StringConstant (types, (string) value, Location.Null);
1129 case TypeCode.UInt16:
1130 return new UShortConstant (types, (ushort) value, Location.Null);
1131 case TypeCode.UInt32:
1132 return new UIntConstant (types, (uint) value, Location.Null);
1133 case TypeCode.UInt64:
1134 return new ULongConstant (types, (ulong) value, Location.Null);
1137 throw new NotImplementedException (value.GetType ().ToString ());
1140 public TypeSpec ImportType (MetaType type)
1142 return ImportType (type, new DynamicTypeReader (type));
1145 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1147 if (type.HasElementType) {
1148 var element = type.GetElementType ();
1150 var spec = ImportType (element, dtype);
1153 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1155 return ReferenceContainer.MakeType (module, spec);
1157 return PointerContainer.MakeType (module, spec);
1159 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1162 TypeSpec compiled_type;
1163 if (compiled_types.TryGetValue (type, out compiled_type)) {
1164 if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
1165 return module.Compiler.BuiltinTypes.Dynamic;
1167 return compiled_type;
1170 return CreateType (type, dtype, true);
1173 static bool IsMissingType (MetaType type)
1176 return type.__IsMissing;
1183 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1184 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1185 // DecimalConstantAttribute metadata.
1187 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1189 if (attrs.Count == 0)
1192 foreach (var ca in attrs) {
1193 var dt = ca.Constructor.DeclaringType;
1194 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1197 var value = new decimal (
1198 (int) (uint) ca.ConstructorArguments[4].Value,
1199 (int) (uint) ca.ConstructorArguments[3].Value,
1200 (int) (uint) ca.ConstructorArguments[2].Value,
1201 (byte) ca.ConstructorArguments[1].Value != 0,
1202 (byte) ca.ConstructorArguments[0].Value);
1204 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1210 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1213 var ma = mb.Attributes;
1214 switch (ma & MethodAttributes.MemberAccessMask) {
1215 case MethodAttributes.Public:
1216 mod = Modifiers.PUBLIC;
1218 case MethodAttributes.Assembly:
1219 mod = Modifiers.INTERNAL;
1221 case MethodAttributes.Family:
1222 mod = Modifiers.PROTECTED;
1224 case MethodAttributes.FamORAssem:
1225 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1228 mod = Modifiers.PRIVATE;
1232 if ((ma & MethodAttributes.Static) != 0) {
1233 mod |= Modifiers.STATIC;
1236 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1237 mod |= Modifiers.ABSTRACT;
1241 // It can be sealed and override
1242 if ((ma & MethodAttributes.Final) != 0)
1243 mod |= Modifiers.SEALED;
1245 if ((ma & MethodAttributes.Virtual) != 0) {
1246 // Not every member can be detected based on MethodAttribute, we
1247 // set virtual or non-virtual only when we are certain. Further checks
1248 // to really find out what `virtual' means for this member are done
1250 if ((ma & MethodAttributes.NewSlot) != 0) {
1251 if ((mod & Modifiers.SEALED) != 0) {
1252 mod &= ~Modifiers.SEALED;
1254 mod |= Modifiers.VIRTUAL;
1257 mod |= Modifiers.OVERRIDE;
1265 abstract class ImportedDefinition : IMemberDefinition
1267 protected class AttributesBag
1269 public static readonly AttributesBag Default = new AttributesBag ();
1271 public AttributeUsageAttribute AttributeUsage;
1272 public ObsoleteAttribute Obsolete;
1273 public string[] Conditionals;
1274 public string DefaultIndexerName;
1275 public bool? CLSAttributeValue;
1276 public TypeSpec CoClass;
1278 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1280 AttributesBag bag = null;
1281 List<string> conditionals = null;
1283 // It should not throw any loading exception
1284 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1286 foreach (var a in attrs) {
1287 var dt = a.Constructor.DeclaringType;
1288 string name = dt.Name;
1289 if (name == "ObsoleteAttribute") {
1290 if (dt.Namespace != "System")
1294 bag = new AttributesBag ();
1296 var args = a.ConstructorArguments;
1298 if (args.Count == 1) {
1299 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1300 } else if (args.Count == 2) {
1301 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1303 bag.Obsolete = new ObsoleteAttribute ();
1309 if (name == "ConditionalAttribute") {
1310 if (dt.Namespace != "System.Diagnostics")
1314 bag = new AttributesBag ();
1316 if (conditionals == null)
1317 conditionals = new List<string> (2);
1319 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1323 if (name == "CLSCompliantAttribute") {
1324 if (dt.Namespace != "System")
1328 bag = new AttributesBag ();
1330 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1334 // Type only attributes
1335 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1336 if (name == "DefaultMemberAttribute") {
1337 if (dt.Namespace != "System.Reflection")
1341 bag = new AttributesBag ();
1343 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1347 if (name == "AttributeUsageAttribute") {
1348 if (dt.Namespace != "System")
1352 bag = new AttributesBag ();
1354 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1355 foreach (var named in a.NamedArguments) {
1356 if (named.MemberInfo.Name == "AllowMultiple")
1357 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1358 else if (named.MemberInfo.Name == "Inherited")
1359 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1364 // Interface only attribute
1365 if (name == "CoClassAttribute") {
1366 if (dt.Namespace != "System.Runtime.InteropServices")
1370 bag = new AttributesBag ();
1372 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1381 if (conditionals != null)
1382 bag.Conditionals = conditionals.ToArray ();
1388 protected readonly MemberInfo provider;
1389 protected AttributesBag cattrs;
1390 protected readonly MetadataImporter importer;
1392 protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1394 this.provider = provider;
1395 this.importer = importer;
1400 public bool IsImported {
1406 public virtual string Name {
1408 return provider.Name;
1414 public string[] ConditionalConditions ()
1419 return cattrs.Conditionals;
1422 public ObsoleteAttribute GetAttributeObsolete ()
1427 return cattrs.Obsolete;
1430 public bool? CLSAttributeValue {
1435 return cattrs.CLSAttributeValue;
1439 protected void ReadAttributes ()
1441 cattrs = AttributesBag.Read (provider, importer);
1444 public void SetIsAssigned ()
1446 // Unused for imported members
1449 public void SetIsUsed ()
1451 // Unused for imported members
1455 public class ImportedModuleDefinition
1457 readonly Module module;
1460 public ImportedModuleDefinition (Module module)
1462 this.module = module;
1467 public bool IsCLSCompliant {
1469 return cls_compliant;
1473 public string Name {
1481 public void ReadAttributes ()
1483 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1485 foreach (var a in attrs) {
1486 var dt = a.Constructor.DeclaringType;
1487 if (dt.Name == "CLSCompliantAttribute") {
1488 if (dt.Namespace != "System")
1491 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1498 // Reads assembly attributes which where attached to a special type because
1499 // module does have assembly manifest
1501 public List<Attribute> ReadAssemblyAttributes ()
1503 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1507 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1511 // TODO: implement, the idea is to fabricate specil Attribute class and
1512 // add it to OptAttributes before resolving the source code attributes
1513 // Need to build module location as well for correct error reporting
1515 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1516 //var attrs = new List<Attribute> (assembly_attributes.Count);
1517 //foreach (var a in assembly_attributes)
1519 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1520 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1522 // foreach (var carg in a.ConstructorArguments) {
1526 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1533 public class ImportedAssemblyDefinition : IAssemblyDefinition
1535 readonly Assembly assembly;
1536 readonly AssemblyName aname;
1539 List<AssemblyName> internals_visible_to;
1540 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1542 public ImportedAssemblyDefinition (Assembly assembly)
1544 this.assembly = assembly;
1545 this.aname = assembly.GetName ();
1550 public Assembly Assembly {
1556 public string FullName {
1558 return aname.FullName;
1562 public bool HasStrongName {
1564 return aname.GetPublicKey ().Length != 0;
1568 public bool IsMissing {
1571 return assembly.__IsMissing;
1578 public bool IsCLSCompliant {
1580 return cls_compliant;
1584 public string Location {
1586 return assembly.Location;
1590 public string Name {
1598 public byte[] GetPublicKeyToken ()
1600 return aname.GetPublicKeyToken ();
1603 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1605 return internals_visible_to_cache [assembly];
1608 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1610 if (internals_visible_to == null)
1613 AssemblyName is_visible = null;
1614 if (internals_visible_to_cache == null) {
1615 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1617 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1618 return is_visible != null;
1621 var token = assembly.GetPublicKeyToken ();
1622 if (token != null && token.Length == 0)
1625 foreach (var internals in internals_visible_to) {
1626 if (internals.Name != assembly.Name)
1629 if (token == null && assembly is AssemblyDefinition) {
1630 is_visible = internals;
1634 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1637 is_visible = internals;
1641 internals_visible_to_cache.Add (assembly, is_visible);
1642 return is_visible != null;
1645 public void ReadAttributes ()
1648 if (assembly.__IsMissing)
1652 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1654 foreach (var a in attrs) {
1655 var dt = a.Constructor.DeclaringType;
1657 if (name == "CLSCompliantAttribute") {
1658 if (dt.Namespace == "System") {
1659 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1664 if (name == "InternalsVisibleToAttribute") {
1665 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1668 string s = a.ConstructorArguments[0].Value as string;
1672 var an = new AssemblyName (s);
1673 if (internals_visible_to == null)
1674 internals_visible_to = new List<AssemblyName> ();
1676 internals_visible_to.Add (an);
1682 public override string ToString ()
1688 class ImportedMemberDefinition : ImportedDefinition
1690 readonly TypeSpec type;
1692 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1693 : base (member, importer)
1700 public TypeSpec MemberType {
1709 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1711 readonly AParametersCollection parameters;
1713 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1714 : base (provider, type, importer)
1716 this.parameters = parameters;
1719 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1720 : base (provider, type, importer)
1722 this.parameters = parameters;
1727 public AParametersCollection Parameters {
1736 class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1738 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1739 : base (provider, type, parameters, importer)
1743 MethodBase IMethodDefinition.Metadata {
1745 return (MethodBase) provider;
1750 class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1752 readonly TypeParameterSpec[] tparams;
1754 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1755 : base (provider, type, parameters, importer)
1757 this.tparams = tparams;
1762 public TypeParameterSpec[] TypeParameters {
1768 public int TypeParametersCount {
1770 return tparams.Length;
1777 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1779 TypeParameterSpec[] tparams;
1782 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1783 : base (type, importer)
1789 public IAssemblyDefinition DeclaringAssembly {
1791 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1795 bool ITypeDefinition.IsComImport {
1797 return ((MetaType) provider).IsImport;
1802 bool ITypeDefinition.IsPartial {
1808 bool ITypeDefinition.IsTypeForwarder {
1811 return ((MetaType) provider).__IsTypeForwarder;
1818 bool ITypeDefinition.IsCyclicTypeForwarder {
1821 return ((MetaType) provider).__IsCyclicTypeForwarder;
1828 public override string Name {
1832 if (tparams != null) {
1833 int arity_start = name.IndexOf ('`');
1834 if (arity_start > 0)
1835 name = name.Substring (0, arity_start);
1843 public string Namespace {
1845 return ((MetaType) provider).Namespace;
1849 public int TypeParametersCount {
1851 return tparams == null ? 0 : tparams.Length;
1855 public TypeParameterSpec[] TypeParameters {
1866 public void DefineInterfaces (TypeSpec spec)
1868 var type = (MetaType) provider;
1871 ifaces = type.__GetDeclaredInterfaces ();
1872 if (ifaces.Length != 0) {
1873 foreach (var iface in ifaces) {
1874 var it = importer.CreateType (iface);
1878 spec.AddInterfaceDefined (it);
1880 // Unfortunately not all languages expand inherited interfaces
1881 var bifaces = it.Interfaces;
1882 if (bifaces != null) {
1883 foreach (var biface in bifaces) {
1884 spec.AddInterfaceDefined (biface);
1891 // It's impossible to get declared interfaces only using System.Reflection
1892 // hence we need to mimic the behavior with ikvm-reflection too to keep
1893 // our type look-up logic same
1895 if (spec.BaseType != null) {
1896 var bifaces = spec.BaseType.Interfaces;
1897 if (bifaces != null) {
1899 // Before adding base class interfaces close defined interfaces
1900 // on type parameter
1902 var tp = spec as TypeParameterSpec;
1903 if (tp != null && tp.InterfacesDefined == null) {
1904 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1907 foreach (var iface in bifaces)
1908 spec.AddInterfaceDefined (iface);
1912 ifaces = type.GetInterfaces ();
1914 if (ifaces.Length > 0) {
1915 foreach (var iface in ifaces) {
1916 spec.AddInterface (importer.CreateType (iface));
1923 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
1926 // Report details about missing type and most likely cause of the problem.
1927 // csc reports 1683, 1684 as warnings but we report them only when used
1928 // or referenced from the user core in which case compilation error has to
1929 // be reported because compiler cannot continue anyway
1932 var report = ctx.Module.Compiler.Report;
1934 for (int i = 0; i < missing.Count; ++i) {
1935 var t = missing [i].Type;
1938 // Report missing types only once
1940 if (report.Printer.MissingTypeReported (t.MemberDefinition))
1943 string name = t.GetSignatureForError ();
1945 var caller = missing[i].Caller;
1946 if (caller.Kind != MemberKind.MissingType)
1947 report.SymbolRelatedToPreviousError (caller);
1949 var definition = t.MemberDefinition;
1950 if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1951 report.Error (1683, loc,
1952 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1954 } else if (definition.DeclaringAssembly.IsMissing) {
1955 if (definition.IsTypeForwarder) {
1956 report.Error (1070, loc,
1957 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1958 name, definition.DeclaringAssembly.FullName);
1960 report.Error (12, loc,
1961 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1962 name, definition.DeclaringAssembly.FullName);
1964 } else if (definition.IsTypeForwarder) {
1965 report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
1966 name, definition.DeclaringAssembly.FullName);
1968 report.Error (1684, loc,
1969 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1970 name, t.MemberDefinition.DeclaringAssembly.FullName);
1975 public TypeSpec GetAttributeCoClass ()
1980 return cattrs.CoClass;
1983 public string GetAttributeDefaultMember ()
1988 return cattrs.DefaultIndexerName;
1991 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1996 return cattrs.AttributeUsage;
1999 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2001 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
2002 return a == assembly || a.IsFriendAssemblyTo (assembly);
2005 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2008 // Not interested in members of nested private types unless the importer needs them
2010 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
2011 cache = MemberCache.Empty;
2015 var loading_type = (MetaType) provider;
2016 const BindingFlags all_members = BindingFlags.DeclaredOnly |
2017 BindingFlags.Static | BindingFlags.Instance |
2018 BindingFlags.Public | BindingFlags.NonPublic;
2020 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
2021 MethodAttributes.Virtual | MethodAttributes.HideBySig |
2022 MethodAttributes.Final;
2024 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
2025 List<EventSpec> imported_events = null;
2026 EventSpec event_spec;
2027 MemberSpec imported;
2031 all = loading_type.GetMembers (all_members);
2032 } catch (Exception e) {
2033 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2034 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2037 if (cache == null) {
2038 cache = new MemberCache (all.Length);
2041 // Do the types first as they can be referenced by the members before
2042 // they are found or inflated
2044 foreach (var member in all) {
2045 if (member.MemberType != MemberTypes.NestedType)
2048 var t = (MetaType) member;
2050 // Ignore compiler generated types, mostly lambda containers
2051 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2055 imported = importer.CreateNestedType (t, declaringType);
2056 } catch (Exception e) {
2057 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2058 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2061 cache.AddMemberImported (imported);
2064 foreach (var member in all) {
2065 if (member.MemberType != MemberTypes.NestedType)
2068 var t = (MetaType) member;
2070 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2073 importer.ImportTypeBase (t);
2078 // Load base interfaces first to minic behaviour of compiled members
2080 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2081 foreach (var iface in declaringType.Interfaces) {
2082 cache.AddInterface (iface);
2088 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2090 foreach (var member in all) {
2091 switch (member.MemberType) {
2092 case MemberTypes.Constructor:
2093 if (declaringType.IsInterface)
2096 goto case MemberTypes.Method;
2097 case MemberTypes.Method:
2098 MethodBase mb = (MethodBase) member;
2099 var attrs = mb.Attributes;
2101 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2102 if (importer.IgnorePrivateMembers)
2105 // Ignore explicitly implemented members
2106 if ((attrs & explicit_impl) == explicit_impl)
2109 // Ignore compiler generated methods
2110 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2114 imported = importer.CreateMethod (mb, declaringType);
2115 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2116 if (possible_accessors == null)
2117 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2119 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2120 possible_accessors.Add (mb, (MethodSpec) imported);
2124 case MemberTypes.Property:
2125 if (possible_accessors == null)
2128 var p = (PropertyInfo) member;
2130 // Links possible accessors with property
2132 MethodSpec get, set;
2133 m = p.GetGetMethod (true);
2134 if (m == null || !possible_accessors.TryGetValue (m, out get))
2137 m = p.GetSetMethod (true);
2138 if (m == null || !possible_accessors.TryGetValue (m, out set))
2141 // No accessors registered (e.g. explicit implementation)
2142 if (get == null && set == null)
2146 imported = importer.CreateProperty (p, declaringType, get, set);
2147 } catch (Exception ex) {
2148 throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2149 p.Name, declaringType.GetSignatureForError ());
2152 if (imported == null)
2156 case MemberTypes.Event:
2157 if (possible_accessors == null)
2160 var e = (EventInfo) member;
2162 // Links accessors with event
2164 MethodSpec add, remove;
2165 m = e.GetAddMethod (true);
2166 if (m == null || !possible_accessors.TryGetValue (m, out add))
2169 m = e.GetRemoveMethod (true);
2170 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2173 // Both accessors are required
2174 if (add == null || remove == null)
2177 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2178 if (!importer.IgnorePrivateMembers) {
2179 if (imported_events == null)
2180 imported_events = new List<EventSpec> ();
2182 imported_events.Add (event_spec);
2185 imported = event_spec;
2187 case MemberTypes.Field:
2188 var fi = (FieldInfo) member;
2190 imported = importer.CreateField (fi, declaringType);
2191 if (imported == null)
2195 // For dynamic binder event has to be fully restored to allow operations
2196 // within the type container to work correctly
2198 if (imported_events != null) {
2199 // The backing event field should be private but it may not
2201 for (i = 0; i < imported_events.Count; ++i) {
2202 var ev = imported_events[i];
2203 if (ev.Name == fi.Name) {
2204 ev.BackingField = (FieldSpec) imported;
2205 imported_events.RemoveAt (i);
2216 case MemberTypes.NestedType:
2217 // Already in the cache from the first pass
2220 throw new NotImplementedException (member.ToString ());
2223 if (imported.IsStatic && declaringType.IsInterface)
2226 cache.AddMemberImported (imported);
2232 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2234 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2235 : base (type, importer)
2241 public IAssemblyDefinition DeclaringAssembly {
2243 throw new NotImplementedException ();
2247 bool ITypeDefinition.IsComImport {
2253 bool ITypeDefinition.IsPartial {
2259 bool ITypeDefinition.IsTypeForwarder {
2265 bool ITypeDefinition.IsCyclicTypeForwarder {
2271 public string Namespace {
2277 public int TypeParametersCount {
2283 public TypeParameterSpec[] TypeParameters {
2291 public TypeSpec GetAttributeCoClass ()
2296 public string GetAttributeDefaultMember ()
2298 throw new NotSupportedException ();
2301 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2303 throw new NotSupportedException ();
2306 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2308 throw new NotImplementedException ();
2311 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2313 throw new NotImplementedException ();