2 // import.cs: System.Reflection conversions
4 // Authors: Marek Safar (marek.safar@gmail.com)
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 // Copyright 2009-2011 Novell, Inc
9 // Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
13 using System.Runtime.CompilerServices;
15 using System.Collections.Generic;
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
29 public abstract class MetadataImporter
32 // Dynamic types reader with additional logic to reconstruct a dynamic
33 // type using DynamicAttribute values
35 protected struct DynamicTypeReader
37 static readonly bool[] single_attribute = { true };
42 // There is no common type for CustomAttributeData and we cannot
43 // use ICustomAttributeProvider
47 // A member provider which can be used to get CustomAttributeData
49 public DynamicTypeReader (object provider)
53 this.provider = provider;
57 // Returns true when object at local position has dynamic attribute flag
59 public bool IsDynamicObject ()
64 return flags != null && Position < flags.Length && flags[Position];
68 // Returns true when DynamicAttribute exists
70 public bool HasDynamicAttribute ()
80 IList<CustomAttributeData> cad;
81 if (provider is MemberInfo) {
82 cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
83 } else if (provider is ParameterInfo) {
84 cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
91 foreach (var ca in cad) {
92 var dt = ca.Constructor.DeclaringType;
93 if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace)
96 if (ca.ConstructorArguments.Count == 0) {
97 flags = single_attribute;
101 var arg_type = ca.ConstructorArguments[0].ArgumentType;
103 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
104 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
105 flags = new bool[carg.Count];
106 for (int i = 0; i < flags.Length; ++i) {
107 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
108 flags[i] = (bool) carg[i].Value;
120 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
121 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
122 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
123 protected readonly ModuleContainer module;
125 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
127 protected MetadataImporter (ModuleContainer module)
129 this.module = module;
131 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
132 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
133 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
134 IgnorePrivateMembers = true;
139 public ICollection<IAssemblyDefinition> Assemblies {
141 return assembly_2_definition.Values;
145 public bool IgnorePrivateMembers { get; set; }
149 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
150 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
151 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
153 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
156 var fa = fi.Attributes;
157 switch (fa & FieldAttributes.FieldAccessMask) {
158 case FieldAttributes.Public:
159 mod = Modifiers.PUBLIC;
161 case FieldAttributes.Assembly:
162 mod = Modifiers.INTERNAL;
164 case FieldAttributes.Family:
165 mod = Modifiers.PROTECTED;
167 case FieldAttributes.FamORAssem:
168 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
171 // Ignore private fields (even for error reporting) to not require extra dependencies
172 if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
173 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
176 mod = Modifiers.PRIVATE;
183 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
184 } catch (Exception e) {
185 // TODO: I should construct fake TypeSpec based on TypeRef signature
186 // but there is no way to do it with System.Reflection
187 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
188 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
191 var definition = new ImportedMemberDefinition (fi, field_type, this);
193 if ((fa & FieldAttributes.Literal) != 0) {
194 Constant c = field_type.Kind == MemberKind.MissingType ?
195 new NullConstant (InternalType.ErrorType, Location.Null) :
196 Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
197 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
200 if ((fa & FieldAttributes.InitOnly) != 0) {
201 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
202 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
204 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
207 mod |= Modifiers.READONLY;
209 var req_mod = fi.GetRequiredCustomModifiers ();
210 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
211 mod |= Modifiers.VOLATILE;
214 if ((fa & FieldAttributes.Static) != 0) {
215 mod |= Modifiers.STATIC;
217 // Fixed buffers cannot be static
218 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
219 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
221 // TODO: Sanity check on field_type (only few types are allowed)
222 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
223 return new FixedFieldSpec (module, declaringType, definition, fi, element_field, mod);
227 return new FieldSpec (declaringType, definition, field_type, fi, mod);
230 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
232 add.IsAccessor = true;
233 remove.IsAccessor = true;
235 if (add.Modifiers != remove.Modifiers)
236 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
238 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
239 var definition = new ImportedMemberDefinition (ei, event_type, this);
240 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
243 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
245 var tparams = type.GetGenericArguments ();
247 int parent_owned_count;
249 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
252 // System.Reflection duplicates parent type parameters for each
253 // nested type with slightly modified properties (eg. different owner)
254 // This just makes things more complicated (think of cloned constraints)
255 // therefore we remap any nested type owned by parent using `type_cache'
256 // to the single TypeParameterSpec
258 if (declaringType != null && parent_owned_count > 0) {
260 while (read_count != parent_owned_count) {
261 var tparams_count = declaringType.Arity;
262 if (tparams_count != 0) {
263 var parent_tp = declaringType.MemberDefinition.TypeParameters;
264 read_count += tparams_count;
265 for (int i = 0; i < tparams_count; i++) {
266 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
270 declaringType = declaringType.DeclaringType;
274 parent_owned_count = 0;
277 if (tparams.Length - parent_owned_count == 0)
280 return CreateGenericParameters (parent_owned_count, tparams);
283 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
285 var tspec = new TypeParameterSpec[tparams.Length - first];
286 for (int pos = first; pos < tparams.Length; ++pos) {
287 var type = tparams[pos];
288 int index = pos - first;
290 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
296 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
300 var tspec = new TypeSpec [tparams.Length - first];
301 for (int pos = first; pos < tparams.Length; ++pos) {
302 var type = tparams[pos];
303 int index = pos - first;
306 if (type.HasElementType) {
307 var element = type.GetElementType ();
309 spec = ImportType (element, dtype);
312 throw new NotImplementedException ("Unknown element type " + type.ToString ());
315 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
317 spec = CreateType (type, dtype, true);
320 // We treat nested generic types as inflated internally where
321 // reflection uses type definition
324 // IFoo<A<T>> foo; // A<T> is definition in this case
327 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
328 var start_pos = spec.DeclaringType == null ? 0 : spec.DeclaringType.MemberDefinition.TypeParametersCount;
329 var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype);
330 spec = spec.MakeGenericType (module, targs);
341 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
343 Modifiers mod = ReadMethodModifiers (mb, declaringType);
344 TypeParameterSpec[] tparams;
346 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
348 if (mb.IsGenericMethod) {
349 if (!mb.IsGenericMethodDefinition)
350 throw new NotSupportedException ("assert");
352 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
359 if (mb.MemberType == MemberTypes.Constructor) {
360 kind = MemberKind.Constructor;
361 returnType = module.Compiler.BuiltinTypes.Void;
364 // Detect operators and destructors
366 string name = mb.Name;
367 kind = MemberKind.Method;
368 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
369 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
370 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
371 var op_type = Operator.GetType (name);
372 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
373 kind = MemberKind.Operator;
376 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
377 kind = MemberKind.Destructor;
378 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
379 mod &= ~Modifiers.OVERRIDE;
380 mod |= Modifiers.VIRTUAL;
385 var mi = (MethodInfo) mb;
386 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
388 // Cannot set to OVERRIDE without full hierarchy checks
389 // this flag indicates that the method could be override
390 // but further validation is needed
391 if ((mod & Modifiers.OVERRIDE) != 0) {
392 bool is_real_override = false;
393 if (kind == MemberKind.Method && declaringType.BaseType != null) {
394 var btype = declaringType.BaseType;
395 if (IsOverrideMethodBaseTypeAccessible (btype)) {
396 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
397 var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
400 // For imported class method do additional validation to be sure that metadata
401 // override flag was correct
403 // Difference between protected internal and protected is ok
405 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
406 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
407 is_real_override = true;
412 if (!is_real_override) {
413 mod &= ~Modifiers.OVERRIDE;
414 if ((mod & Modifiers.SEALED) != 0)
415 mod &= ~Modifiers.SEALED;
417 mod |= Modifiers.VIRTUAL;
422 IMethodDefinition definition;
423 if (tparams != null) {
424 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
425 foreach (var tp in gmd.TypeParameters) {
426 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
431 definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
434 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
441 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
443 switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
444 case Modifiers.PUBLIC:
446 case Modifiers.INTERNAL:
448 // Check whether imported method in base type is accessible from compiled
451 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
452 case Modifiers.PRIVATE:
456 // protected internal
458 // Method accessibility checks will be done later based on context
459 // where the method is called (CS0122 error will be reported for inaccessible)
466 // Imports System.Reflection parameters
468 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
470 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
472 if (pi.Length == 0 && varargs == 0)
473 return ParametersCompiled.EmptyReadOnlyParameters;
475 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
476 IParameterData[] par = new IParameterData[pi.Length + varargs];
477 bool is_params = false;
478 for (int i = 0; i < pi.Length; i++) {
479 ParameterInfo p = pi[i];
480 Parameter.Modifier mod = 0;
481 Expression default_value = null;
482 if (p.ParameterType.IsByRef) {
483 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
484 mod = Parameter.Modifier.OUT;
486 mod = Parameter.Modifier.REF;
489 // Strip reference wrapping
491 var el = p.ParameterType.GetElementType ();
492 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
493 } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
494 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
495 mod = Parameter.Modifier.This;
496 types[i] = ImportType (p.ParameterType);
498 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
500 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
501 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
502 mod = Parameter.Modifier.PARAMS;
507 if (!is_params && p.IsOptional) {
508 object value = p.RawDefaultValue;
509 var ptype = types[i];
510 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
512 default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
514 default_value = ImportParameterConstant (value);
517 default_value = new EnumConstant ((Constant) default_value, ptype);
521 var attrs = CustomAttributeData.GetCustomAttributes (p);
522 for (int ii = 0; ii < attrs.Count; ++ii) {
523 var attr = attrs[ii];
524 var dt = attr.Constructor.DeclaringType;
525 if (dt.Namespace != CompilerServicesNamespace)
528 if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
529 mod |= Parameter.Modifier.CallerLineNumber;
530 else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
531 mod |= Parameter.Modifier.CallerFilePath;
532 else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
533 mod |= Parameter.Modifier.CallerMemberName;
535 } else if (value == Missing.Value) {
536 default_value = EmptyExpression.MissingValue;
537 } else if (value == null) {
538 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
539 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
540 default_value = ImportParameterConstant (value);
545 par[i] = new ParameterData (p.Name, mod, default_value);
549 par[par.Length - 1] = new ArglistParameter (Location.Null);
550 types[types.Length - 1] = InternalType.Arglist;
553 return method != null ?
554 new ParametersImported (par, types, varargs != 0, is_params) :
555 new ParametersImported (par, types, is_params);
559 // Returns null when the property is not valid C# property
561 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
564 AParametersCollection param = null;
565 TypeSpec type = null;
568 param = get.Parameters;
569 type = get.ReturnType;
572 bool is_valid_property = true;
574 if (set.ReturnType.Kind != MemberKind.Void)
575 is_valid_property = false;
577 var set_param_count = set.Parameters.Count - 1;
579 if (set_param_count < 0) {
581 is_valid_property = false;
584 var set_type = set.Parameters.Types[set_param_count];
587 AParametersCollection set_based_param;
589 if (set_param_count == 0) {
590 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
593 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
595 var data = new IParameterData[set_param_count];
596 var types = new TypeSpec[set_param_count];
597 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
598 Array.Copy (set.Parameters.Types, types, set_param_count);
599 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
603 param = set_based_param;
606 if (set_param_count != get.Parameters.Count)
607 is_valid_property = false;
609 if (get.ReturnType != set_type)
610 is_valid_property = false;
612 // Possible custom accessor modifiers
613 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
614 var get_acc = mod & Modifiers.AccessibilityMask;
615 if (get_acc != Modifiers.PUBLIC) {
616 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
617 // If the accessor modifiers are not same, do extra restriction checks
618 if (get_acc != set_acc) {
619 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
620 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
621 if (get_restr && set_restr) {
622 is_valid_property = false; // Neither is more restrictive
626 mod &= ~Modifiers.AccessibilityMask;
635 PropertySpec spec = null;
636 if (!param.IsEmpty) {
637 if (is_valid_property) {
638 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
639 if (index_name == null) {
640 is_valid_property = false;
644 is_valid_property = false;
645 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
646 is_valid_property = false;
650 is_valid_property = false;
651 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
652 is_valid_property = false;
656 if (is_valid_property) {
657 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
658 } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
660 // Enables support for properties with parameters (must have default value) of COM-imported types
662 is_valid_property = true;
664 for (int i = 0; i < param.FixedParameters.Length; ++i) {
665 if (!param.FixedParameters[i].HasDefaultValue) {
666 is_valid_property = false;
675 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
677 if (!is_valid_property) {
678 spec.IsNotCSharpCompatible = true;
690 public TypeSpec CreateType (MetaType type)
692 return CreateType (type, new DynamicTypeReader (), true);
695 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
697 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
700 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
702 TypeSpec declaring_type;
703 if (type.IsNested && !type.IsGenericParameter)
704 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
706 declaring_type = null;
708 return CreateType (type, declaring_type, dtype, canImportBaseType);
711 protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
714 if (import_cache.TryGetValue (type, out spec)) {
715 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
716 if (dtype.IsDynamicObject ())
717 return module.Compiler.BuiltinTypes.Dynamic;
722 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
725 if (!dtype.HasDynamicAttribute ())
728 // We've found same object in the cache but this one has a dynamic custom attribute
729 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
730 // Do type resolve process again in that case
732 // TODO: Handle cases where they still unify
735 if (IsMissingType (type)) {
736 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
737 spec.MemberCache = MemberCache.Empty;
738 import_cache.Add (type, spec);
742 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
743 var type_def = type.GetGenericTypeDefinition ();
745 // Generic type definition can also be forwarded
746 if (compiled_types.TryGetValue (type_def, out spec))
749 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
750 if (declaringType == null) {
751 // Simple case, no nesting
752 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
753 spec = spec.MakeGenericType (module, targs);
756 // Nested type case, converting .NET types like
757 // A`1.B`1.C`1<int, long, string> to typespec like
758 // A<int>.B<long>.C<string>
760 var nested_hierarchy = new List<TypeSpec> ();
761 while (declaringType.IsNested) {
762 nested_hierarchy.Add (declaringType);
763 declaringType = declaringType.DeclaringType;
767 if (declaringType.Arity > 0) {
768 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
769 targs_pos = spec.Arity;
771 spec = declaringType;
774 for (int i = nested_hierarchy.Count; i != 0; --i) {
775 var t = nested_hierarchy [i - 1];
776 if (t.Kind == MemberKind.MissingType)
779 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
782 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
783 targs_pos += t.Arity;
787 if (spec.Kind == MemberKind.MissingType) {
788 spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC);
789 spec.MemberCache = MemberCache.Empty;
791 if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
794 string name = type.Name;
795 int index = name.IndexOf ('`');
797 name = name.Substring (0, index);
799 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
801 if (spec.Arity > 0) {
802 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
807 // Don't add generic type with dynamic arguments, they can interfere with same type
808 // using object type arguments
809 if (!spec.HasDynamicElement) {
811 // Add to reading cache to speed up reading
812 if (!import_cache.ContainsKey (type))
813 import_cache.Add (type, spec);
822 var ma = type.Attributes;
823 switch (ma & TypeAttributes.VisibilityMask) {
824 case TypeAttributes.Public:
825 case TypeAttributes.NestedPublic:
826 mod = Modifiers.PUBLIC;
828 case TypeAttributes.NestedPrivate:
829 mod = Modifiers.PRIVATE;
831 case TypeAttributes.NestedFamily:
832 mod = Modifiers.PROTECTED;
834 case TypeAttributes.NestedFamORAssem:
835 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
838 mod = Modifiers.INTERNAL;
842 if ((ma & TypeAttributes.Interface) != 0) {
843 kind = MemberKind.Interface;
844 } else if (type.IsGenericParameter) {
845 kind = MemberKind.TypeParameter;
847 var base_type = type.BaseType;
848 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
849 kind = MemberKind.Class;
851 kind = DetermineKindFromBaseType (base_type);
852 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
853 mod |= Modifiers.SEALED;
857 if (kind == MemberKind.Class) {
858 if ((ma & TypeAttributes.Sealed) != 0) {
859 if ((ma & TypeAttributes.Abstract) != 0)
860 mod |= Modifiers.STATIC;
862 mod |= Modifiers.SEALED;
863 } else if ((ma & TypeAttributes.Abstract) != 0) {
864 mod |= Modifiers.ABSTRACT;
869 var definition = new ImportedTypeDefinition (type, this);
872 if (kind == MemberKind.Enum) {
873 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
874 BindingFlags.Instance |
875 BindingFlags.Public | BindingFlags.NonPublic;
877 var type_members = type.GetFields (underlying_member);
878 foreach (var type_member in type_members) {
879 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
884 kind = MemberKind.Class;
886 } else if (kind == MemberKind.TypeParameter) {
887 spec = CreateTypeParameter (type, declaringType);
888 } else if (type.IsGenericTypeDefinition) {
889 definition.TypeParameters = CreateGenericParameters (type, declaringType);
890 } else if (compiled_types.TryGetValue (type, out pt)) {
892 // Same type was found in inside compiled types. It's
893 // either build-in type or forward referenced typed
894 // which point into just compiled assembly.
897 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
899 bts.SetDefinition (definition, type, mod);
903 spec = new TypeSpec (kind, declaringType, definition, type, mod);
905 import_cache.Add (type, spec);
907 if (kind == MemberKind.TypeParameter) {
908 if (canImportBaseType)
909 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
915 // Two stage setup as the base type can be inflated declaring type or
916 // another nested type inside same declaring type which has not been
917 // loaded, therefore we can import a base type of nested types once
918 // the types have been imported
920 if (canImportBaseType)
921 ImportTypeBase (spec, type);
926 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
928 IAssemblyDefinition found;
929 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
931 // This can happen in dynamic context only
932 var def = new ImportedAssemblyDefinition (assembly);
933 assembly_2_definition.Add (assembly, def);
934 def.ReadAttributes ();
941 public void ImportTypeBase (MetaType type)
943 TypeSpec spec = import_cache[type];
945 ImportTypeBase (spec, type);
948 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
951 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
952 case GenericParameterAttributes.Covariant:
953 variance = Variance.Covariant;
955 case GenericParameterAttributes.Contravariant:
956 variance = Variance.Contravariant;
959 variance = Variance.None;
963 SpecialConstraint special = SpecialConstraint.None;
964 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
966 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
967 special |= SpecialConstraint.Struct;
968 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
969 special = SpecialConstraint.Constructor;
972 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
973 special |= SpecialConstraint.Class;
976 TypeParameterSpec spec;
977 var def = new ImportedTypeParameterDefinition (type, this);
978 if (type.DeclaringMethod != null) {
979 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
981 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
988 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
989 // they can be assembly specific therefore we do check based on names only
991 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
993 if (attributesData.Count == 0)
996 foreach (var attr in attributesData) {
997 var dt = attr.Constructor.DeclaringType;
998 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1005 void ImportTypeBase (TypeSpec spec, MetaType type)
1007 if (spec.Kind == MemberKind.Interface)
1008 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1009 else if (type.BaseType != null) {
1011 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1012 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1014 base_type = CreateType (type.BaseType);
1016 spec.BaseType = base_type;
1019 if (spec.MemberDefinition.TypeParametersCount > 0) {
1020 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1021 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1026 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1028 Namespace ns = targetNamespace;
1029 string prev_namespace = null;
1030 foreach (var t in types) {
1034 // Be careful not to trigger full parent type loading
1035 if (t.MemberType == MemberTypes.NestedType)
1038 if (t.Name[0] == '<')
1041 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1045 if (prev_namespace != t.Namespace) {
1046 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1047 prev_namespace = t.Namespace;
1050 // Cannot rely on assembly level Extension attribute or static modifier because they
1051 // are not followed by other compilers (e.g. F#).
1052 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1053 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1054 it.SetExtensionMethodContainer ();
1057 ns.AddType (module, it);
1061 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1063 var constraints = type.GetGenericParameterConstraints ();
1064 List<TypeSpec> tparams = null;
1065 foreach (var ct in constraints) {
1066 if (ct.IsGenericParameter) {
1067 if (tparams == null)
1068 tparams = new List<TypeSpec> ();
1070 tparams.Add (CreateType (ct));
1074 var constraint_type = CreateType (ct);
1075 if (constraint_type.IsClass) {
1076 spec.BaseType = constraint_type;
1080 spec.AddInterface (constraint_type);
1083 if (spec.BaseType == null)
1084 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1086 if (tparams != null)
1087 spec.TypeArguments = tparams.ToArray ();
1090 Constant ImportParameterConstant (object value)
1093 // Get type of underlying value as int constant can be used for object
1094 // parameter type. This is not allowed in C# but other languages can do that
1096 var types = module.Compiler.BuiltinTypes;
1097 switch (System.Type.GetTypeCode (value.GetType ())) {
1098 case TypeCode.Boolean:
1099 return new BoolConstant (types, (bool) value, Location.Null);
1101 return new ByteConstant (types, (byte) value, Location.Null);
1103 return new CharConstant (types, (char) value, Location.Null);
1104 case TypeCode.Decimal:
1105 return new DecimalConstant (types, (decimal) value, Location.Null);
1106 case TypeCode.Double:
1107 return new DoubleConstant (types, (double) value, Location.Null);
1108 case TypeCode.Int16:
1109 return new ShortConstant (types, (short) value, Location.Null);
1110 case TypeCode.Int32:
1111 return new IntConstant (types, (int) value, Location.Null);
1112 case TypeCode.Int64:
1113 return new LongConstant (types, (long) value, Location.Null);
1114 case TypeCode.SByte:
1115 return new SByteConstant (types, (sbyte) value, Location.Null);
1116 case TypeCode.Single:
1117 return new FloatConstant (types, (float) value, Location.Null);
1118 case TypeCode.String:
1119 return new StringConstant (types, (string) value, Location.Null);
1120 case TypeCode.UInt16:
1121 return new UShortConstant (types, (ushort) value, Location.Null);
1122 case TypeCode.UInt32:
1123 return new UIntConstant (types, (uint) value, Location.Null);
1124 case TypeCode.UInt64:
1125 return new ULongConstant (types, (ulong) value, Location.Null);
1128 throw new NotImplementedException (value.GetType ().ToString ());
1131 public TypeSpec ImportType (MetaType type)
1133 return ImportType (type, new DynamicTypeReader (type));
1136 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1138 if (type.HasElementType) {
1139 var element = type.GetElementType ();
1141 var spec = ImportType (element, dtype);
1144 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1146 return ReferenceContainer.MakeType (module, spec);
1148 return PointerContainer.MakeType (module, spec);
1150 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1153 return CreateType (type, dtype, true);
1156 static bool IsMissingType (MetaType type)
1159 return type.__IsMissing;
1166 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1167 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1168 // DecimalConstantAttribute metadata.
1170 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1172 if (attrs.Count == 0)
1175 foreach (var ca in attrs) {
1176 var dt = ca.Constructor.DeclaringType;
1177 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1180 var value = new decimal (
1181 (int) (uint) ca.ConstructorArguments[4].Value,
1182 (int) (uint) ca.ConstructorArguments[3].Value,
1183 (int) (uint) ca.ConstructorArguments[2].Value,
1184 (byte) ca.ConstructorArguments[1].Value != 0,
1185 (byte) ca.ConstructorArguments[0].Value);
1187 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1193 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1196 var ma = mb.Attributes;
1197 switch (ma & MethodAttributes.MemberAccessMask) {
1198 case MethodAttributes.Public:
1199 mod = Modifiers.PUBLIC;
1201 case MethodAttributes.Assembly:
1202 mod = Modifiers.INTERNAL;
1204 case MethodAttributes.Family:
1205 mod = Modifiers.PROTECTED;
1207 case MethodAttributes.FamORAssem:
1208 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1211 mod = Modifiers.PRIVATE;
1215 if ((ma & MethodAttributes.Static) != 0) {
1216 mod |= Modifiers.STATIC;
1219 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1220 mod |= Modifiers.ABSTRACT;
1224 // It can be sealed and override
1225 if ((ma & MethodAttributes.Final) != 0)
1226 mod |= Modifiers.SEALED;
1228 if ((ma & MethodAttributes.Virtual) != 0) {
1229 // Not every member can be detected based on MethodAttribute, we
1230 // set virtual or non-virtual only when we are certain. Further checks
1231 // to really find out what `virtual' means for this member are done
1233 if ((ma & MethodAttributes.NewSlot) != 0) {
1234 if ((mod & Modifiers.SEALED) != 0) {
1235 mod &= ~Modifiers.SEALED;
1237 mod |= Modifiers.VIRTUAL;
1240 mod |= Modifiers.OVERRIDE;
1248 abstract class ImportedDefinition : IMemberDefinition
1250 protected class AttributesBag
1252 public static readonly AttributesBag Default = new AttributesBag ();
1254 public AttributeUsageAttribute AttributeUsage;
1255 public ObsoleteAttribute Obsolete;
1256 public string[] Conditionals;
1257 public string DefaultIndexerName;
1258 public bool? CLSAttributeValue;
1259 public TypeSpec CoClass;
1261 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1263 AttributesBag bag = null;
1264 List<string> conditionals = null;
1266 // It should not throw any loading exception
1267 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1269 foreach (var a in attrs) {
1270 var dt = a.Constructor.DeclaringType;
1271 string name = dt.Name;
1272 if (name == "ObsoleteAttribute") {
1273 if (dt.Namespace != "System")
1277 bag = new AttributesBag ();
1279 var args = a.ConstructorArguments;
1281 if (args.Count == 1) {
1282 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1283 } else if (args.Count == 2) {
1284 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1286 bag.Obsolete = new ObsoleteAttribute ();
1292 if (name == "ConditionalAttribute") {
1293 if (dt.Namespace != "System.Diagnostics")
1297 bag = new AttributesBag ();
1299 if (conditionals == null)
1300 conditionals = new List<string> (2);
1302 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1306 if (name == "CLSCompliantAttribute") {
1307 if (dt.Namespace != "System")
1311 bag = new AttributesBag ();
1313 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1317 // Type only attributes
1318 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1319 if (name == "DefaultMemberAttribute") {
1320 if (dt.Namespace != "System.Reflection")
1324 bag = new AttributesBag ();
1326 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1330 if (name == "AttributeUsageAttribute") {
1331 if (dt.Namespace != "System")
1335 bag = new AttributesBag ();
1337 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1338 foreach (var named in a.NamedArguments) {
1339 if (named.MemberInfo.Name == "AllowMultiple")
1340 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1341 else if (named.MemberInfo.Name == "Inherited")
1342 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1347 // Interface only attribute
1348 if (name == "CoClassAttribute") {
1349 if (dt.Namespace != "System.Runtime.InteropServices")
1353 bag = new AttributesBag ();
1355 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1364 if (conditionals != null)
1365 bag.Conditionals = conditionals.ToArray ();
1371 protected readonly MemberInfo provider;
1372 protected AttributesBag cattrs;
1373 protected readonly MetadataImporter importer;
1375 protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1377 this.provider = provider;
1378 this.importer = importer;
1383 public bool IsImported {
1389 public virtual string Name {
1391 return provider.Name;
1397 public string[] ConditionalConditions ()
1402 return cattrs.Conditionals;
1405 public ObsoleteAttribute GetAttributeObsolete ()
1410 return cattrs.Obsolete;
1413 public bool? CLSAttributeValue {
1418 return cattrs.CLSAttributeValue;
1422 protected void ReadAttributes ()
1424 cattrs = AttributesBag.Read (provider, importer);
1427 public void SetIsAssigned ()
1429 // Unused for imported members
1432 public void SetIsUsed ()
1434 // Unused for imported members
1438 public class ImportedModuleDefinition
1440 readonly Module module;
1443 public ImportedModuleDefinition (Module module)
1445 this.module = module;
1450 public bool IsCLSCompliant {
1452 return cls_compliant;
1456 public string Name {
1464 public void ReadAttributes ()
1466 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1468 foreach (var a in attrs) {
1469 var dt = a.Constructor.DeclaringType;
1470 if (dt.Name == "CLSCompliantAttribute") {
1471 if (dt.Namespace != "System")
1474 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1481 // Reads assembly attributes which where attached to a special type because
1482 // module does have assembly manifest
1484 public List<Attribute> ReadAssemblyAttributes ()
1486 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1490 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1494 // TODO: implement, the idea is to fabricate specil Attribute class and
1495 // add it to OptAttributes before resolving the source code attributes
1496 // Need to build module location as well for correct error reporting
1498 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1499 //var attrs = new List<Attribute> (assembly_attributes.Count);
1500 //foreach (var a in assembly_attributes)
1502 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1503 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1505 // foreach (var carg in a.ConstructorArguments) {
1509 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1516 public class ImportedAssemblyDefinition : IAssemblyDefinition
1518 readonly Assembly assembly;
1519 readonly AssemblyName aname;
1522 List<AssemblyName> internals_visible_to;
1523 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1525 public ImportedAssemblyDefinition (Assembly assembly)
1527 this.assembly = assembly;
1528 this.aname = assembly.GetName ();
1533 public Assembly Assembly {
1539 public string FullName {
1541 return aname.FullName;
1545 public bool HasStrongName {
1547 return aname.GetPublicKey ().Length != 0;
1551 public bool IsMissing {
1554 return assembly.__IsMissing;
1561 public bool IsCLSCompliant {
1563 return cls_compliant;
1567 public string Location {
1569 return assembly.Location;
1573 public string Name {
1581 public byte[] GetPublicKeyToken ()
1583 return aname.GetPublicKeyToken ();
1586 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1588 return internals_visible_to_cache [assembly];
1591 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1593 if (internals_visible_to == null)
1596 AssemblyName is_visible = null;
1597 if (internals_visible_to_cache == null) {
1598 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1600 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1601 return is_visible != null;
1604 var token = assembly.GetPublicKeyToken ();
1605 if (token != null && token.Length == 0)
1608 foreach (var internals in internals_visible_to) {
1609 if (internals.Name != assembly.Name)
1612 if (token == null && assembly is AssemblyDefinition) {
1613 is_visible = internals;
1617 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1620 is_visible = internals;
1624 internals_visible_to_cache.Add (assembly, is_visible);
1625 return is_visible != null;
1628 public void ReadAttributes ()
1631 if (assembly.__IsMissing)
1635 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1637 foreach (var a in attrs) {
1638 var dt = a.Constructor.DeclaringType;
1640 if (name == "CLSCompliantAttribute") {
1641 if (dt.Namespace == "System") {
1642 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1647 if (name == "InternalsVisibleToAttribute") {
1648 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1651 string s = a.ConstructorArguments[0].Value as string;
1655 var an = new AssemblyName (s);
1656 if (internals_visible_to == null)
1657 internals_visible_to = new List<AssemblyName> ();
1659 internals_visible_to.Add (an);
1665 public override string ToString ()
1671 class ImportedMemberDefinition : ImportedDefinition
1673 readonly TypeSpec type;
1675 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1676 : base (member, importer)
1683 public TypeSpec MemberType {
1692 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1694 readonly AParametersCollection parameters;
1696 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1697 : base (provider, type, importer)
1699 this.parameters = parameters;
1702 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1703 : base (provider, type, importer)
1705 this.parameters = parameters;
1710 public AParametersCollection Parameters {
1719 class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1721 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1722 : base (provider, type, parameters, importer)
1726 MethodBase IMethodDefinition.Metadata {
1728 return (MethodBase) provider;
1733 class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1735 readonly TypeParameterSpec[] tparams;
1737 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1738 : base (provider, type, parameters, importer)
1740 this.tparams = tparams;
1745 public TypeParameterSpec[] TypeParameters {
1751 public int TypeParametersCount {
1753 return tparams.Length;
1760 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1762 TypeParameterSpec[] tparams;
1765 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1766 : base (type, importer)
1772 public IAssemblyDefinition DeclaringAssembly {
1774 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1778 bool ITypeDefinition.IsComImport {
1780 return ((MetaType) provider).IsImport;
1785 bool ITypeDefinition.IsPartial {
1791 bool ITypeDefinition.IsTypeForwarder {
1794 return ((MetaType) provider).__IsTypeForwarder;
1801 public override string Name {
1805 if (tparams != null) {
1806 int arity_start = name.IndexOf ('`');
1807 if (arity_start > 0)
1808 name = name.Substring (0, arity_start);
1816 public string Namespace {
1818 return ((MetaType) provider).Namespace;
1822 public int TypeParametersCount {
1824 return tparams == null ? 0 : tparams.Length;
1828 public TypeParameterSpec[] TypeParameters {
1839 public void DefineInterfaces (TypeSpec spec)
1841 var type = (MetaType) provider;
1844 ifaces = type.__GetDeclaredInterfaces ();
1845 if (ifaces.Length != 0) {
1846 foreach (var iface in ifaces) {
1847 var it = importer.CreateType (iface);
1851 spec.AddInterfaceDefined (it);
1853 // Unfortunately not all languages expand inherited interfaces
1854 var bifaces = it.Interfaces;
1855 if (bifaces != null) {
1856 foreach (var biface in bifaces) {
1857 spec.AddInterfaceDefined (biface);
1864 // It's impossible to get declared interfaces only using System.Reflection
1865 // hence we need to mimic the behavior with ikvm-reflection too to keep
1866 // our type look-up logic same
1868 if (spec.BaseType != null) {
1869 var bifaces = spec.BaseType.Interfaces;
1870 if (bifaces != null) {
1872 // Before adding base class interfaces close defined interfaces
1873 // on type parameter
1875 var tp = spec as TypeParameterSpec;
1876 if (tp != null && tp.InterfacesDefined == null) {
1877 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1880 foreach (var iface in bifaces)
1881 spec.AddInterfaceDefined (iface);
1885 ifaces = type.GetInterfaces ();
1887 if (ifaces.Length > 0) {
1888 foreach (var iface in ifaces) {
1889 spec.AddInterface (importer.CreateType (iface));
1896 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
1899 // Report details about missing type and most likely cause of the problem.
1900 // csc reports 1683, 1684 as warnings but we report them only when used
1901 // or referenced from the user core in which case compilation error has to
1902 // be reported because compiler cannot continue anyway
1905 var report = ctx.Module.Compiler.Report;
1907 for (int i = 0; i < missing.Count; ++i) {
1908 var t = missing [i].Type;
1911 // Report missing types only once
1913 if (report.Printer.MissingTypeReported (t.MemberDefinition))
1916 string name = t.GetSignatureForError ();
1918 var caller = missing[i].Caller;
1919 if (caller.Kind != MemberKind.MissingType)
1920 report.SymbolRelatedToPreviousError (caller);
1922 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1923 report.Error (1683, loc,
1924 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1926 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1927 if (t.MemberDefinition.IsTypeForwarder) {
1928 report.Error (1070, loc,
1929 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1930 name, t.MemberDefinition.DeclaringAssembly.FullName);
1932 report.Error (12, loc,
1933 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1934 name, t.MemberDefinition.DeclaringAssembly.FullName);
1937 report.Error (1684, loc,
1938 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1939 name, t.MemberDefinition.DeclaringAssembly.FullName);
1944 public TypeSpec GetAttributeCoClass ()
1949 return cattrs.CoClass;
1952 public string GetAttributeDefaultMember ()
1957 return cattrs.DefaultIndexerName;
1960 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1965 return cattrs.AttributeUsage;
1968 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1970 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1971 return a == assembly || a.IsFriendAssemblyTo (assembly);
1974 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1977 // Not interested in members of nested private types unless the importer needs them
1979 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1980 cache = MemberCache.Empty;
1984 var loading_type = (MetaType) provider;
1985 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1986 BindingFlags.Static | BindingFlags.Instance |
1987 BindingFlags.Public | BindingFlags.NonPublic;
1989 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1990 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1991 MethodAttributes.Final;
1993 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1994 List<EventSpec> imported_events = null;
1995 EventSpec event_spec;
1996 MemberSpec imported;
2000 all = loading_type.GetMembers (all_members);
2001 } catch (Exception e) {
2002 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2003 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2006 if (cache == null) {
2007 cache = new MemberCache (all.Length);
2010 // Do the types first as they can be referenced by the members before
2011 // they are found or inflated
2013 foreach (var member in all) {
2014 if (member.MemberType != MemberTypes.NestedType)
2017 var t = (MetaType) member;
2019 // Ignore compiler generated types, mostly lambda containers
2020 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2024 imported = importer.CreateNestedType (t, declaringType);
2025 } catch (Exception e) {
2026 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2027 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2030 cache.AddMemberImported (imported);
2033 foreach (var member in all) {
2034 if (member.MemberType != MemberTypes.NestedType)
2037 var t = (MetaType) member;
2039 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2042 importer.ImportTypeBase (t);
2047 // Load base interfaces first to minic behaviour of compiled members
2049 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2050 foreach (var iface in declaringType.Interfaces) {
2051 cache.AddInterface (iface);
2057 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2059 foreach (var member in all) {
2060 switch (member.MemberType) {
2061 case MemberTypes.Constructor:
2062 if (declaringType.IsInterface)
2065 goto case MemberTypes.Method;
2066 case MemberTypes.Method:
2067 MethodBase mb = (MethodBase) member;
2068 var attrs = mb.Attributes;
2070 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2071 if (importer.IgnorePrivateMembers)
2074 // Ignore explicitly implemented members
2075 if ((attrs & explicit_impl) == explicit_impl)
2078 // Ignore compiler generated methods
2079 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2083 imported = importer.CreateMethod (mb, declaringType);
2084 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2085 if (possible_accessors == null)
2086 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2088 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2089 possible_accessors.Add (mb, (MethodSpec) imported);
2093 case MemberTypes.Property:
2094 if (possible_accessors == null)
2097 var p = (PropertyInfo) member;
2099 // Links possible accessors with property
2101 MethodSpec get, set;
2102 m = p.GetGetMethod (true);
2103 if (m == null || !possible_accessors.TryGetValue (m, out get))
2106 m = p.GetSetMethod (true);
2107 if (m == null || !possible_accessors.TryGetValue (m, out set))
2110 // No accessors registered (e.g. explicit implementation)
2111 if (get == null && set == null)
2115 imported = importer.CreateProperty (p, declaringType, get, set);
2116 } catch (Exception ex) {
2117 throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2118 p.Name, declaringType.GetSignatureForError ());
2121 if (imported == null)
2125 case MemberTypes.Event:
2126 if (possible_accessors == null)
2129 var e = (EventInfo) member;
2131 // Links accessors with event
2133 MethodSpec add, remove;
2134 m = e.GetAddMethod (true);
2135 if (m == null || !possible_accessors.TryGetValue (m, out add))
2138 m = e.GetRemoveMethod (true);
2139 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2142 // Both accessors are required
2143 if (add == null || remove == null)
2146 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2147 if (!importer.IgnorePrivateMembers) {
2148 if (imported_events == null)
2149 imported_events = new List<EventSpec> ();
2151 imported_events.Add (event_spec);
2154 imported = event_spec;
2156 case MemberTypes.Field:
2157 var fi = (FieldInfo) member;
2159 imported = importer.CreateField (fi, declaringType);
2160 if (imported == null)
2164 // For dynamic binder event has to be fully restored to allow operations
2165 // within the type container to work correctly
2167 if (imported_events != null) {
2168 // The backing event field should be private but it may not
2170 for (i = 0; i < imported_events.Count; ++i) {
2171 var ev = imported_events[i];
2172 if (ev.Name == fi.Name) {
2173 ev.BackingField = (FieldSpec) imported;
2174 imported_events.RemoveAt (i);
2185 case MemberTypes.NestedType:
2186 // Already in the cache from the first pass
2189 throw new NotImplementedException (member.ToString ());
2192 if (imported.IsStatic && declaringType.IsInterface)
2195 cache.AddMemberImported (imported);
2201 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2203 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2204 : base (type, importer)
2210 public IAssemblyDefinition DeclaringAssembly {
2212 throw new NotImplementedException ();
2216 bool ITypeDefinition.IsComImport {
2222 bool ITypeDefinition.IsPartial {
2228 bool ITypeDefinition.IsTypeForwarder {
2234 public string Namespace {
2240 public int TypeParametersCount {
2246 public TypeParameterSpec[] TypeParameters {
2254 public TypeSpec GetAttributeCoClass ()
2259 public string GetAttributeDefaultMember ()
2261 throw new NotSupportedException ();
2264 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2266 throw new NotSupportedException ();
2269 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2271 throw new NotImplementedException ();
2274 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2276 throw new NotImplementedException ();