2 // import.cs: System.Reflection conversions
4 // Authors: Marek Safar (marek.safar@gmail.com)
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
8 // Copyright 2009-2011 Novell, Inc
9 // Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
13 using System.Runtime.CompilerServices;
15 using System.Collections.Generic;
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
29 public abstract class MetadataImporter
32 // Dynamic types reader with additional logic to reconstruct a dynamic
33 // type using DynamicAttribute values
35 protected struct DynamicTypeReader
37 static readonly bool[] single_attribute = { true };
42 // There is no common type for CustomAttributeData and we cannot
43 // use ICustomAttributeProvider
47 // A member provider which can be used to get CustomAttributeData
49 public DynamicTypeReader (object provider)
53 this.provider = provider;
57 // Returns true when object at local position has dynamic attribute flag
59 public bool IsDynamicObject ()
64 return flags != null && Position < flags.Length && flags[Position];
68 // Returns true when DynamicAttribute exists
70 public bool HasDynamicAttribute ()
78 IList<CustomAttributeData> GetCustomAttributes ()
80 var mi = provider as MemberInfo;
82 return CustomAttributeData.GetCustomAttributes (mi);
84 var pi = provider as ParameterInfo;
86 return CustomAttributeData.GetCustomAttributes (pi);
94 var cad = GetCustomAttributes ();
100 foreach (var ca in cad) {
101 var dt = ca.Constructor.DeclaringType;
102 if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace)
105 if (ca.ConstructorArguments.Count == 0) {
106 flags = single_attribute;
110 var arg_type = ca.ConstructorArguments[0].ArgumentType;
112 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
113 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
114 flags = new bool[carg.Count];
115 for (int i = 0; i < flags.Length; ++i) {
116 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
117 flags[i] = (bool) carg[i].Value;
129 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
130 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
131 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
132 protected readonly ModuleContainer module;
134 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
136 protected MetadataImporter (ModuleContainer module)
138 this.module = module;
140 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
141 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
142 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
143 IgnorePrivateMembers = true;
148 public ICollection<IAssemblyDefinition> Assemblies {
150 return assembly_2_definition.Values;
154 public bool IgnorePrivateMembers { get; set; }
158 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
159 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
160 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
162 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
165 var fa = fi.Attributes;
166 switch (fa & FieldAttributes.FieldAccessMask) {
167 case FieldAttributes.Public:
168 mod = Modifiers.PUBLIC;
170 case FieldAttributes.Assembly:
171 mod = Modifiers.INTERNAL;
173 case FieldAttributes.Family:
174 mod = Modifiers.PROTECTED;
176 case FieldAttributes.FamORAssem:
177 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
180 // Ignore private fields (even for error reporting) to not require extra dependencies
181 if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
182 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
185 mod = Modifiers.PRIVATE;
192 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
195 // Private field has private type which is not fixed buffer
197 if (field_type == null)
199 } catch (Exception e) {
200 // TODO: I should construct fake TypeSpec based on TypeRef signature
201 // but there is no way to do it with System.Reflection
202 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
203 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
206 var definition = new ImportedMemberDefinition (fi, field_type, this);
208 if ((fa & FieldAttributes.Literal) != 0) {
209 Constant c = field_type.Kind == MemberKind.MissingType ?
210 new NullConstant (InternalType.ErrorType, Location.Null) :
211 Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
212 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
215 if ((fa & FieldAttributes.InitOnly) != 0) {
216 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
217 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
219 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
222 mod |= Modifiers.READONLY;
224 var req_mod = fi.GetRequiredCustomModifiers ();
225 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
226 mod |= Modifiers.VOLATILE;
229 if ((fa & FieldAttributes.Static) != 0) {
230 mod |= Modifiers.STATIC;
232 // Fixed buffers cannot be static
233 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
234 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
236 // TODO: Sanity check on field_type (only few types are allowed)
237 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
238 return new FixedFieldSpec (module, declaringType, definition, fi, element_field, mod);
242 return new FieldSpec (declaringType, definition, field_type, fi, mod);
245 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
247 add.IsAccessor = true;
248 remove.IsAccessor = true;
250 if (add.Modifiers != remove.Modifiers)
251 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
253 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
254 var definition = new ImportedMemberDefinition (ei, event_type, this);
255 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
258 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
260 var tparams = type.GetGenericArguments ();
262 int parent_owned_count;
264 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
267 // System.Reflection duplicates parent type parameters for each
268 // nested type with slightly modified properties (eg. different owner)
269 // This just makes things more complicated (think of cloned constraints)
270 // therefore we remap any nested type owned by parent using `type_cache'
271 // to the single TypeParameterSpec
273 if (declaringType != null && parent_owned_count > 0) {
275 while (read_count != parent_owned_count) {
276 var tparams_count = declaringType.Arity;
277 if (tparams_count != 0) {
278 var parent_tp = declaringType.MemberDefinition.TypeParameters;
279 read_count += tparams_count;
280 for (int i = 0; i < tparams_count; i++) {
281 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
285 declaringType = declaringType.DeclaringType;
289 parent_owned_count = 0;
292 if (tparams.Length - parent_owned_count == 0)
295 return CreateGenericParameters (parent_owned_count, tparams);
298 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
300 var tspec = new TypeParameterSpec[tparams.Length - first];
301 for (int pos = first; pos < tparams.Length; ++pos) {
302 var type = tparams[pos];
303 int index = pos - first;
305 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
311 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
315 var tspec = new TypeSpec [tparams.Length - first];
316 for (int pos = first; pos < tparams.Length; ++pos) {
317 var type = tparams[pos];
318 int index = pos - first;
321 if (type.HasElementType) {
322 var element = type.GetElementType ();
324 spec = ImportType (element, dtype);
327 throw new NotImplementedException ("Unknown element type " + type.ToString ());
330 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
332 spec = CreateType (type, dtype, true);
335 // We treat nested generic types as inflated internally where
336 // reflection uses type definition
339 // IFoo<A<T>> foo; // A<T> is definition in this case
342 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
343 var start_pos = spec.DeclaringType == null ? 0 : spec.DeclaringType.MemberDefinition.TypeParametersCount;
344 var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype);
345 spec = spec.MakeGenericType (module, targs);
359 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
361 Modifiers mod = ReadMethodModifiers (mb, declaringType);
362 TypeParameterSpec[] tparams;
364 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
366 if (mb.IsGenericMethod) {
367 if (!mb.IsGenericMethodDefinition)
368 throw new NotSupportedException ("assert");
370 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
377 if (mb.MemberType == MemberTypes.Constructor) {
378 kind = MemberKind.Constructor;
379 returnType = module.Compiler.BuiltinTypes.Void;
382 // Detect operators and destructors
384 string name = mb.Name;
385 kind = MemberKind.Method;
386 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
387 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
388 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o' && (mb.Attributes & MethodAttributes.SpecialName) != 0) {
389 var op_type = Operator.GetType (name);
390 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
391 kind = MemberKind.Operator;
394 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
395 kind = MemberKind.Destructor;
396 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
397 mod &= ~Modifiers.OVERRIDE;
398 mod |= Modifiers.VIRTUAL;
403 var mi = (MethodInfo) mb;
404 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
406 // Cannot set to OVERRIDE without full hierarchy checks
407 // this flag indicates that the method could be override
408 // but further validation is needed
409 if ((mod & Modifiers.OVERRIDE) != 0) {
410 bool is_real_override = false;
411 if (kind == MemberKind.Method && declaringType.BaseType != null) {
412 var btype = declaringType.BaseType;
413 if (IsOverrideMethodBaseTypeAccessible (btype)) {
414 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
415 var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
418 // For imported class method do additional validation to be sure that metadata
419 // override flag was correct
421 // Difference between protected internal and protected is ok
423 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
424 if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
425 is_real_override = true;
430 if (!is_real_override) {
431 mod &= ~Modifiers.OVERRIDE;
432 if ((mod & Modifiers.SEALED) != 0)
433 mod &= ~Modifiers.SEALED;
435 mod |= Modifiers.VIRTUAL;
437 } else if (parameters.HasExtensionMethodType) {
438 mod |= Modifiers.METHOD_EXTENSION;
442 IMethodDefinition definition;
443 if (tparams != null) {
444 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
445 foreach (var tp in gmd.TypeParameters) {
446 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
451 definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
454 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
461 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
463 switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
464 case Modifiers.PUBLIC:
466 case Modifiers.INTERNAL:
468 // Check whether imported method in base type is accessible from compiled
471 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
472 case Modifiers.PRIVATE:
476 // protected internal
478 // Method accessibility checks will be done later based on context
479 // where the method is called (CS0122 error will be reported for inaccessible)
486 // Imports System.Reflection parameters
488 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
490 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
492 if (pi.Length == 0 && varargs == 0)
493 return ParametersCompiled.EmptyReadOnlyParameters;
495 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
496 IParameterData[] par = new IParameterData[pi.Length + varargs];
497 bool is_params = false;
498 for (int i = 0; i < pi.Length; i++) {
499 ParameterInfo p = pi[i];
500 Parameter.Modifier mod = 0;
501 Expression default_value = null;
502 if (p.ParameterType.IsByRef) {
503 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
504 mod = Parameter.Modifier.OUT;
506 mod = Parameter.Modifier.REF;
509 // Strip reference wrapping
511 var el = p.ParameterType.GetElementType ();
512 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
513 } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
514 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
515 mod = Parameter.Modifier.This;
516 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
518 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
520 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
521 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
522 mod = Parameter.Modifier.PARAMS;
527 if (!is_params && p.IsOptional) {
528 object value = p.RawDefaultValue;
529 var ptype = types[i];
530 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
532 default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
534 default_value = ImportParameterConstant (value);
537 default_value = new EnumConstant ((Constant) default_value, ptype);
541 var attrs = CustomAttributeData.GetCustomAttributes (p);
542 for (int ii = 0; ii < attrs.Count; ++ii) {
543 var attr = attrs[ii];
544 var dt = attr.Constructor.DeclaringType;
545 if (dt.Namespace != CompilerServicesNamespace)
548 if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
549 mod |= Parameter.Modifier.CallerLineNumber;
550 else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
551 mod |= Parameter.Modifier.CallerFilePath;
552 else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
553 mod |= Parameter.Modifier.CallerMemberName;
555 } else if (value == Missing.Value) {
556 default_value = EmptyExpression.MissingValue;
557 } else if (value == null) {
558 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
559 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
560 default_value = ImportParameterConstant (value);
565 par[i] = new ParameterData (p.Name, mod, default_value);
569 par[par.Length - 1] = new ArglistParameter (Location.Null);
570 types[types.Length - 1] = InternalType.Arglist;
573 return method != null ?
574 new ParametersImported (par, types, varargs != 0, is_params) :
575 new ParametersImported (par, types, is_params);
579 // Returns null when the property is not valid C# property
581 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
584 AParametersCollection param = null;
585 TypeSpec type = null;
588 param = get.Parameters;
589 type = get.ReturnType;
592 bool is_valid_property = true;
594 if (set.ReturnType.Kind != MemberKind.Void)
595 is_valid_property = false;
597 var set_param_count = set.Parameters.Count - 1;
599 if (set_param_count < 0) {
601 is_valid_property = false;
604 var set_type = set.Parameters.Types[set_param_count];
607 AParametersCollection set_based_param;
609 if (set_param_count == 0) {
610 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
613 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
615 var data = new IParameterData[set_param_count];
616 var types = new TypeSpec[set_param_count];
617 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
618 Array.Copy (set.Parameters.Types, types, set_param_count);
619 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
623 param = set_based_param;
626 if (set_param_count != get.Parameters.Count)
627 is_valid_property = false;
629 if (get.ReturnType != set_type)
630 is_valid_property = false;
632 // Possible custom accessor modifiers
633 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
634 var get_acc = mod & Modifiers.AccessibilityMask;
635 if (get_acc != Modifiers.PUBLIC) {
636 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
637 // If the accessor modifiers are not same, do extra restriction checks
638 if (get_acc != set_acc) {
639 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
640 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
641 if (get_restr && set_restr) {
642 is_valid_property = false; // Neither is more restrictive
646 mod &= ~Modifiers.AccessibilityMask;
655 PropertySpec spec = null;
656 if (!param.IsEmpty) {
657 if (is_valid_property) {
658 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
659 if (index_name == null) {
660 is_valid_property = false;
664 is_valid_property = false;
665 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
666 is_valid_property = false;
670 is_valid_property = false;
671 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
672 is_valid_property = false;
676 if (is_valid_property) {
677 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
678 } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
680 // Enables support for properties with parameters (must have default value) of COM-imported types
682 is_valid_property = true;
684 for (int i = 0; i < param.FixedParameters.Length; ++i) {
685 if (!param.FixedParameters[i].HasDefaultValue) {
686 is_valid_property = false;
695 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
697 if (!is_valid_property) {
698 spec.IsNotCSharpCompatible = true;
710 public TypeSpec CreateType (MetaType type)
712 return CreateType (type, new DynamicTypeReader (), true);
715 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
717 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
720 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
722 TypeSpec declaring_type;
723 if (type.IsNested && !type.IsGenericParameter)
724 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
726 declaring_type = null;
728 return CreateType (type, declaring_type, dtype, canImportBaseType);
731 protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
734 if (import_cache.TryGetValue (type, out spec)) {
735 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
736 if (dtype.IsDynamicObject ())
737 return module.Compiler.BuiltinTypes.Dynamic;
742 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
745 if (!dtype.HasDynamicAttribute ())
748 // We've found same object in the cache but this one has a dynamic custom attribute
749 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
750 // Do type resolve process again in that case
752 // TODO: Handle cases where they still unify
755 if (IsMissingType (type)) {
756 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
757 spec.MemberCache = MemberCache.Empty;
758 import_cache.Add (type, spec);
762 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
763 var type_def = type.GetGenericTypeDefinition ();
765 // Generic type definition can also be forwarded
766 if (compiled_types.TryGetValue (type_def, out spec))
769 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
772 if (declaringType == null) {
773 // Simple case, no nesting
774 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
775 spec = spec.MakeGenericType (module, targs);
778 // Nested type case, converting .NET types like
779 // A`1.B`1.C`1<int, long, string> to typespec like
780 // A<int>.B<long>.C<string>
782 var nested_hierarchy = new List<TypeSpec> ();
783 while (declaringType.IsNested) {
784 nested_hierarchy.Add (declaringType);
785 declaringType = declaringType.DeclaringType;
789 if (declaringType.Arity > 0) {
790 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
791 targs_pos = spec.Arity;
793 spec = declaringType;
796 for (int i = nested_hierarchy.Count; i != 0; --i) {
797 var t = nested_hierarchy [i - 1];
798 if (t.Kind == MemberKind.MissingType)
801 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
804 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
805 targs_pos += t.Arity;
809 if (spec.Kind == MemberKind.MissingType) {
810 spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC);
811 spec.MemberCache = MemberCache.Empty;
813 if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
816 string name = type.Name;
817 int index = name.IndexOf ('`');
819 name = name.Substring (0, index);
821 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
823 if (spec.Arity > 0) {
824 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
829 // Don't add generic type with dynamic arguments, they can interfere with same type
830 // using object type arguments
831 if (!spec.HasDynamicElement) {
833 // Add to reading cache to speed up reading
834 if (!import_cache.ContainsKey (type))
835 import_cache.Add (type, spec);
844 var ma = type.Attributes;
845 switch (ma & TypeAttributes.VisibilityMask) {
846 case TypeAttributes.Public:
847 case TypeAttributes.NestedPublic:
848 mod = Modifiers.PUBLIC;
850 case TypeAttributes.NestedPrivate:
851 mod = Modifiers.PRIVATE;
853 case TypeAttributes.NestedFamily:
854 mod = Modifiers.PROTECTED;
856 case TypeAttributes.NestedFamORAssem:
857 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
860 mod = Modifiers.INTERNAL;
864 if ((ma & TypeAttributes.Interface) != 0) {
865 kind = MemberKind.Interface;
866 } else if (type.IsGenericParameter) {
867 kind = MemberKind.TypeParameter;
869 var base_type = type.BaseType;
870 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
871 kind = MemberKind.Class;
873 kind = DetermineKindFromBaseType (base_type);
874 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
875 mod |= Modifiers.SEALED;
879 if (kind == MemberKind.Class) {
880 if ((ma & TypeAttributes.Sealed) != 0) {
881 if ((ma & TypeAttributes.Abstract) != 0)
882 mod |= Modifiers.STATIC;
884 mod |= Modifiers.SEALED;
885 } else if ((ma & TypeAttributes.Abstract) != 0) {
886 mod |= Modifiers.ABSTRACT;
891 var definition = new ImportedTypeDefinition (type, this);
894 if (kind == MemberKind.Enum) {
895 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
896 BindingFlags.Instance |
897 BindingFlags.Public | BindingFlags.NonPublic;
899 var type_members = type.GetFields (underlying_member);
900 foreach (var type_member in type_members) {
901 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
906 kind = MemberKind.Class;
908 } else if (kind == MemberKind.TypeParameter) {
909 spec = CreateTypeParameter (type, declaringType);
910 } else if (type.IsGenericTypeDefinition) {
911 definition.TypeParameters = CreateGenericParameters (type, declaringType);
912 } else if (compiled_types.TryGetValue (type, out pt)) {
914 // Same type was found in inside compiled types. It's
915 // either build-in type or forward referenced typed
916 // which point into just compiled assembly.
919 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
921 bts.SetDefinition (definition, type, mod);
925 spec = new TypeSpec (kind, declaringType, definition, type, mod);
927 import_cache.Add (type, spec);
929 if (kind == MemberKind.TypeParameter) {
930 if (canImportBaseType)
931 ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
937 // Two stage setup as the base type can be inflated declaring type or
938 // another nested type inside same declaring type which has not been
939 // loaded, therefore we can import a base type of nested types once
940 // the types have been imported
942 if (canImportBaseType)
943 ImportTypeBase (spec, type);
948 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
950 IAssemblyDefinition found;
951 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
953 // This can happen in dynamic context only
954 var def = new ImportedAssemblyDefinition (assembly);
955 assembly_2_definition.Add (assembly, def);
956 def.ReadAttributes ();
963 public void ImportTypeBase (MetaType type)
965 TypeSpec spec = import_cache[type];
967 ImportTypeBase (spec, type);
970 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
973 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
974 case GenericParameterAttributes.Covariant:
975 variance = Variance.Covariant;
977 case GenericParameterAttributes.Contravariant:
978 variance = Variance.Contravariant;
981 variance = Variance.None;
985 SpecialConstraint special = SpecialConstraint.None;
986 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
988 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
989 special |= SpecialConstraint.Struct;
990 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
991 special = SpecialConstraint.Constructor;
994 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
995 special |= SpecialConstraint.Class;
998 TypeParameterSpec spec;
999 var def = new ImportedTypeParameterDefinition (type, this);
1000 if (type.DeclaringMethod != null) {
1001 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
1003 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
1010 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
1011 // they can be assembly specific therefore we do check based on names only
1013 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
1015 if (attributesData.Count == 0)
1018 foreach (var attr in attributesData) {
1019 var dt = attr.Constructor.DeclaringType;
1020 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1027 void ImportTypeBase (TypeSpec spec, MetaType type)
1029 if (spec.Kind == MemberKind.Interface)
1030 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1031 else if (type.BaseType != null) {
1033 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1034 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1036 base_type = CreateType (type.BaseType);
1038 spec.BaseType = base_type;
1041 if (spec.MemberDefinition.TypeParametersCount > 0) {
1042 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1043 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1048 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1050 Namespace ns = targetNamespace;
1051 string prev_namespace = null;
1052 foreach (var t in types) {
1056 // Be careful not to trigger full parent type loading
1057 if (t.MemberType == MemberTypes.NestedType)
1060 if (t.Name[0] == '<')
1063 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1067 if (prev_namespace != t.Namespace) {
1068 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1069 prev_namespace = t.Namespace;
1072 // Cannot rely on assembly level Extension attribute or static modifier because they
1073 // are not followed by other compilers (e.g. F#).
1074 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1075 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1076 it.SetExtensionMethodContainer ();
1079 ns.AddType (module, it);
1083 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1085 var constraints = type.GetGenericParameterConstraints ();
1086 List<TypeSpec> tparams = null;
1087 foreach (var ct in constraints) {
1088 if (ct.IsGenericParameter) {
1089 if (tparams == null)
1090 tparams = new List<TypeSpec> ();
1092 tparams.Add (CreateType (ct));
1096 var constraint_type = CreateType (ct);
1097 if (constraint_type.IsClass) {
1098 spec.BaseType = constraint_type;
1102 spec.AddInterface (constraint_type);
1105 if (spec.BaseType == null)
1106 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1108 if (tparams != null)
1109 spec.TypeArguments = tparams.ToArray ();
1112 Constant ImportParameterConstant (object value)
1115 // Get type of underlying value as int constant can be used for object
1116 // parameter type. This is not allowed in C# but other languages can do that
1118 var types = module.Compiler.BuiltinTypes;
1119 switch (System.Type.GetTypeCode (value.GetType ())) {
1120 case TypeCode.Boolean:
1121 return new BoolConstant (types, (bool) value, Location.Null);
1123 return new ByteConstant (types, (byte) value, Location.Null);
1125 return new CharConstant (types, (char) value, Location.Null);
1126 case TypeCode.Decimal:
1127 return new DecimalConstant (types, (decimal) value, Location.Null);
1128 case TypeCode.Double:
1129 return new DoubleConstant (types, (double) value, Location.Null);
1130 case TypeCode.Int16:
1131 return new ShortConstant (types, (short) value, Location.Null);
1132 case TypeCode.Int32:
1133 return new IntConstant (types, (int) value, Location.Null);
1134 case TypeCode.Int64:
1135 return new LongConstant (types, (long) value, Location.Null);
1136 case TypeCode.SByte:
1137 return new SByteConstant (types, (sbyte) value, Location.Null);
1138 case TypeCode.Single:
1139 return new FloatConstant (types, (float) value, Location.Null);
1140 case TypeCode.String:
1141 return new StringConstant (types, (string) value, Location.Null);
1142 case TypeCode.UInt16:
1143 return new UShortConstant (types, (ushort) value, Location.Null);
1144 case TypeCode.UInt32:
1145 return new UIntConstant (types, (uint) value, Location.Null);
1146 case TypeCode.UInt64:
1147 return new ULongConstant (types, (ulong) value, Location.Null);
1150 throw new NotImplementedException (value.GetType ().ToString ());
1153 public TypeSpec ImportType (MetaType type)
1155 return ImportType (type, new DynamicTypeReader (type));
1158 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1160 if (type.HasElementType) {
1161 var element = type.GetElementType ();
1163 var spec = ImportType (element, dtype);
1166 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1168 return ReferenceContainer.MakeType (module, spec);
1170 return PointerContainer.MakeType (module, spec);
1172 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1175 TypeSpec compiled_type;
1176 if (compiled_types.TryGetValue (type, out compiled_type)) {
1177 if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
1178 return module.Compiler.BuiltinTypes.Dynamic;
1180 return compiled_type;
1183 return CreateType (type, dtype, true);
1186 static bool IsMissingType (MetaType type)
1189 return type.__IsMissing;
1196 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1197 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1198 // DecimalConstantAttribute metadata.
1200 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1202 if (attrs.Count == 0)
1205 foreach (var ca in attrs) {
1206 var dt = ca.Constructor.DeclaringType;
1207 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1210 var value = new decimal (
1211 (int) (uint) ca.ConstructorArguments[4].Value,
1212 (int) (uint) ca.ConstructorArguments[3].Value,
1213 (int) (uint) ca.ConstructorArguments[2].Value,
1214 (byte) ca.ConstructorArguments[1].Value != 0,
1215 (byte) ca.ConstructorArguments[0].Value);
1217 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1223 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1226 var ma = mb.Attributes;
1227 switch (ma & MethodAttributes.MemberAccessMask) {
1228 case MethodAttributes.Public:
1229 mod = Modifiers.PUBLIC;
1231 case MethodAttributes.Assembly:
1232 mod = Modifiers.INTERNAL;
1234 case MethodAttributes.Family:
1235 mod = Modifiers.PROTECTED;
1237 case MethodAttributes.FamORAssem:
1238 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1241 mod = Modifiers.PRIVATE;
1245 if ((ma & MethodAttributes.Static) != 0) {
1246 mod |= Modifiers.STATIC;
1249 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1250 mod |= Modifiers.ABSTRACT;
1254 // It can be sealed and override
1255 if ((ma & MethodAttributes.Final) != 0)
1256 mod |= Modifiers.SEALED;
1258 if ((ma & MethodAttributes.Virtual) != 0) {
1259 // Not every member can be detected based on MethodAttribute, we
1260 // set virtual or non-virtual only when we are certain. Further checks
1261 // to really find out what `virtual' means for this member are done
1263 if ((ma & MethodAttributes.NewSlot) != 0) {
1264 if ((mod & Modifiers.SEALED) != 0) {
1265 mod &= ~Modifiers.SEALED;
1267 mod |= Modifiers.VIRTUAL;
1270 mod |= Modifiers.OVERRIDE;
1278 abstract class ImportedDefinition : IMemberDefinition
1280 protected class AttributesBag
1282 public static readonly AttributesBag Default = new AttributesBag ();
1284 public AttributeUsageAttribute AttributeUsage;
1285 public ObsoleteAttribute Obsolete;
1286 public string[] Conditionals;
1287 public string DefaultIndexerName;
1288 public bool? CLSAttributeValue;
1289 public TypeSpec CoClass;
1291 static bool HasMissingType (ConstructorInfo ctor)
1295 // Mimic odd csc behaviour where missing type on predefined
1296 // attributes means the attribute is silently ignored. This can
1297 // happen with PCL facades
1299 foreach (var p in ctor.GetParameters ()) {
1300 if (p.ParameterType.__ContainsMissingType)
1308 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1310 AttributesBag bag = null;
1311 List<string> conditionals = null;
1313 // It should not throw any loading exception
1314 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1316 foreach (var a in attrs) {
1317 var dt = a.Constructor.DeclaringType;
1318 string name = dt.Name;
1319 if (name == "ObsoleteAttribute") {
1320 if (dt.Namespace != "System")
1324 bag = new AttributesBag ();
1326 var args = a.ConstructorArguments;
1328 if (args.Count == 1) {
1329 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1330 } else if (args.Count == 2) {
1331 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1333 bag.Obsolete = new ObsoleteAttribute ();
1339 if (name == "ConditionalAttribute") {
1340 if (dt.Namespace != "System.Diagnostics")
1344 bag = new AttributesBag ();
1346 if (conditionals == null)
1347 conditionals = new List<string> (2);
1349 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1353 if (name == "CLSCompliantAttribute") {
1354 if (dt.Namespace != "System")
1358 bag = new AttributesBag ();
1360 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1364 // Type only attributes
1365 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1366 if (name == "DefaultMemberAttribute") {
1367 if (dt.Namespace != "System.Reflection")
1371 bag = new AttributesBag ();
1373 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1377 if (name == "AttributeUsageAttribute") {
1378 if (dt.Namespace != "System")
1381 if (HasMissingType (a.Constructor))
1385 bag = new AttributesBag ();
1387 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1388 foreach (var named in a.NamedArguments) {
1389 if (named.MemberInfo.Name == "AllowMultiple")
1390 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1391 else if (named.MemberInfo.Name == "Inherited")
1392 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1397 // Interface only attribute
1398 if (name == "CoClassAttribute") {
1399 if (dt.Namespace != "System.Runtime.InteropServices")
1402 if (HasMissingType (a.Constructor))
1406 bag = new AttributesBag ();
1408 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1417 if (conditionals != null)
1418 bag.Conditionals = conditionals.ToArray ();
1424 protected readonly MemberInfo provider;
1425 protected AttributesBag cattrs;
1426 protected readonly MetadataImporter importer;
1428 protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1430 this.provider = provider;
1431 this.importer = importer;
1436 public bool IsImported {
1442 public virtual string Name {
1444 return provider.Name;
1450 public string[] ConditionalConditions ()
1455 return cattrs.Conditionals;
1458 public ObsoleteAttribute GetAttributeObsolete ()
1463 return cattrs.Obsolete;
1466 public bool? CLSAttributeValue {
1471 return cattrs.CLSAttributeValue;
1475 protected void ReadAttributes ()
1477 cattrs = AttributesBag.Read (provider, importer);
1480 public void SetIsAssigned ()
1482 // Unused for imported members
1485 public void SetIsUsed ()
1487 // Unused for imported members
1491 public class ImportedModuleDefinition
1493 readonly Module module;
1496 public ImportedModuleDefinition (Module module)
1498 this.module = module;
1503 public bool IsCLSCompliant {
1505 return cls_compliant;
1509 public string Name {
1517 public void ReadAttributes ()
1519 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1521 foreach (var a in attrs) {
1522 var dt = a.Constructor.DeclaringType;
1523 if (dt.Name == "CLSCompliantAttribute") {
1524 if (dt.Namespace != "System")
1527 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1534 // Reads assembly attributes which where attached to a special type because
1535 // module does have assembly manifest
1537 public List<Attribute> ReadAssemblyAttributes ()
1539 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1543 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1547 // TODO: implement, the idea is to fabricate specil Attribute class and
1548 // add it to OptAttributes before resolving the source code attributes
1549 // Need to build module location as well for correct error reporting
1551 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1552 //var attrs = new List<Attribute> (assembly_attributes.Count);
1553 //foreach (var a in assembly_attributes)
1555 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1556 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1558 // foreach (var carg in a.ConstructorArguments) {
1562 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1569 public class ImportedAssemblyDefinition : IAssemblyDefinition
1571 readonly Assembly assembly;
1572 readonly AssemblyName aname;
1575 List<AssemblyName> internals_visible_to;
1576 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1578 public ImportedAssemblyDefinition (Assembly assembly)
1580 this.assembly = assembly;
1581 this.aname = assembly.GetName ();
1586 public Assembly Assembly {
1592 public string FullName {
1594 return aname.FullName;
1598 public bool HasStrongName {
1600 return aname.GetPublicKey ().Length != 0;
1604 public bool IsMissing {
1607 return assembly.__IsMissing;
1614 public bool IsCLSCompliant {
1616 return cls_compliant;
1620 public string Location {
1622 return assembly.Location;
1626 public string Name {
1634 public byte[] GetPublicKeyToken ()
1636 return aname.GetPublicKeyToken ();
1639 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1641 return internals_visible_to_cache [assembly];
1644 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1646 if (internals_visible_to == null)
1649 AssemblyName is_visible = null;
1650 if (internals_visible_to_cache == null) {
1651 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1653 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1654 return is_visible != null;
1657 var token = assembly.GetPublicKeyToken ();
1658 if (token != null && token.Length == 0)
1661 foreach (var internals in internals_visible_to) {
1662 if (internals.Name != assembly.Name)
1665 if (token == null && assembly is AssemblyDefinition) {
1666 is_visible = internals;
1670 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1673 is_visible = internals;
1677 internals_visible_to_cache.Add (assembly, is_visible);
1678 return is_visible != null;
1681 public void ReadAttributes ()
1684 if (assembly.__IsMissing)
1688 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1690 foreach (var a in attrs) {
1691 var dt = a.Constructor.DeclaringType;
1693 if (name == "CLSCompliantAttribute") {
1694 if (dt.Namespace == "System") {
1695 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1700 if (name == "InternalsVisibleToAttribute") {
1701 if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1704 string s = a.ConstructorArguments[0].Value as string;
1708 var an = new AssemblyName (s);
1709 if (internals_visible_to == null)
1710 internals_visible_to = new List<AssemblyName> ();
1712 internals_visible_to.Add (an);
1718 public override string ToString ()
1724 class ImportedMemberDefinition : ImportedDefinition
1726 readonly TypeSpec type;
1728 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1729 : base (member, importer)
1736 public TypeSpec MemberType {
1745 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1747 readonly AParametersCollection parameters;
1749 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1750 : base (provider, type, importer)
1752 this.parameters = parameters;
1755 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1756 : base (provider, type, importer)
1758 this.parameters = parameters;
1763 public AParametersCollection Parameters {
1772 class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1774 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1775 : base (provider, type, parameters, importer)
1779 MethodBase IMethodDefinition.Metadata {
1781 return (MethodBase) provider;
1786 class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1788 readonly TypeParameterSpec[] tparams;
1790 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1791 : base (provider, type, parameters, importer)
1793 this.tparams = tparams;
1798 public TypeParameterSpec[] TypeParameters {
1804 public int TypeParametersCount {
1806 return tparams.Length;
1813 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1815 TypeParameterSpec[] tparams;
1818 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1819 : base (type, importer)
1825 public IAssemblyDefinition DeclaringAssembly {
1827 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1831 bool ITypeDefinition.IsComImport {
1833 return ((MetaType) provider).IsImport;
1838 bool ITypeDefinition.IsPartial {
1844 bool ITypeDefinition.IsTypeForwarder {
1847 return ((MetaType) provider).__IsTypeForwarder;
1854 bool ITypeDefinition.IsCyclicTypeForwarder {
1857 return ((MetaType) provider).__IsCyclicTypeForwarder;
1864 public override string Name {
1868 if (tparams != null) {
1869 int arity_start = name.IndexOf ('`');
1870 if (arity_start > 0)
1871 name = name.Substring (0, arity_start);
1879 public string Namespace {
1881 return ((MetaType) provider).Namespace;
1885 public int TypeParametersCount {
1887 return tparams == null ? 0 : tparams.Length;
1891 public TypeParameterSpec[] TypeParameters {
1902 public void DefineInterfaces (TypeSpec spec)
1904 var type = (MetaType) provider;
1907 ifaces = type.__GetDeclaredInterfaces ();
1908 if (ifaces.Length != 0) {
1909 foreach (var iface in ifaces) {
1910 var it = importer.CreateType (iface);
1914 spec.AddInterfaceDefined (it);
1916 // Unfortunately not all languages expand inherited interfaces
1917 var bifaces = it.Interfaces;
1918 if (bifaces != null) {
1919 foreach (var biface in bifaces) {
1920 spec.AddInterfaceDefined (biface);
1927 // It's impossible to get declared interfaces only using System.Reflection
1928 // hence we need to mimic the behavior with ikvm-reflection too to keep
1929 // our type look-up logic same
1931 if (spec.BaseType != null) {
1932 var bifaces = spec.BaseType.Interfaces;
1933 if (bifaces != null) {
1935 // Before adding base class interfaces close defined interfaces
1936 // on type parameter
1938 var tp = spec as TypeParameterSpec;
1939 if (tp != null && tp.InterfacesDefined == null) {
1940 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1943 foreach (var iface in bifaces)
1944 spec.AddInterfaceDefined (iface);
1948 ifaces = type.GetInterfaces ();
1950 if (ifaces.Length > 0) {
1951 foreach (var iface in ifaces) {
1952 spec.AddInterface (importer.CreateType (iface));
1959 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
1962 // Report details about missing type and most likely cause of the problem.
1963 // csc reports 1683, 1684 as warnings but we report them only when used
1964 // or referenced from the user core in which case compilation error has to
1965 // be reported because compiler cannot continue anyway
1968 var report = ctx.Module.Compiler.Report;
1970 for (int i = 0; i < missing.Count; ++i) {
1971 var t = missing [i].Type;
1974 // Report missing types only once
1976 if (report.Printer.MissingTypeReported (t.MemberDefinition))
1979 string name = t.GetSignatureForError ();
1981 var caller = missing[i].Caller;
1982 if (caller.Kind != MemberKind.MissingType)
1983 report.SymbolRelatedToPreviousError (caller);
1985 var definition = t.MemberDefinition;
1986 if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1987 report.Error (1683, loc,
1988 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1990 } else if (definition.DeclaringAssembly.IsMissing) {
1991 if (definition.IsTypeForwarder) {
1992 report.Error (1070, loc,
1993 "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1994 name, definition.DeclaringAssembly.FullName);
1996 report.Error (12, loc,
1997 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1998 name, definition.DeclaringAssembly.FullName);
2000 } else if (definition.IsTypeForwarder) {
2001 report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
2002 name, definition.DeclaringAssembly.FullName);
2004 report.Error (1684, loc,
2005 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
2006 name, t.MemberDefinition.DeclaringAssembly.FullName);
2011 public TypeSpec GetAttributeCoClass ()
2016 return cattrs.CoClass;
2019 public string GetAttributeDefaultMember ()
2024 return cattrs.DefaultIndexerName;
2027 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2032 return cattrs.AttributeUsage;
2035 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2037 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
2038 return a == assembly || a.IsFriendAssemblyTo (assembly);
2041 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2044 // Not interested in members of nested private types unless the importer needs them
2046 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
2047 cache = MemberCache.Empty;
2051 var loading_type = (MetaType) provider;
2052 const BindingFlags all_members = BindingFlags.DeclaredOnly |
2053 BindingFlags.Static | BindingFlags.Instance |
2054 BindingFlags.Public | BindingFlags.NonPublic;
2056 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
2057 MethodAttributes.Virtual | MethodAttributes.HideBySig |
2058 MethodAttributes.Final;
2060 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
2061 List<EventSpec> imported_events = null;
2062 EventSpec event_spec;
2063 MemberSpec imported;
2067 all = loading_type.GetMembers (all_members);
2068 } catch (Exception e) {
2069 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2070 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2073 if (cache == null) {
2074 cache = new MemberCache (all.Length);
2077 // Do the types first as they can be referenced by the members before
2078 // they are found or inflated
2080 foreach (var member in all) {
2081 if (member.MemberType != MemberTypes.NestedType)
2084 var t = (MetaType) member;
2086 // Ignore compiler generated types, mostly lambda containers
2087 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2091 imported = importer.CreateNestedType (t, declaringType);
2092 } catch (Exception e) {
2093 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2094 t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2097 cache.AddMemberImported (imported);
2100 foreach (var member in all) {
2101 if (member.MemberType != MemberTypes.NestedType)
2104 var t = (MetaType) member;
2106 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2109 importer.ImportTypeBase (t);
2114 // Load base interfaces first to minic behaviour of compiled members
2116 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2117 foreach (var iface in declaringType.Interfaces) {
2118 cache.AddInterface (iface);
2124 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2126 foreach (var member in all) {
2127 switch (member.MemberType) {
2128 case MemberTypes.Constructor:
2129 if (declaringType.IsInterface)
2132 goto case MemberTypes.Method;
2133 case MemberTypes.Method:
2134 MethodBase mb = (MethodBase) member;
2135 var attrs = mb.Attributes;
2137 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2138 if (importer.IgnorePrivateMembers)
2141 // Ignore explicitly implemented members
2142 if ((attrs & explicit_impl) == explicit_impl)
2145 // Ignore compiler generated methods
2146 if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2150 imported = importer.CreateMethod (mb, declaringType);
2151 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2152 if (possible_accessors == null)
2153 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2155 // There are no metadata rules for accessors, we have to consider any method as possible candidate
2156 possible_accessors.Add (mb, (MethodSpec) imported);
2160 case MemberTypes.Property:
2161 if (possible_accessors == null)
2164 var p = (PropertyInfo) member;
2166 // Links possible accessors with property
2168 MethodSpec get, set;
2169 m = p.GetGetMethod (true);
2170 if (m == null || !possible_accessors.TryGetValue (m, out get))
2173 m = p.GetSetMethod (true);
2174 if (m == null || !possible_accessors.TryGetValue (m, out set))
2177 // No accessors registered (e.g. explicit implementation)
2178 if (get == null && set == null)
2182 imported = importer.CreateProperty (p, declaringType, get, set);
2183 } catch (Exception ex) {
2184 throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2185 p.Name, declaringType.GetSignatureForError ());
2188 if (imported == null)
2192 case MemberTypes.Event:
2193 if (possible_accessors == null)
2196 var e = (EventInfo) member;
2198 // Links accessors with event
2200 MethodSpec add, remove;
2201 m = e.GetAddMethod (true);
2202 if (m == null || !possible_accessors.TryGetValue (m, out add))
2205 m = e.GetRemoveMethod (true);
2206 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2209 // Both accessors are required
2210 if (add == null || remove == null)
2213 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2214 if (!importer.IgnorePrivateMembers) {
2215 if (imported_events == null)
2216 imported_events = new List<EventSpec> ();
2218 imported_events.Add (event_spec);
2221 imported = event_spec;
2223 case MemberTypes.Field:
2224 var fi = (FieldInfo) member;
2226 imported = importer.CreateField (fi, declaringType);
2227 if (imported == null)
2231 // For dynamic binder event has to be fully restored to allow operations
2232 // within the type container to work correctly
2234 if (imported_events != null) {
2235 // The backing event field should be private but it may not
2237 for (i = 0; i < imported_events.Count; ++i) {
2238 var ev = imported_events[i];
2239 if (ev.Name == fi.Name) {
2240 ev.BackingField = (FieldSpec) imported;
2241 imported_events.RemoveAt (i);
2252 case MemberTypes.NestedType:
2253 // Already in the cache from the first pass
2256 throw new NotImplementedException (member.ToString ());
2259 if (imported.IsStatic && declaringType.IsInterface)
2262 cache.AddMemberImported (imported);
2268 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2270 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2271 : base (type, importer)
2277 public IAssemblyDefinition DeclaringAssembly {
2279 throw new NotImplementedException ();
2283 bool ITypeDefinition.IsComImport {
2289 bool ITypeDefinition.IsPartial {
2295 bool ITypeDefinition.IsTypeForwarder {
2301 bool ITypeDefinition.IsCyclicTypeForwarder {
2307 public string Namespace {
2313 public int TypeParametersCount {
2319 public TypeParameterSpec[] TypeParameters {
2327 public TypeSpec GetAttributeCoClass ()
2332 public string GetAttributeDefaultMember ()
2334 throw new NotSupportedException ();
2337 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2339 throw new NotSupportedException ();
2342 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2344 throw new NotImplementedException ();
2347 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2349 throw new NotImplementedException ();