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 (MetadataImporter importer)
62 ReadAttribute (importer);
64 return flags != null && Position < flags.Length && flags[Position];
68 // Returns true when DynamicAttribute exists
70 public bool HasDynamicAttribute (MetadataImporter importer)
73 ReadAttribute (importer);
78 void ReadAttribute (MetadataImporter importer)
80 IList<CustomAttributeData> cad;
81 if (provider is MemberInfo) {
82 cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
83 } else if (provider is ParameterInfo) {
84 cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
91 foreach (var ca in cad) {
92 var dt = ca.Constructor.DeclaringType;
93 if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace)
96 if (ca.ConstructorArguments.Count == 0) {
97 flags = single_attribute;
101 var arg_type = ca.ConstructorArguments[0].ArgumentType;
103 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
104 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
105 flags = new bool[carg.Count];
106 for (int i = 0; i < flags.Length; ++i) {
107 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
108 flags[i] = (bool) carg[i].Value;
120 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
121 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
122 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
123 protected readonly ModuleContainer module;
125 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
127 protected MetadataImporter (ModuleContainer module)
129 this.module = module;
131 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
132 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
133 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
134 IgnorePrivateMembers = true;
139 public ICollection<IAssemblyDefinition> Assemblies {
141 return assembly_2_definition.Values;
145 public bool IgnorePrivateMembers { get; set; }
149 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
150 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
151 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
153 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
156 var fa = fi.Attributes;
157 switch (fa & FieldAttributes.FieldAccessMask) {
158 case FieldAttributes.Public:
159 mod = Modifiers.PUBLIC;
161 case FieldAttributes.Assembly:
162 mod = Modifiers.INTERNAL;
164 case FieldAttributes.Family:
165 mod = Modifiers.PROTECTED;
167 case FieldAttributes.FamORAssem:
168 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
171 // Ignore private fields (even for error reporting) to not require extra dependencies
172 if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
173 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
176 mod = Modifiers.PRIVATE;
183 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
184 } catch (Exception e) {
185 // TODO: I should construct fake TypeSpec based on TypeRef signature
186 // but there is no way to do it with System.Reflection
187 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
188 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
191 var definition = new ImportedMemberDefinition (fi, field_type, this);
193 if ((fa & FieldAttributes.Literal) != 0) {
194 Constant c = field_type.Kind == MemberKind.MissingType ?
195 new NullConstant (InternalType.ErrorType, Location.Null) :
196 Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
197 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
200 if ((fa & FieldAttributes.InitOnly) != 0) {
201 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
202 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
204 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
207 mod |= Modifiers.READONLY;
209 var req_mod = fi.GetRequiredCustomModifiers ();
210 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
211 mod |= Modifiers.VOLATILE;
214 if ((fa & FieldAttributes.Static) != 0) {
215 mod |= Modifiers.STATIC;
217 // Fixed buffers cannot be static
218 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
219 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
221 // TODO: Sanity check on field_type (only few types are allowed)
222 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
223 return new FixedFieldSpec (declaringType, definition, fi, element_field, mod);
227 return new FieldSpec (declaringType, definition, field_type, fi, mod);
230 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
232 add.IsAccessor = true;
233 remove.IsAccessor = true;
235 if (add.Modifiers != remove.Modifiers)
236 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
238 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
239 var definition = new ImportedMemberDefinition (ei, event_type, this);
240 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
243 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
245 var tparams = type.GetGenericArguments ();
247 int parent_owned_count;
249 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
252 // System.Reflection duplicates parent type parameters for each
253 // nested type with slightly modified properties (eg. different owner)
254 // This just makes things more complicated (think of cloned constraints)
255 // therefore we remap any nested type owned by parent using `type_cache'
256 // to the single TypeParameterSpec
258 if (declaringType != null && parent_owned_count > 0) {
260 while (read_count != parent_owned_count) {
261 var tparams_count = declaringType.Arity;
262 if (tparams_count != 0) {
263 var parent_tp = declaringType.MemberDefinition.TypeParameters;
264 read_count += tparams_count;
265 for (int i = 0; i < tparams_count; i++) {
266 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
270 declaringType = declaringType.DeclaringType;
274 parent_owned_count = 0;
277 if (tparams.Length - parent_owned_count == 0)
280 return CreateGenericParameters (parent_owned_count, tparams);
283 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
285 var tspec = new TypeParameterSpec[tparams.Length - first];
286 for (int pos = first; pos < tparams.Length; ++pos) {
287 var type = tparams[pos];
288 int index = pos - first;
290 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
296 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
300 var tspec = new TypeSpec [tparams.Length - first];
301 for (int pos = first; pos < tparams.Length; ++pos) {
302 var type = tparams[pos];
303 int index = pos - first;
306 if (type.HasElementType) {
307 var element = type.GetElementType ();
309 spec = ImportType (element, dtype);
312 throw new NotImplementedException ("Unknown element type " + type.ToString ());
315 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
317 spec = CreateType (type, dtype, true);
320 // We treat nested generic types as inflated internally where
321 // reflection uses type definition
324 // IFoo<A<T>> foo; // A<T> is definition in this case
327 // TODO: Is full logic from CreateType needed here as well?
329 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
330 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
331 spec = spec.MakeGenericType (module, targs);
342 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
344 Modifiers mod = ReadMethodModifiers (mb, declaringType);
345 TypeParameterSpec[] tparams;
347 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
349 if (mb.IsGenericMethod) {
350 if (!mb.IsGenericMethodDefinition)
351 throw new NotSupportedException ("assert");
353 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
360 if (mb.MemberType == MemberTypes.Constructor) {
361 kind = MemberKind.Constructor;
362 returnType = module.Compiler.BuiltinTypes.Void;
365 // Detect operators and destructors
367 string name = mb.Name;
368 kind = MemberKind.Method;
369 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
370 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
371 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
372 var op_type = Operator.GetType (name);
373 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
374 kind = MemberKind.Operator;
377 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
378 kind = MemberKind.Destructor;
379 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
380 mod &= ~Modifiers.OVERRIDE;
381 mod |= Modifiers.VIRTUAL;
386 var mi = (MethodInfo) mb;
387 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
389 // Cannot set to OVERRIDE without full hierarchy checks
390 // this flag indicates that the method could be override
391 // but further validation is needed
392 if ((mod & Modifiers.OVERRIDE) != 0) {
393 bool is_real_override = false;
394 if (kind == MemberKind.Method && declaringType.BaseType != null) {
395 var btype = declaringType.BaseType;
396 if (IsOverrideMethodBaseTypeAccessible (btype)) {
397 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
398 var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
401 // For imported class method do additional validation to be sure that metadata
402 // override flag was correct
404 // Difference between protected internal and protected is ok
406 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
407 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
408 is_real_override = true;
413 if (!is_real_override) {
414 mod &= ~Modifiers.OVERRIDE;
415 if ((mod & Modifiers.SEALED) != 0)
416 mod &= ~Modifiers.SEALED;
418 mod |= Modifiers.VIRTUAL;
423 IMemberDefinition definition;
424 if (tparams != null) {
425 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
426 foreach (var tp in gmd.TypeParameters) {
427 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
432 definition = new ImportedParameterMemberDefinition (mb, returnType, parameters, this);
435 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, mb, parameters, mod);
442 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
444 switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
445 case Modifiers.PUBLIC:
447 case Modifiers.INTERNAL:
449 // Check whether imported method in base type is accessible from compiled
452 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
453 case Modifiers.PRIVATE:
457 // protected internal
459 // Method accessibility checks will be done later based on context
460 // where the method is called (CS0122 error will be reported for inaccessible)
467 // Imports System.Reflection parameters
469 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
471 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
473 if (pi.Length == 0 && varargs == 0)
474 return ParametersCompiled.EmptyReadOnlyParameters;
476 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
477 IParameterData[] par = new IParameterData[pi.Length + varargs];
478 bool is_params = false;
479 for (int i = 0; i < pi.Length; i++) {
480 ParameterInfo p = pi[i];
481 Parameter.Modifier mod = 0;
482 Expression default_value = null;
483 if (p.ParameterType.IsByRef) {
484 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
485 mod = Parameter.Modifier.OUT;
487 mod = Parameter.Modifier.REF;
490 // Strip reference wrapping
492 var el = p.ParameterType.GetElementType ();
493 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
494 } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
495 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
496 mod = Parameter.Modifier.This;
497 types[i] = ImportType (p.ParameterType);
499 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
501 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
502 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
503 mod = Parameter.Modifier.PARAMS;
508 if (!is_params && p.IsOptional) {
509 object value = p.RawDefaultValue;
510 var ptype = types[i];
511 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
513 default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
515 default_value = ImportParameterConstant (value);
518 default_value = new EnumConstant ((Constant) default_value, ptype);
522 var attrs = CustomAttributeData.GetCustomAttributes (p);
523 for (int ii = 0; ii < attrs.Count; ++ii) {
524 var attr = attrs[ii];
525 var dt = attr.Constructor.DeclaringType;
526 if (dt.Namespace != CompilerServicesNamespace)
529 if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
530 mod |= Parameter.Modifier.CallerLineNumber;
531 else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
532 mod |= Parameter.Modifier.CallerFilePath;
533 else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
534 mod |= Parameter.Modifier.CallerMemberName;
536 } else if (value == Missing.Value) {
537 default_value = EmptyExpression.MissingValue;
538 } else if (value == null) {
539 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
540 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
541 default_value = ImportParameterConstant (value);
546 par[i] = new ParameterData (p.Name, mod, default_value);
550 par[par.Length - 1] = new ArglistParameter (Location.Null);
551 types[types.Length - 1] = InternalType.Arglist;
554 return method != null ?
555 new ParametersImported (par, types, varargs != 0, is_params) :
556 new ParametersImported (par, types, is_params);
560 // Returns null when the property is not valid C# property
562 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
565 AParametersCollection param = null;
566 TypeSpec type = null;
569 param = get.Parameters;
570 type = get.ReturnType;
573 bool is_valid_property = true;
575 if (set.ReturnType.Kind != MemberKind.Void)
576 is_valid_property = false;
578 var set_param_count = set.Parameters.Count - 1;
580 if (set_param_count < 0) {
582 is_valid_property = false;
585 var set_type = set.Parameters.Types[set_param_count];
588 AParametersCollection set_based_param;
590 if (set_param_count == 0) {
591 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
594 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
596 var data = new IParameterData[set_param_count];
597 var types = new TypeSpec[set_param_count];
598 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
599 Array.Copy (set.Parameters.Types, types, set_param_count);
600 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
604 param = set_based_param;
607 if (set_param_count != get.Parameters.Count)
608 is_valid_property = false;
610 if (get.ReturnType != set_type)
611 is_valid_property = false;
613 // Possible custom accessor modifiers
614 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
615 var get_acc = mod & Modifiers.AccessibilityMask;
616 if (get_acc != Modifiers.PUBLIC) {
617 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
618 // If the accessor modifiers are not same, do extra restriction checks
619 if (get_acc != set_acc) {
620 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
621 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
622 if (get_restr && set_restr) {
623 is_valid_property = false; // Neither is more restrictive
627 mod &= ~Modifiers.AccessibilityMask;
636 PropertySpec spec = null;
637 if (!param.IsEmpty) {
638 if (is_valid_property) {
639 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
640 if (index_name == null) {
641 is_valid_property = false;
645 is_valid_property = false;
646 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
647 is_valid_property = false;
651 is_valid_property = false;
652 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
653 is_valid_property = false;
657 if (is_valid_property) {
658 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
659 } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
661 // Enables support for properties with parameters (must have default value) of COM-imported types
663 is_valid_property = true;
665 for (int i = 0; i < param.FixedParameters.Length; ++i) {
666 if (!param.FixedParameters[i].HasDefaultValue) {
667 is_valid_property = false;
676 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
678 if (!is_valid_property) {
679 spec.IsNotCSharpCompatible = true;
691 public TypeSpec CreateType (MetaType type)
693 return CreateType (type, new DynamicTypeReader (), true);
696 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
698 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
701 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
703 TypeSpec declaring_type;
704 if (type.IsNested && !type.IsGenericParameter)
705 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
707 declaring_type = null;
709 return CreateType (type, declaring_type, dtype, canImportBaseType);
712 protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
715 if (import_cache.TryGetValue (type, out spec)) {
716 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
717 if (dtype.IsDynamicObject (this))
718 return module.Compiler.BuiltinTypes.Dynamic;
723 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
726 if (!dtype.HasDynamicAttribute (this))
729 // We've found same object in the cache but this one has a dynamic custom attribute
730 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
731 // Do type resolve process again in that case
733 // TODO: Handle cases where they still unify
736 if (IsMissingType (type)) {
737 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
738 spec.MemberCache = MemberCache.Empty;
739 import_cache.Add (type, spec);
743 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
744 var type_def = type.GetGenericTypeDefinition ();
746 // Generic type definition can also be forwarded
747 if (compiled_types.TryGetValue (type_def, out spec))
750 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
751 if (declaringType == null) {
752 // Simple case, no nesting
753 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
754 spec = spec.MakeGenericType (module, targs);
757 // Nested type case, converting .NET types like
758 // A`1.B`1.C`1<int, long, string> to typespec like
759 // A<int>.B<long>.C<string>
761 var nested_hierarchy = new List<TypeSpec> ();
762 while (declaringType.IsNested) {
763 nested_hierarchy.Add (declaringType);
764 declaringType = declaringType.DeclaringType;
768 if (declaringType.Arity > 0) {
769 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
770 targs_pos = spec.Arity;
772 spec = declaringType;
775 for (int i = nested_hierarchy.Count; i != 0; --i) {
776 var t = nested_hierarchy [i - 1];
777 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
779 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
780 targs_pos += t.Arity;
784 string name = type.Name;
785 int index = name.IndexOf ('`');
787 name = name.Substring (0, index);
789 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
793 if (spec.Arity > 0) {
794 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
798 // Don't add generic type with dynamic arguments, they can interfere with same type
799 // using object type arguments
800 if (!spec.HasDynamicElement) {
802 // Add to reading cache to speed up reading
803 if (!import_cache.ContainsKey (type))
804 import_cache.Add (type, spec);
813 var ma = type.Attributes;
814 switch (ma & TypeAttributes.VisibilityMask) {
815 case TypeAttributes.Public:
816 case TypeAttributes.NestedPublic:
817 mod = Modifiers.PUBLIC;
819 case TypeAttributes.NestedPrivate:
820 mod = Modifiers.PRIVATE;
822 case TypeAttributes.NestedFamily:
823 mod = Modifiers.PROTECTED;
825 case TypeAttributes.NestedFamORAssem:
826 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
829 mod = Modifiers.INTERNAL;
833 if ((ma & TypeAttributes.Interface) != 0) {
834 kind = MemberKind.Interface;
835 } else if (type.IsGenericParameter) {
836 kind = MemberKind.TypeParameter;
838 var base_type = type.BaseType;
839 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
840 kind = MemberKind.Class;
842 kind = DetermineKindFromBaseType (base_type);
843 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
844 mod |= Modifiers.SEALED;
848 if (kind == MemberKind.Class) {
849 if ((ma & TypeAttributes.Sealed) != 0) {
850 mod |= Modifiers.SEALED;
851 if ((ma & TypeAttributes.Abstract) != 0)
852 mod |= Modifiers.STATIC;
853 } else if ((ma & TypeAttributes.Abstract) != 0) {
854 mod |= Modifiers.ABSTRACT;
859 var definition = new ImportedTypeDefinition (type, this);
862 if (kind == MemberKind.Enum) {
863 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
864 BindingFlags.Instance |
865 BindingFlags.Public | BindingFlags.NonPublic;
867 var type_members = type.GetFields (underlying_member);
868 foreach (var type_member in type_members) {
869 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
874 kind = MemberKind.Class;
876 } else if (kind == MemberKind.TypeParameter) {
877 spec = CreateTypeParameter (type, declaringType);
878 } else if (type.IsGenericTypeDefinition) {
879 definition.TypeParameters = CreateGenericParameters (type, declaringType);
880 } else if (compiled_types.TryGetValue (type, out pt)) {
882 // Same type was found in inside compiled types. It's
883 // either build-in type or forward referenced typed
884 // which point into just compiled assembly.
887 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
889 bts.SetDefinition (definition, type, mod);
893 spec = new TypeSpec (kind, declaringType, definition, type, mod);
895 import_cache.Add (type, spec);
897 if (kind == MemberKind.TypeParameter) {
898 if (canImportBaseType)
899 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
905 // Two stage setup as the base type can be inflated declaring type or
906 // another nested type inside same declaring type which has not been
907 // loaded, therefore we can import a base type of nested types once
908 // the types have been imported
910 if (canImportBaseType)
911 ImportTypeBase (spec, type);
916 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
918 IAssemblyDefinition found;
919 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
921 // This can happen in dynamic context only
922 var def = new ImportedAssemblyDefinition (assembly);
923 assembly_2_definition.Add (assembly, def);
924 def.ReadAttributes ();
931 public void ImportTypeBase (MetaType type)
933 TypeSpec spec = import_cache[type];
935 ImportTypeBase (spec, type);
938 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
941 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
942 case GenericParameterAttributes.Covariant:
943 variance = Variance.Covariant;
945 case GenericParameterAttributes.Contravariant:
946 variance = Variance.Contravariant;
949 variance = Variance.None;
953 SpecialConstraint special = SpecialConstraint.None;
954 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
956 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
957 special |= SpecialConstraint.Struct;
958 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
959 special = SpecialConstraint.Constructor;
962 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
963 special |= SpecialConstraint.Class;
966 TypeParameterSpec spec;
967 var def = new ImportedTypeParameterDefinition (type, this);
968 if (type.DeclaringMethod != null) {
969 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
971 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
978 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
979 // they can be assembly specific therefore we do check based on names only
981 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
983 if (attributesData.Count == 0)
986 foreach (var attr in attributesData) {
987 var dt = attr.Constructor.DeclaringType;
988 if (dt.Name == attrName && dt.Namespace == attrNamespace)
995 void ImportTypeBase (TypeSpec spec, MetaType type)
997 if (spec.Kind == MemberKind.Interface)
998 spec.BaseType = module.Compiler.BuiltinTypes.Object;
999 else if (type.BaseType != null) {
1001 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1002 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1004 base_type = CreateType (type.BaseType);
1006 spec.BaseType = base_type;
1011 ifaces = type.__GetDeclaredInterfaces ();
1012 if (ifaces.Length != 0) {
1013 foreach (var iface in ifaces) {
1014 var it = CreateType (iface);
1018 spec.AddInterface (it);
1020 // Unfortunately not all languages expand inherited interfaces
1021 var bifaces = it.Interfaces;
1022 if (bifaces != null) {
1023 foreach (var biface in bifaces) {
1024 spec.AddInterface (biface);
1030 if (spec.BaseType != null) {
1031 var bifaces = spec.BaseType.Interfaces;
1032 if (bifaces != null) {
1034 // Before adding base class interfaces close defined interfaces
1035 // on type parameter
1037 var tp = spec as TypeParameterSpec;
1038 if (tp != null && tp.InterfacesDefined == null) {
1039 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1042 foreach (var iface in bifaces)
1043 spec.AddInterface (iface);
1047 ifaces = type.GetInterfaces ();
1049 if (ifaces.Length > 0) {
1050 foreach (var iface in ifaces) {
1051 spec.AddInterface (CreateType (iface));
1056 if (spec.MemberDefinition.TypeParametersCount > 0) {
1057 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1058 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1063 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1065 Namespace ns = targetNamespace;
1066 string prev_namespace = null;
1067 foreach (var t in types) {
1071 // Be careful not to trigger full parent type loading
1072 if (t.MemberType == MemberTypes.NestedType)
1075 if (t.Name[0] == '<')
1078 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1082 if (prev_namespace != t.Namespace) {
1083 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1084 prev_namespace = t.Namespace;
1087 // Cannot rely on assembly level Extension attribute or static modifier because they
1088 // are not followed by other compilers (e.g. F#).
1089 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1090 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1091 it.SetExtensionMethodContainer ();
1094 ns.AddType (module, it);
1098 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1100 var constraints = type.GetGenericParameterConstraints ();
1101 List<TypeSpec> tparams = null;
1102 foreach (var ct in constraints) {
1103 if (ct.IsGenericParameter) {
1104 if (tparams == null)
1105 tparams = new List<TypeSpec> ();
1107 tparams.Add (CreateType (ct));
1111 var constraint_type = CreateType (ct);
1112 if (constraint_type.IsClass) {
1113 spec.BaseType = constraint_type;
1117 spec.AddInterface (constraint_type);
1120 if (spec.BaseType == null)
1121 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1123 if (tparams != null)
1124 spec.TypeArguments = tparams.ToArray ();
1127 Constant ImportParameterConstant (object value)
1130 // Get type of underlying value as int constant can be used for object
1131 // parameter type. This is not allowed in C# but other languages can do that
1133 var types = module.Compiler.BuiltinTypes;
1134 switch (System.Type.GetTypeCode (value.GetType ())) {
1135 case TypeCode.Boolean:
1136 return new BoolConstant (types, (bool) value, Location.Null);
1138 return new ByteConstant (types, (byte) value, Location.Null);
1140 return new CharConstant (types, (char) value, Location.Null);
1141 case TypeCode.Decimal:
1142 return new DecimalConstant (types, (decimal) value, Location.Null);
1143 case TypeCode.Double:
1144 return new DoubleConstant (types, (double) value, Location.Null);
1145 case TypeCode.Int16:
1146 return new ShortConstant (types, (short) value, Location.Null);
1147 case TypeCode.Int32:
1148 return new IntConstant (types, (int) value, Location.Null);
1149 case TypeCode.Int64:
1150 return new LongConstant (types, (long) value, Location.Null);
1151 case TypeCode.SByte:
1152 return new SByteConstant (types, (sbyte) value, Location.Null);
1153 case TypeCode.Single:
1154 return new FloatConstant (types, (float) value, Location.Null);
1155 case TypeCode.String:
1156 return new StringConstant (types, (string) value, Location.Null);
1157 case TypeCode.UInt16:
1158 return new UShortConstant (types, (ushort) value, Location.Null);
1159 case TypeCode.UInt32:
1160 return new UIntConstant (types, (uint) value, Location.Null);
1161 case TypeCode.UInt64:
1162 return new ULongConstant (types, (ulong) value, Location.Null);
1165 throw new NotImplementedException (value.GetType ().ToString ());
1168 public TypeSpec ImportType (MetaType type)
1170 return ImportType (type, new DynamicTypeReader (type));
1173 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1175 if (type.HasElementType) {
1176 var element = type.GetElementType ();
1178 var spec = ImportType (element, dtype);
1181 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1183 return ReferenceContainer.MakeType (module, spec);
1185 return PointerContainer.MakeType (module, spec);
1187 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1190 return CreateType (type, dtype, true);
1193 static bool IsMissingType (MetaType type)
1196 return type.__IsMissing;
1203 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1204 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1205 // DecimalConstantAttribute metadata.
1207 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1209 if (attrs.Count == 0)
1212 foreach (var ca in attrs) {
1213 var dt = ca.Constructor.DeclaringType;
1214 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1217 var value = new decimal (
1218 (int) (uint) ca.ConstructorArguments[4].Value,
1219 (int) (uint) ca.ConstructorArguments[3].Value,
1220 (int) (uint) ca.ConstructorArguments[2].Value,
1221 (byte) ca.ConstructorArguments[1].Value != 0,
1222 (byte) ca.ConstructorArguments[0].Value);
1224 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1230 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1233 var ma = mb.Attributes;
1234 switch (ma & MethodAttributes.MemberAccessMask) {
1235 case MethodAttributes.Public:
1236 mod = Modifiers.PUBLIC;
1238 case MethodAttributes.Assembly:
1239 mod = Modifiers.INTERNAL;
1241 case MethodAttributes.Family:
1242 mod = Modifiers.PROTECTED;
1244 case MethodAttributes.FamORAssem:
1245 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1248 mod = Modifiers.PRIVATE;
1252 if ((ma & MethodAttributes.Static) != 0) {
1253 mod |= Modifiers.STATIC;
1256 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1257 mod |= Modifiers.ABSTRACT;
1261 // It can be sealed and override
1262 if ((ma & MethodAttributes.Final) != 0)
1263 mod |= Modifiers.SEALED;
1265 if ((ma & MethodAttributes.Virtual) != 0) {
1266 // Not every member can be detected based on MethodAttribute, we
1267 // set virtual or non-virtual only when we are certain. Further checks
1268 // to really find out what `virtual' means for this member are done
1270 if ((ma & MethodAttributes.NewSlot) != 0) {
1271 if ((mod & Modifiers.SEALED) != 0) {
1272 mod &= ~Modifiers.SEALED;
1274 mod |= Modifiers.VIRTUAL;
1277 mod |= Modifiers.OVERRIDE;
1285 abstract class ImportedDefinition : IMemberDefinition
1287 protected class AttributesBag
1289 public static readonly AttributesBag Default = new AttributesBag ();
1291 public AttributeUsageAttribute AttributeUsage;
1292 public ObsoleteAttribute Obsolete;
1293 public string[] Conditionals;
1294 public string DefaultIndexerName;
1295 public bool? CLSAttributeValue;
1296 public TypeSpec CoClass;
1298 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1300 AttributesBag bag = null;
1301 List<string> conditionals = null;
1303 // It should not throw any loading exception
1304 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1306 foreach (var a in attrs) {
1307 var dt = a.Constructor.DeclaringType;
1308 string name = dt.Name;
1309 if (name == "ObsoleteAttribute") {
1310 if (dt.Namespace != "System")
1314 bag = new AttributesBag ();
1316 var args = a.ConstructorArguments;
1318 if (args.Count == 1) {
1319 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1320 } else if (args.Count == 2) {
1321 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1323 bag.Obsolete = new ObsoleteAttribute ();
1329 if (name == "ConditionalAttribute") {
1330 if (dt.Namespace != "System.Diagnostics")
1334 bag = new AttributesBag ();
1336 if (conditionals == null)
1337 conditionals = new List<string> (2);
1339 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1343 if (name == "CLSCompliantAttribute") {
1344 if (dt.Namespace != "System")
1348 bag = new AttributesBag ();
1350 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1354 // Type only attributes
1355 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1356 if (name == "DefaultMemberAttribute") {
1357 if (dt.Namespace != "System.Reflection")
1361 bag = new AttributesBag ();
1363 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1367 if (name == "AttributeUsageAttribute") {
1368 if (dt.Namespace != "System")
1372 bag = new AttributesBag ();
1374 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1375 foreach (var named in a.NamedArguments) {
1376 if (named.MemberInfo.Name == "AllowMultiple")
1377 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1378 else if (named.MemberInfo.Name == "Inherited")
1379 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1384 // Interface only attribute
1385 if (name == "CoClassAttribute") {
1386 if (dt.Namespace != "System.Runtime.InteropServices")
1390 bag = new AttributesBag ();
1392 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1401 if (conditionals != null)
1402 bag.Conditionals = conditionals.ToArray ();
1408 protected readonly MemberInfo provider;
1409 protected AttributesBag cattrs;
1410 protected readonly MetadataImporter importer;
1412 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1414 this.provider = provider;
1415 this.importer = importer;
1420 public bool IsImported {
1426 public virtual string Name {
1428 return provider.Name;
1434 public string[] ConditionalConditions ()
1439 return cattrs.Conditionals;
1442 public ObsoleteAttribute GetAttributeObsolete ()
1447 return cattrs.Obsolete;
1450 public bool? CLSAttributeValue {
1455 return cattrs.CLSAttributeValue;
1459 protected void ReadAttributes ()
1461 cattrs = AttributesBag.Read (provider, importer);
1464 public void SetIsAssigned ()
1466 // Unused for imported members
1469 public void SetIsUsed ()
1471 // Unused for imported members
1475 public class ImportedModuleDefinition
1477 readonly Module module;
1480 public ImportedModuleDefinition (Module module)
1482 this.module = module;
1487 public bool IsCLSCompliant {
1489 return cls_compliant;
1493 public string Name {
1501 public void ReadAttributes ()
1503 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1505 foreach (var a in attrs) {
1506 var dt = a.Constructor.DeclaringType;
1507 if (dt.Name == "CLSCompliantAttribute") {
1508 if (dt.Namespace != "System")
1511 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1518 // Reads assembly attributes which where attached to a special type because
1519 // module does have assembly manifest
1521 public List<Attribute> ReadAssemblyAttributes ()
1523 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1527 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1531 // TODO: implement, the idea is to fabricate specil Attribute class and
1532 // add it to OptAttributes before resolving the source code attributes
1533 // Need to build module location as well for correct error reporting
1535 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1536 //var attrs = new List<Attribute> (assembly_attributes.Count);
1537 //foreach (var a in assembly_attributes)
1539 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1540 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1542 // foreach (var carg in a.ConstructorArguments) {
1546 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1553 public class ImportedAssemblyDefinition : IAssemblyDefinition
1555 readonly Assembly assembly;
1556 readonly AssemblyName aname;
1559 List<AssemblyName> internals_visible_to;
1560 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1562 public ImportedAssemblyDefinition (Assembly assembly)
1564 this.assembly = assembly;
1565 this.aname = assembly.GetName ();
1570 public Assembly Assembly {
1576 public string FullName {
1578 return aname.FullName;
1582 public bool HasStrongName {
1584 return aname.GetPublicKey ().Length != 0;
1588 public bool IsMissing {
1591 return assembly.__IsMissing;
1598 public bool IsCLSCompliant {
1600 return cls_compliant;
1604 public string Location {
1606 return assembly.Location;
1610 public string Name {
1618 public byte[] GetPublicKeyToken ()
1620 return aname.GetPublicKeyToken ();
1623 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1625 return internals_visible_to_cache [assembly];
1628 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1630 if (internals_visible_to == null)
1633 AssemblyName is_visible = null;
1634 if (internals_visible_to_cache == null) {
1635 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1637 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1638 return is_visible != null;
1641 var token = assembly.GetPublicKeyToken ();
1642 if (token != null && token.Length == 0)
1645 foreach (var internals in internals_visible_to) {
1646 if (internals.Name != assembly.Name)
1649 if (token == null && assembly is AssemblyDefinition) {
1650 is_visible = internals;
1654 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1657 is_visible = internals;
1661 internals_visible_to_cache.Add (assembly, is_visible);
1662 return is_visible != null;
1665 public void ReadAttributes ()
1668 if (assembly.__IsMissing)
1672 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1674 foreach (var a in attrs) {
1675 var dt = a.Constructor.DeclaringType;
1677 if (name == "CLSCompliantAttribute") {
1678 if (dt.Namespace == "System") {
1679 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1684 if (name == "InternalsVisibleToAttribute") {
1685 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1688 string s = a.ConstructorArguments[0].Value as string;
1692 var an = new AssemblyName (s);
1693 if (internals_visible_to == null)
1694 internals_visible_to = new List<AssemblyName> ();
1696 internals_visible_to.Add (an);
1702 public override string ToString ()
1708 class ImportedMemberDefinition : ImportedDefinition
1710 readonly TypeSpec type;
1712 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1713 : base (member, importer)
1720 public TypeSpec MemberType {
1729 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1731 readonly AParametersCollection parameters;
1733 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1734 : base (provider, type, importer)
1736 this.parameters = parameters;
1739 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1740 : base (provider, type, importer)
1742 this.parameters = parameters;
1747 public AParametersCollection Parameters {
1756 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1758 readonly TypeParameterSpec[] tparams;
1760 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1761 : base (provider, type, parameters, importer)
1763 this.tparams = tparams;
1768 public TypeParameterSpec[] TypeParameters {
1774 public int TypeParametersCount {
1776 return tparams.Length;
1783 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1785 TypeParameterSpec[] tparams;
1788 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1789 : base (type, importer)
1795 public IAssemblyDefinition DeclaringAssembly {
1797 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1801 bool ITypeDefinition.IsComImport {
1803 return ((MetaType) provider).IsImport;
1808 bool ITypeDefinition.IsPartial {
1814 bool ITypeDefinition.IsTypeForwarder {
1817 return ((MetaType) provider).__IsTypeForwarder;
1824 public override string Name {
1828 if (tparams != null) {
1829 int arity_start = name.IndexOf ('`');
1830 if (arity_start > 0)
1831 name = name.Substring (0, arity_start);
1839 public string Namespace {
1841 return ((MetaType) provider).Namespace;
1845 public int TypeParametersCount {
1847 return tparams == null ? 0 : tparams.Length;
1851 public TypeParameterSpec[] TypeParameters {
1862 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1865 // Report details about missing type and most likely cause of the problem.
1866 // csc reports 1683, 1684 as warnings but we report them only when used
1867 // or referenced from the user core in which case compilation error has to
1868 // be reported because compiler cannot continue anyway
1870 for (int i = 0; i < types.Count; ++i) {
1874 // Report missing types only once per type
1876 if (i > 0 && types.IndexOf (t) < i)
1879 string name = t.GetSignatureForError ();
1881 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1882 ctx.Module.Compiler.Report.Error (1683, loc,
1883 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1885 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1886 if (t.MemberDefinition.IsTypeForwarder) {
1887 ctx.Module.Compiler.Report.Error (1070, loc,
1888 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1889 name, t.MemberDefinition.DeclaringAssembly.FullName);
1891 ctx.Module.Compiler.Report.Error (12, loc,
1892 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1893 name, t.MemberDefinition.DeclaringAssembly.FullName);
1896 ctx.Module.Compiler.Report.Error (1684, loc,
1897 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1898 name, t.MemberDefinition.DeclaringAssembly.FullName);
1903 public TypeSpec GetAttributeCoClass ()
1908 return cattrs.CoClass;
1911 public string GetAttributeDefaultMember ()
1916 return cattrs.DefaultIndexerName;
1919 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1924 return cattrs.AttributeUsage;
1927 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1929 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1930 return a == assembly || a.IsFriendAssemblyTo (assembly);
1933 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1936 // Not interested in members of nested private types unless the importer needs them
1938 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1939 cache = MemberCache.Empty;
1943 var loading_type = (MetaType) provider;
1944 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1945 BindingFlags.Static | BindingFlags.Instance |
1946 BindingFlags.Public | BindingFlags.NonPublic;
1948 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1949 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1950 MethodAttributes.Final;
1952 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1953 List<EventSpec> imported_events = null;
1954 EventSpec event_spec;
1955 MemberSpec imported;
1959 all = loading_type.GetMembers (all_members);
1960 } catch (Exception e) {
1961 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1962 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1965 if (cache == null) {
1966 cache = new MemberCache (all.Length);
1969 // Do the types first as they can be referenced by the members before
1970 // they are found or inflated
1972 foreach (var member in all) {
1973 if (member.MemberType != MemberTypes.NestedType)
1976 var t = (MetaType) member;
1978 // Ignore compiler generated types, mostly lambda containers
1979 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1983 imported = importer.CreateNestedType (t, declaringType);
1984 } catch (Exception e) {
1985 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
1986 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
1989 cache.AddMemberImported (imported);
1992 foreach (var member in all) {
1993 if (member.MemberType != MemberTypes.NestedType)
1996 var t = (MetaType) member;
1998 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2001 importer.ImportTypeBase (t);
2006 // Load base interfaces first to minic behaviour of compiled members
2008 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2009 foreach (var iface in declaringType.Interfaces) {
2010 cache.AddInterface (iface);
2016 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2018 foreach (var member in all) {
2019 switch (member.MemberType) {
2020 case MemberTypes.Constructor:
2021 if (declaringType.IsInterface)
2024 goto case MemberTypes.Method;
2025 case MemberTypes.Method:
2026 MethodBase mb = (MethodBase) member;
2027 var attrs = mb.Attributes;
2029 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2030 if (importer.IgnorePrivateMembers)
2033 // Ignore explicitly implemented members
2034 if ((attrs & explicit_impl) == explicit_impl)
2037 // Ignore compiler generated methods
2038 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2042 imported = importer.CreateMethod (mb, declaringType);
2043 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2044 if (possible_accessors == null)
2045 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2047 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2048 possible_accessors.Add (mb, (MethodSpec) imported);
2052 case MemberTypes.Property:
2053 if (possible_accessors == null)
2056 var p = (PropertyInfo) member;
2058 // Links possible accessors with property
2060 MethodSpec get, set;
2061 m = p.GetGetMethod (true);
2062 if (m == null || !possible_accessors.TryGetValue (m, out get))
2065 m = p.GetSetMethod (true);
2066 if (m == null || !possible_accessors.TryGetValue (m, out set))
2069 // No accessors registered (e.g. explicit implementation)
2070 if (get == null && set == null)
2073 imported = importer.CreateProperty (p, declaringType, get, set);
2074 if (imported == null)
2078 case MemberTypes.Event:
2079 if (possible_accessors == null)
2082 var e = (EventInfo) member;
2084 // Links accessors with event
2086 MethodSpec add, remove;
2087 m = e.GetAddMethod (true);
2088 if (m == null || !possible_accessors.TryGetValue (m, out add))
2091 m = e.GetRemoveMethod (true);
2092 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2095 // Both accessors are required
2096 if (add == null || remove == null)
2099 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2100 if (!importer.IgnorePrivateMembers) {
2101 if (imported_events == null)
2102 imported_events = new List<EventSpec> ();
2104 imported_events.Add (event_spec);
2107 imported = event_spec;
2109 case MemberTypes.Field:
2110 var fi = (FieldInfo) member;
2112 imported = importer.CreateField (fi, declaringType);
2113 if (imported == null)
2117 // For dynamic binder event has to be fully restored to allow operations
2118 // within the type container to work correctly
2120 if (imported_events != null) {
2121 // The backing event field should be private but it may not
2123 for (i = 0; i < imported_events.Count; ++i) {
2124 var ev = imported_events[i];
2125 if (ev.Name == fi.Name) {
2126 ev.BackingField = (FieldSpec) imported;
2127 imported_events.RemoveAt (i);
2138 case MemberTypes.NestedType:
2139 // Already in the cache from the first pass
2142 throw new NotImplementedException (member.ToString ());
2145 if (imported.IsStatic && declaringType.IsInterface)
2148 cache.AddMemberImported (imported);
2154 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2156 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2157 : base (type, importer)
2163 public IAssemblyDefinition DeclaringAssembly {
2165 throw new NotImplementedException ();
2169 bool ITypeDefinition.IsComImport {
2175 bool ITypeDefinition.IsPartial {
2181 bool ITypeDefinition.IsTypeForwarder {
2187 public string Namespace {
2193 public int TypeParametersCount {
2199 public TypeParameterSpec[] TypeParameters {
2207 public TypeSpec GetAttributeCoClass ()
2212 public string GetAttributeDefaultMember ()
2214 throw new NotSupportedException ();
2217 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2219 throw new NotSupportedException ();
2222 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2224 throw new NotImplementedException ();
2227 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2229 throw new NotImplementedException ();