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;
19 using MetaType = IKVM.Reflection.Type;
20 using IKVM.Reflection;
21 using IKVM.Reflection.Emit;
23 using MetaType = System.Type;
24 using System.Reflection;
25 using System.Reflection.Emit;
30 public abstract class MetadataImporter
33 // Types reader with additional logic to reconstruct extra
34 // type information encoded in custom attributes values
36 protected struct AttributesTypeInfoReader
38 static readonly bool[] single_attribute = { true };
40 public int DynamicPosition;
43 public int TuplePosition;
46 // There is no common type for CustomAttributeData and we cannot
47 // use ICustomAttributeProvider
51 // A member provider which can be used to get CustomAttributeData
53 public AttributesTypeInfoReader (object provider)
59 this.provider = provider;
63 // Returns true when object at local position has dynamic attribute flag
65 public bool IsDynamicObject ()
70 return dynamicFlags != null && DynamicPosition < dynamicFlags.Length && dynamicFlags [DynamicPosition];
74 // Returns true when DynamicAttribute exists
76 public bool HasDynamicAttribute ()
81 return dynamicFlags != null;
84 public bool HasNamedTupleAttribute ()
89 return tupleNames != null;
92 public IList<string> GetNamedTupleElements (int length)
94 if (TuplePosition == 0 && length == tupleNames.Length)
97 for (int i = TuplePosition; i < length + TuplePosition; ++i) {
98 if (tupleNames [i] != null) {
99 var res = new string [length];
100 Array.Copy (tupleNames, TuplePosition, res, 0, length);
106 // Current range can be just padding
111 IList<CustomAttributeData> GetCustomAttributes ()
113 var mi = provider as MemberInfo;
115 return CustomAttributeData.GetCustomAttributes (mi);
117 var pi = provider as ParameterInfo;
119 return CustomAttributeData.GetCustomAttributes (pi);
125 void ReadAttribute ()
127 var cad = GetCustomAttributes ();
133 foreach (var ca in cad) {
134 var dt = ca.Constructor.DeclaringType;
135 if (dt.Namespace != CompilerServicesNamespace)
139 case "DynamicAttribute":
140 if (ca.ConstructorArguments.Count == 0) {
141 dynamicFlags = single_attribute;
145 var arg_type = ca.ConstructorArguments [0].ArgumentType;
147 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
148 var carg = (IList<CustomAttributeTypedArgument>)ca.ConstructorArguments [0].Value;
149 dynamicFlags = new bool [carg.Count];
150 for (int i = 0; i < dynamicFlags.Length; ++i) {
151 if (MetaType.GetTypeCode (carg [i].ArgumentType) == TypeCode.Boolean)
152 dynamicFlags [i] = (bool)carg [i].Value;
157 case "TupleElementNamesAttribute":
158 if (ca.ConstructorArguments.Count != 1)
161 var tuple_arg_type = ca.ConstructorArguments [0].ArgumentType;
162 if (tuple_arg_type.IsArray && MetaType.GetTypeCode (tuple_arg_type.GetElementType ()) == TypeCode.String) {
163 var carg = (IList<CustomAttributeTypedArgument>)ca.ConstructorArguments [0].Value;
164 tupleNames = new string [carg.Count];
165 for (int i = 0; i < tupleNames.Length; ++i) {
166 if (MetaType.GetTypeCode (carg [i].ArgumentType) == TypeCode.String)
167 tupleNames [i] = (string)carg [i].Value;
180 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
181 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
182 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
183 protected readonly ModuleContainer module;
185 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
187 protected MetadataImporter (ModuleContainer module)
189 this.module = module;
191 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
192 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
193 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
194 IgnorePrivateMembers = true;
195 IgnoreCompilerGeneratedField = true;
200 public ICollection<IAssemblyDefinition> Assemblies {
202 return assembly_2_definition.Values;
206 public bool IgnorePrivateMembers { get; set; }
208 public bool IgnoreCompilerGeneratedField { get; set; }
212 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
213 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
214 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
216 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
219 var fa = fi.Attributes;
220 switch (fa & FieldAttributes.FieldAccessMask) {
221 case FieldAttributes.Public:
222 mod = Modifiers.PUBLIC;
224 case FieldAttributes.Assembly:
225 mod = Modifiers.INTERNAL;
227 case FieldAttributes.Family:
228 mod = Modifiers.PROTECTED;
230 case FieldAttributes.FamORAssem:
231 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
234 // Ignore private fields (even for error reporting) to not require extra dependencies
235 if (IgnorePrivateMembers && !declaringType.IsStruct)
238 if (IgnoreCompilerGeneratedField && HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
241 mod = Modifiers.PRIVATE;
248 field_type = ImportType (fi.FieldType, new AttributesTypeInfoReader (fi), declaringType);
251 // Private field has private type which is not fixed buffer
253 if (field_type == null)
255 } catch (Exception e) {
256 // TODO: I should construct fake TypeSpec based on TypeRef signature
257 // but there is no way to do it with System.Reflection
258 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
259 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
262 var definition = new ImportedMemberDefinition (fi, field_type, this);
264 if ((fa & FieldAttributes.Literal) != 0) {
265 Constant c = field_type.Kind == MemberKind.MissingType ?
266 new NullConstant (InternalType.ErrorType, Location.Null) :
267 CreateConstantFromValue (field_type, fi);
268 return new ConstSpec (declaringType, definition, field_type, fi, mod | Modifiers.STATIC, c);
271 if ((fa & FieldAttributes.InitOnly) != 0) {
272 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
273 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
275 return new ConstSpec (declaringType, definition, field_type, fi, mod | Modifiers.STATIC, dc);
278 mod |= Modifiers.READONLY;
280 var req_mod = fi.GetRequiredCustomModifiers ();
281 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
282 mod |= Modifiers.VOLATILE;
285 if ((fa & FieldAttributes.Static) != 0) {
286 mod |= Modifiers.STATIC;
288 // Fixed buffers cannot be static
289 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
290 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
292 // TODO: Sanity check on field_type (only few types are allowed)
293 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
294 return new FixedFieldSpec (module, declaringType, definition, fi, element_field, mod);
298 return new FieldSpec (declaringType, definition, field_type, fi, mod);
301 Constant CreateConstantFromValue (TypeSpec fieldType, FieldInfo fi)
303 var value = fi.GetRawConstantValue ();
305 // Metadata value can be encoded using different constant value type
306 // than is actual field type
308 // e.g. unsigned int16 CONSTANT = int16 (0x0000ffff)
310 if (value != null && !fieldType.IsEnum) {
311 var c = ImportConstant (value);
313 return fieldType == c.Type ? c : c.ConvertExplicitly (false, fieldType);
317 return Constant.CreateConstantFromValue (fieldType, value, Location.Null);
320 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
322 add.IsAccessor = true;
323 remove.IsAccessor = true;
325 if (add.Modifiers != remove.Modifiers)
326 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
328 var event_type = ImportType (ei.EventHandlerType, new AttributesTypeInfoReader (ei), declaringType);
329 var definition = new ImportedMemberDefinition (ei, event_type, this);
330 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
333 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
335 var tparams = type.GetGenericArguments ();
337 int parent_owned_count;
339 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
342 // System.Reflection duplicates parent type parameters for each
343 // nested type with slightly modified properties (eg. different owner)
344 // This just makes things more complicated (think of cloned constraints)
345 // therefore we remap any nested type owned by parent using `type_cache'
346 // to the single TypeParameterSpec
348 if (declaringType != null && parent_owned_count > 0) {
350 while (read_count != parent_owned_count) {
351 var tparams_count = declaringType.Arity;
352 if (tparams_count != 0) {
353 var parent_tp = declaringType.MemberDefinition.TypeParameters;
354 read_count += tparams_count;
355 for (int i = 0; i < tparams_count; i++) {
356 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
360 declaringType = declaringType.DeclaringType;
364 parent_owned_count = 0;
367 if (tparams.Length - parent_owned_count == 0)
370 return CreateGenericParameters (parent_owned_count, tparams);
373 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
375 var tspec = new TypeParameterSpec[tparams.Length - first];
376 for (int pos = first; pos < tparams.Length; ++pos) {
377 var type = tparams[pos];
378 int index = pos - first;
380 tspec[index] = (TypeParameterSpec) CreateType (type, new AttributesTypeInfoReader (), false);
386 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, AttributesTypeInfoReader dtype)
388 ++dtype.DynamicPosition;
390 var tspec = new TypeSpec [tparams.Length - first];
391 for (int pos = first; pos < tparams.Length; ++pos) {
392 var type = tparams[pos];
393 int index = pos - first;
396 if (type.HasElementType) {
397 var element = type.GetElementType ();
398 ++dtype.DynamicPosition;
399 spec = ImportType (element, dtype, null);
402 throw new NotImplementedException ("Unknown element type " + type.ToString ());
405 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
407 spec = CreateType (type, dtype, true);
410 // We treat nested generic types as inflated internally where
411 // reflection uses type definition
414 // IFoo<A<T>> foo; // A<T> is definition in this case
417 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
418 var start_pos = GetDeclaringTypesTypeParametersCount (spec);
419 var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype);
420 spec = spec.MakeGenericType (module, targs);
427 ++dtype.DynamicPosition;
434 static int GetDeclaringTypesTypeParametersCount (TypeSpec spec)
437 while (spec.DeclaringType != null) {
438 total += spec.DeclaringType.MemberDefinition.TypeParametersCount;
439 spec = spec.DeclaringType;
445 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
447 Modifiers mod = ReadMethodModifiers (mb, declaringType);
448 TypeParameterSpec[] tparams;
450 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
452 if (mb.IsGenericMethod) {
453 if (!mb.IsGenericMethodDefinition)
454 throw new NotSupportedException ("assert");
456 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
463 if (mb.MemberType == MemberTypes.Constructor) {
464 kind = MemberKind.Constructor;
465 returnType = module.Compiler.BuiltinTypes.Void;
467 var mi = (MethodInfo)mb;
468 returnType = ImportType (mi.ReturnType, new AttributesTypeInfoReader (mi.ReturnParameter), declaringType);
471 // Detect operators and destructors
473 string name = mb.Name;
474 kind = MemberKind.Method;
475 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
476 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
477 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o' && (mb.Attributes & MethodAttributes.SpecialName) != 0) {
478 var op_type = Operator.GetType (name);
479 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
480 kind = MemberKind.Operator;
483 } else if (parameters.IsEmpty && name == Destructor.MetadataName && returnType.Kind == MemberKind.Void) {
484 kind = MemberKind.Destructor;
485 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
486 mod &= ~Modifiers.OVERRIDE;
487 mod |= Modifiers.VIRTUAL;
492 // Cannot set to OVERRIDE without full hierarchy checks
493 // this flag indicates that the method could be override
494 // but further validation is needed
495 if ((mod & Modifiers.OVERRIDE) != 0) {
496 bool is_real_override = false;
497 if (kind == MemberKind.Method && declaringType.BaseType != null) {
498 var btype = declaringType.BaseType;
499 if (IsOverrideMethodBaseTypeAccessible (btype)) {
500 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
501 var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
504 // For imported class method do additional validation to be sure that metadata
505 // override flag was correct
507 // Difference between protected internal and protected is ok
509 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
510 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
511 is_real_override = true;
516 if (!is_real_override) {
517 mod &= ~Modifiers.OVERRIDE;
518 if ((mod & Modifiers.SEALED) != 0)
519 mod &= ~Modifiers.SEALED;
521 mod |= Modifiers.VIRTUAL;
523 } else if (parameters.HasExtensionMethodType) {
524 mod |= Modifiers.METHOD_EXTENSION;
528 IMethodDefinition definition;
529 if (tparams != null) {
530 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
531 foreach (var tp in gmd.TypeParameters) {
532 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
537 definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
540 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
547 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
549 switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
550 case Modifiers.PUBLIC:
552 case Modifiers.INTERNAL:
554 // Check whether imported method in base type is accessible from compiled
557 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
558 case Modifiers.PRIVATE:
562 // protected internal
564 // Method accessibility checks will be done later based on context
565 // where the method is called (CS0122 error will be reported for inaccessible)
572 // Imports System.Reflection parameters
574 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
576 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
578 if (pi.Length == 0 && varargs == 0)
579 return ParametersCompiled.EmptyReadOnlyParameters;
581 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
582 IParameterData[] par = new IParameterData[pi.Length + varargs];
583 bool is_params = false;
584 for (int i = 0; i < pi.Length; i++) {
585 ParameterInfo p = pi[i];
586 Parameter.Modifier mod = 0;
587 Expression default_value = null;
588 if (p.ParameterType.IsByRef) {
589 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
590 mod = Parameter.Modifier.OUT;
592 mod = Parameter.Modifier.REF;
595 // Strip reference wrapping
597 var el = p.ParameterType.GetElementType ();
598 types[i] = ImportType (el, new AttributesTypeInfoReader (p), parent); // TODO: 1-based positio to be csc compatible
599 } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
600 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
601 mod = Parameter.Modifier.This;
602 types[i] = ImportType (p.ParameterType, new AttributesTypeInfoReader (p), parent);
604 types[i] = ImportType (p.ParameterType, new AttributesTypeInfoReader (p), parent);
606 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
607 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
608 mod = Parameter.Modifier.PARAMS;
613 if (!is_params && p.IsOptional) {
614 object value = p.RawDefaultValue;
615 var ptype = types[i];
616 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
618 default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
620 default_value = ImportConstant (value);
623 default_value = new EnumConstant ((Constant) default_value, ptype);
627 var attrs = CustomAttributeData.GetCustomAttributes (p);
628 for (int ii = 0; ii < attrs.Count; ++ii) {
629 var attr = attrs[ii];
630 var dt = attr.Constructor.DeclaringType;
631 if (dt.Namespace != CompilerServicesNamespace)
634 if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
635 mod |= Parameter.Modifier.CallerLineNumber;
636 else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
637 mod |= Parameter.Modifier.CallerFilePath;
638 else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
639 mod |= Parameter.Modifier.CallerMemberName;
641 } else if (value == Missing.Value) {
642 default_value = EmptyExpression.MissingValue;
643 } else if (value == null) {
644 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
645 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
646 default_value = ImportConstant (value);
651 par[i] = new ParameterData (p.Name, mod, default_value);
655 par[par.Length - 1] = new ArglistParameter (Location.Null);
656 types[types.Length - 1] = InternalType.Arglist;
659 return method != null ?
660 new ParametersImported (par, types, varargs != 0, is_params) :
661 new ParametersImported (par, types, is_params);
665 // Returns null when the property is not valid C# property
667 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
670 AParametersCollection param = null;
671 TypeSpec type = null;
674 param = get.Parameters;
675 type = get.ReturnType;
678 bool is_valid_property = true;
680 if (set.ReturnType.Kind != MemberKind.Void)
681 is_valid_property = false;
683 var set_param_count = set.Parameters.Count - 1;
685 if (set_param_count < 0) {
687 is_valid_property = false;
690 var set_type = set.Parameters.Types[set_param_count];
693 AParametersCollection set_based_param;
695 if (set_param_count == 0) {
696 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
698 set_based_param = IndexerSpec.CreateParametersFromSetter (set, set_param_count);
702 param = set_based_param;
705 if (set_param_count != get.Parameters.Count)
706 is_valid_property = false;
708 if (get.ReturnType != set_type)
709 is_valid_property = false;
711 // Possible custom accessor modifiers
712 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
713 var get_acc = mod & Modifiers.AccessibilityMask;
714 if (get_acc != Modifiers.PUBLIC) {
715 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
716 // If the accessor modifiers are not same, do extra restriction checks
717 if (get_acc != set_acc) {
718 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
719 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
720 if (get_restr && set_restr) {
721 is_valid_property = false; // Neither is more restrictive
725 mod &= ~Modifiers.AccessibilityMask;
734 PropertySpec spec = null;
735 if (!param.IsEmpty) {
736 if (is_valid_property) {
737 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
738 if (index_name == null || index_name != pi.Name) {
739 is_valid_property = false;
743 is_valid_property = false;
747 is_valid_property = false;
751 if (is_valid_property) {
752 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
753 } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
755 // Enables support for properties with parameters (must have default value) of COM-imported types
757 is_valid_property = true;
759 for (int i = 0; i < param.FixedParameters.Length; ++i) {
760 if (!param.FixedParameters[i].HasDefaultValue) {
761 is_valid_property = false;
770 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
772 if (!is_valid_property) {
773 spec.IsNotCSharpCompatible = true;
785 public TypeSpec CreateType (MetaType type)
787 return CreateType (type, new AttributesTypeInfoReader (), true);
790 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
792 return CreateType (type, declaringType, new AttributesTypeInfoReader (type), false);
795 TypeSpec CreateType (MetaType type, AttributesTypeInfoReader dtype, bool canImportBaseType)
797 TypeSpec declaring_type;
798 if (type.IsNested && !type.IsGenericParameter)
799 declaring_type = CreateType (type.DeclaringType, new AttributesTypeInfoReader (type.DeclaringType), true);
801 declaring_type = null;
803 return CreateType (type, declaring_type, dtype, canImportBaseType);
806 protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, AttributesTypeInfoReader dtype, bool canImportBaseType)
809 if (import_cache.TryGetValue (type, out spec)) {
810 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
811 if (dtype.IsDynamicObject ())
812 return module.Compiler.BuiltinTypes.Dynamic;
817 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
820 if (!dtype.HasDynamicAttribute ())
823 // We've found same object in the cache but this one has a dynamic custom attribute
824 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
825 // Do type resolve process again in that case
827 // TODO: Handle cases where they still unify
830 if (IsMissingType (type)) {
831 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
832 spec.MemberCache = MemberCache.Empty;
833 import_cache.Add (type, spec);
837 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
838 var type_def = type.GetGenericTypeDefinition ();
840 // Generic type definition can also be forwarded
841 if (compiled_types.TryGetValue (type_def, out spec))
844 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
847 if (declaringType == null) {
848 // Simple case, no nesting
849 spec = CreateType (type_def, null, new AttributesTypeInfoReader (), canImportBaseType);
850 spec = spec.MakeGenericType (module, targs);
853 // Nested type case, converting .NET types like
854 // A`1.B`1.C`1<int, long, string> to typespec like
855 // A<int>.B<long>.C<string>
857 var nested_hierarchy = new List<TypeSpec> ();
858 while (declaringType.IsNested) {
859 nested_hierarchy.Add (declaringType);
860 declaringType = declaringType.DeclaringType;
864 if (declaringType.Arity > 0) {
865 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
866 targs_pos = spec.Arity;
868 spec = declaringType;
871 for (int i = nested_hierarchy.Count; i != 0; --i) {
872 var t = nested_hierarchy [i - 1];
873 if (t.Kind == MemberKind.MissingType)
876 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity, false);
879 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
880 targs_pos += t.Arity;
884 if (spec.Kind == MemberKind.MissingType) {
885 spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC);
886 spec.MemberCache = MemberCache.Empty;
888 if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
891 string name = type.Name;
892 int index = name.IndexOf ('`');
894 name = name.Substring (0, index);
896 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos, false);
898 if (spec.Arity > 0) {
899 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
904 if (spec.IsTupleType && dtype.HasNamedTupleAttribute ()) {
905 var names = dtype.GetNamedTupleElements (spec.Arity);
907 return NamedTupleSpec.MakeType (module, (InflatedTypeSpec) spec, names);
909 dtype.TuplePosition += spec.Arity;
912 // Don't add generic type with dynamic arguments, they can interfere with same type
913 // using object type arguments
914 if (!spec.HasDynamicElement) {
916 // Add to reading cache to speed up reading
917 if (!import_cache.ContainsKey (type))
918 import_cache.Add (type, spec);
927 var ma = type.Attributes;
928 switch (ma & TypeAttributes.VisibilityMask) {
929 case TypeAttributes.Public:
930 case TypeAttributes.NestedPublic:
931 mod = Modifiers.PUBLIC;
933 case TypeAttributes.NestedPrivate:
934 mod = Modifiers.PRIVATE;
936 case TypeAttributes.NestedFamily:
937 mod = Modifiers.PROTECTED;
939 case TypeAttributes.NestedFamORAssem:
940 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
943 mod = Modifiers.INTERNAL;
947 if ((ma & TypeAttributes.Interface) != 0) {
948 kind = MemberKind.Interface;
949 } else if (type.IsGenericParameter) {
950 kind = MemberKind.TypeParameter;
952 var base_type = type.BaseType;
953 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
954 kind = MemberKind.Class;
956 kind = DetermineKindFromBaseType (base_type);
957 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
958 mod |= Modifiers.SEALED;
963 case MemberKind.Class:
964 if ((ma & TypeAttributes.Sealed) != 0) {
965 if ((ma & TypeAttributes.Abstract) != 0)
966 mod |= Modifiers.STATIC;
968 mod |= Modifiers.SEALED;
969 } else if ((ma & TypeAttributes.Abstract) != 0) {
970 mod |= Modifiers.ABSTRACT;
973 case MemberKind.Struct:
974 if (HasAttribute (CustomAttributeData.GetCustomAttributes (type), "IsReadOnlyAttribute", CompilerServicesNamespace)) {
975 mod |= Modifiers.READONLY;
982 var definition = new ImportedTypeDefinition (type, this);
985 if (kind == MemberKind.Enum) {
986 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
987 BindingFlags.Instance |
988 BindingFlags.Public | BindingFlags.NonPublic;
990 var type_members = type.GetFields (underlying_member);
991 foreach (var type_member in type_members) {
992 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
997 kind = MemberKind.Class;
999 } else if (kind == MemberKind.TypeParameter) {
1000 spec = CreateTypeParameter (type, declaringType);
1001 } else if (type.IsGenericTypeDefinition) {
1002 definition.TypeParameters = CreateGenericParameters (type, declaringType);
1003 } else if (compiled_types.TryGetValue (type, out pt)) {
1005 // Same type was found in inside compiled types. It's
1006 // either build-in type or forward referenced typed
1007 // which point into just compiled assembly.
1010 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
1012 bts.SetDefinition (definition, type, mod);
1016 spec = new TypeSpec (kind, declaringType, definition, type, mod);
1018 import_cache.Add (type, spec);
1020 if (kind == MemberKind.TypeParameter) {
1021 if (canImportBaseType)
1022 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
1028 // Two stage setup as the base type can be inflated declaring type or
1029 // another nested type inside same declaring type which has not been
1030 // loaded, therefore we can import a base type of nested types once
1031 // the types have been imported
1033 if (canImportBaseType)
1034 ImportTypeBase (spec, type);
1039 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
1041 IAssemblyDefinition found;
1042 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
1044 // This can happen in dynamic context only
1045 var def = new ImportedAssemblyDefinition (assembly);
1046 assembly_2_definition.Add (assembly, def);
1047 def.ReadAttributes ();
1054 public ImportedAssemblyDefinition GetImportedAssemblyDefinition (AssemblyName assemblyName)
1056 foreach (var a in Assemblies) {
1057 var ia = a as ImportedAssemblyDefinition;
1061 if (a.Name == assemblyName.Name)
1069 public void ImportTypeBase (MetaType type)
1071 TypeSpec spec = import_cache[type];
1073 ImportTypeBase (spec, type);
1076 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
1079 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
1080 case GenericParameterAttributes.Covariant:
1081 variance = Variance.Covariant;
1083 case GenericParameterAttributes.Contravariant:
1084 variance = Variance.Contravariant;
1087 variance = Variance.None;
1091 SpecialConstraint special = SpecialConstraint.None;
1092 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
1094 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
1095 special |= SpecialConstraint.Struct;
1096 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
1097 special = SpecialConstraint.Constructor;
1100 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
1101 special |= SpecialConstraint.Class;
1104 TypeParameterSpec spec;
1105 var def = new ImportedTypeParameterDefinition (type, this);
1106 if (type.DeclaringMethod != null) {
1107 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
1109 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
1116 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
1117 // they can be assembly specific therefore we do check based on names only
1119 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
1121 if (attributesData.Count == 0)
1124 foreach (var attr in attributesData) {
1125 var dt = attr.Constructor.DeclaringType;
1126 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1133 void ImportTypeBase (TypeSpec spec, MetaType type)
1135 if (spec.Kind == MemberKind.Interface)
1136 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1137 else if (type.BaseType != null) {
1139 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1140 base_type = CreateType (type.BaseType, new AttributesTypeInfoReader (type), true);
1142 base_type = CreateType (type.BaseType);
1144 spec.BaseType = base_type;
1147 if (spec.MemberDefinition.TypeParametersCount > 0) {
1148 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1149 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1154 public void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1156 Namespace ns = targetNamespace;
1157 string prev_namespace = null;
1158 foreach (var t in types) {
1162 // Be careful not to trigger full parent type loading
1163 if (t.MemberType == MemberTypes.NestedType)
1166 if (t.Name[0] == '<')
1169 var it = CreateType (t, null, new AttributesTypeInfoReader (t), true);
1173 if (prev_namespace != t.Namespace) {
1174 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1175 prev_namespace = t.Namespace;
1178 // Cannot rely on assembly level Extension attribute or static modifier because they
1179 // are not followed by other compilers (e.g. F#).
1180 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1181 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1182 it.SetExtensionMethodContainer ();
1185 ns.AddType (module, it);
1189 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1191 var constraints = type.GetGenericParameterConstraints ();
1192 List<TypeSpec> tparams = null;
1193 foreach (var ct in constraints) {
1194 if (ct.IsGenericParameter) {
1195 if (tparams == null)
1196 tparams = new List<TypeSpec> ();
1198 tparams.Add (CreateType (ct));
1202 var constraint_type = CreateType (ct);
1203 if (constraint_type.IsClass) {
1204 spec.BaseType = constraint_type;
1208 spec.AddInterface (constraint_type);
1211 if (spec.BaseType == null)
1212 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1214 if (tparams != null)
1215 spec.TypeArguments = tparams.ToArray ();
1218 Constant ImportConstant (object value)
1221 // Get type of underlying value as int constant can be used for object
1222 // parameter type. This is not allowed in C# but other languages can do that
1224 var types = module.Compiler.BuiltinTypes;
1225 switch (System.Type.GetTypeCode (value.GetType ())) {
1226 case TypeCode.Boolean:
1227 return new BoolConstant (types, (bool) value, Location.Null);
1229 return new ByteConstant (types, (byte) value, Location.Null);
1231 return new CharConstant (types, (char) value, Location.Null);
1232 case TypeCode.Decimal:
1233 return new DecimalConstant (types, (decimal) value, Location.Null);
1234 case TypeCode.Double:
1235 return new DoubleConstant (types, (double) value, Location.Null);
1236 case TypeCode.Int16:
1237 return new ShortConstant (types, (short) value, Location.Null);
1238 case TypeCode.Int32:
1239 return new IntConstant (types, (int) value, Location.Null);
1240 case TypeCode.Int64:
1241 return new LongConstant (types, (long) value, Location.Null);
1242 case TypeCode.SByte:
1243 return new SByteConstant (types, (sbyte) value, Location.Null);
1244 case TypeCode.Single:
1245 return new FloatConstant (types, (float) value, Location.Null);
1246 case TypeCode.String:
1247 return new StringConstant (types, (string) value, Location.Null);
1248 case TypeCode.UInt16:
1249 return new UShortConstant (types, (ushort) value, Location.Null);
1250 case TypeCode.UInt32:
1251 return new UIntConstant (types, (uint) value, Location.Null);
1252 case TypeCode.UInt64:
1253 return new ULongConstant (types, (ulong) value, Location.Null);
1256 throw new NotImplementedException (value.GetType ().ToString ());
1259 public TypeSpec ImportType (MetaType type)
1261 return ImportType (type, new AttributesTypeInfoReader (type), null);
1264 TypeSpec ImportType (MetaType type, AttributesTypeInfoReader dtype, TypeSpec currentType)
1266 if (type.HasElementType) {
1267 var element = type.GetElementType ();
1268 ++dtype.DynamicPosition;
1269 var spec = ImportType (element, dtype, currentType);
1272 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1274 return ReferenceContainer.MakeType (module, spec);
1276 return PointerContainer.MakeType (module, spec);
1278 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1281 TypeSpec compiled_type;
1282 if (compiled_types.TryGetValue (type, out compiled_type)) {
1283 if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
1284 return module.Compiler.BuiltinTypes.Dynamic;
1286 compiled_type = CreateType (type, dtype, true);
1289 if (currentType == compiled_type && currentType?.IsGeneric == true) {
1291 // Inflates current type to match behaviour of TypeDefinition::CurrentType used by compiled types
1293 var targs = compiled_type.MemberDefinition.TypeParameters;
1294 compiled_type = compiled_type.MakeGenericType (module, targs);
1297 return compiled_type;
1300 static bool IsMissingType (MetaType type)
1303 return type.__IsMissing;
1310 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1311 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1312 // DecimalConstantAttribute metadata.
1314 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1316 if (attrs.Count == 0)
1319 foreach (var ca in attrs) {
1320 var dt = ca.Constructor.DeclaringType;
1321 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1324 var value = new decimal (
1325 (int) (uint) ca.ConstructorArguments[4].Value,
1326 (int) (uint) ca.ConstructorArguments[3].Value,
1327 (int) (uint) ca.ConstructorArguments[2].Value,
1328 (byte) ca.ConstructorArguments[1].Value != 0,
1329 (byte) ca.ConstructorArguments[0].Value);
1331 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1337 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1340 var ma = mb.Attributes;
1341 switch (ma & MethodAttributes.MemberAccessMask) {
1342 case MethodAttributes.Public:
1343 mod = Modifiers.PUBLIC;
1345 case MethodAttributes.Assembly:
1346 mod = Modifiers.INTERNAL;
1348 case MethodAttributes.Family:
1349 mod = Modifiers.PROTECTED;
1351 case MethodAttributes.FamORAssem:
1352 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1355 mod = Modifiers.PRIVATE;
1359 if ((ma & MethodAttributes.Static) != 0) {
1360 mod |= Modifiers.STATIC;
1363 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1364 mod |= Modifiers.ABSTRACT;
1368 // It can be sealed and override
1369 if ((ma & MethodAttributes.Final) != 0)
1370 mod |= Modifiers.SEALED;
1372 if ((ma & MethodAttributes.Virtual) != 0) {
1373 // Not every member can be detected based on MethodAttribute, we
1374 // set virtual or non-virtual only when we are certain. Further checks
1375 // to really find out what `virtual' means for this member are done
1377 if ((ma & MethodAttributes.NewSlot) != 0) {
1378 if ((mod & Modifiers.SEALED) != 0) {
1379 mod &= ~Modifiers.SEALED;
1381 mod |= Modifiers.VIRTUAL;
1384 mod |= Modifiers.OVERRIDE;
1392 abstract class ImportedDefinition : IMemberDefinition
1394 protected class AttributesBag
1396 public static readonly AttributesBag Default = new AttributesBag ();
1398 public AttributeUsageAttribute AttributeUsage;
1399 public ObsoleteAttribute Obsolete;
1400 public string[] Conditionals;
1401 public string DefaultIndexerName;
1402 public bool? CLSAttributeValue;
1403 public TypeSpec CoClass;
1405 static bool HasMissingType (ConstructorInfo ctor)
1409 // Mimic odd csc behaviour where missing type on predefined
1410 // attributes means the attribute is silently ignored. This can
1411 // happen with PCL facades
1413 foreach (var p in ctor.GetParameters ()) {
1414 if (p.ParameterType.__ContainsMissingType)
1422 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1424 AttributesBag bag = null;
1425 List<string> conditionals = null;
1427 // It should not throw any loading exception
1428 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1430 foreach (var a in attrs) {
1431 var dt = a.Constructor.DeclaringType;
1432 string name = dt.Name;
1433 if (name == "ObsoleteAttribute") {
1434 if (dt.Namespace != "System")
1438 bag = new AttributesBag ();
1440 var args = a.ConstructorArguments;
1442 if (args.Count == 1) {
1443 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1444 } else if (args.Count == 2) {
1445 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1447 bag.Obsolete = new ObsoleteAttribute ();
1453 if (name == "ConditionalAttribute") {
1454 if (dt.Namespace != "System.Diagnostics")
1458 bag = new AttributesBag ();
1460 if (conditionals == null)
1461 conditionals = new List<string> (2);
1463 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1467 if (name == "CLSCompliantAttribute") {
1468 if (dt.Namespace != "System")
1472 bag = new AttributesBag ();
1474 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1478 // Type only attributes
1479 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1480 if (name == "DefaultMemberAttribute") {
1481 if (dt.Namespace != "System.Reflection")
1485 bag = new AttributesBag ();
1487 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1491 if (name == "AttributeUsageAttribute") {
1492 if (dt.Namespace != "System")
1495 if (HasMissingType (a.Constructor))
1499 bag = new AttributesBag ();
1501 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1502 foreach (var named in a.NamedArguments) {
1503 if (named.MemberInfo.Name == "AllowMultiple")
1504 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1505 else if (named.MemberInfo.Name == "Inherited")
1506 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1511 // Interface only attribute
1512 if (name == "CoClassAttribute") {
1513 if (dt.Namespace != "System.Runtime.InteropServices")
1516 if (HasMissingType (a.Constructor))
1520 bag = new AttributesBag ();
1522 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1531 if (conditionals != null)
1532 bag.Conditionals = conditionals.ToArray ();
1538 protected readonly MemberInfo provider;
1539 protected AttributesBag cattrs;
1540 protected readonly MetadataImporter importer;
1542 protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1544 this.provider = provider;
1545 this.importer = importer;
1550 public bool IsImported {
1556 public virtual string Name {
1558 return provider.Name;
1564 public string[] ConditionalConditions ()
1569 return cattrs.Conditionals;
1572 public ObsoleteAttribute GetAttributeObsolete ()
1577 return cattrs.Obsolete;
1580 public bool? CLSAttributeValue {
1585 return cattrs.CLSAttributeValue;
1589 protected void ReadAttributes ()
1591 cattrs = AttributesBag.Read (provider, importer);
1594 public void SetIsAssigned ()
1596 // Unused for imported members
1599 public void SetIsUsed ()
1601 // Unused for imported members
1605 public class ImportedModuleDefinition
1607 readonly Module module;
1610 public ImportedModuleDefinition (Module module)
1612 this.module = module;
1617 public bool IsCLSCompliant {
1619 return cls_compliant;
1623 public string Name {
1631 public void ReadAttributes ()
1633 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1635 foreach (var a in attrs) {
1636 var dt = a.Constructor.DeclaringType;
1637 if (dt.Name == "CLSCompliantAttribute") {
1638 if (dt.Namespace != "System")
1641 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1648 // Reads assembly attributes which where attached to a special type because
1649 // module does have assembly manifest
1651 public List<Attribute> ReadAssemblyAttributes ()
1653 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1657 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1661 // TODO: implement, the idea is to fabricate specil Attribute class and
1662 // add it to OptAttributes before resolving the source code attributes
1663 // Need to build module location as well for correct error reporting
1665 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1666 //var attrs = new List<Attribute> (assembly_attributes.Count);
1667 //foreach (var a in assembly_attributes)
1669 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1670 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1672 // foreach (var carg in a.ConstructorArguments) {
1676 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1683 public class ImportedAssemblyDefinition : IAssemblyDefinition
1685 readonly Assembly assembly;
1686 readonly AssemblyName aname;
1689 List<AssemblyName> internals_visible_to;
1690 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1692 public ImportedAssemblyDefinition (Assembly assembly)
1694 this.assembly = assembly;
1695 this.aname = assembly.GetName ();
1700 public Assembly Assembly {
1706 public string FullName {
1708 return aname.FullName;
1712 public bool HasStrongName {
1714 return aname.GetPublicKey ().Length != 0;
1718 public bool IsMissing {
1721 return assembly.__IsMissing;
1728 public bool IsCLSCompliant {
1730 return cls_compliant;
1734 public string Location {
1736 return assembly.Location;
1740 public string Name {
1748 public byte[] GetPublicKeyToken ()
1750 return aname.GetPublicKeyToken ();
1753 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1755 return internals_visible_to_cache [assembly];
1758 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1760 if (internals_visible_to == null)
1763 AssemblyName is_visible = null;
1764 if (internals_visible_to_cache == null) {
1765 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1767 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1768 return is_visible != null;
1771 var token = assembly.GetPublicKeyToken ();
1772 if (token != null && token.Length == 0)
1775 foreach (var internals in internals_visible_to) {
1776 if (!String.Equals(internals.Name, assembly.Name, StringComparison.OrdinalIgnoreCase))
1779 if (token == null && assembly is AssemblyDefinition) {
1780 is_visible = internals;
1784 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1787 is_visible = internals;
1791 internals_visible_to_cache.Add (assembly, is_visible);
1792 return is_visible != null;
1795 public void ReadAttributes ()
1798 if (assembly.__IsMissing)
1802 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1804 foreach (var a in attrs) {
1805 var dt = a.Constructor.DeclaringType;
1807 if (name == "CLSCompliantAttribute") {
1808 if (dt.Namespace == "System") {
1809 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1814 if (name == "InternalsVisibleToAttribute") {
1815 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1818 string s = a.ConstructorArguments[0].Value as string;
1824 an = new AssemblyName (s);
1825 } catch (FileLoadException) {
1826 // Invalid assembly name reuses FileLoadException
1830 if (internals_visible_to == null)
1831 internals_visible_to = new List<AssemblyName> ();
1833 internals_visible_to.Add (an);
1839 public override string ToString ()
1845 class ImportedMemberDefinition : ImportedDefinition
1847 readonly TypeSpec type;
1849 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1850 : base (member, importer)
1857 public TypeSpec MemberType {
1866 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1868 readonly AParametersCollection parameters;
1870 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1871 : base (provider, type, importer)
1873 this.parameters = parameters;
1876 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1877 : base (provider, type, importer)
1879 this.parameters = parameters;
1884 public AParametersCollection Parameters {
1893 class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1895 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1896 : base (provider, type, parameters, importer)
1900 MethodBase IMethodDefinition.Metadata {
1902 return (MethodBase) provider;
1907 class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1909 readonly TypeParameterSpec[] tparams;
1911 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1912 : base (provider, type, parameters, importer)
1914 this.tparams = tparams;
1919 public TypeParameterSpec[] TypeParameters {
1925 public int TypeParametersCount {
1927 return tparams.Length;
1934 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1936 TypeParameterSpec[] tparams;
1939 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1940 : base (type, importer)
1946 public IAssemblyDefinition DeclaringAssembly {
1948 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1952 bool ITypeDefinition.IsComImport {
1954 return ((MetaType) provider).IsImport;
1959 bool ITypeDefinition.IsPartial {
1965 bool ITypeDefinition.IsTypeForwarder {
1968 return ((MetaType) provider).__IsTypeForwarder;
1975 bool ITypeDefinition.IsCyclicTypeForwarder {
1978 return ((MetaType) provider).__IsCyclicTypeForwarder;
1985 public override string Name {
1989 if (tparams != null) {
1990 int arity_start = name.IndexOf ('`');
1991 if (arity_start > 0)
1992 name = name.Substring (0, arity_start);
2000 public string Namespace {
2002 return ((MetaType) provider).Namespace;
2006 public int TypeParametersCount {
2008 return tparams == null ? 0 : tparams.Length;
2012 public TypeParameterSpec[] TypeParameters {
2023 public void DefineInterfaces (TypeSpec spec)
2025 var type = (MetaType) provider;
2028 ifaces = type.__GetDeclaredInterfaces ();
2029 if (ifaces.Length != 0) {
2030 foreach (var iface in ifaces) {
2031 var it = importer.CreateType (iface);
2035 spec.AddInterfaceDefined (it);
2037 // Unfortunately not all languages expand inherited interfaces
2038 var bifaces = it.Interfaces;
2039 if (bifaces != null) {
2040 foreach (var biface in bifaces) {
2041 spec.AddInterfaceDefined (biface);
2048 // It's impossible to get declared interfaces only using System.Reflection
2049 // hence we need to mimic the behavior with ikvm-reflection too to keep
2050 // our type look-up logic same
2052 if (spec.BaseType != null) {
2053 var bifaces = spec.BaseType.Interfaces;
2054 if (bifaces != null) {
2056 // Before adding base class interfaces close defined interfaces
2057 // on type parameter
2059 var tp = spec as TypeParameterSpec;
2060 if (tp != null && tp.InterfacesDefined == null) {
2061 tp.InterfacesDefined = TypeSpec.EmptyTypes;
2064 foreach (var iface in bifaces)
2065 spec.AddInterfaceDefined (iface);
2069 ifaces = type.GetInterfaces ();
2071 if (ifaces.Length > 0) {
2072 foreach (var iface in ifaces) {
2073 spec.AddInterface (importer.CreateType (iface));
2080 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
2083 // Report details about missing type and most likely cause of the problem.
2084 // csc used to reports 1683, 1684 (now 7069) as warnings but we report them only when used
2085 // or referenced from the user core in which case compilation error has to
2086 // be reported because compiler cannot continue anyway
2089 var report = ctx.Module.Compiler.Report;
2091 for (int i = 0; i < missing.Count; ++i) {
2092 var t = missing [i].Type;
2095 // Report missing types only once
2097 if (report.Printer.MissingTypeReported (t.MemberDefinition))
2100 string name = t.GetSignatureForError ();
2102 var caller = missing[i].Caller;
2103 if (caller.Kind != MemberKind.MissingType)
2104 report.SymbolRelatedToPreviousError (caller);
2106 var definition = t.MemberDefinition;
2107 if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
2108 report.Error (1683, loc,
2109 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
2111 } else if (definition.DeclaringAssembly.IsMissing) {
2112 if (definition.IsTypeForwarder) {
2113 report.Error (1070, loc,
2114 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2115 name, definition.DeclaringAssembly.FullName);
2117 report.Error (12, loc,
2118 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2119 name, definition.DeclaringAssembly.FullName);
2121 } else if (definition.IsTypeForwarder) {
2122 report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
2123 name, definition.DeclaringAssembly.FullName);
2125 report.Error (7069, loc,
2126 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
2127 name, t.MemberDefinition.DeclaringAssembly.FullName);
2132 public TypeSpec GetAttributeCoClass ()
2137 return cattrs.CoClass;
2140 public string GetAttributeDefaultMember ()
2145 return cattrs.DefaultIndexerName;
2148 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2153 return cattrs.AttributeUsage;
2156 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2158 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
2159 return a == assembly || a.IsFriendAssemblyTo (assembly);
2162 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2165 // Not interested in members of nested private types unless the importer needs them
2167 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
2168 cache = MemberCache.Empty;
2172 var loading_type = (MetaType) provider;
2173 const BindingFlags all_members = BindingFlags.DeclaredOnly |
2174 BindingFlags.Static | BindingFlags.Instance |
2175 BindingFlags.Public | BindingFlags.NonPublic;
2177 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
2178 MethodAttributes.Virtual | MethodAttributes.HideBySig |
2179 MethodAttributes.Final;
2181 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
2182 List<EventSpec> imported_events = null;
2183 EventSpec event_spec;
2184 MemberSpec imported;
2188 all = loading_type.GetMembers (all_members);
2189 } catch (Exception e) {
2190 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2191 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2194 if (cache == null) {
2195 cache = new MemberCache (all.Length);
2198 // Do the types first as they can be referenced by the members before
2199 // they are found or inflated
2201 foreach (var member in all) {
2202 if (member.MemberType != MemberTypes.NestedType)
2205 var t = (MetaType) member;
2207 // Ignore compiler generated types, mostly lambda containers
2208 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2212 imported = importer.CreateNestedType (t, declaringType);
2213 } catch (Exception e) {
2214 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2215 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2218 cache.AddMemberImported (imported);
2221 foreach (var member in all) {
2222 if (member.MemberType != MemberTypes.NestedType)
2225 var t = (MetaType) member;
2227 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2230 importer.ImportTypeBase (t);
2235 // Load base interfaces first to minic behaviour of compiled members
2237 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2238 foreach (var iface in declaringType.Interfaces) {
2239 cache.AddInterface (iface);
2245 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2247 foreach (var member in all) {
2248 switch (member.MemberType) {
2249 case MemberTypes.Constructor:
2250 if (declaringType.IsInterface)
2253 goto case MemberTypes.Method;
2254 case MemberTypes.Method:
2255 MethodBase mb = (MethodBase) member;
2256 var attrs = mb.Attributes;
2258 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2259 if (importer.IgnorePrivateMembers)
2262 // Ignore explicitly implemented members
2263 if ((attrs & explicit_impl) == explicit_impl)
2266 // Ignore compiler generated methods
2267 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2271 imported = importer.CreateMethod (mb, declaringType);
2272 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2273 if (possible_accessors == null)
2274 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2276 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2277 possible_accessors.Add (mb, (MethodSpec) imported);
2281 case MemberTypes.Property:
2282 if (possible_accessors == null)
2285 var p = (PropertyInfo) member;
2287 // Links possible accessors with property
2289 MethodSpec get, set;
2290 m = p.GetGetMethod (true);
2291 if (m == null || !possible_accessors.TryGetValue (m, out get))
2294 m = p.GetSetMethod (true);
2295 if (m == null || !possible_accessors.TryGetValue (m, out set))
2298 // No accessors registered (e.g. explicit implementation)
2299 if (get == null && set == null)
2303 imported = importer.CreateProperty (p, declaringType, get, set);
2304 } catch (Exception ex) {
2305 throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2306 p.Name, declaringType.GetSignatureForError ());
2309 if (imported == null)
2313 case MemberTypes.Event:
2314 if (possible_accessors == null)
2317 var e = (EventInfo) member;
2319 // Links accessors with event
2321 MethodSpec add, remove;
2322 m = e.GetAddMethod (true);
2323 if (m == null || !possible_accessors.TryGetValue (m, out add))
2326 m = e.GetRemoveMethod (true);
2327 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2330 // Both accessors are required
2331 if (add == null || remove == null)
2334 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2335 if (!importer.IgnorePrivateMembers) {
2336 if (imported_events == null)
2337 imported_events = new List<EventSpec> ();
2339 imported_events.Add (event_spec);
2342 imported = event_spec;
2344 case MemberTypes.Field:
2345 var fi = (FieldInfo) member;
2347 imported = importer.CreateField (fi, declaringType);
2348 if (imported == null)
2352 // For dynamic binder event has to be fully restored to allow operations
2353 // within the type container to work correctly
2355 if (imported_events != null) {
2356 // The backing event field should be private but it may not
2358 for (i = 0; i < imported_events.Count; ++i) {
2359 var ev = imported_events[i];
2360 if (ev.Name == fi.Name) {
2361 ev.BackingField = (FieldSpec) imported;
2362 imported_events.RemoveAt (i);
2373 case MemberTypes.NestedType:
2374 // Already in the cache from the first pass
2377 throw new NotImplementedException (member.ToString ());
2380 if (imported.IsStatic && declaringType.IsInterface)
2383 cache.AddMemberImported (imported);
2389 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2391 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2392 : base (type, importer)
2398 public IAssemblyDefinition DeclaringAssembly {
2400 throw new NotImplementedException ();
2404 bool ITypeDefinition.IsComImport {
2410 bool ITypeDefinition.IsPartial {
2416 bool ITypeDefinition.IsTypeForwarder {
2422 bool ITypeDefinition.IsCyclicTypeForwarder {
2428 public string Namespace {
2434 public int TypeParametersCount {
2440 public TypeParameterSpec[] TypeParameters {
2448 public TypeSpec GetAttributeCoClass ()
2453 public string GetAttributeDefaultMember ()
2455 throw new NotSupportedException ();
2458 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2460 throw new NotSupportedException ();
2463 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2465 throw new NotImplementedException ();
2468 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2470 throw new NotImplementedException ();