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 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 var c = Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
195 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
198 if ((fa & FieldAttributes.InitOnly) != 0) {
199 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
200 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
202 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
205 mod |= Modifiers.READONLY;
207 var req_mod = fi.GetRequiredCustomModifiers ();
208 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
209 mod |= Modifiers.VOLATILE;
212 if ((fa & FieldAttributes.Static) != 0) {
213 mod |= Modifiers.STATIC;
215 // Fixed buffers cannot be static
216 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
217 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
219 // TODO: Sanity check on field_type (only few types are allowed)
220 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
221 return new FixedFieldSpec (declaringType, definition, fi, element_field, mod);
225 return new FieldSpec (declaringType, definition, field_type, fi, mod);
228 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
230 add.IsAccessor = true;
231 remove.IsAccessor = true;
233 if (add.Modifiers != remove.Modifiers)
234 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
236 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
237 var definition = new ImportedMemberDefinition (ei, event_type, this);
238 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
241 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
243 var tparams = type.GetGenericArguments ();
245 int parent_owned_count;
247 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
250 // System.Reflection duplicates parent type parameters for each
251 // nested type with slightly modified properties (eg. different owner)
252 // This just makes things more complicated (think of cloned constraints)
253 // therefore we remap any nested type owned by parent using `type_cache'
254 // to the single TypeParameterSpec
256 if (declaringType != null && parent_owned_count > 0) {
258 while (read_count != parent_owned_count) {
259 var tparams_count = declaringType.Arity;
260 if (tparams_count != 0) {
261 var parent_tp = declaringType.MemberDefinition.TypeParameters;
262 read_count += tparams_count;
263 for (int i = 0; i < tparams_count; i++) {
264 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
268 declaringType = declaringType.DeclaringType;
272 parent_owned_count = 0;
275 if (tparams.Length - parent_owned_count == 0)
278 return CreateGenericParameters (parent_owned_count, tparams);
281 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
283 var tspec = new TypeParameterSpec[tparams.Length - first];
284 for (int pos = first; pos < tparams.Length; ++pos) {
285 var type = tparams[pos];
286 int index = pos - first;
288 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
294 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
298 var tspec = new TypeSpec [tparams.Length - first];
299 for (int pos = first; pos < tparams.Length; ++pos) {
300 var type = tparams[pos];
301 int index = pos - first;
304 if (type.HasElementType) {
305 var element = type.GetElementType ();
307 spec = ImportType (element, dtype);
310 throw new NotImplementedException ("Unknown element type " + type.ToString ());
313 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
315 spec = CreateType (type, dtype, true);
318 // We treat nested generic types as inflated internally where
319 // reflection uses type definition
322 // IFoo<A<T>> foo; // A<T> is definition in this case
325 // TODO: Is full logic from CreateType needed here as well?
327 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
328 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
329 spec = spec.MakeGenericType (module, targs);
340 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
342 Modifiers mod = ReadMethodModifiers (mb, declaringType);
343 TypeParameterSpec[] tparams;
345 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
347 if (mb.IsGenericMethod) {
348 if (!mb.IsGenericMethodDefinition)
349 throw new NotSupportedException ("assert");
351 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
358 if (mb.MemberType == MemberTypes.Constructor) {
359 kind = MemberKind.Constructor;
360 returnType = module.Compiler.BuiltinTypes.Void;
363 // Detect operators and destructors
365 string name = mb.Name;
366 kind = MemberKind.Method;
367 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
368 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
369 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
370 var op_type = Operator.GetType (name);
371 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
372 kind = MemberKind.Operator;
375 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
376 kind = MemberKind.Destructor;
377 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
378 mod &= ~Modifiers.OVERRIDE;
379 mod |= Modifiers.VIRTUAL;
384 var mi = (MethodInfo) mb;
385 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
387 // Cannot set to OVERRIDE without full hierarchy checks
388 // this flag indicates that the method could be override
389 // but further validation is needed
390 if ((mod & Modifiers.OVERRIDE) != 0) {
391 bool is_real_override = false;
392 if (kind == MemberKind.Method && declaringType.BaseType != null) {
393 var btype = declaringType.BaseType;
394 if (IsOverrideMethodBaseTypeAccessible (btype)) {
395 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
396 var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
399 // For imported class method do additional validation to be sure that metadata
400 // override flag was correct
402 // Difference between protected internal and protected is ok
404 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
405 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
406 is_real_override = true;
411 if (!is_real_override) {
412 mod &= ~Modifiers.OVERRIDE;
413 if ((mod & Modifiers.SEALED) != 0)
414 mod &= ~Modifiers.SEALED;
416 mod |= Modifiers.VIRTUAL;
421 IMemberDefinition definition;
422 if (tparams != null) {
423 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
424 foreach (var tp in gmd.TypeParameters) {
425 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
430 definition = new ImportedParameterMemberDefinition (mb, returnType, parameters, this);
433 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, mb, parameters, mod);
440 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
442 switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
443 case Modifiers.PUBLIC:
445 case Modifiers.INTERNAL:
447 // Check whether imported method in base type is accessible from compiled
450 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
451 case Modifiers.PRIVATE:
455 // protected internal
457 // Method accessibility checks will be done later based on context
458 // where the method is called (CS0122 error will be reported for inaccessible)
465 // Imports System.Reflection parameters
467 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
469 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
471 if (pi.Length == 0 && varargs == 0)
472 return ParametersCompiled.EmptyReadOnlyParameters;
474 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
475 IParameterData[] par = new IParameterData[pi.Length + varargs];
476 bool is_params = false;
477 for (int i = 0; i < pi.Length; i++) {
478 ParameterInfo p = pi[i];
479 Parameter.Modifier mod = 0;
480 Expression default_value = null;
481 if (p.ParameterType.IsByRef) {
482 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
483 mod = Parameter.Modifier.OUT;
485 mod = Parameter.Modifier.REF;
488 // Strip reference wrapping
490 var el = p.ParameterType.GetElementType ();
491 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
492 } else if (i == 0 && method.IsStatic && parent.IsStatic && parent.MemberDefinition.DeclaringAssembly.HasExtensionMethod &&
493 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
494 mod = Parameter.Modifier.This;
495 types[i] = ImportType (p.ParameterType);
497 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
499 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
500 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
501 mod = Parameter.Modifier.PARAMS;
506 if (!is_params && p.IsOptional) {
507 object value = p.RawDefaultValue;
508 var ptype = types[i];
509 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
511 default_value = Constant.CreateConstant (ptype, null, Location.Null);
513 default_value = ImportParameterConstant (value);
516 default_value = new EnumConstant ((Constant) default_value, ptype);
519 } else if (value == Missing.Value) {
520 default_value = EmptyExpression.MissingValue;
521 } else if (value == null) {
522 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
523 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
524 default_value = ImportParameterConstant (value);
529 par[i] = new ParameterData (p.Name, mod, default_value);
533 par[par.Length - 1] = new ArglistParameter (Location.Null);
534 types[types.Length - 1] = InternalType.Arglist;
537 return method != null ?
538 new ParametersImported (par, types, varargs != 0, is_params) :
539 new ParametersImported (par, types, is_params);
543 // Returns null when the property is not valid C# property
545 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
548 AParametersCollection param = null;
549 TypeSpec type = null;
552 param = get.Parameters;
553 type = get.ReturnType;
556 bool is_valid_property = true;
558 if (set.ReturnType.Kind != MemberKind.Void)
559 is_valid_property = false;
561 var set_param_count = set.Parameters.Count - 1;
563 if (set_param_count < 0) {
565 is_valid_property = false;
568 var set_type = set.Parameters.Types[set_param_count];
571 AParametersCollection set_based_param;
573 if (set_param_count == 0) {
574 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
577 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
579 var data = new IParameterData[set_param_count];
580 var types = new TypeSpec[set_param_count];
581 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
582 Array.Copy (set.Parameters.Types, types, set_param_count);
583 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
587 param = set_based_param;
590 if (set_param_count != get.Parameters.Count)
591 is_valid_property = false;
593 if (get.ReturnType != set_type)
594 is_valid_property = false;
596 // Possible custom accessor modifiers
597 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
598 var get_acc = mod & Modifiers.AccessibilityMask;
599 if (get_acc != Modifiers.PUBLIC) {
600 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
601 // If the accessor modifiers are not same, do extra restriction checks
602 if (get_acc != set_acc) {
603 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
604 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
605 if (get_restr && set_restr) {
606 is_valid_property = false; // Neither is more restrictive
610 mod &= ~Modifiers.AccessibilityMask;
619 PropertySpec spec = null;
620 if (!param.IsEmpty) {
621 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
622 if (index_name == null) {
623 is_valid_property = false;
627 is_valid_property = false;
628 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
629 is_valid_property = false;
633 is_valid_property = false;
634 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
635 is_valid_property = false;
639 if (is_valid_property)
640 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
644 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
646 if (!is_valid_property) {
647 spec.IsNotCSharpCompatible = true;
659 public TypeSpec CreateType (MetaType type)
661 return CreateType (type, new DynamicTypeReader (), true);
664 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
666 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
669 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
671 TypeSpec declaring_type;
672 if (type.IsNested && !type.IsGenericParameter)
673 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
675 declaring_type = null;
677 return CreateType (type, declaring_type, dtype, canImportBaseType);
680 TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
683 if (import_cache.TryGetValue (type, out spec)) {
684 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
685 if (dtype.IsDynamicObject (this))
686 return module.Compiler.BuiltinTypes.Dynamic;
691 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
694 if (!dtype.HasDynamicAttribute (this))
697 // We've found same object in the cache but this one has a dynamic custom attribute
698 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
699 // Do type resolve process again in that case
701 // TODO: Handle cases where they still unify
704 if (IsMissingType (type)) {
705 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
706 spec.MemberCache = MemberCache.Empty;
707 import_cache.Add (type, spec);
711 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
712 var type_def = type.GetGenericTypeDefinition ();
714 // Generic type definition can also be forwarded
715 if (compiled_types.TryGetValue (type_def, out spec))
718 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
719 if (declaringType == null) {
720 // Simple case, no nesting
721 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
722 spec = spec.MakeGenericType (module, targs);
725 // Nested type case, converting .NET types like
726 // A`1.B`1.C`1<int, long, string> to typespec like
727 // A<int>.B<long>.C<string>
729 var nested_hierarchy = new List<TypeSpec> ();
730 while (declaringType.IsNested) {
731 nested_hierarchy.Add (declaringType);
732 declaringType = declaringType.DeclaringType;
736 if (declaringType.Arity > 0) {
737 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
738 targs_pos = spec.Arity;
740 spec = declaringType;
743 for (int i = nested_hierarchy.Count; i != 0; --i) {
744 var t = nested_hierarchy [i - 1];
745 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
747 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
748 targs_pos += t.Arity;
752 string name = type.Name;
753 int index = name.IndexOf ('`');
755 name = name.Substring (0, index);
757 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
761 if (spec.Arity > 0) {
762 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
766 // Don't add generic type with dynamic arguments, they can interfere with same type
767 // using object type arguments
768 if (!spec.HasDynamicElement) {
770 // Add to reading cache to speed up reading
771 if (!import_cache.ContainsKey (type))
772 import_cache.Add (type, spec);
781 var ma = type.Attributes;
782 switch (ma & TypeAttributes.VisibilityMask) {
783 case TypeAttributes.Public:
784 case TypeAttributes.NestedPublic:
785 mod = Modifiers.PUBLIC;
787 case TypeAttributes.NestedPrivate:
788 mod = Modifiers.PRIVATE;
790 case TypeAttributes.NestedFamily:
791 mod = Modifiers.PROTECTED;
793 case TypeAttributes.NestedFamORAssem:
794 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
797 mod = Modifiers.INTERNAL;
801 if ((ma & TypeAttributes.Interface) != 0) {
802 kind = MemberKind.Interface;
803 } else if (type.IsGenericParameter) {
804 kind = MemberKind.TypeParameter;
806 var base_type = type.BaseType;
807 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
808 kind = MemberKind.Class;
810 kind = DetermineKindFromBaseType (base_type);
811 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
812 mod |= Modifiers.SEALED;
816 if (kind == MemberKind.Class) {
817 if ((ma & TypeAttributes.Sealed) != 0) {
818 mod |= Modifiers.SEALED;
819 if ((ma & TypeAttributes.Abstract) != 0)
820 mod |= Modifiers.STATIC;
821 } else if ((ma & TypeAttributes.Abstract) != 0) {
822 mod |= Modifiers.ABSTRACT;
827 var definition = new ImportedTypeDefinition (type, this);
830 if (kind == MemberKind.Enum) {
831 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
832 BindingFlags.Instance |
833 BindingFlags.Public | BindingFlags.NonPublic;
835 var type_members = type.GetFields (underlying_member);
836 foreach (var type_member in type_members) {
837 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
842 kind = MemberKind.Class;
844 } else if (kind == MemberKind.TypeParameter) {
845 spec = CreateTypeParameter (type, declaringType);
846 } else if (type.IsGenericTypeDefinition) {
847 definition.TypeParameters = CreateGenericParameters (type, declaringType);
848 } else if (compiled_types.TryGetValue (type, out pt)) {
850 // Same type was found in inside compiled types. It's
851 // either build-in type or forward referenced typed
852 // which point into just compiled assembly.
855 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
857 bts.SetDefinition (definition, type, mod);
861 spec = new TypeSpec (kind, declaringType, definition, type, mod);
863 import_cache.Add (type, spec);
865 if (kind == MemberKind.TypeParameter) {
866 if (canImportBaseType)
867 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
873 // Two stage setup as the base type can be inflated declaring type or
874 // another nested type inside same declaring type which has not been
875 // loaded, therefore we can import a base type of nested types once
876 // the types have been imported
878 if (canImportBaseType)
879 ImportTypeBase (spec, type);
884 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
886 IAssemblyDefinition found;
887 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
889 // This can happen in dynamic context only
890 var def = new ImportedAssemblyDefinition (assembly);
891 assembly_2_definition.Add (assembly, def);
892 def.ReadAttributes ();
899 public void ImportTypeBase (MetaType type)
901 TypeSpec spec = import_cache[type];
903 ImportTypeBase (spec, type);
906 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
909 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
910 case GenericParameterAttributes.Covariant:
911 variance = Variance.Covariant;
913 case GenericParameterAttributes.Contravariant:
914 variance = Variance.Contravariant;
917 variance = Variance.None;
921 SpecialConstraint special = SpecialConstraint.None;
922 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
924 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
925 special |= SpecialConstraint.Struct;
926 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
927 special = SpecialConstraint.Constructor;
930 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
931 special |= SpecialConstraint.Class;
934 TypeParameterSpec spec;
935 var def = new ImportedTypeParameterDefinition (type, this);
936 if (type.DeclaringMethod != null) {
937 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
939 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
946 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
947 // they can be assembly specific therefore we do check based on names only
949 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
951 if (attributesData.Count == 0)
954 foreach (var attr in attributesData) {
955 var dt = attr.Constructor.DeclaringType;
956 if (dt.Name == attrName && dt.Namespace == attrNamespace)
963 void ImportTypeBase (TypeSpec spec, MetaType type)
965 if (spec.Kind == MemberKind.Interface)
966 spec.BaseType = module.Compiler.BuiltinTypes.Object;
967 else if (type.BaseType != null) {
969 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
970 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
972 base_type = CreateType (type.BaseType);
974 spec.BaseType = base_type;
979 ifaces = type.__GetDeclaredInterfaces ();
980 if (ifaces.Length != 0) {
981 foreach (var iface in ifaces) {
982 var it = CreateType (iface);
986 spec.AddInterface (it);
988 // Unfortunately not all languages expand inherited interfaces
989 var bifaces = it.Interfaces;
990 if (bifaces != null) {
991 foreach (var biface in bifaces) {
992 spec.AddInterface (biface);
998 if (spec.BaseType != null) {
999 var bifaces = spec.BaseType.Interfaces;
1000 if (bifaces != null) {
1002 // Before adding base class interfaces close defined interfaces
1003 // on type parameter
1005 var tp = spec as TypeParameterSpec;
1006 if (tp != null && tp.InterfacesDefined == null) {
1007 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1010 foreach (var iface in bifaces)
1011 spec.AddInterface (iface);
1015 ifaces = type.GetInterfaces ();
1017 if (ifaces.Length > 0) {
1018 foreach (var iface in ifaces) {
1019 spec.AddInterface (CreateType (iface));
1024 if (spec.MemberDefinition.TypeParametersCount > 0) {
1025 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1026 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1031 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
1033 Namespace ns = targetNamespace;
1034 string prev_namespace = null;
1035 foreach (var t in types) {
1039 // Be careful not to trigger full parent type loading
1040 if (t.MemberType == MemberTypes.NestedType)
1043 if (t.Name[0] == '<')
1046 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1050 if (prev_namespace != t.Namespace) {
1051 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1052 prev_namespace = t.Namespace;
1055 ns.AddType (module, it);
1057 if (it.IsStatic && hasExtensionTypes &&
1058 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1059 it.SetExtensionMethodContainer ();
1064 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1066 var constraints = type.GetGenericParameterConstraints ();
1067 List<TypeSpec> tparams = null;
1068 foreach (var ct in constraints) {
1069 if (ct.IsGenericParameter) {
1070 if (tparams == null)
1071 tparams = new List<TypeSpec> ();
1073 tparams.Add (CreateType (ct));
1077 if (!IsMissingType (ct) && ct.IsClass) {
1078 spec.BaseType = CreateType (ct);
1082 spec.AddInterface (CreateType (ct));
1085 if (spec.BaseType == null)
1086 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1088 if (tparams != null)
1089 spec.TypeArguments = tparams.ToArray ();
1092 Constant ImportParameterConstant (object value)
1095 // Get type of underlying value as int constant can be used for object
1096 // parameter type. This is not allowed in C# but other languages can do that
1098 var types = module.Compiler.BuiltinTypes;
1099 switch (System.Type.GetTypeCode (value.GetType ())) {
1100 case TypeCode.Boolean:
1101 return new BoolConstant (types, (bool) value, Location.Null);
1103 return new ByteConstant (types, (byte) value, Location.Null);
1105 return new CharConstant (types, (char) value, Location.Null);
1106 case TypeCode.Decimal:
1107 return new DecimalConstant (types, (decimal) value, Location.Null);
1108 case TypeCode.Double:
1109 return new DoubleConstant (types, (double) value, Location.Null);
1110 case TypeCode.Int16:
1111 return new ShortConstant (types, (short) value, Location.Null);
1112 case TypeCode.Int32:
1113 return new IntConstant (types, (int) value, Location.Null);
1114 case TypeCode.Int64:
1115 return new LongConstant (types, (long) value, Location.Null);
1116 case TypeCode.SByte:
1117 return new SByteConstant (types, (sbyte) value, Location.Null);
1118 case TypeCode.Single:
1119 return new FloatConstant (types, (float) value, Location.Null);
1120 case TypeCode.String:
1121 return new StringConstant (types, (string) value, Location.Null);
1122 case TypeCode.UInt16:
1123 return new UShortConstant (types, (ushort) value, Location.Null);
1124 case TypeCode.UInt32:
1125 return new UIntConstant (types, (uint) value, Location.Null);
1126 case TypeCode.UInt64:
1127 return new ULongConstant (types, (ulong) value, Location.Null);
1130 throw new NotImplementedException (value.GetType ().ToString ());
1133 public TypeSpec ImportType (MetaType type)
1135 return ImportType (type, new DynamicTypeReader (type));
1138 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1140 if (type.HasElementType) {
1141 var element = type.GetElementType ();
1143 var spec = ImportType (element, dtype);
1146 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1148 return ReferenceContainer.MakeType (module, spec);
1150 return PointerContainer.MakeType (module, spec);
1152 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1155 return CreateType (type, dtype, true);
1158 static bool IsMissingType (MetaType type)
1161 return type.__IsMissing;
1168 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1169 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1170 // DecimalConstantAttribute metadata.
1172 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1174 if (attrs.Count == 0)
1177 foreach (var ca in attrs) {
1178 var dt = ca.Constructor.DeclaringType;
1179 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1182 var value = new decimal (
1183 (int) (uint) ca.ConstructorArguments[4].Value,
1184 (int) (uint) ca.ConstructorArguments[3].Value,
1185 (int) (uint) ca.ConstructorArguments[2].Value,
1186 (byte) ca.ConstructorArguments[1].Value != 0,
1187 (byte) ca.ConstructorArguments[0].Value);
1189 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1195 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1198 var ma = mb.Attributes;
1199 switch (ma & MethodAttributes.MemberAccessMask) {
1200 case MethodAttributes.Public:
1201 mod = Modifiers.PUBLIC;
1203 case MethodAttributes.Assembly:
1204 mod = Modifiers.INTERNAL;
1206 case MethodAttributes.Family:
1207 mod = Modifiers.PROTECTED;
1209 case MethodAttributes.FamORAssem:
1210 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1213 mod = Modifiers.PRIVATE;
1217 if ((ma & MethodAttributes.Static) != 0) {
1218 mod |= Modifiers.STATIC;
1221 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1222 mod |= Modifiers.ABSTRACT;
1226 // It can be sealed and override
1227 if ((ma & MethodAttributes.Final) != 0)
1228 mod |= Modifiers.SEALED;
1230 if ((ma & MethodAttributes.Virtual) != 0) {
1231 // Not every member can be detected based on MethodAttribute, we
1232 // set virtual or non-virtual only when we are certain. Further checks
1233 // to really find out what `virtual' means for this member are done
1235 if ((ma & MethodAttributes.NewSlot) != 0) {
1236 if ((mod & Modifiers.SEALED) != 0) {
1237 mod &= ~Modifiers.SEALED;
1239 mod |= Modifiers.VIRTUAL;
1242 mod |= Modifiers.OVERRIDE;
1250 abstract class ImportedDefinition : IMemberDefinition
1252 protected class AttributesBag
1254 public static readonly AttributesBag Default = new AttributesBag ();
1256 public AttributeUsageAttribute AttributeUsage;
1257 public ObsoleteAttribute Obsolete;
1258 public string[] Conditionals;
1259 public string DefaultIndexerName;
1260 public bool? CLSAttributeValue;
1261 public TypeSpec CoClass;
1263 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1265 AttributesBag bag = null;
1266 List<string> conditionals = null;
1268 // It should not throw any loading exception
1269 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1271 foreach (var a in attrs) {
1272 var dt = a.Constructor.DeclaringType;
1273 string name = dt.Name;
1274 if (name == "ObsoleteAttribute") {
1275 if (dt.Namespace != "System")
1279 bag = new AttributesBag ();
1281 var args = a.ConstructorArguments;
1283 if (args.Count == 1) {
1284 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1285 } else if (args.Count == 2) {
1286 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1288 bag.Obsolete = new ObsoleteAttribute ();
1294 if (name == "ConditionalAttribute") {
1295 if (dt.Namespace != "System.Diagnostics")
1299 bag = new AttributesBag ();
1301 if (conditionals == null)
1302 conditionals = new List<string> (2);
1304 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1308 if (name == "CLSCompliantAttribute") {
1309 if (dt.Namespace != "System")
1313 bag = new AttributesBag ();
1315 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1319 // Type only attributes
1320 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1321 if (name == "DefaultMemberAttribute") {
1322 if (dt.Namespace != "System.Reflection")
1326 bag = new AttributesBag ();
1328 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1332 if (name == "AttributeUsageAttribute") {
1333 if (dt.Namespace != "System")
1337 bag = new AttributesBag ();
1339 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1340 foreach (var named in a.NamedArguments) {
1341 if (named.MemberInfo.Name == "AllowMultiple")
1342 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1343 else if (named.MemberInfo.Name == "Inherited")
1344 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1349 // Interface only attribute
1350 if (name == "CoClassAttribute") {
1351 if (dt.Namespace != "System.Runtime.InteropServices")
1355 bag = new AttributesBag ();
1357 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1366 if (conditionals != null)
1367 bag.Conditionals = conditionals.ToArray ();
1373 protected readonly MemberInfo provider;
1374 protected AttributesBag cattrs;
1375 protected readonly MetadataImporter importer;
1377 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1379 this.provider = provider;
1380 this.importer = importer;
1385 public bool IsImported {
1391 public virtual string Name {
1393 return provider.Name;
1399 public string[] ConditionalConditions ()
1404 return cattrs.Conditionals;
1407 public ObsoleteAttribute GetAttributeObsolete ()
1412 return cattrs.Obsolete;
1415 public bool? CLSAttributeValue {
1420 return cattrs.CLSAttributeValue;
1424 protected void ReadAttributes ()
1426 cattrs = AttributesBag.Read (provider, importer);
1429 public void SetIsAssigned ()
1431 // Unused for imported members
1434 public void SetIsUsed ()
1436 // Unused for imported members
1440 public class ImportedModuleDefinition
1442 readonly Module module;
1445 public ImportedModuleDefinition (Module module)
1447 this.module = module;
1452 public bool IsCLSCompliant {
1454 return cls_compliant;
1458 public string Name {
1466 public void ReadAttributes ()
1468 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1470 foreach (var a in attrs) {
1471 var dt = a.Constructor.DeclaringType;
1472 if (dt.Name == "CLSCompliantAttribute") {
1473 if (dt.Namespace != "System")
1476 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1483 // Reads assembly attributes which where attached to a special type because
1484 // module does have assembly manifest
1486 public List<Attribute> ReadAssemblyAttributes ()
1488 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1492 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1496 // TODO: implement, the idea is to fabricate specil Attribute class and
1497 // add it to OptAttributes before resolving the source code attributes
1498 // Need to build module location as well for correct error reporting
1500 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1501 //var attrs = new List<Attribute> (assembly_attributes.Count);
1502 //foreach (var a in assembly_attributes)
1504 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1505 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1507 // foreach (var carg in a.ConstructorArguments) {
1511 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1518 public class ImportedAssemblyDefinition : IAssemblyDefinition
1520 readonly Assembly assembly;
1521 readonly AssemblyName aname;
1523 bool contains_extension_methods;
1525 List<AssemblyName> internals_visible_to;
1526 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1528 public ImportedAssemblyDefinition (Assembly assembly)
1530 this.assembly = assembly;
1531 this.aname = assembly.GetName ();
1536 public Assembly Assembly {
1542 public string FullName {
1544 return aname.FullName;
1548 public bool HasExtensionMethod {
1550 return contains_extension_methods;
1554 public bool HasStrongName {
1556 return aname.GetPublicKey ().Length != 0;
1560 public bool IsMissing {
1563 return assembly.__IsMissing;
1570 public bool IsCLSCompliant {
1572 return cls_compliant;
1576 public string Location {
1578 return assembly.Location;
1582 public string Name {
1590 public byte[] GetPublicKeyToken ()
1592 return aname.GetPublicKeyToken ();
1595 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1597 return internals_visible_to_cache [assembly];
1600 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1602 if (internals_visible_to == null)
1605 AssemblyName is_visible = null;
1606 if (internals_visible_to_cache == null) {
1607 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1609 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1610 return is_visible != null;
1613 var token = assembly.GetPublicKeyToken ();
1614 if (token != null && token.Length == 0)
1617 foreach (var internals in internals_visible_to) {
1618 if (internals.Name != assembly.Name)
1621 if (token == null && assembly is AssemblyDefinition) {
1622 is_visible = internals;
1626 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1629 is_visible = internals;
1633 internals_visible_to_cache.Add (assembly, is_visible);
1634 return is_visible != null;
1637 public void ReadAttributes ()
1640 if (assembly.__IsMissing)
1644 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1646 foreach (var a in attrs) {
1647 var dt = a.Constructor.DeclaringType;
1649 if (name == "CLSCompliantAttribute") {
1650 if (dt.Namespace == "System") {
1651 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1656 if (name == "InternalsVisibleToAttribute") {
1657 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1660 string s = a.ConstructorArguments[0].Value as string;
1664 var an = new AssemblyName (s);
1665 if (internals_visible_to == null)
1666 internals_visible_to = new List<AssemblyName> ();
1668 internals_visible_to.Add (an);
1672 if (name == "ExtensionAttribute") {
1673 if (dt.Namespace == MetadataImporter.CompilerServicesNamespace)
1674 contains_extension_methods = true;
1681 public override string ToString ()
1687 class ImportedMemberDefinition : ImportedDefinition
1689 readonly TypeSpec type;
1691 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1692 : base (member, importer)
1699 public TypeSpec MemberType {
1708 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1710 readonly AParametersCollection parameters;
1712 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1713 : base (provider, type, importer)
1715 this.parameters = parameters;
1718 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1719 : base (provider, type, importer)
1721 this.parameters = parameters;
1726 public AParametersCollection Parameters {
1735 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1737 readonly TypeParameterSpec[] tparams;
1739 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1740 : base (provider, type, parameters, importer)
1742 this.tparams = tparams;
1747 public TypeParameterSpec[] TypeParameters {
1753 public int TypeParametersCount {
1755 return tparams.Length;
1762 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1764 TypeParameterSpec[] tparams;
1767 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1768 : base (type, importer)
1774 public IAssemblyDefinition DeclaringAssembly {
1776 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1780 bool ITypeDefinition.IsPartial {
1786 public override string Name {
1790 if (tparams != null) {
1791 int arity_start = name.IndexOf ('`');
1792 if (arity_start > 0)
1793 name = name.Substring (0, arity_start);
1801 public string Namespace {
1803 return ((MetaType) provider).Namespace;
1807 public int TypeParametersCount {
1809 return tparams == null ? 0 : tparams.Length;
1813 public TypeParameterSpec[] TypeParameters {
1824 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1827 // Report details about missing type and most likely cause of the problem.
1828 // csc reports 1683, 1684 as warnings but we report them only when used
1829 // or referenced from the user core in which case compilation error has to
1830 // be reported because compiler cannot continue anyway
1832 for (int i = 0; i < types.Count; ++i) {
1836 // Report missing types only once per type
1838 if (i > 0 && types.IndexOf (t) < i)
1841 string name = t.GetSignatureForError ();
1843 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1844 ctx.Module.Compiler.Report.Error (1683, loc,
1845 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1847 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1848 ctx.Module.Compiler.Report.Error (12, loc,
1849 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1850 name, t.MemberDefinition.DeclaringAssembly.FullName);
1852 ctx.Module.Compiler.Report.Error (1684, loc,
1853 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1854 name, t.MemberDefinition.DeclaringAssembly.FullName);
1859 public TypeSpec GetAttributeCoClass ()
1864 return cattrs.CoClass;
1867 public string GetAttributeDefaultMember ()
1872 return cattrs.DefaultIndexerName;
1875 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1880 return cattrs.AttributeUsage;
1883 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1885 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1886 return a == assembly || a.IsFriendAssemblyTo (assembly);
1889 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1892 // Not interested in members of nested private types unless the importer needs them
1894 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1895 cache = MemberCache.Empty;
1899 var loading_type = (MetaType) provider;
1900 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1901 BindingFlags.Static | BindingFlags.Instance |
1902 BindingFlags.Public | BindingFlags.NonPublic;
1904 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1905 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1906 MethodAttributes.Final;
1908 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1909 List<EventSpec> imported_events = null;
1910 EventSpec event_spec;
1911 MemberSpec imported;
1915 all = loading_type.GetMembers (all_members);
1916 } catch (Exception e) {
1917 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1918 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1921 if (cache == null) {
1922 cache = new MemberCache (all.Length);
1925 // Do the types first as they can be referenced by the members before
1926 // they are found or inflated
1928 foreach (var member in all) {
1929 if (member.MemberType != MemberTypes.NestedType)
1932 var t = (MetaType) member;
1934 // Ignore compiler generated types, mostly lambda containers
1935 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1939 imported = importer.CreateNestedType (t, declaringType);
1940 } catch (Exception e) {
1941 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
1942 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
1945 cache.AddMemberImported (imported);
1948 foreach (var member in all) {
1949 if (member.MemberType != MemberTypes.NestedType)
1952 var t = (MetaType) member;
1954 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1957 importer.ImportTypeBase (t);
1962 // Load base interfaces first to minic behaviour of compiled members
1964 if (declaringType.IsInterface && declaringType.Interfaces != null) {
1965 foreach (var iface in declaringType.Interfaces) {
1966 cache.AddInterface (iface);
1972 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1974 foreach (var member in all) {
1975 switch (member.MemberType) {
1976 case MemberTypes.Constructor:
1977 case MemberTypes.Method:
1978 MethodBase mb = (MethodBase) member;
1979 var attrs = mb.Attributes;
1981 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1982 if (importer.IgnorePrivateMembers)
1985 // Ignore explicitly implemented members
1986 if ((attrs & explicit_impl) == explicit_impl)
1989 // Ignore compiler generated methods
1990 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1994 imported = importer.CreateMethod (mb, declaringType);
1995 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1996 if (possible_accessors == null)
1997 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1999 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2000 possible_accessors.Add (mb, (MethodSpec) imported);
2004 case MemberTypes.Property:
2005 if (possible_accessors == null)
2008 var p = (PropertyInfo) member;
2010 // Links possible accessors with property
2012 MethodSpec get, set;
2013 m = p.GetGetMethod (true);
2014 if (m == null || !possible_accessors.TryGetValue (m, out get))
2017 m = p.GetSetMethod (true);
2018 if (m == null || !possible_accessors.TryGetValue (m, out set))
2021 // No accessors registered (e.g. explicit implementation)
2022 if (get == null && set == null)
2025 imported = importer.CreateProperty (p, declaringType, get, set);
2026 if (imported == null)
2030 case MemberTypes.Event:
2031 if (possible_accessors == null)
2034 var e = (EventInfo) member;
2036 // Links accessors with event
2038 MethodSpec add, remove;
2039 m = e.GetAddMethod (true);
2040 if (m == null || !possible_accessors.TryGetValue (m, out add))
2043 m = e.GetRemoveMethod (true);
2044 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2047 // Both accessors are required
2048 if (add == null || remove == null)
2051 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2052 if (!importer.IgnorePrivateMembers) {
2053 if (imported_events == null)
2054 imported_events = new List<EventSpec> ();
2056 imported_events.Add (event_spec);
2059 imported = event_spec;
2061 case MemberTypes.Field:
2062 var fi = (FieldInfo) member;
2064 imported = importer.CreateField (fi, declaringType);
2065 if (imported == null)
2069 // For dynamic binder event has to be fully restored to allow operations
2070 // within the type container to work correctly
2072 if (imported_events != null) {
2073 // The backing event field should be private but it may not
2075 for (i = 0; i < imported_events.Count; ++i) {
2076 var ev = imported_events[i];
2077 if (ev.Name == fi.Name) {
2078 ev.BackingField = (FieldSpec) imported;
2079 imported_events.RemoveAt (i);
2090 case MemberTypes.NestedType:
2091 // Already in the cache from the first pass
2094 throw new NotImplementedException (member.ToString ());
2097 cache.AddMemberImported (imported);
2103 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2105 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2106 : base (type, importer)
2112 public IAssemblyDefinition DeclaringAssembly {
2114 throw new NotImplementedException ();
2118 bool ITypeDefinition.IsPartial {
2124 public string Namespace {
2130 public int TypeParametersCount {
2136 public TypeParameterSpec[] TypeParameters {
2144 public TypeSpec GetAttributeCoClass ()
2149 public string GetAttributeDefaultMember ()
2151 throw new NotSupportedException ();
2154 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2156 throw new NotSupportedException ();
2159 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2161 throw new NotImplementedException ();
2164 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2166 throw new NotImplementedException ();