2 // import.cs: System.Reflection conversions
4 // Authors: Marek Safar (marek.safar@gmail.com)
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 // Copyright 2009-2011 Novell, Inc
9 // Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
13 using System.Runtime.CompilerServices;
15 using System.Collections.Generic;
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
29 public abstract class MetadataImporter
32 // Dynamic types reader with additional logic to reconstruct a dynamic
33 // type using DynamicAttribute values
35 protected struct DynamicTypeReader
37 static readonly bool[] single_attribute = { true };
42 // There is no common type for CustomAttributeData and we cannot
43 // use ICustomAttributeProvider
47 // A member provider which can be used to get CustomAttributeData
49 public DynamicTypeReader (object provider)
53 this.provider = provider;
57 // Returns true when object at local position has dynamic attribute flag
59 public bool IsDynamicObject (MetadataImporter importer)
62 ReadAttribute (importer);
64 return flags != null && Position < flags.Length && flags[Position];
68 // Returns true when DynamicAttribute exists
70 public bool HasDynamicAttribute (MetadataImporter importer)
73 ReadAttribute (importer);
78 void ReadAttribute (MetadataImporter importer)
80 IList<CustomAttributeData> cad;
81 if (provider is MemberInfo) {
82 cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
83 } else if (provider is ParameterInfo) {
84 cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
91 foreach (var ca in cad) {
92 var dt = ca.Constructor.DeclaringType;
93 if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace)
96 if (ca.ConstructorArguments.Count == 0) {
97 flags = single_attribute;
101 var arg_type = ca.ConstructorArguments[0].ArgumentType;
103 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
104 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
105 flags = new bool[carg.Count];
106 for (int i = 0; i < flags.Length; ++i) {
107 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
108 flags[i] = (bool) carg[i].Value;
120 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
121 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
122 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
123 protected readonly ModuleContainer module;
125 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
127 protected MetadataImporter (ModuleContainer module)
129 this.module = module;
131 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
132 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
133 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
134 IgnorePrivateMembers = true;
139 public ICollection<IAssemblyDefinition> Assemblies {
141 return assembly_2_definition.Values;
145 public bool IgnorePrivateMembers { get; set; }
149 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
150 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
151 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
153 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
156 var fa = fi.Attributes;
157 switch (fa & FieldAttributes.FieldAccessMask) {
158 case FieldAttributes.Public:
159 mod = Modifiers.PUBLIC;
161 case FieldAttributes.Assembly:
162 mod = Modifiers.INTERNAL;
164 case FieldAttributes.Family:
165 mod = Modifiers.PROTECTED;
167 case FieldAttributes.FamORAssem:
168 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
171 // Ignore private fields (even for error reporting) to not require extra dependencies
172 if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
173 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
176 mod = Modifiers.PRIVATE;
183 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
184 } catch (Exception e) {
185 // TODO: I should construct fake TypeSpec based on TypeRef signature
186 // but there is no way to do it with System.Reflection
187 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
188 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
191 var definition = new ImportedMemberDefinition (fi, field_type, this);
193 if ((fa & FieldAttributes.Literal) != 0) {
194 Constant c = field_type.Kind == MemberKind.MissingType ?
195 new NullConstant (InternalType.ErrorType, Location.Null) :
196 Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
197 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
200 if ((fa & FieldAttributes.InitOnly) != 0) {
201 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
202 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
204 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
207 mod |= Modifiers.READONLY;
209 var req_mod = fi.GetRequiredCustomModifiers ();
210 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
211 mod |= Modifiers.VOLATILE;
214 if ((fa & FieldAttributes.Static) != 0) {
215 mod |= Modifiers.STATIC;
217 // Fixed buffers cannot be static
218 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
219 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
221 // TODO: Sanity check on field_type (only few types are allowed)
222 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
223 return new FixedFieldSpec (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 (this))
717 return module.Compiler.BuiltinTypes.Dynamic;
722 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
725 if (!dtype.HasDynamicAttribute (this))
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 mod |= Modifiers.SEALED;
860 if ((ma & TypeAttributes.Abstract) != 0)
861 mod |= Modifiers.STATIC;
862 } else if ((ma & TypeAttributes.Abstract) != 0) {
863 mod |= Modifiers.ABSTRACT;
868 var definition = new ImportedTypeDefinition (type, this);
871 if (kind == MemberKind.Enum) {
872 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
873 BindingFlags.Instance |
874 BindingFlags.Public | BindingFlags.NonPublic;
876 var type_members = type.GetFields (underlying_member);
877 foreach (var type_member in type_members) {
878 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
883 kind = MemberKind.Class;
885 } else if (kind == MemberKind.TypeParameter) {
886 spec = CreateTypeParameter (type, declaringType);
887 } else if (type.IsGenericTypeDefinition) {
888 definition.TypeParameters = CreateGenericParameters (type, declaringType);
889 } else if (compiled_types.TryGetValue (type, out pt)) {
891 // Same type was found in inside compiled types. It's
892 // either build-in type or forward referenced typed
893 // which point into just compiled assembly.
896 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
898 bts.SetDefinition (definition, type, mod);
902 spec = new TypeSpec (kind, declaringType, definition, type, mod);
904 import_cache.Add (type, spec);
906 if (kind == MemberKind.TypeParameter) {
907 if (canImportBaseType)
908 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
914 // Two stage setup as the base type can be inflated declaring type or
915 // another nested type inside same declaring type which has not been
916 // loaded, therefore we can import a base type of nested types once
917 // the types have been imported
919 if (canImportBaseType)
920 ImportTypeBase (spec, type);
925 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
927 IAssemblyDefinition found;
928 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
930 // This can happen in dynamic context only
931 var def = new ImportedAssemblyDefinition (assembly);
932 assembly_2_definition.Add (assembly, def);
933 def.ReadAttributes ();
940 public void ImportTypeBase (MetaType type)
942 TypeSpec spec = import_cache[type];
944 ImportTypeBase (spec, type);
947 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
950 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
951 case GenericParameterAttributes.Covariant:
952 variance = Variance.Covariant;
954 case GenericParameterAttributes.Contravariant:
955 variance = Variance.Contravariant;
958 variance = Variance.None;
962 SpecialConstraint special = SpecialConstraint.None;
963 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
965 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
966 special |= SpecialConstraint.Struct;
967 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
968 special = SpecialConstraint.Constructor;
971 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
972 special |= SpecialConstraint.Class;
975 TypeParameterSpec spec;
976 var def = new ImportedTypeParameterDefinition (type, this);
977 if (type.DeclaringMethod != null) {
978 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
980 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
987 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
988 // they can be assembly specific therefore we do check based on names only
990 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
992 if (attributesData.Count == 0)
995 foreach (var attr in attributesData) {
996 var dt = attr.Constructor.DeclaringType;
997 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1004 void ImportTypeBase (TypeSpec spec, MetaType type)
1006 if (spec.Kind == MemberKind.Interface)
1007 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1008 else if (type.BaseType != null) {
1010 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1011 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1013 base_type = CreateType (type.BaseType);
1015 spec.BaseType = base_type;
1018 if (spec.MemberDefinition.TypeParametersCount > 0) {
1019 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1020 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1025 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1027 Namespace ns = targetNamespace;
1028 string prev_namespace = null;
1029 foreach (var t in types) {
1033 // Be careful not to trigger full parent type loading
1034 if (t.MemberType == MemberTypes.NestedType)
1037 if (t.Name[0] == '<')
1040 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1044 if (prev_namespace != t.Namespace) {
1045 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1046 prev_namespace = t.Namespace;
1049 // Cannot rely on assembly level Extension attribute or static modifier because they
1050 // are not followed by other compilers (e.g. F#).
1051 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1052 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1053 it.SetExtensionMethodContainer ();
1056 ns.AddType (module, it);
1060 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1062 var constraints = type.GetGenericParameterConstraints ();
1063 List<TypeSpec> tparams = null;
1064 foreach (var ct in constraints) {
1065 if (ct.IsGenericParameter) {
1066 if (tparams == null)
1067 tparams = new List<TypeSpec> ();
1069 tparams.Add (CreateType (ct));
1073 var constraint_type = CreateType (ct);
1074 if (constraint_type.IsClass) {
1075 spec.BaseType = constraint_type;
1079 spec.AddInterface (constraint_type);
1082 if (spec.BaseType == null)
1083 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1085 if (tparams != null)
1086 spec.TypeArguments = tparams.ToArray ();
1089 Constant ImportParameterConstant (object value)
1092 // Get type of underlying value as int constant can be used for object
1093 // parameter type. This is not allowed in C# but other languages can do that
1095 var types = module.Compiler.BuiltinTypes;
1096 switch (System.Type.GetTypeCode (value.GetType ())) {
1097 case TypeCode.Boolean:
1098 return new BoolConstant (types, (bool) value, Location.Null);
1100 return new ByteConstant (types, (byte) value, Location.Null);
1102 return new CharConstant (types, (char) value, Location.Null);
1103 case TypeCode.Decimal:
1104 return new DecimalConstant (types, (decimal) value, Location.Null);
1105 case TypeCode.Double:
1106 return new DoubleConstant (types, (double) value, Location.Null);
1107 case TypeCode.Int16:
1108 return new ShortConstant (types, (short) value, Location.Null);
1109 case TypeCode.Int32:
1110 return new IntConstant (types, (int) value, Location.Null);
1111 case TypeCode.Int64:
1112 return new LongConstant (types, (long) value, Location.Null);
1113 case TypeCode.SByte:
1114 return new SByteConstant (types, (sbyte) value, Location.Null);
1115 case TypeCode.Single:
1116 return new FloatConstant (types, (float) value, Location.Null);
1117 case TypeCode.String:
1118 return new StringConstant (types, (string) value, Location.Null);
1119 case TypeCode.UInt16:
1120 return new UShortConstant (types, (ushort) value, Location.Null);
1121 case TypeCode.UInt32:
1122 return new UIntConstant (types, (uint) value, Location.Null);
1123 case TypeCode.UInt64:
1124 return new ULongConstant (types, (ulong) value, Location.Null);
1127 throw new NotImplementedException (value.GetType ().ToString ());
1130 public TypeSpec ImportType (MetaType type)
1132 return ImportType (type, new DynamicTypeReader (type));
1135 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1137 if (type.HasElementType) {
1138 var element = type.GetElementType ();
1140 var spec = ImportType (element, dtype);
1143 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1145 return ReferenceContainer.MakeType (module, spec);
1147 return PointerContainer.MakeType (module, spec);
1149 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1152 return CreateType (type, dtype, true);
1155 static bool IsMissingType (MetaType type)
1158 return type.__IsMissing;
1165 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1166 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1167 // DecimalConstantAttribute metadata.
1169 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1171 if (attrs.Count == 0)
1174 foreach (var ca in attrs) {
1175 var dt = ca.Constructor.DeclaringType;
1176 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1179 var value = new decimal (
1180 (int) (uint) ca.ConstructorArguments[4].Value,
1181 (int) (uint) ca.ConstructorArguments[3].Value,
1182 (int) (uint) ca.ConstructorArguments[2].Value,
1183 (byte) ca.ConstructorArguments[1].Value != 0,
1184 (byte) ca.ConstructorArguments[0].Value);
1186 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1192 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1195 var ma = mb.Attributes;
1196 switch (ma & MethodAttributes.MemberAccessMask) {
1197 case MethodAttributes.Public:
1198 mod = Modifiers.PUBLIC;
1200 case MethodAttributes.Assembly:
1201 mod = Modifiers.INTERNAL;
1203 case MethodAttributes.Family:
1204 mod = Modifiers.PROTECTED;
1206 case MethodAttributes.FamORAssem:
1207 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1210 mod = Modifiers.PRIVATE;
1214 if ((ma & MethodAttributes.Static) != 0) {
1215 mod |= Modifiers.STATIC;
1218 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1219 mod |= Modifiers.ABSTRACT;
1223 // It can be sealed and override
1224 if ((ma & MethodAttributes.Final) != 0)
1225 mod |= Modifiers.SEALED;
1227 if ((ma & MethodAttributes.Virtual) != 0) {
1228 // Not every member can be detected based on MethodAttribute, we
1229 // set virtual or non-virtual only when we are certain. Further checks
1230 // to really find out what `virtual' means for this member are done
1232 if ((ma & MethodAttributes.NewSlot) != 0) {
1233 if ((mod & Modifiers.SEALED) != 0) {
1234 mod &= ~Modifiers.SEALED;
1236 mod |= Modifiers.VIRTUAL;
1239 mod |= Modifiers.OVERRIDE;
1247 abstract class ImportedDefinition : IMemberDefinition
1249 protected class AttributesBag
1251 public static readonly AttributesBag Default = new AttributesBag ();
1253 public AttributeUsageAttribute AttributeUsage;
1254 public ObsoleteAttribute Obsolete;
1255 public string[] Conditionals;
1256 public string DefaultIndexerName;
1257 public bool? CLSAttributeValue;
1258 public TypeSpec CoClass;
1260 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1262 AttributesBag bag = null;
1263 List<string> conditionals = null;
1265 // It should not throw any loading exception
1266 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1268 foreach (var a in attrs) {
1269 var dt = a.Constructor.DeclaringType;
1270 string name = dt.Name;
1271 if (name == "ObsoleteAttribute") {
1272 if (dt.Namespace != "System")
1276 bag = new AttributesBag ();
1278 var args = a.ConstructorArguments;
1280 if (args.Count == 1) {
1281 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1282 } else if (args.Count == 2) {
1283 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1285 bag.Obsolete = new ObsoleteAttribute ();
1291 if (name == "ConditionalAttribute") {
1292 if (dt.Namespace != "System.Diagnostics")
1296 bag = new AttributesBag ();
1298 if (conditionals == null)
1299 conditionals = new List<string> (2);
1301 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1305 if (name == "CLSCompliantAttribute") {
1306 if (dt.Namespace != "System")
1310 bag = new AttributesBag ();
1312 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1316 // Type only attributes
1317 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1318 if (name == "DefaultMemberAttribute") {
1319 if (dt.Namespace != "System.Reflection")
1323 bag = new AttributesBag ();
1325 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1329 if (name == "AttributeUsageAttribute") {
1330 if (dt.Namespace != "System")
1334 bag = new AttributesBag ();
1336 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1337 foreach (var named in a.NamedArguments) {
1338 if (named.MemberInfo.Name == "AllowMultiple")
1339 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1340 else if (named.MemberInfo.Name == "Inherited")
1341 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1346 // Interface only attribute
1347 if (name == "CoClassAttribute") {
1348 if (dt.Namespace != "System.Runtime.InteropServices")
1352 bag = new AttributesBag ();
1354 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1363 if (conditionals != null)
1364 bag.Conditionals = conditionals.ToArray ();
1370 protected readonly MemberInfo provider;
1371 protected AttributesBag cattrs;
1372 protected readonly MetadataImporter importer;
1374 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1376 this.provider = provider;
1377 this.importer = importer;
1382 public bool IsImported {
1388 public virtual string Name {
1390 return provider.Name;
1396 public string[] ConditionalConditions ()
1401 return cattrs.Conditionals;
1404 public ObsoleteAttribute GetAttributeObsolete ()
1409 return cattrs.Obsolete;
1412 public bool? CLSAttributeValue {
1417 return cattrs.CLSAttributeValue;
1421 protected void ReadAttributes ()
1423 cattrs = AttributesBag.Read (provider, importer);
1426 public void SetIsAssigned ()
1428 // Unused for imported members
1431 public void SetIsUsed ()
1433 // Unused for imported members
1437 public class ImportedModuleDefinition
1439 readonly Module module;
1442 public ImportedModuleDefinition (Module module)
1444 this.module = module;
1449 public bool IsCLSCompliant {
1451 return cls_compliant;
1455 public string Name {
1463 public void ReadAttributes ()
1465 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1467 foreach (var a in attrs) {
1468 var dt = a.Constructor.DeclaringType;
1469 if (dt.Name == "CLSCompliantAttribute") {
1470 if (dt.Namespace != "System")
1473 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1480 // Reads assembly attributes which where attached to a special type because
1481 // module does have assembly manifest
1483 public List<Attribute> ReadAssemblyAttributes ()
1485 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1489 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1493 // TODO: implement, the idea is to fabricate specil Attribute class and
1494 // add it to OptAttributes before resolving the source code attributes
1495 // Need to build module location as well for correct error reporting
1497 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1498 //var attrs = new List<Attribute> (assembly_attributes.Count);
1499 //foreach (var a in assembly_attributes)
1501 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1502 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1504 // foreach (var carg in a.ConstructorArguments) {
1508 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1515 public class ImportedAssemblyDefinition : IAssemblyDefinition
1517 readonly Assembly assembly;
1518 readonly AssemblyName aname;
1521 List<AssemblyName> internals_visible_to;
1522 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1524 public ImportedAssemblyDefinition (Assembly assembly)
1526 this.assembly = assembly;
1527 this.aname = assembly.GetName ();
1532 public Assembly Assembly {
1538 public string FullName {
1540 return aname.FullName;
1544 public bool HasStrongName {
1546 return aname.GetPublicKey ().Length != 0;
1550 public bool IsMissing {
1553 return assembly.__IsMissing;
1560 public bool IsCLSCompliant {
1562 return cls_compliant;
1566 public string Location {
1568 return assembly.Location;
1572 public string Name {
1580 public byte[] GetPublicKeyToken ()
1582 return aname.GetPublicKeyToken ();
1585 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1587 return internals_visible_to_cache [assembly];
1590 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1592 if (internals_visible_to == null)
1595 AssemblyName is_visible = null;
1596 if (internals_visible_to_cache == null) {
1597 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1599 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1600 return is_visible != null;
1603 var token = assembly.GetPublicKeyToken ();
1604 if (token != null && token.Length == 0)
1607 foreach (var internals in internals_visible_to) {
1608 if (internals.Name != assembly.Name)
1611 if (token == null && assembly is AssemblyDefinition) {
1612 is_visible = internals;
1616 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1619 is_visible = internals;
1623 internals_visible_to_cache.Add (assembly, is_visible);
1624 return is_visible != null;
1627 public void ReadAttributes ()
1630 if (assembly.__IsMissing)
1634 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1636 foreach (var a in attrs) {
1637 var dt = a.Constructor.DeclaringType;
1639 if (name == "CLSCompliantAttribute") {
1640 if (dt.Namespace == "System") {
1641 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1646 if (name == "InternalsVisibleToAttribute") {
1647 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1650 string s = a.ConstructorArguments[0].Value as string;
1654 var an = new AssemblyName (s);
1655 if (internals_visible_to == null)
1656 internals_visible_to = new List<AssemblyName> ();
1658 internals_visible_to.Add (an);
1664 public override string ToString ()
1670 class ImportedMemberDefinition : ImportedDefinition
1672 readonly TypeSpec type;
1674 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1675 : base (member, importer)
1682 public TypeSpec MemberType {
1691 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1693 readonly AParametersCollection parameters;
1695 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1696 : base (provider, type, importer)
1698 this.parameters = parameters;
1701 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1702 : base (provider, type, importer)
1704 this.parameters = parameters;
1709 public AParametersCollection Parameters {
1718 class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1720 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1721 : base (provider, type, parameters, importer)
1725 MethodBase IMethodDefinition.Metadata {
1727 return (MethodBase) provider;
1732 class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1734 readonly TypeParameterSpec[] tparams;
1736 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1737 : base (provider, type, parameters, importer)
1739 this.tparams = tparams;
1744 public TypeParameterSpec[] TypeParameters {
1750 public int TypeParametersCount {
1752 return tparams.Length;
1759 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1761 TypeParameterSpec[] tparams;
1764 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1765 : base (type, importer)
1771 public IAssemblyDefinition DeclaringAssembly {
1773 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1777 bool ITypeDefinition.IsComImport {
1779 return ((MetaType) provider).IsImport;
1784 bool ITypeDefinition.IsPartial {
1790 bool ITypeDefinition.IsTypeForwarder {
1793 return ((MetaType) provider).__IsTypeForwarder;
1800 public override string Name {
1804 if (tparams != null) {
1805 int arity_start = name.IndexOf ('`');
1806 if (arity_start > 0)
1807 name = name.Substring (0, arity_start);
1815 public string Namespace {
1817 return ((MetaType) provider).Namespace;
1821 public int TypeParametersCount {
1823 return tparams == null ? 0 : tparams.Length;
1827 public TypeParameterSpec[] TypeParameters {
1838 public void DefineInterfaces (TypeSpec spec)
1840 var type = (MetaType) provider;
1843 ifaces = type.__GetDeclaredInterfaces ();
1844 if (ifaces.Length != 0) {
1845 foreach (var iface in ifaces) {
1846 var it = importer.CreateType (iface);
1850 spec.AddInterfaceDefined (it);
1852 // Unfortunately not all languages expand inherited interfaces
1853 var bifaces = it.Interfaces;
1854 if (bifaces != null) {
1855 foreach (var biface in bifaces) {
1856 spec.AddInterfaceDefined (biface);
1863 // It's impossible to get declared interfaces only using System.Reflection
1864 // hence we need to mimic the behavior with ikvm-reflection too to keep
1865 // our type look-up logic same
1867 if (spec.BaseType != null) {
1868 var bifaces = spec.BaseType.Interfaces;
1869 if (bifaces != null) {
1871 // Before adding base class interfaces close defined interfaces
1872 // on type parameter
1874 var tp = spec as TypeParameterSpec;
1875 if (tp != null && tp.InterfacesDefined == null) {
1876 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1879 foreach (var iface in bifaces)
1880 spec.AddInterfaceDefined (iface);
1884 ifaces = type.GetInterfaces ();
1886 if (ifaces.Length > 0) {
1887 foreach (var iface in ifaces) {
1888 spec.AddInterface (importer.CreateType (iface));
1895 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
1898 // Report details about missing type and most likely cause of the problem.
1899 // csc reports 1683, 1684 as warnings but we report them only when used
1900 // or referenced from the user core in which case compilation error has to
1901 // be reported because compiler cannot continue anyway
1904 var report = ctx.Module.Compiler.Report;
1906 for (int i = 0; i < missing.Count; ++i) {
1907 var t = missing [i].Type;
1910 // Report missing types only once
1912 if (report.Printer.MissingTypeReported (t.MemberDefinition))
1915 string name = t.GetSignatureForError ();
1917 var caller = missing[i].Caller;
1918 if (caller.Kind != MemberKind.MissingType)
1919 report.SymbolRelatedToPreviousError (caller);
1921 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1922 report.Error (1683, loc,
1923 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1925 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1926 if (t.MemberDefinition.IsTypeForwarder) {
1927 report.Error (1070, loc,
1928 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1929 name, t.MemberDefinition.DeclaringAssembly.FullName);
1931 report.Error (12, loc,
1932 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1933 name, t.MemberDefinition.DeclaringAssembly.FullName);
1936 report.Error (1684, loc,
1937 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1938 name, t.MemberDefinition.DeclaringAssembly.FullName);
1943 public TypeSpec GetAttributeCoClass ()
1948 return cattrs.CoClass;
1951 public string GetAttributeDefaultMember ()
1956 return cattrs.DefaultIndexerName;
1959 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1964 return cattrs.AttributeUsage;
1967 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1969 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1970 return a == assembly || a.IsFriendAssemblyTo (assembly);
1973 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1976 // Not interested in members of nested private types unless the importer needs them
1978 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1979 cache = MemberCache.Empty;
1983 var loading_type = (MetaType) provider;
1984 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1985 BindingFlags.Static | BindingFlags.Instance |
1986 BindingFlags.Public | BindingFlags.NonPublic;
1988 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1989 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1990 MethodAttributes.Final;
1992 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1993 List<EventSpec> imported_events = null;
1994 EventSpec event_spec;
1995 MemberSpec imported;
1999 all = loading_type.GetMembers (all_members);
2000 } catch (Exception e) {
2001 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2002 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2005 if (cache == null) {
2006 cache = new MemberCache (all.Length);
2009 // Do the types first as they can be referenced by the members before
2010 // they are found or inflated
2012 foreach (var member in all) {
2013 if (member.MemberType != MemberTypes.NestedType)
2016 var t = (MetaType) member;
2018 // Ignore compiler generated types, mostly lambda containers
2019 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2023 imported = importer.CreateNestedType (t, declaringType);
2024 } catch (Exception e) {
2025 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2026 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2029 cache.AddMemberImported (imported);
2032 foreach (var member in all) {
2033 if (member.MemberType != MemberTypes.NestedType)
2036 var t = (MetaType) member;
2038 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2041 importer.ImportTypeBase (t);
2046 // Load base interfaces first to minic behaviour of compiled members
2048 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2049 foreach (var iface in declaringType.Interfaces) {
2050 cache.AddInterface (iface);
2056 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2058 foreach (var member in all) {
2059 switch (member.MemberType) {
2060 case MemberTypes.Constructor:
2061 if (declaringType.IsInterface)
2064 goto case MemberTypes.Method;
2065 case MemberTypes.Method:
2066 MethodBase mb = (MethodBase) member;
2067 var attrs = mb.Attributes;
2069 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2070 if (importer.IgnorePrivateMembers)
2073 // Ignore explicitly implemented members
2074 if ((attrs & explicit_impl) == explicit_impl)
2077 // Ignore compiler generated methods
2078 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2082 imported = importer.CreateMethod (mb, declaringType);
2083 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2084 if (possible_accessors == null)
2085 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2087 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2088 possible_accessors.Add (mb, (MethodSpec) imported);
2092 case MemberTypes.Property:
2093 if (possible_accessors == null)
2096 var p = (PropertyInfo) member;
2098 // Links possible accessors with property
2100 MethodSpec get, set;
2101 m = p.GetGetMethod (true);
2102 if (m == null || !possible_accessors.TryGetValue (m, out get))
2105 m = p.GetSetMethod (true);
2106 if (m == null || !possible_accessors.TryGetValue (m, out set))
2109 // No accessors registered (e.g. explicit implementation)
2110 if (get == null && set == null)
2114 imported = importer.CreateProperty (p, declaringType, get, set);
2115 } catch (Exception ex) {
2116 throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2117 p.Name, declaringType.GetSignatureForError ());
2120 if (imported == null)
2124 case MemberTypes.Event:
2125 if (possible_accessors == null)
2128 var e = (EventInfo) member;
2130 // Links accessors with event
2132 MethodSpec add, remove;
2133 m = e.GetAddMethod (true);
2134 if (m == null || !possible_accessors.TryGetValue (m, out add))
2137 m = e.GetRemoveMethod (true);
2138 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2141 // Both accessors are required
2142 if (add == null || remove == null)
2145 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2146 if (!importer.IgnorePrivateMembers) {
2147 if (imported_events == null)
2148 imported_events = new List<EventSpec> ();
2150 imported_events.Add (event_spec);
2153 imported = event_spec;
2155 case MemberTypes.Field:
2156 var fi = (FieldInfo) member;
2158 imported = importer.CreateField (fi, declaringType);
2159 if (imported == null)
2163 // For dynamic binder event has to be fully restored to allow operations
2164 // within the type container to work correctly
2166 if (imported_events != null) {
2167 // The backing event field should be private but it may not
2169 for (i = 0; i < imported_events.Count; ++i) {
2170 var ev = imported_events[i];
2171 if (ev.Name == fi.Name) {
2172 ev.BackingField = (FieldSpec) imported;
2173 imported_events.RemoveAt (i);
2184 case MemberTypes.NestedType:
2185 // Already in the cache from the first pass
2188 throw new NotImplementedException (member.ToString ());
2191 if (imported.IsStatic && declaringType.IsInterface)
2194 cache.AddMemberImported (imported);
2200 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2202 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2203 : base (type, importer)
2209 public IAssemblyDefinition DeclaringAssembly {
2211 throw new NotImplementedException ();
2215 bool ITypeDefinition.IsComImport {
2221 bool ITypeDefinition.IsPartial {
2227 bool ITypeDefinition.IsTypeForwarder {
2233 public string Namespace {
2239 public int TypeParametersCount {
2245 public TypeParameterSpec[] TypeParameters {
2253 public TypeSpec GetAttributeCoClass ()
2258 public string GetAttributeDefaultMember ()
2260 throw new NotSupportedException ();
2263 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2265 throw new NotSupportedException ();
2268 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2270 throw new NotImplementedException ();
2273 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2275 throw new NotImplementedException ();