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 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 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.IsStatic && parent.MemberDefinition.DeclaringAssembly.HasExtensionMethod &&
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.CreateConstant (ptype, null, Location.Null);
515 default_value = ImportParameterConstant (value);
518 default_value = new EnumConstant ((Constant) default_value, ptype);
521 } else if (value == Missing.Value) {
522 default_value = EmptyExpression.MissingValue;
523 } else if (value == null) {
524 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
525 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
526 default_value = ImportParameterConstant (value);
531 par[i] = new ParameterData (p.Name, mod, default_value);
535 par[par.Length - 1] = new ArglistParameter (Location.Null);
536 types[types.Length - 1] = InternalType.Arglist;
539 return method != null ?
540 new ParametersImported (par, types, varargs != 0, is_params) :
541 new ParametersImported (par, types, is_params);
545 // Returns null when the property is not valid C# property
547 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
550 AParametersCollection param = null;
551 TypeSpec type = null;
554 param = get.Parameters;
555 type = get.ReturnType;
558 bool is_valid_property = true;
560 if (set.ReturnType.Kind != MemberKind.Void)
561 is_valid_property = false;
563 var set_param_count = set.Parameters.Count - 1;
565 if (set_param_count < 0) {
567 is_valid_property = false;
570 var set_type = set.Parameters.Types[set_param_count];
573 AParametersCollection set_based_param;
575 if (set_param_count == 0) {
576 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
579 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
581 var data = new IParameterData[set_param_count];
582 var types = new TypeSpec[set_param_count];
583 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
584 Array.Copy (set.Parameters.Types, types, set_param_count);
585 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
589 param = set_based_param;
592 if (set_param_count != get.Parameters.Count)
593 is_valid_property = false;
595 if (get.ReturnType != set_type)
596 is_valid_property = false;
598 // Possible custom accessor modifiers
599 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
600 var get_acc = mod & Modifiers.AccessibilityMask;
601 if (get_acc != Modifiers.PUBLIC) {
602 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
603 // If the accessor modifiers are not same, do extra restriction checks
604 if (get_acc != set_acc) {
605 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
606 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
607 if (get_restr && set_restr) {
608 is_valid_property = false; // Neither is more restrictive
612 mod &= ~Modifiers.AccessibilityMask;
621 PropertySpec spec = null;
622 if (!param.IsEmpty) {
623 if (is_valid_property) {
624 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
625 if (index_name == null) {
626 is_valid_property = false;
630 is_valid_property = false;
631 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
632 is_valid_property = false;
636 is_valid_property = false;
637 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
638 is_valid_property = false;
642 if (is_valid_property) {
643 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
644 } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
646 // Enables support for properties with parameters (must have default value) of COM-imported types
648 is_valid_property = true;
650 for (int i = 0; i < param.FixedParameters.Length; ++i) {
651 if (!param.FixedParameters[i].HasDefaultValue) {
652 is_valid_property = false;
661 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
663 if (!is_valid_property) {
664 spec.IsNotCSharpCompatible = true;
676 public TypeSpec CreateType (MetaType type)
678 return CreateType (type, new DynamicTypeReader (), true);
681 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
683 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
686 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
688 TypeSpec declaring_type;
689 if (type.IsNested && !type.IsGenericParameter)
690 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
692 declaring_type = null;
694 return CreateType (type, declaring_type, dtype, canImportBaseType);
697 TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
700 if (import_cache.TryGetValue (type, out spec)) {
701 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
702 if (dtype.IsDynamicObject (this))
703 return module.Compiler.BuiltinTypes.Dynamic;
708 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
711 if (!dtype.HasDynamicAttribute (this))
714 // We've found same object in the cache but this one has a dynamic custom attribute
715 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
716 // Do type resolve process again in that case
718 // TODO: Handle cases where they still unify
721 if (IsMissingType (type)) {
722 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
723 spec.MemberCache = MemberCache.Empty;
724 import_cache.Add (type, spec);
728 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
729 var type_def = type.GetGenericTypeDefinition ();
731 // Generic type definition can also be forwarded
732 if (compiled_types.TryGetValue (type_def, out spec))
735 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
736 if (declaringType == null) {
737 // Simple case, no nesting
738 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
739 spec = spec.MakeGenericType (module, targs);
742 // Nested type case, converting .NET types like
743 // A`1.B`1.C`1<int, long, string> to typespec like
744 // A<int>.B<long>.C<string>
746 var nested_hierarchy = new List<TypeSpec> ();
747 while (declaringType.IsNested) {
748 nested_hierarchy.Add (declaringType);
749 declaringType = declaringType.DeclaringType;
753 if (declaringType.Arity > 0) {
754 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
755 targs_pos = spec.Arity;
757 spec = declaringType;
760 for (int i = nested_hierarchy.Count; i != 0; --i) {
761 var t = nested_hierarchy [i - 1];
762 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
764 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
765 targs_pos += t.Arity;
769 string name = type.Name;
770 int index = name.IndexOf ('`');
772 name = name.Substring (0, index);
774 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
778 if (spec.Arity > 0) {
779 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
783 // Don't add generic type with dynamic arguments, they can interfere with same type
784 // using object type arguments
785 if (!spec.HasDynamicElement) {
787 // Add to reading cache to speed up reading
788 if (!import_cache.ContainsKey (type))
789 import_cache.Add (type, spec);
798 var ma = type.Attributes;
799 switch (ma & TypeAttributes.VisibilityMask) {
800 case TypeAttributes.Public:
801 case TypeAttributes.NestedPublic:
802 mod = Modifiers.PUBLIC;
804 case TypeAttributes.NestedPrivate:
805 mod = Modifiers.PRIVATE;
807 case TypeAttributes.NestedFamily:
808 mod = Modifiers.PROTECTED;
810 case TypeAttributes.NestedFamORAssem:
811 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
814 mod = Modifiers.INTERNAL;
818 if ((ma & TypeAttributes.Interface) != 0) {
819 kind = MemberKind.Interface;
820 } else if (type.IsGenericParameter) {
821 kind = MemberKind.TypeParameter;
823 var base_type = type.BaseType;
824 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
825 kind = MemberKind.Class;
827 kind = DetermineKindFromBaseType (base_type);
828 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
829 mod |= Modifiers.SEALED;
833 if (kind == MemberKind.Class) {
834 if ((ma & TypeAttributes.Sealed) != 0) {
835 mod |= Modifiers.SEALED;
836 if ((ma & TypeAttributes.Abstract) != 0)
837 mod |= Modifiers.STATIC;
838 } else if ((ma & TypeAttributes.Abstract) != 0) {
839 mod |= Modifiers.ABSTRACT;
844 var definition = new ImportedTypeDefinition (type, this);
847 if (kind == MemberKind.Enum) {
848 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
849 BindingFlags.Instance |
850 BindingFlags.Public | BindingFlags.NonPublic;
852 var type_members = type.GetFields (underlying_member);
853 foreach (var type_member in type_members) {
854 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
859 kind = MemberKind.Class;
861 } else if (kind == MemberKind.TypeParameter) {
862 spec = CreateTypeParameter (type, declaringType);
863 } else if (type.IsGenericTypeDefinition) {
864 definition.TypeParameters = CreateGenericParameters (type, declaringType);
865 } else if (compiled_types.TryGetValue (type, out pt)) {
867 // Same type was found in inside compiled types. It's
868 // either build-in type or forward referenced typed
869 // which point into just compiled assembly.
872 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
874 bts.SetDefinition (definition, type, mod);
878 spec = new TypeSpec (kind, declaringType, definition, type, mod);
880 import_cache.Add (type, spec);
882 if (kind == MemberKind.TypeParameter) {
883 if (canImportBaseType)
884 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
890 // Two stage setup as the base type can be inflated declaring type or
891 // another nested type inside same declaring type which has not been
892 // loaded, therefore we can import a base type of nested types once
893 // the types have been imported
895 if (canImportBaseType)
896 ImportTypeBase (spec, type);
901 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
903 IAssemblyDefinition found;
904 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
906 // This can happen in dynamic context only
907 var def = new ImportedAssemblyDefinition (assembly);
908 assembly_2_definition.Add (assembly, def);
909 def.ReadAttributes ();
916 public void ImportTypeBase (MetaType type)
918 TypeSpec spec = import_cache[type];
920 ImportTypeBase (spec, type);
923 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
926 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
927 case GenericParameterAttributes.Covariant:
928 variance = Variance.Covariant;
930 case GenericParameterAttributes.Contravariant:
931 variance = Variance.Contravariant;
934 variance = Variance.None;
938 SpecialConstraint special = SpecialConstraint.None;
939 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
941 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
942 special |= SpecialConstraint.Struct;
943 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
944 special = SpecialConstraint.Constructor;
947 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
948 special |= SpecialConstraint.Class;
951 TypeParameterSpec spec;
952 var def = new ImportedTypeParameterDefinition (type, this);
953 if (type.DeclaringMethod != null) {
954 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
956 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
963 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
964 // they can be assembly specific therefore we do check based on names only
966 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
968 if (attributesData.Count == 0)
971 foreach (var attr in attributesData) {
972 var dt = attr.Constructor.DeclaringType;
973 if (dt.Name == attrName && dt.Namespace == attrNamespace)
980 void ImportTypeBase (TypeSpec spec, MetaType type)
982 if (spec.Kind == MemberKind.Interface)
983 spec.BaseType = module.Compiler.BuiltinTypes.Object;
984 else if (type.BaseType != null) {
986 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
987 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
989 base_type = CreateType (type.BaseType);
991 spec.BaseType = base_type;
996 ifaces = type.__GetDeclaredInterfaces ();
997 if (ifaces.Length != 0) {
998 foreach (var iface in ifaces) {
999 var it = CreateType (iface);
1003 spec.AddInterface (it);
1005 // Unfortunately not all languages expand inherited interfaces
1006 var bifaces = it.Interfaces;
1007 if (bifaces != null) {
1008 foreach (var biface in bifaces) {
1009 spec.AddInterface (biface);
1015 if (spec.BaseType != null) {
1016 var bifaces = spec.BaseType.Interfaces;
1017 if (bifaces != null) {
1019 // Before adding base class interfaces close defined interfaces
1020 // on type parameter
1022 var tp = spec as TypeParameterSpec;
1023 if (tp != null && tp.InterfacesDefined == null) {
1024 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1027 foreach (var iface in bifaces)
1028 spec.AddInterface (iface);
1032 ifaces = type.GetInterfaces ();
1034 if (ifaces.Length > 0) {
1035 foreach (var iface in ifaces) {
1036 spec.AddInterface (CreateType (iface));
1041 if (spec.MemberDefinition.TypeParametersCount > 0) {
1042 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1043 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1048 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
1050 Namespace ns = targetNamespace;
1051 string prev_namespace = null;
1052 foreach (var t in types) {
1056 // Be careful not to trigger full parent type loading
1057 if (t.MemberType == MemberTypes.NestedType)
1060 if (t.Name[0] == '<')
1063 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1067 if (prev_namespace != t.Namespace) {
1068 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1069 prev_namespace = t.Namespace;
1072 ns.AddType (module, it);
1074 if (it.IsStatic && hasExtensionTypes &&
1075 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1076 it.SetExtensionMethodContainer ();
1081 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1083 var constraints = type.GetGenericParameterConstraints ();
1084 List<TypeSpec> tparams = null;
1085 foreach (var ct in constraints) {
1086 if (ct.IsGenericParameter) {
1087 if (tparams == null)
1088 tparams = new List<TypeSpec> ();
1090 tparams.Add (CreateType (ct));
1094 var constraint_type = CreateType (ct);
1095 if (constraint_type.IsClass) {
1096 spec.BaseType = constraint_type;
1100 spec.AddInterface (constraint_type);
1103 if (spec.BaseType == null)
1104 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1106 if (tparams != null)
1107 spec.TypeArguments = tparams.ToArray ();
1110 Constant ImportParameterConstant (object value)
1113 // Get type of underlying value as int constant can be used for object
1114 // parameter type. This is not allowed in C# but other languages can do that
1116 var types = module.Compiler.BuiltinTypes;
1117 switch (System.Type.GetTypeCode (value.GetType ())) {
1118 case TypeCode.Boolean:
1119 return new BoolConstant (types, (bool) value, Location.Null);
1121 return new ByteConstant (types, (byte) value, Location.Null);
1123 return new CharConstant (types, (char) value, Location.Null);
1124 case TypeCode.Decimal:
1125 return new DecimalConstant (types, (decimal) value, Location.Null);
1126 case TypeCode.Double:
1127 return new DoubleConstant (types, (double) value, Location.Null);
1128 case TypeCode.Int16:
1129 return new ShortConstant (types, (short) value, Location.Null);
1130 case TypeCode.Int32:
1131 return new IntConstant (types, (int) value, Location.Null);
1132 case TypeCode.Int64:
1133 return new LongConstant (types, (long) value, Location.Null);
1134 case TypeCode.SByte:
1135 return new SByteConstant (types, (sbyte) value, Location.Null);
1136 case TypeCode.Single:
1137 return new FloatConstant (types, (float) value, Location.Null);
1138 case TypeCode.String:
1139 return new StringConstant (types, (string) value, Location.Null);
1140 case TypeCode.UInt16:
1141 return new UShortConstant (types, (ushort) value, Location.Null);
1142 case TypeCode.UInt32:
1143 return new UIntConstant (types, (uint) value, Location.Null);
1144 case TypeCode.UInt64:
1145 return new ULongConstant (types, (ulong) value, Location.Null);
1148 throw new NotImplementedException (value.GetType ().ToString ());
1151 public TypeSpec ImportType (MetaType type)
1153 return ImportType (type, new DynamicTypeReader (type));
1156 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1158 if (type.HasElementType) {
1159 var element = type.GetElementType ();
1161 var spec = ImportType (element, dtype);
1164 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1166 return ReferenceContainer.MakeType (module, spec);
1168 return PointerContainer.MakeType (module, spec);
1170 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1173 return CreateType (type, dtype, true);
1176 static bool IsMissingType (MetaType type)
1179 return type.__IsMissing;
1186 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1187 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1188 // DecimalConstantAttribute metadata.
1190 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1192 if (attrs.Count == 0)
1195 foreach (var ca in attrs) {
1196 var dt = ca.Constructor.DeclaringType;
1197 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1200 var value = new decimal (
1201 (int) (uint) ca.ConstructorArguments[4].Value,
1202 (int) (uint) ca.ConstructorArguments[3].Value,
1203 (int) (uint) ca.ConstructorArguments[2].Value,
1204 (byte) ca.ConstructorArguments[1].Value != 0,
1205 (byte) ca.ConstructorArguments[0].Value);
1207 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1213 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1216 var ma = mb.Attributes;
1217 switch (ma & MethodAttributes.MemberAccessMask) {
1218 case MethodAttributes.Public:
1219 mod = Modifiers.PUBLIC;
1221 case MethodAttributes.Assembly:
1222 mod = Modifiers.INTERNAL;
1224 case MethodAttributes.Family:
1225 mod = Modifiers.PROTECTED;
1227 case MethodAttributes.FamORAssem:
1228 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1231 mod = Modifiers.PRIVATE;
1235 if ((ma & MethodAttributes.Static) != 0) {
1236 mod |= Modifiers.STATIC;
1239 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1240 mod |= Modifiers.ABSTRACT;
1244 // It can be sealed and override
1245 if ((ma & MethodAttributes.Final) != 0)
1246 mod |= Modifiers.SEALED;
1248 if ((ma & MethodAttributes.Virtual) != 0) {
1249 // Not every member can be detected based on MethodAttribute, we
1250 // set virtual or non-virtual only when we are certain. Further checks
1251 // to really find out what `virtual' means for this member are done
1253 if ((ma & MethodAttributes.NewSlot) != 0) {
1254 if ((mod & Modifiers.SEALED) != 0) {
1255 mod &= ~Modifiers.SEALED;
1257 mod |= Modifiers.VIRTUAL;
1260 mod |= Modifiers.OVERRIDE;
1268 abstract class ImportedDefinition : IMemberDefinition
1270 protected class AttributesBag
1272 public static readonly AttributesBag Default = new AttributesBag ();
1274 public AttributeUsageAttribute AttributeUsage;
1275 public ObsoleteAttribute Obsolete;
1276 public string[] Conditionals;
1277 public string DefaultIndexerName;
1278 public bool? CLSAttributeValue;
1279 public TypeSpec CoClass;
1281 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1283 AttributesBag bag = null;
1284 List<string> conditionals = null;
1286 // It should not throw any loading exception
1287 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1289 foreach (var a in attrs) {
1290 var dt = a.Constructor.DeclaringType;
1291 string name = dt.Name;
1292 if (name == "ObsoleteAttribute") {
1293 if (dt.Namespace != "System")
1297 bag = new AttributesBag ();
1299 var args = a.ConstructorArguments;
1301 if (args.Count == 1) {
1302 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1303 } else if (args.Count == 2) {
1304 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1306 bag.Obsolete = new ObsoleteAttribute ();
1312 if (name == "ConditionalAttribute") {
1313 if (dt.Namespace != "System.Diagnostics")
1317 bag = new AttributesBag ();
1319 if (conditionals == null)
1320 conditionals = new List<string> (2);
1322 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1326 if (name == "CLSCompliantAttribute") {
1327 if (dt.Namespace != "System")
1331 bag = new AttributesBag ();
1333 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1337 // Type only attributes
1338 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1339 if (name == "DefaultMemberAttribute") {
1340 if (dt.Namespace != "System.Reflection")
1344 bag = new AttributesBag ();
1346 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1350 if (name == "AttributeUsageAttribute") {
1351 if (dt.Namespace != "System")
1355 bag = new AttributesBag ();
1357 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1358 foreach (var named in a.NamedArguments) {
1359 if (named.MemberInfo.Name == "AllowMultiple")
1360 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1361 else if (named.MemberInfo.Name == "Inherited")
1362 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1367 // Interface only attribute
1368 if (name == "CoClassAttribute") {
1369 if (dt.Namespace != "System.Runtime.InteropServices")
1373 bag = new AttributesBag ();
1375 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1384 if (conditionals != null)
1385 bag.Conditionals = conditionals.ToArray ();
1391 protected readonly MemberInfo provider;
1392 protected AttributesBag cattrs;
1393 protected readonly MetadataImporter importer;
1395 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1397 this.provider = provider;
1398 this.importer = importer;
1403 public bool IsImported {
1409 public virtual string Name {
1411 return provider.Name;
1417 public string[] ConditionalConditions ()
1422 return cattrs.Conditionals;
1425 public ObsoleteAttribute GetAttributeObsolete ()
1430 return cattrs.Obsolete;
1433 public bool? CLSAttributeValue {
1438 return cattrs.CLSAttributeValue;
1442 protected void ReadAttributes ()
1444 cattrs = AttributesBag.Read (provider, importer);
1447 public void SetIsAssigned ()
1449 // Unused for imported members
1452 public void SetIsUsed ()
1454 // Unused for imported members
1458 public class ImportedModuleDefinition
1460 readonly Module module;
1463 public ImportedModuleDefinition (Module module)
1465 this.module = module;
1470 public bool IsCLSCompliant {
1472 return cls_compliant;
1476 public string Name {
1484 public void ReadAttributes ()
1486 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1488 foreach (var a in attrs) {
1489 var dt = a.Constructor.DeclaringType;
1490 if (dt.Name == "CLSCompliantAttribute") {
1491 if (dt.Namespace != "System")
1494 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1501 // Reads assembly attributes which where attached to a special type because
1502 // module does have assembly manifest
1504 public List<Attribute> ReadAssemblyAttributes ()
1506 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1510 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1514 // TODO: implement, the idea is to fabricate specil Attribute class and
1515 // add it to OptAttributes before resolving the source code attributes
1516 // Need to build module location as well for correct error reporting
1518 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1519 //var attrs = new List<Attribute> (assembly_attributes.Count);
1520 //foreach (var a in assembly_attributes)
1522 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1523 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1525 // foreach (var carg in a.ConstructorArguments) {
1529 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1536 public class ImportedAssemblyDefinition : IAssemblyDefinition
1538 readonly Assembly assembly;
1539 readonly AssemblyName aname;
1541 bool contains_extension_methods;
1543 List<AssemblyName> internals_visible_to;
1544 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1546 public ImportedAssemblyDefinition (Assembly assembly)
1548 this.assembly = assembly;
1549 this.aname = assembly.GetName ();
1554 public Assembly Assembly {
1560 public string FullName {
1562 return aname.FullName;
1566 public bool HasExtensionMethod {
1568 return contains_extension_methods;
1572 public bool HasStrongName {
1574 return aname.GetPublicKey ().Length != 0;
1578 public bool IsMissing {
1581 return assembly.__IsMissing;
1588 public bool IsCLSCompliant {
1590 return cls_compliant;
1594 public string Location {
1596 return assembly.Location;
1600 public string Name {
1608 public byte[] GetPublicKeyToken ()
1610 return aname.GetPublicKeyToken ();
1613 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1615 return internals_visible_to_cache [assembly];
1618 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1620 if (internals_visible_to == null)
1623 AssemblyName is_visible = null;
1624 if (internals_visible_to_cache == null) {
1625 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1627 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1628 return is_visible != null;
1631 var token = assembly.GetPublicKeyToken ();
1632 if (token != null && token.Length == 0)
1635 foreach (var internals in internals_visible_to) {
1636 if (internals.Name != assembly.Name)
1639 if (token == null && assembly is AssemblyDefinition) {
1640 is_visible = internals;
1644 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1647 is_visible = internals;
1651 internals_visible_to_cache.Add (assembly, is_visible);
1652 return is_visible != null;
1655 public void ReadAttributes ()
1658 if (assembly.__IsMissing)
1662 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1664 foreach (var a in attrs) {
1665 var dt = a.Constructor.DeclaringType;
1667 if (name == "CLSCompliantAttribute") {
1668 if (dt.Namespace == "System") {
1669 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1674 if (name == "InternalsVisibleToAttribute") {
1675 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1678 string s = a.ConstructorArguments[0].Value as string;
1682 var an = new AssemblyName (s);
1683 if (internals_visible_to == null)
1684 internals_visible_to = new List<AssemblyName> ();
1686 internals_visible_to.Add (an);
1690 if (name == "ExtensionAttribute") {
1691 if (dt.Namespace == MetadataImporter.CompilerServicesNamespace)
1692 contains_extension_methods = true;
1699 public override string ToString ()
1705 class ImportedMemberDefinition : ImportedDefinition
1707 readonly TypeSpec type;
1709 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1710 : base (member, importer)
1717 public TypeSpec MemberType {
1726 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1728 readonly AParametersCollection parameters;
1730 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1731 : base (provider, type, importer)
1733 this.parameters = parameters;
1736 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1737 : base (provider, type, importer)
1739 this.parameters = parameters;
1744 public AParametersCollection Parameters {
1753 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1755 readonly TypeParameterSpec[] tparams;
1757 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1758 : base (provider, type, parameters, importer)
1760 this.tparams = tparams;
1765 public TypeParameterSpec[] TypeParameters {
1771 public int TypeParametersCount {
1773 return tparams.Length;
1780 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1782 TypeParameterSpec[] tparams;
1785 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1786 : base (type, importer)
1792 public IAssemblyDefinition DeclaringAssembly {
1794 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1798 bool ITypeDefinition.IsComImport {
1800 return ((MetaType) provider).IsImport;
1805 bool ITypeDefinition.IsPartial {
1811 public override string Name {
1815 if (tparams != null) {
1816 int arity_start = name.IndexOf ('`');
1817 if (arity_start > 0)
1818 name = name.Substring (0, arity_start);
1826 public string Namespace {
1828 return ((MetaType) provider).Namespace;
1832 public int TypeParametersCount {
1834 return tparams == null ? 0 : tparams.Length;
1838 public TypeParameterSpec[] TypeParameters {
1849 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1852 // Report details about missing type and most likely cause of the problem.
1853 // csc reports 1683, 1684 as warnings but we report them only when used
1854 // or referenced from the user core in which case compilation error has to
1855 // be reported because compiler cannot continue anyway
1857 for (int i = 0; i < types.Count; ++i) {
1861 // Report missing types only once per type
1863 if (i > 0 && types.IndexOf (t) < i)
1866 string name = t.GetSignatureForError ();
1868 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1869 ctx.Module.Compiler.Report.Error (1683, loc,
1870 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1872 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1873 ctx.Module.Compiler.Report.Error (12, loc,
1874 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1875 name, t.MemberDefinition.DeclaringAssembly.FullName);
1877 ctx.Module.Compiler.Report.Error (1684, loc,
1878 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1879 name, t.MemberDefinition.DeclaringAssembly.FullName);
1884 public TypeSpec GetAttributeCoClass ()
1889 return cattrs.CoClass;
1892 public string GetAttributeDefaultMember ()
1897 return cattrs.DefaultIndexerName;
1900 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1905 return cattrs.AttributeUsage;
1908 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1910 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1911 return a == assembly || a.IsFriendAssemblyTo (assembly);
1914 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1917 // Not interested in members of nested private types unless the importer needs them
1919 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1920 cache = MemberCache.Empty;
1924 var loading_type = (MetaType) provider;
1925 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1926 BindingFlags.Static | BindingFlags.Instance |
1927 BindingFlags.Public | BindingFlags.NonPublic;
1929 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1930 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1931 MethodAttributes.Final;
1933 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1934 List<EventSpec> imported_events = null;
1935 EventSpec event_spec;
1936 MemberSpec imported;
1940 all = loading_type.GetMembers (all_members);
1941 } catch (Exception e) {
1942 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1943 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1946 if (cache == null) {
1947 cache = new MemberCache (all.Length);
1950 // Do the types first as they can be referenced by the members before
1951 // they are found or inflated
1953 foreach (var member in all) {
1954 if (member.MemberType != MemberTypes.NestedType)
1957 var t = (MetaType) member;
1959 // Ignore compiler generated types, mostly lambda containers
1960 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1964 imported = importer.CreateNestedType (t, declaringType);
1965 } catch (Exception e) {
1966 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
1967 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
1970 cache.AddMemberImported (imported);
1973 foreach (var member in all) {
1974 if (member.MemberType != MemberTypes.NestedType)
1977 var t = (MetaType) member;
1979 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1982 importer.ImportTypeBase (t);
1987 // Load base interfaces first to minic behaviour of compiled members
1989 if (declaringType.IsInterface && declaringType.Interfaces != null) {
1990 foreach (var iface in declaringType.Interfaces) {
1991 cache.AddInterface (iface);
1997 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1999 foreach (var member in all) {
2000 switch (member.MemberType) {
2001 case MemberTypes.Constructor:
2002 if (declaringType.IsInterface)
2005 goto case MemberTypes.Method;
2006 case MemberTypes.Method:
2007 MethodBase mb = (MethodBase) member;
2008 var attrs = mb.Attributes;
2010 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2011 if (importer.IgnorePrivateMembers)
2014 // Ignore explicitly implemented members
2015 if ((attrs & explicit_impl) == explicit_impl)
2018 // Ignore compiler generated methods
2019 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2023 imported = importer.CreateMethod (mb, declaringType);
2024 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2025 if (possible_accessors == null)
2026 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2028 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2029 possible_accessors.Add (mb, (MethodSpec) imported);
2033 case MemberTypes.Property:
2034 if (possible_accessors == null)
2037 var p = (PropertyInfo) member;
2039 // Links possible accessors with property
2041 MethodSpec get, set;
2042 m = p.GetGetMethod (true);
2043 if (m == null || !possible_accessors.TryGetValue (m, out get))
2046 m = p.GetSetMethod (true);
2047 if (m == null || !possible_accessors.TryGetValue (m, out set))
2050 // No accessors registered (e.g. explicit implementation)
2051 if (get == null && set == null)
2054 imported = importer.CreateProperty (p, declaringType, get, set);
2055 if (imported == null)
2059 case MemberTypes.Event:
2060 if (possible_accessors == null)
2063 var e = (EventInfo) member;
2065 // Links accessors with event
2067 MethodSpec add, remove;
2068 m = e.GetAddMethod (true);
2069 if (m == null || !possible_accessors.TryGetValue (m, out add))
2072 m = e.GetRemoveMethod (true);
2073 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2076 // Both accessors are required
2077 if (add == null || remove == null)
2080 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2081 if (!importer.IgnorePrivateMembers) {
2082 if (imported_events == null)
2083 imported_events = new List<EventSpec> ();
2085 imported_events.Add (event_spec);
2088 imported = event_spec;
2090 case MemberTypes.Field:
2091 var fi = (FieldInfo) member;
2093 imported = importer.CreateField (fi, declaringType);
2094 if (imported == null)
2098 // For dynamic binder event has to be fully restored to allow operations
2099 // within the type container to work correctly
2101 if (imported_events != null) {
2102 // The backing event field should be private but it may not
2104 for (i = 0; i < imported_events.Count; ++i) {
2105 var ev = imported_events[i];
2106 if (ev.Name == fi.Name) {
2107 ev.BackingField = (FieldSpec) imported;
2108 imported_events.RemoveAt (i);
2119 case MemberTypes.NestedType:
2120 // Already in the cache from the first pass
2123 throw new NotImplementedException (member.ToString ());
2126 if (imported.IsStatic && declaringType.IsInterface)
2129 cache.AddMemberImported (imported);
2135 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2137 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2138 : base (type, importer)
2144 public IAssemblyDefinition DeclaringAssembly {
2146 throw new NotImplementedException ();
2150 bool ITypeDefinition.IsComImport {
2156 bool ITypeDefinition.IsPartial {
2162 public string Namespace {
2168 public int TypeParametersCount {
2174 public TypeParameterSpec[] TypeParameters {
2182 public TypeSpec GetAttributeCoClass ()
2187 public string GetAttributeDefaultMember ()
2189 throw new NotSupportedException ();
2192 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2194 throw new NotSupportedException ();
2197 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2199 throw new NotImplementedException ();
2202 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2204 throw new NotImplementedException ();