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 var constraint_type = CreateType (ct);
1078 if (constraint_type.IsClass) {
1079 spec.BaseType = constraint_type;
1083 spec.AddInterface (constraint_type);
1086 if (spec.BaseType == null)
1087 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1089 if (tparams != null)
1090 spec.TypeArguments = tparams.ToArray ();
1093 Constant ImportParameterConstant (object value)
1096 // Get type of underlying value as int constant can be used for object
1097 // parameter type. This is not allowed in C# but other languages can do that
1099 var types = module.Compiler.BuiltinTypes;
1100 switch (System.Type.GetTypeCode (value.GetType ())) {
1101 case TypeCode.Boolean:
1102 return new BoolConstant (types, (bool) value, Location.Null);
1104 return new ByteConstant (types, (byte) value, Location.Null);
1106 return new CharConstant (types, (char) value, Location.Null);
1107 case TypeCode.Decimal:
1108 return new DecimalConstant (types, (decimal) value, Location.Null);
1109 case TypeCode.Double:
1110 return new DoubleConstant (types, (double) value, Location.Null);
1111 case TypeCode.Int16:
1112 return new ShortConstant (types, (short) value, Location.Null);
1113 case TypeCode.Int32:
1114 return new IntConstant (types, (int) value, Location.Null);
1115 case TypeCode.Int64:
1116 return new LongConstant (types, (long) value, Location.Null);
1117 case TypeCode.SByte:
1118 return new SByteConstant (types, (sbyte) value, Location.Null);
1119 case TypeCode.Single:
1120 return new FloatConstant (types, (float) value, Location.Null);
1121 case TypeCode.String:
1122 return new StringConstant (types, (string) value, Location.Null);
1123 case TypeCode.UInt16:
1124 return new UShortConstant (types, (ushort) value, Location.Null);
1125 case TypeCode.UInt32:
1126 return new UIntConstant (types, (uint) value, Location.Null);
1127 case TypeCode.UInt64:
1128 return new ULongConstant (types, (ulong) value, Location.Null);
1131 throw new NotImplementedException (value.GetType ().ToString ());
1134 public TypeSpec ImportType (MetaType type)
1136 return ImportType (type, new DynamicTypeReader (type));
1139 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1141 if (type.HasElementType) {
1142 var element = type.GetElementType ();
1144 var spec = ImportType (element, dtype);
1147 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1149 return ReferenceContainer.MakeType (module, spec);
1151 return PointerContainer.MakeType (module, spec);
1153 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1156 return CreateType (type, dtype, true);
1159 static bool IsMissingType (MetaType type)
1162 return type.__IsMissing;
1169 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1170 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1171 // DecimalConstantAttribute metadata.
1173 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1175 if (attrs.Count == 0)
1178 foreach (var ca in attrs) {
1179 var dt = ca.Constructor.DeclaringType;
1180 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1183 var value = new decimal (
1184 (int) (uint) ca.ConstructorArguments[4].Value,
1185 (int) (uint) ca.ConstructorArguments[3].Value,
1186 (int) (uint) ca.ConstructorArguments[2].Value,
1187 (byte) ca.ConstructorArguments[1].Value != 0,
1188 (byte) ca.ConstructorArguments[0].Value);
1190 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1196 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1199 var ma = mb.Attributes;
1200 switch (ma & MethodAttributes.MemberAccessMask) {
1201 case MethodAttributes.Public:
1202 mod = Modifiers.PUBLIC;
1204 case MethodAttributes.Assembly:
1205 mod = Modifiers.INTERNAL;
1207 case MethodAttributes.Family:
1208 mod = Modifiers.PROTECTED;
1210 case MethodAttributes.FamORAssem:
1211 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1214 mod = Modifiers.PRIVATE;
1218 if ((ma & MethodAttributes.Static) != 0) {
1219 mod |= Modifiers.STATIC;
1222 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1223 mod |= Modifiers.ABSTRACT;
1227 // It can be sealed and override
1228 if ((ma & MethodAttributes.Final) != 0)
1229 mod |= Modifiers.SEALED;
1231 if ((ma & MethodAttributes.Virtual) != 0) {
1232 // Not every member can be detected based on MethodAttribute, we
1233 // set virtual or non-virtual only when we are certain. Further checks
1234 // to really find out what `virtual' means for this member are done
1236 if ((ma & MethodAttributes.NewSlot) != 0) {
1237 if ((mod & Modifiers.SEALED) != 0) {
1238 mod &= ~Modifiers.SEALED;
1240 mod |= Modifiers.VIRTUAL;
1243 mod |= Modifiers.OVERRIDE;
1251 abstract class ImportedDefinition : IMemberDefinition
1253 protected class AttributesBag
1255 public static readonly AttributesBag Default = new AttributesBag ();
1257 public AttributeUsageAttribute AttributeUsage;
1258 public ObsoleteAttribute Obsolete;
1259 public string[] Conditionals;
1260 public string DefaultIndexerName;
1261 public bool? CLSAttributeValue;
1262 public TypeSpec CoClass;
1264 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1266 AttributesBag bag = null;
1267 List<string> conditionals = null;
1269 // It should not throw any loading exception
1270 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1272 foreach (var a in attrs) {
1273 var dt = a.Constructor.DeclaringType;
1274 string name = dt.Name;
1275 if (name == "ObsoleteAttribute") {
1276 if (dt.Namespace != "System")
1280 bag = new AttributesBag ();
1282 var args = a.ConstructorArguments;
1284 if (args.Count == 1) {
1285 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1286 } else if (args.Count == 2) {
1287 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1289 bag.Obsolete = new ObsoleteAttribute ();
1295 if (name == "ConditionalAttribute") {
1296 if (dt.Namespace != "System.Diagnostics")
1300 bag = new AttributesBag ();
1302 if (conditionals == null)
1303 conditionals = new List<string> (2);
1305 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1309 if (name == "CLSCompliantAttribute") {
1310 if (dt.Namespace != "System")
1314 bag = new AttributesBag ();
1316 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1320 // Type only attributes
1321 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1322 if (name == "DefaultMemberAttribute") {
1323 if (dt.Namespace != "System.Reflection")
1327 bag = new AttributesBag ();
1329 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1333 if (name == "AttributeUsageAttribute") {
1334 if (dt.Namespace != "System")
1338 bag = new AttributesBag ();
1340 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1341 foreach (var named in a.NamedArguments) {
1342 if (named.MemberInfo.Name == "AllowMultiple")
1343 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1344 else if (named.MemberInfo.Name == "Inherited")
1345 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1350 // Interface only attribute
1351 if (name == "CoClassAttribute") {
1352 if (dt.Namespace != "System.Runtime.InteropServices")
1356 bag = new AttributesBag ();
1358 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1367 if (conditionals != null)
1368 bag.Conditionals = conditionals.ToArray ();
1374 protected readonly MemberInfo provider;
1375 protected AttributesBag cattrs;
1376 protected readonly MetadataImporter importer;
1378 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1380 this.provider = provider;
1381 this.importer = importer;
1386 public bool IsImported {
1392 public virtual string Name {
1394 return provider.Name;
1400 public string[] ConditionalConditions ()
1405 return cattrs.Conditionals;
1408 public ObsoleteAttribute GetAttributeObsolete ()
1413 return cattrs.Obsolete;
1416 public bool? CLSAttributeValue {
1421 return cattrs.CLSAttributeValue;
1425 protected void ReadAttributes ()
1427 cattrs = AttributesBag.Read (provider, importer);
1430 public void SetIsAssigned ()
1432 // Unused for imported members
1435 public void SetIsUsed ()
1437 // Unused for imported members
1441 public class ImportedModuleDefinition
1443 readonly Module module;
1446 public ImportedModuleDefinition (Module module)
1448 this.module = module;
1453 public bool IsCLSCompliant {
1455 return cls_compliant;
1459 public string Name {
1467 public void ReadAttributes ()
1469 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1471 foreach (var a in attrs) {
1472 var dt = a.Constructor.DeclaringType;
1473 if (dt.Name == "CLSCompliantAttribute") {
1474 if (dt.Namespace != "System")
1477 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1484 // Reads assembly attributes which where attached to a special type because
1485 // module does have assembly manifest
1487 public List<Attribute> ReadAssemblyAttributes ()
1489 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1493 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1497 // TODO: implement, the idea is to fabricate specil Attribute class and
1498 // add it to OptAttributes before resolving the source code attributes
1499 // Need to build module location as well for correct error reporting
1501 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1502 //var attrs = new List<Attribute> (assembly_attributes.Count);
1503 //foreach (var a in assembly_attributes)
1505 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1506 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1508 // foreach (var carg in a.ConstructorArguments) {
1512 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1519 public class ImportedAssemblyDefinition : IAssemblyDefinition
1521 readonly Assembly assembly;
1522 readonly AssemblyName aname;
1524 bool contains_extension_methods;
1526 List<AssemblyName> internals_visible_to;
1527 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1529 public ImportedAssemblyDefinition (Assembly assembly)
1531 this.assembly = assembly;
1532 this.aname = assembly.GetName ();
1537 public Assembly Assembly {
1543 public string FullName {
1545 return aname.FullName;
1549 public bool HasExtensionMethod {
1551 return contains_extension_methods;
1555 public bool HasStrongName {
1557 return aname.GetPublicKey ().Length != 0;
1561 public bool IsMissing {
1564 return assembly.__IsMissing;
1571 public bool IsCLSCompliant {
1573 return cls_compliant;
1577 public string Location {
1579 return assembly.Location;
1583 public string Name {
1591 public byte[] GetPublicKeyToken ()
1593 return aname.GetPublicKeyToken ();
1596 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1598 return internals_visible_to_cache [assembly];
1601 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1603 if (internals_visible_to == null)
1606 AssemblyName is_visible = null;
1607 if (internals_visible_to_cache == null) {
1608 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1610 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1611 return is_visible != null;
1614 var token = assembly.GetPublicKeyToken ();
1615 if (token != null && token.Length == 0)
1618 foreach (var internals in internals_visible_to) {
1619 if (internals.Name != assembly.Name)
1622 if (token == null && assembly is AssemblyDefinition) {
1623 is_visible = internals;
1627 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1630 is_visible = internals;
1634 internals_visible_to_cache.Add (assembly, is_visible);
1635 return is_visible != null;
1638 public void ReadAttributes ()
1641 if (assembly.__IsMissing)
1645 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1647 foreach (var a in attrs) {
1648 var dt = a.Constructor.DeclaringType;
1650 if (name == "CLSCompliantAttribute") {
1651 if (dt.Namespace == "System") {
1652 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1657 if (name == "InternalsVisibleToAttribute") {
1658 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1661 string s = a.ConstructorArguments[0].Value as string;
1665 var an = new AssemblyName (s);
1666 if (internals_visible_to == null)
1667 internals_visible_to = new List<AssemblyName> ();
1669 internals_visible_to.Add (an);
1673 if (name == "ExtensionAttribute") {
1674 if (dt.Namespace == MetadataImporter.CompilerServicesNamespace)
1675 contains_extension_methods = true;
1682 public override string ToString ()
1688 class ImportedMemberDefinition : ImportedDefinition
1690 readonly TypeSpec type;
1692 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1693 : base (member, importer)
1700 public TypeSpec MemberType {
1709 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1711 readonly AParametersCollection parameters;
1713 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1714 : base (provider, type, importer)
1716 this.parameters = parameters;
1719 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1720 : base (provider, type, importer)
1722 this.parameters = parameters;
1727 public AParametersCollection Parameters {
1736 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1738 readonly TypeParameterSpec[] tparams;
1740 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1741 : base (provider, type, parameters, importer)
1743 this.tparams = tparams;
1748 public TypeParameterSpec[] TypeParameters {
1754 public int TypeParametersCount {
1756 return tparams.Length;
1763 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1765 TypeParameterSpec[] tparams;
1768 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1769 : base (type, importer)
1775 public IAssemblyDefinition DeclaringAssembly {
1777 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1781 bool ITypeDefinition.IsPartial {
1787 public override string Name {
1791 if (tparams != null) {
1792 int arity_start = name.IndexOf ('`');
1793 if (arity_start > 0)
1794 name = name.Substring (0, arity_start);
1802 public string Namespace {
1804 return ((MetaType) provider).Namespace;
1808 public int TypeParametersCount {
1810 return tparams == null ? 0 : tparams.Length;
1814 public TypeParameterSpec[] TypeParameters {
1825 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1828 // Report details about missing type and most likely cause of the problem.
1829 // csc reports 1683, 1684 as warnings but we report them only when used
1830 // or referenced from the user core in which case compilation error has to
1831 // be reported because compiler cannot continue anyway
1833 for (int i = 0; i < types.Count; ++i) {
1837 // Report missing types only once per type
1839 if (i > 0 && types.IndexOf (t) < i)
1842 string name = t.GetSignatureForError ();
1844 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1845 ctx.Module.Compiler.Report.Error (1683, loc,
1846 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1848 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1849 ctx.Module.Compiler.Report.Error (12, loc,
1850 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1851 name, t.MemberDefinition.DeclaringAssembly.FullName);
1853 ctx.Module.Compiler.Report.Error (1684, loc,
1854 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1855 name, t.MemberDefinition.DeclaringAssembly.FullName);
1860 public TypeSpec GetAttributeCoClass ()
1865 return cattrs.CoClass;
1868 public string GetAttributeDefaultMember ()
1873 return cattrs.DefaultIndexerName;
1876 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1881 return cattrs.AttributeUsage;
1884 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1886 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1887 return a == assembly || a.IsFriendAssemblyTo (assembly);
1890 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1893 // Not interested in members of nested private types unless the importer needs them
1895 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1896 cache = MemberCache.Empty;
1900 var loading_type = (MetaType) provider;
1901 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1902 BindingFlags.Static | BindingFlags.Instance |
1903 BindingFlags.Public | BindingFlags.NonPublic;
1905 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1906 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1907 MethodAttributes.Final;
1909 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1910 List<EventSpec> imported_events = null;
1911 EventSpec event_spec;
1912 MemberSpec imported;
1916 all = loading_type.GetMembers (all_members);
1917 } catch (Exception e) {
1918 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1919 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1922 if (cache == null) {
1923 cache = new MemberCache (all.Length);
1926 // Do the types first as they can be referenced by the members before
1927 // they are found or inflated
1929 foreach (var member in all) {
1930 if (member.MemberType != MemberTypes.NestedType)
1933 var t = (MetaType) member;
1935 // Ignore compiler generated types, mostly lambda containers
1936 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1940 imported = importer.CreateNestedType (t, declaringType);
1941 } catch (Exception e) {
1942 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
1943 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
1946 cache.AddMemberImported (imported);
1949 foreach (var member in all) {
1950 if (member.MemberType != MemberTypes.NestedType)
1953 var t = (MetaType) member;
1955 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1958 importer.ImportTypeBase (t);
1963 // Load base interfaces first to minic behaviour of compiled members
1965 if (declaringType.IsInterface && declaringType.Interfaces != null) {
1966 foreach (var iface in declaringType.Interfaces) {
1967 cache.AddInterface (iface);
1973 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1975 foreach (var member in all) {
1976 switch (member.MemberType) {
1977 case MemberTypes.Constructor:
1978 if (declaringType.IsInterface)
1981 goto case MemberTypes.Method;
1982 case MemberTypes.Method:
1983 MethodBase mb = (MethodBase) member;
1984 var attrs = mb.Attributes;
1986 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1987 if (importer.IgnorePrivateMembers)
1990 // Ignore explicitly implemented members
1991 if ((attrs & explicit_impl) == explicit_impl)
1994 // Ignore compiler generated methods
1995 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1999 imported = importer.CreateMethod (mb, declaringType);
2000 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2001 if (possible_accessors == null)
2002 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2004 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2005 possible_accessors.Add (mb, (MethodSpec) imported);
2009 case MemberTypes.Property:
2010 if (possible_accessors == null)
2013 var p = (PropertyInfo) member;
2015 // Links possible accessors with property
2017 MethodSpec get, set;
2018 m = p.GetGetMethod (true);
2019 if (m == null || !possible_accessors.TryGetValue (m, out get))
2022 m = p.GetSetMethod (true);
2023 if (m == null || !possible_accessors.TryGetValue (m, out set))
2026 // No accessors registered (e.g. explicit implementation)
2027 if (get == null && set == null)
2030 imported = importer.CreateProperty (p, declaringType, get, set);
2031 if (imported == null)
2035 case MemberTypes.Event:
2036 if (possible_accessors == null)
2039 var e = (EventInfo) member;
2041 // Links accessors with event
2043 MethodSpec add, remove;
2044 m = e.GetAddMethod (true);
2045 if (m == null || !possible_accessors.TryGetValue (m, out add))
2048 m = e.GetRemoveMethod (true);
2049 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2052 // Both accessors are required
2053 if (add == null || remove == null)
2056 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2057 if (!importer.IgnorePrivateMembers) {
2058 if (imported_events == null)
2059 imported_events = new List<EventSpec> ();
2061 imported_events.Add (event_spec);
2064 imported = event_spec;
2066 case MemberTypes.Field:
2067 var fi = (FieldInfo) member;
2069 imported = importer.CreateField (fi, declaringType);
2070 if (imported == null)
2074 // For dynamic binder event has to be fully restored to allow operations
2075 // within the type container to work correctly
2077 if (imported_events != null) {
2078 // The backing event field should be private but it may not
2080 for (i = 0; i < imported_events.Count; ++i) {
2081 var ev = imported_events[i];
2082 if (ev.Name == fi.Name) {
2083 ev.BackingField = (FieldSpec) imported;
2084 imported_events.RemoveAt (i);
2095 case MemberTypes.NestedType:
2096 // Already in the cache from the first pass
2099 throw new NotImplementedException (member.ToString ());
2102 if (imported.IsStatic && declaringType.IsInterface)
2105 cache.AddMemberImported (imported);
2111 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2113 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2114 : base (type, importer)
2120 public IAssemblyDefinition DeclaringAssembly {
2122 throw new NotImplementedException ();
2126 bool ITypeDefinition.IsPartial {
2132 public string Namespace {
2138 public int TypeParametersCount {
2144 public TypeParameterSpec[] TypeParameters {
2152 public TypeSpec GetAttributeCoClass ()
2157 public string GetAttributeDefaultMember ()
2159 throw new NotSupportedException ();
2162 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2164 throw new NotSupportedException ();
2167 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2169 throw new NotImplementedException ();
2172 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2174 throw new NotImplementedException ();