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;
962 if (kind == MemberKind.Class) {
963 if ((ma & TypeAttributes.Sealed) != 0) {
964 if ((ma & TypeAttributes.Abstract) != 0)
965 mod |= Modifiers.STATIC;
967 mod |= Modifiers.SEALED;
968 } else if ((ma & TypeAttributes.Abstract) != 0) {
969 mod |= Modifiers.ABSTRACT;
974 var definition = new ImportedTypeDefinition (type, this);
977 if (kind == MemberKind.Enum) {
978 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
979 BindingFlags.Instance |
980 BindingFlags.Public | BindingFlags.NonPublic;
982 var type_members = type.GetFields (underlying_member);
983 foreach (var type_member in type_members) {
984 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
989 kind = MemberKind.Class;
991 } else if (kind == MemberKind.TypeParameter) {
992 spec = CreateTypeParameter (type, declaringType);
993 } else if (type.IsGenericTypeDefinition) {
994 definition.TypeParameters = CreateGenericParameters (type, declaringType);
995 } else if (compiled_types.TryGetValue (type, out pt)) {
997 // Same type was found in inside compiled types. It's
998 // either build-in type or forward referenced typed
999 // which point into just compiled assembly.
1002 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
1004 bts.SetDefinition (definition, type, mod);
1008 spec = new TypeSpec (kind, declaringType, definition, type, mod);
1010 import_cache.Add (type, spec);
1012 if (kind == MemberKind.TypeParameter) {
1013 if (canImportBaseType)
1014 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
1020 // Two stage setup as the base type can be inflated declaring type or
1021 // another nested type inside same declaring type which has not been
1022 // loaded, therefore we can import a base type of nested types once
1023 // the types have been imported
1025 if (canImportBaseType)
1026 ImportTypeBase (spec, type);
1031 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
1033 IAssemblyDefinition found;
1034 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
1036 // This can happen in dynamic context only
1037 var def = new ImportedAssemblyDefinition (assembly);
1038 assembly_2_definition.Add (assembly, def);
1039 def.ReadAttributes ();
1046 public ImportedAssemblyDefinition GetImportedAssemblyDefinition (AssemblyName assemblyName)
1048 foreach (var a in Assemblies) {
1049 var ia = a as ImportedAssemblyDefinition;
1053 if (a.Name == assemblyName.Name)
1061 public void ImportTypeBase (MetaType type)
1063 TypeSpec spec = import_cache[type];
1065 ImportTypeBase (spec, type);
1068 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
1071 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
1072 case GenericParameterAttributes.Covariant:
1073 variance = Variance.Covariant;
1075 case GenericParameterAttributes.Contravariant:
1076 variance = Variance.Contravariant;
1079 variance = Variance.None;
1083 SpecialConstraint special = SpecialConstraint.None;
1084 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
1086 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
1087 special |= SpecialConstraint.Struct;
1088 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
1089 special = SpecialConstraint.Constructor;
1092 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
1093 special |= SpecialConstraint.Class;
1096 TypeParameterSpec spec;
1097 var def = new ImportedTypeParameterDefinition (type, this);
1098 if (type.DeclaringMethod != null) {
1099 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
1101 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
1108 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
1109 // they can be assembly specific therefore we do check based on names only
1111 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
1113 if (attributesData.Count == 0)
1116 foreach (var attr in attributesData) {
1117 var dt = attr.Constructor.DeclaringType;
1118 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1125 void ImportTypeBase (TypeSpec spec, MetaType type)
1127 if (spec.Kind == MemberKind.Interface)
1128 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1129 else if (type.BaseType != null) {
1131 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1132 base_type = CreateType (type.BaseType, new AttributesTypeInfoReader (type), true);
1134 base_type = CreateType (type.BaseType);
1136 spec.BaseType = base_type;
1139 if (spec.MemberDefinition.TypeParametersCount > 0) {
1140 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1141 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1146 public void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1148 Namespace ns = targetNamespace;
1149 string prev_namespace = null;
1150 foreach (var t in types) {
1154 // Be careful not to trigger full parent type loading
1155 if (t.MemberType == MemberTypes.NestedType)
1158 if (t.Name[0] == '<')
1161 var it = CreateType (t, null, new AttributesTypeInfoReader (t), true);
1165 if (prev_namespace != t.Namespace) {
1166 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1167 prev_namespace = t.Namespace;
1170 // Cannot rely on assembly level Extension attribute or static modifier because they
1171 // are not followed by other compilers (e.g. F#).
1172 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1173 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1174 it.SetExtensionMethodContainer ();
1177 ns.AddType (module, it);
1181 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1183 var constraints = type.GetGenericParameterConstraints ();
1184 List<TypeSpec> tparams = null;
1185 foreach (var ct in constraints) {
1186 if (ct.IsGenericParameter) {
1187 if (tparams == null)
1188 tparams = new List<TypeSpec> ();
1190 tparams.Add (CreateType (ct));
1194 var constraint_type = CreateType (ct);
1195 if (constraint_type.IsClass) {
1196 spec.BaseType = constraint_type;
1200 spec.AddInterface (constraint_type);
1203 if (spec.BaseType == null)
1204 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1206 if (tparams != null)
1207 spec.TypeArguments = tparams.ToArray ();
1210 Constant ImportConstant (object value)
1213 // Get type of underlying value as int constant can be used for object
1214 // parameter type. This is not allowed in C# but other languages can do that
1216 var types = module.Compiler.BuiltinTypes;
1217 switch (System.Type.GetTypeCode (value.GetType ())) {
1218 case TypeCode.Boolean:
1219 return new BoolConstant (types, (bool) value, Location.Null);
1221 return new ByteConstant (types, (byte) value, Location.Null);
1223 return new CharConstant (types, (char) value, Location.Null);
1224 case TypeCode.Decimal:
1225 return new DecimalConstant (types, (decimal) value, Location.Null);
1226 case TypeCode.Double:
1227 return new DoubleConstant (types, (double) value, Location.Null);
1228 case TypeCode.Int16:
1229 return new ShortConstant (types, (short) value, Location.Null);
1230 case TypeCode.Int32:
1231 return new IntConstant (types, (int) value, Location.Null);
1232 case TypeCode.Int64:
1233 return new LongConstant (types, (long) value, Location.Null);
1234 case TypeCode.SByte:
1235 return new SByteConstant (types, (sbyte) value, Location.Null);
1236 case TypeCode.Single:
1237 return new FloatConstant (types, (float) value, Location.Null);
1238 case TypeCode.String:
1239 return new StringConstant (types, (string) value, Location.Null);
1240 case TypeCode.UInt16:
1241 return new UShortConstant (types, (ushort) value, Location.Null);
1242 case TypeCode.UInt32:
1243 return new UIntConstant (types, (uint) value, Location.Null);
1244 case TypeCode.UInt64:
1245 return new ULongConstant (types, (ulong) value, Location.Null);
1248 throw new NotImplementedException (value.GetType ().ToString ());
1251 public TypeSpec ImportType (MetaType type)
1253 return ImportType (type, new AttributesTypeInfoReader (type), null);
1256 TypeSpec ImportType (MetaType type, AttributesTypeInfoReader dtype, TypeSpec currentType)
1258 if (type.HasElementType) {
1259 var element = type.GetElementType ();
1260 ++dtype.DynamicPosition;
1261 var spec = ImportType (element, dtype, currentType);
1264 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1266 return ReferenceContainer.MakeType (module, spec);
1268 return PointerContainer.MakeType (module, spec);
1270 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1273 TypeSpec compiled_type;
1274 if (compiled_types.TryGetValue (type, out compiled_type)) {
1275 if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
1276 return module.Compiler.BuiltinTypes.Dynamic;
1278 compiled_type = CreateType (type, dtype, true);
1281 if (currentType == compiled_type && currentType?.IsGeneric == true) {
1283 // Inflates current type to match behaviour of TypeDefinition::CurrentType used by compiled types
1285 var targs = compiled_type.MemberDefinition.TypeParameters;
1286 compiled_type = compiled_type.MakeGenericType (module, targs);
1289 return compiled_type;
1292 static bool IsMissingType (MetaType type)
1295 return type.__IsMissing;
1302 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1303 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1304 // DecimalConstantAttribute metadata.
1306 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1308 if (attrs.Count == 0)
1311 foreach (var ca in attrs) {
1312 var dt = ca.Constructor.DeclaringType;
1313 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1316 var value = new decimal (
1317 (int) (uint) ca.ConstructorArguments[4].Value,
1318 (int) (uint) ca.ConstructorArguments[3].Value,
1319 (int) (uint) ca.ConstructorArguments[2].Value,
1320 (byte) ca.ConstructorArguments[1].Value != 0,
1321 (byte) ca.ConstructorArguments[0].Value);
1323 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1329 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1332 var ma = mb.Attributes;
1333 switch (ma & MethodAttributes.MemberAccessMask) {
1334 case MethodAttributes.Public:
1335 mod = Modifiers.PUBLIC;
1337 case MethodAttributes.Assembly:
1338 mod = Modifiers.INTERNAL;
1340 case MethodAttributes.Family:
1341 mod = Modifiers.PROTECTED;
1343 case MethodAttributes.FamORAssem:
1344 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1347 mod = Modifiers.PRIVATE;
1351 if ((ma & MethodAttributes.Static) != 0) {
1352 mod |= Modifiers.STATIC;
1355 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1356 mod |= Modifiers.ABSTRACT;
1360 // It can be sealed and override
1361 if ((ma & MethodAttributes.Final) != 0)
1362 mod |= Modifiers.SEALED;
1364 if ((ma & MethodAttributes.Virtual) != 0) {
1365 // Not every member can be detected based on MethodAttribute, we
1366 // set virtual or non-virtual only when we are certain. Further checks
1367 // to really find out what `virtual' means for this member are done
1369 if ((ma & MethodAttributes.NewSlot) != 0) {
1370 if ((mod & Modifiers.SEALED) != 0) {
1371 mod &= ~Modifiers.SEALED;
1373 mod |= Modifiers.VIRTUAL;
1376 mod |= Modifiers.OVERRIDE;
1384 abstract class ImportedDefinition : IMemberDefinition
1386 protected class AttributesBag
1388 public static readonly AttributesBag Default = new AttributesBag ();
1390 public AttributeUsageAttribute AttributeUsage;
1391 public ObsoleteAttribute Obsolete;
1392 public string[] Conditionals;
1393 public string DefaultIndexerName;
1394 public bool? CLSAttributeValue;
1395 public TypeSpec CoClass;
1397 static bool HasMissingType (ConstructorInfo ctor)
1401 // Mimic odd csc behaviour where missing type on predefined
1402 // attributes means the attribute is silently ignored. This can
1403 // happen with PCL facades
1405 foreach (var p in ctor.GetParameters ()) {
1406 if (p.ParameterType.__ContainsMissingType)
1414 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1416 AttributesBag bag = null;
1417 List<string> conditionals = null;
1419 // It should not throw any loading exception
1420 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1422 foreach (var a in attrs) {
1423 var dt = a.Constructor.DeclaringType;
1424 string name = dt.Name;
1425 if (name == "ObsoleteAttribute") {
1426 if (dt.Namespace != "System")
1430 bag = new AttributesBag ();
1432 var args = a.ConstructorArguments;
1434 if (args.Count == 1) {
1435 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1436 } else if (args.Count == 2) {
1437 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1439 bag.Obsolete = new ObsoleteAttribute ();
1445 if (name == "ConditionalAttribute") {
1446 if (dt.Namespace != "System.Diagnostics")
1450 bag = new AttributesBag ();
1452 if (conditionals == null)
1453 conditionals = new List<string> (2);
1455 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1459 if (name == "CLSCompliantAttribute") {
1460 if (dt.Namespace != "System")
1464 bag = new AttributesBag ();
1466 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1470 // Type only attributes
1471 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1472 if (name == "DefaultMemberAttribute") {
1473 if (dt.Namespace != "System.Reflection")
1477 bag = new AttributesBag ();
1479 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1483 if (name == "AttributeUsageAttribute") {
1484 if (dt.Namespace != "System")
1487 if (HasMissingType (a.Constructor))
1491 bag = new AttributesBag ();
1493 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1494 foreach (var named in a.NamedArguments) {
1495 if (named.MemberInfo.Name == "AllowMultiple")
1496 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1497 else if (named.MemberInfo.Name == "Inherited")
1498 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1503 // Interface only attribute
1504 if (name == "CoClassAttribute") {
1505 if (dt.Namespace != "System.Runtime.InteropServices")
1508 if (HasMissingType (a.Constructor))
1512 bag = new AttributesBag ();
1514 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1523 if (conditionals != null)
1524 bag.Conditionals = conditionals.ToArray ();
1530 protected readonly MemberInfo provider;
1531 protected AttributesBag cattrs;
1532 protected readonly MetadataImporter importer;
1534 protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1536 this.provider = provider;
1537 this.importer = importer;
1542 public bool IsImported {
1548 public virtual string Name {
1550 return provider.Name;
1556 public string[] ConditionalConditions ()
1561 return cattrs.Conditionals;
1564 public ObsoleteAttribute GetAttributeObsolete ()
1569 return cattrs.Obsolete;
1572 public bool? CLSAttributeValue {
1577 return cattrs.CLSAttributeValue;
1581 protected void ReadAttributes ()
1583 cattrs = AttributesBag.Read (provider, importer);
1586 public void SetIsAssigned ()
1588 // Unused for imported members
1591 public void SetIsUsed ()
1593 // Unused for imported members
1597 public class ImportedModuleDefinition
1599 readonly Module module;
1602 public ImportedModuleDefinition (Module module)
1604 this.module = module;
1609 public bool IsCLSCompliant {
1611 return cls_compliant;
1615 public string Name {
1623 public void ReadAttributes ()
1625 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1627 foreach (var a in attrs) {
1628 var dt = a.Constructor.DeclaringType;
1629 if (dt.Name == "CLSCompliantAttribute") {
1630 if (dt.Namespace != "System")
1633 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1640 // Reads assembly attributes which where attached to a special type because
1641 // module does have assembly manifest
1643 public List<Attribute> ReadAssemblyAttributes ()
1645 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1649 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1653 // TODO: implement, the idea is to fabricate specil Attribute class and
1654 // add it to OptAttributes before resolving the source code attributes
1655 // Need to build module location as well for correct error reporting
1657 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1658 //var attrs = new List<Attribute> (assembly_attributes.Count);
1659 //foreach (var a in assembly_attributes)
1661 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1662 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1664 // foreach (var carg in a.ConstructorArguments) {
1668 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1675 public class ImportedAssemblyDefinition : IAssemblyDefinition
1677 readonly Assembly assembly;
1678 readonly AssemblyName aname;
1681 List<AssemblyName> internals_visible_to;
1682 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1684 public ImportedAssemblyDefinition (Assembly assembly)
1686 this.assembly = assembly;
1687 this.aname = assembly.GetName ();
1692 public Assembly Assembly {
1698 public string FullName {
1700 return aname.FullName;
1704 public bool HasStrongName {
1706 return aname.GetPublicKey ().Length != 0;
1710 public bool IsMissing {
1713 return assembly.__IsMissing;
1720 public bool IsCLSCompliant {
1722 return cls_compliant;
1726 public string Location {
1728 return assembly.Location;
1732 public string Name {
1740 public byte[] GetPublicKeyToken ()
1742 return aname.GetPublicKeyToken ();
1745 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1747 return internals_visible_to_cache [assembly];
1750 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1752 if (internals_visible_to == null)
1755 AssemblyName is_visible = null;
1756 if (internals_visible_to_cache == null) {
1757 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1759 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1760 return is_visible != null;
1763 var token = assembly.GetPublicKeyToken ();
1764 if (token != null && token.Length == 0)
1767 foreach (var internals in internals_visible_to) {
1768 if (!String.Equals(internals.Name, assembly.Name, StringComparison.OrdinalIgnoreCase))
1771 if (token == null && assembly is AssemblyDefinition) {
1772 is_visible = internals;
1776 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1779 is_visible = internals;
1783 internals_visible_to_cache.Add (assembly, is_visible);
1784 return is_visible != null;
1787 public void ReadAttributes ()
1790 if (assembly.__IsMissing)
1794 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1796 foreach (var a in attrs) {
1797 var dt = a.Constructor.DeclaringType;
1799 if (name == "CLSCompliantAttribute") {
1800 if (dt.Namespace == "System") {
1801 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1806 if (name == "InternalsVisibleToAttribute") {
1807 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1810 string s = a.ConstructorArguments[0].Value as string;
1816 an = new AssemblyName (s);
1817 } catch (FileLoadException) {
1818 // Invalid assembly name reuses FileLoadException
1822 if (internals_visible_to == null)
1823 internals_visible_to = new List<AssemblyName> ();
1825 internals_visible_to.Add (an);
1831 public override string ToString ()
1837 class ImportedMemberDefinition : ImportedDefinition
1839 readonly TypeSpec type;
1841 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1842 : base (member, importer)
1849 public TypeSpec MemberType {
1858 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1860 readonly AParametersCollection parameters;
1862 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1863 : base (provider, type, importer)
1865 this.parameters = parameters;
1868 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1869 : base (provider, type, importer)
1871 this.parameters = parameters;
1876 public AParametersCollection Parameters {
1885 class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1887 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1888 : base (provider, type, parameters, importer)
1892 MethodBase IMethodDefinition.Metadata {
1894 return (MethodBase) provider;
1899 class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1901 readonly TypeParameterSpec[] tparams;
1903 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1904 : base (provider, type, parameters, importer)
1906 this.tparams = tparams;
1911 public TypeParameterSpec[] TypeParameters {
1917 public int TypeParametersCount {
1919 return tparams.Length;
1926 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1928 TypeParameterSpec[] tparams;
1931 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1932 : base (type, importer)
1938 public IAssemblyDefinition DeclaringAssembly {
1940 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1944 bool ITypeDefinition.IsComImport {
1946 return ((MetaType) provider).IsImport;
1951 bool ITypeDefinition.IsPartial {
1957 bool ITypeDefinition.IsTypeForwarder {
1960 return ((MetaType) provider).__IsTypeForwarder;
1967 bool ITypeDefinition.IsCyclicTypeForwarder {
1970 return ((MetaType) provider).__IsCyclicTypeForwarder;
1977 public override string Name {
1981 if (tparams != null) {
1982 int arity_start = name.IndexOf ('`');
1983 if (arity_start > 0)
1984 name = name.Substring (0, arity_start);
1992 public string Namespace {
1994 return ((MetaType) provider).Namespace;
1998 public int TypeParametersCount {
2000 return tparams == null ? 0 : tparams.Length;
2004 public TypeParameterSpec[] TypeParameters {
2015 public void DefineInterfaces (TypeSpec spec)
2017 var type = (MetaType) provider;
2020 ifaces = type.__GetDeclaredInterfaces ();
2021 if (ifaces.Length != 0) {
2022 foreach (var iface in ifaces) {
2023 var it = importer.CreateType (iface);
2027 spec.AddInterfaceDefined (it);
2029 // Unfortunately not all languages expand inherited interfaces
2030 var bifaces = it.Interfaces;
2031 if (bifaces != null) {
2032 foreach (var biface in bifaces) {
2033 spec.AddInterfaceDefined (biface);
2040 // It's impossible to get declared interfaces only using System.Reflection
2041 // hence we need to mimic the behavior with ikvm-reflection too to keep
2042 // our type look-up logic same
2044 if (spec.BaseType != null) {
2045 var bifaces = spec.BaseType.Interfaces;
2046 if (bifaces != null) {
2048 // Before adding base class interfaces close defined interfaces
2049 // on type parameter
2051 var tp = spec as TypeParameterSpec;
2052 if (tp != null && tp.InterfacesDefined == null) {
2053 tp.InterfacesDefined = TypeSpec.EmptyTypes;
2056 foreach (var iface in bifaces)
2057 spec.AddInterfaceDefined (iface);
2061 ifaces = type.GetInterfaces ();
2063 if (ifaces.Length > 0) {
2064 foreach (var iface in ifaces) {
2065 spec.AddInterface (importer.CreateType (iface));
2072 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
2075 // Report details about missing type and most likely cause of the problem.
2076 // csc used to reports 1683, 1684 (now 7069) as warnings but we report them only when used
2077 // or referenced from the user core in which case compilation error has to
2078 // be reported because compiler cannot continue anyway
2081 var report = ctx.Module.Compiler.Report;
2083 for (int i = 0; i < missing.Count; ++i) {
2084 var t = missing [i].Type;
2087 // Report missing types only once
2089 if (report.Printer.MissingTypeReported (t.MemberDefinition))
2092 string name = t.GetSignatureForError ();
2094 var caller = missing[i].Caller;
2095 if (caller.Kind != MemberKind.MissingType)
2096 report.SymbolRelatedToPreviousError (caller);
2098 var definition = t.MemberDefinition;
2099 if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
2100 report.Error (1683, loc,
2101 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
2103 } else if (definition.DeclaringAssembly.IsMissing) {
2104 if (definition.IsTypeForwarder) {
2105 report.Error (1070, loc,
2106 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2107 name, definition.DeclaringAssembly.FullName);
2109 report.Error (12, loc,
2110 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2111 name, definition.DeclaringAssembly.FullName);
2113 } else if (definition.IsTypeForwarder) {
2114 report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
2115 name, definition.DeclaringAssembly.FullName);
2117 report.Error (7069, loc,
2118 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
2119 name, t.MemberDefinition.DeclaringAssembly.FullName);
2124 public TypeSpec GetAttributeCoClass ()
2129 return cattrs.CoClass;
2132 public string GetAttributeDefaultMember ()
2137 return cattrs.DefaultIndexerName;
2140 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2145 return cattrs.AttributeUsage;
2148 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2150 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
2151 return a == assembly || a.IsFriendAssemblyTo (assembly);
2154 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2157 // Not interested in members of nested private types unless the importer needs them
2159 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
2160 cache = MemberCache.Empty;
2164 var loading_type = (MetaType) provider;
2165 const BindingFlags all_members = BindingFlags.DeclaredOnly |
2166 BindingFlags.Static | BindingFlags.Instance |
2167 BindingFlags.Public | BindingFlags.NonPublic;
2169 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
2170 MethodAttributes.Virtual | MethodAttributes.HideBySig |
2171 MethodAttributes.Final;
2173 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
2174 List<EventSpec> imported_events = null;
2175 EventSpec event_spec;
2176 MemberSpec imported;
2180 all = loading_type.GetMembers (all_members);
2181 } catch (Exception e) {
2182 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2183 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2186 if (cache == null) {
2187 cache = new MemberCache (all.Length);
2190 // Do the types first as they can be referenced by the members before
2191 // they are found or inflated
2193 foreach (var member in all) {
2194 if (member.MemberType != MemberTypes.NestedType)
2197 var t = (MetaType) member;
2199 // Ignore compiler generated types, mostly lambda containers
2200 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2204 imported = importer.CreateNestedType (t, declaringType);
2205 } catch (Exception e) {
2206 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2207 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2210 cache.AddMemberImported (imported);
2213 foreach (var member in all) {
2214 if (member.MemberType != MemberTypes.NestedType)
2217 var t = (MetaType) member;
2219 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2222 importer.ImportTypeBase (t);
2227 // Load base interfaces first to minic behaviour of compiled members
2229 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2230 foreach (var iface in declaringType.Interfaces) {
2231 cache.AddInterface (iface);
2237 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2239 foreach (var member in all) {
2240 switch (member.MemberType) {
2241 case MemberTypes.Constructor:
2242 if (declaringType.IsInterface)
2245 goto case MemberTypes.Method;
2246 case MemberTypes.Method:
2247 MethodBase mb = (MethodBase) member;
2248 var attrs = mb.Attributes;
2250 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2251 if (importer.IgnorePrivateMembers)
2254 // Ignore explicitly implemented members
2255 if ((attrs & explicit_impl) == explicit_impl)
2258 // Ignore compiler generated methods
2259 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2263 imported = importer.CreateMethod (mb, declaringType);
2264 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2265 if (possible_accessors == null)
2266 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2268 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2269 possible_accessors.Add (mb, (MethodSpec) imported);
2273 case MemberTypes.Property:
2274 if (possible_accessors == null)
2277 var p = (PropertyInfo) member;
2279 // Links possible accessors with property
2281 MethodSpec get, set;
2282 m = p.GetGetMethod (true);
2283 if (m == null || !possible_accessors.TryGetValue (m, out get))
2286 m = p.GetSetMethod (true);
2287 if (m == null || !possible_accessors.TryGetValue (m, out set))
2290 // No accessors registered (e.g. explicit implementation)
2291 if (get == null && set == null)
2295 imported = importer.CreateProperty (p, declaringType, get, set);
2296 } catch (Exception ex) {
2297 throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2298 p.Name, declaringType.GetSignatureForError ());
2301 if (imported == null)
2305 case MemberTypes.Event:
2306 if (possible_accessors == null)
2309 var e = (EventInfo) member;
2311 // Links accessors with event
2313 MethodSpec add, remove;
2314 m = e.GetAddMethod (true);
2315 if (m == null || !possible_accessors.TryGetValue (m, out add))
2318 m = e.GetRemoveMethod (true);
2319 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2322 // Both accessors are required
2323 if (add == null || remove == null)
2326 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2327 if (!importer.IgnorePrivateMembers) {
2328 if (imported_events == null)
2329 imported_events = new List<EventSpec> ();
2331 imported_events.Add (event_spec);
2334 imported = event_spec;
2336 case MemberTypes.Field:
2337 var fi = (FieldInfo) member;
2339 imported = importer.CreateField (fi, declaringType);
2340 if (imported == null)
2344 // For dynamic binder event has to be fully restored to allow operations
2345 // within the type container to work correctly
2347 if (imported_events != null) {
2348 // The backing event field should be private but it may not
2350 for (i = 0; i < imported_events.Count; ++i) {
2351 var ev = imported_events[i];
2352 if (ev.Name == fi.Name) {
2353 ev.BackingField = (FieldSpec) imported;
2354 imported_events.RemoveAt (i);
2365 case MemberTypes.NestedType:
2366 // Already in the cache from the first pass
2369 throw new NotImplementedException (member.ToString ());
2372 if (imported.IsStatic && declaringType.IsInterface)
2375 cache.AddMemberImported (imported);
2381 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2383 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2384 : base (type, importer)
2390 public IAssemblyDefinition DeclaringAssembly {
2392 throw new NotImplementedException ();
2396 bool ITypeDefinition.IsComImport {
2402 bool ITypeDefinition.IsPartial {
2408 bool ITypeDefinition.IsTypeForwarder {
2414 bool ITypeDefinition.IsCyclicTypeForwarder {
2420 public string Namespace {
2426 public int TypeParametersCount {
2432 public TypeParameterSpec[] TypeParameters {
2440 public TypeSpec GetAttributeCoClass ()
2445 public string GetAttributeDefaultMember ()
2447 throw new NotSupportedException ();
2450 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2452 throw new NotSupportedException ();
2455 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2457 throw new NotImplementedException ();
2460 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2462 throw new NotImplementedException ();