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, 2010 Novell, Inc
12 using System.Runtime.CompilerServices;
14 using System.Collections.Generic;
17 using MetaType = IKVM.Reflection.Type;
18 using IKVM.Reflection;
19 using IKVM.Reflection.Emit;
21 using MetaType = System.Type;
22 using System.Reflection;
23 using System.Reflection.Emit;
28 public abstract class MetadataImporter
31 // Dynamic types reader with additional logic to reconstruct a dynamic
32 // type using DynamicAttribute values
34 struct DynamicTypeReader
36 static readonly bool[] single_attribute = { true };
41 // There is no common type for CustomAttributeData and we cannot
42 // use ICustomAttributeProvider
46 // A member provider which can be used to get CustomAttributeData
48 public DynamicTypeReader (object provider)
52 this.provider = provider;
56 // Returns true when object at local position has dynamic attribute flag
58 public bool IsDynamicObject (MetadataImporter importer)
61 ReadAttribute (importer);
63 return flags != null && Position < flags.Length && flags[Position];
67 // Returns true when DynamicAttribute exists
69 public bool HasDynamicAttribute (MetadataImporter importer)
72 ReadAttribute (importer);
77 void ReadAttribute (MetadataImporter importer)
79 IList<CustomAttributeData> cad;
80 if (provider is MemberInfo) {
81 cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
82 } else if (provider is ParameterInfo) {
83 cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
91 foreach (var ca in cad) {
92 importer.GetCustomAttributeTypeName (ca, out ns, out name);
93 if (name != "DynamicAttribute" && ns != CompilerServicesNamespace)
96 if (ca.ConstructorArguments.Count == 0) {
97 flags = single_attribute;
101 var arg_type = ca.ConstructorArguments[0].ArgumentType;
103 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
104 var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
105 flags = new bool[carg.Count];
106 for (int i = 0; i < flags.Length; ++i) {
107 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
108 flags[i] = (bool) carg[i].Value;
120 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
121 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
122 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
123 readonly ModuleContainer module;
125 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
127 protected MetadataImporter (ModuleContainer module)
129 this.module = module;
131 import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
132 compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
133 assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
134 IgnorePrivateMembers = true;
139 public ICollection<IAssemblyDefinition> Assemblies {
141 return assembly_2_definition.Values;
145 public bool IgnorePrivateMembers { get; set; }
149 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
150 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
151 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
152 public abstract void GetCustomAttributeTypeName (CustomAttributeData cad, out string typeNamespace, out string typeName);
154 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
157 var fa = fi.Attributes;
158 switch (fa & FieldAttributes.FieldAccessMask) {
159 case FieldAttributes.Public:
160 mod = Modifiers.PUBLIC;
162 case FieldAttributes.Assembly:
163 mod = Modifiers.INTERNAL;
165 case FieldAttributes.Family:
166 mod = Modifiers.PROTECTED;
168 case FieldAttributes.FamORAssem:
169 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
172 // Ignore private fields (even for error reporting) to not require extra dependencies
173 if (IgnorePrivateMembers || HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
176 mod = Modifiers.PRIVATE;
183 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
184 } catch (Exception e) {
185 // TODO: I should construct fake TypeSpec based on TypeRef signature
186 // but there is no way to do it with System.Reflection
187 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
188 declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
191 var definition = new ImportedMemberDefinition (fi, field_type, this);
193 if ((fa & FieldAttributes.Literal) != 0) {
194 var c = Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
195 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
198 if ((fa & FieldAttributes.InitOnly) != 0) {
199 if (field_type.BuildinType == BuildinTypeSpec.Type.Decimal) {
200 var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
202 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
205 mod |= Modifiers.READONLY;
207 var req_mod = fi.GetRequiredCustomModifiers ();
208 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
209 mod |= Modifiers.VOLATILE;
212 if ((fa & FieldAttributes.Static) != 0) {
213 mod |= Modifiers.STATIC;
215 // Fixed buffers cannot be static
216 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
217 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
219 // TODO: Sanity check on field_type (only few types are allowed)
220 var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
221 return new FixedFieldSpec (declaringType, definition, fi, element_field, mod);
225 return new FieldSpec (declaringType, definition, field_type, fi, mod);
228 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
230 add.IsAccessor = true;
231 remove.IsAccessor = true;
233 if (add.Modifiers != remove.Modifiers)
234 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
236 var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
237 var definition = new ImportedMemberDefinition (ei, event_type, this);
238 return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
241 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
243 var tparams = type.GetGenericArguments ();
245 int parent_owned_count;
247 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
250 // System.Reflection duplicates parent type parameters for each
251 // nested type with slightly modified properties (eg. different owner)
252 // This just makes things more complicated (think of cloned constraints)
253 // therefore we remap any nested type owned by parent using `type_cache'
254 // to the single TypeParameterSpec
256 if (declaringType != null && parent_owned_count > 0) {
258 while (read_count != parent_owned_count) {
259 var tparams_count = declaringType.Arity;
260 if (tparams_count != 0) {
261 var parent_tp = declaringType.MemberDefinition.TypeParameters;
262 read_count += tparams_count;
263 for (int i = 0; i < tparams_count; i++) {
264 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
268 declaringType = declaringType.DeclaringType;
272 parent_owned_count = 0;
275 if (tparams.Length - parent_owned_count == 0)
278 return CreateGenericParameters (parent_owned_count, tparams);
281 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
283 var tspec = new TypeParameterSpec[tparams.Length - first];
284 for (int pos = first; pos < tparams.Length; ++pos) {
285 var type = tparams[pos];
286 int index = pos - first;
288 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
294 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
298 var tspec = new TypeSpec [tparams.Length - first];
299 for (int pos = first; pos < tparams.Length; ++pos) {
300 var type = tparams[pos];
301 int index = pos - first;
304 if (type.HasElementType) {
305 var element = type.GetElementType ();
307 spec = ImportType (element, dtype);
310 throw new NotImplementedException ("Unknown element type " + type.ToString ());
313 spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
315 spec = CreateType (type, dtype, true);
318 // We treat nested generic types as inflated internally where
319 // reflection uses type definition
322 // IFoo<A<T>> foo; // A<T> is definition in this case
325 // TODO: Is full logic from CreateType needed here as well?
327 if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
328 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
329 spec = spec.MakeGenericType (module, targs);
340 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
342 Modifiers mod = ReadMethodModifiers (mb, declaringType);
343 TypeParameterSpec[] tparams;
345 var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
347 if (mb.IsGenericMethod) {
348 if (!mb.IsGenericMethodDefinition)
349 throw new NotSupportedException ("assert");
351 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
358 if (mb.MemberType == MemberTypes.Constructor) {
359 kind = MemberKind.Constructor;
360 returnType = module.Compiler.BuildinTypes.Void;
363 // Detect operators and destructors
365 string name = mb.Name;
366 kind = MemberKind.Method;
367 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
368 if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
369 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
370 var op_type = Operator.GetType (name);
371 if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
372 kind = MemberKind.Operator;
375 } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
376 kind = MemberKind.Destructor;
377 if (declaringType.BuildinType == BuildinTypeSpec.Type.Object) {
378 mod &= ~Modifiers.OVERRIDE;
379 mod |= Modifiers.VIRTUAL;
384 var mi = (MethodInfo) mb;
385 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
387 // Cannot set to OVERRIDE without full hierarchy checks
388 // this flag indicates that the method could be override
389 // but further validation is needed
390 if ((mod & Modifiers.OVERRIDE) != 0 && kind == MemberKind.Method && declaringType.BaseType != null) {
391 var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
392 var candidate = MemberCache.FindMember (declaringType.BaseType, filter, BindingRestriction.None);
395 // For imported class method do additional validation to be sure that metadata
396 // override flag was correct
398 // Difference between protected internal and protected is ok
400 const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
401 if (candidate == null || (candidate.Modifiers & conflict_mask) != (mod & conflict_mask) || candidate.IsStatic) {
402 mod &= ~Modifiers.OVERRIDE;
403 mod |= Modifiers.VIRTUAL;
408 IMemberDefinition definition;
409 if (tparams != null) {
410 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
411 foreach (var tp in gmd.TypeParameters) {
412 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
417 definition = new ImportedParameterMemberDefinition (mb, returnType, parameters, this);
420 MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, mb, parameters, mod);
428 // Imports System.Reflection parameters
430 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
432 int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
434 if (pi.Length == 0 && varargs == 0)
435 return ParametersCompiled.EmptyReadOnlyParameters;
437 TypeSpec[] types = new TypeSpec[pi.Length + varargs];
438 IParameterData[] par = new IParameterData[pi.Length + varargs];
439 bool is_params = false;
440 for (int i = 0; i < pi.Length; i++) {
441 ParameterInfo p = pi[i];
442 Parameter.Modifier mod = 0;
443 Expression default_value = null;
444 if (p.ParameterType.IsByRef) {
445 if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
446 mod = Parameter.Modifier.OUT;
448 mod = Parameter.Modifier.REF;
451 // Strip reference wrapping
453 var el = p.ParameterType.GetElementType ();
454 types[i] = ImportType (el, new DynamicTypeReader (p)); // TODO: 1-based positio to be csc compatible
455 } else if (i == 0 && method.IsStatic && parent.IsStatic && parent.MemberDefinition.DeclaringAssembly.HasExtensionMethod &&
456 HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
457 mod = Parameter.Modifier.This;
458 types[i] = ImportType (p.ParameterType);
460 types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
462 if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
463 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
464 mod = Parameter.Modifier.PARAMS;
469 if (!is_params && p.IsOptional) {
470 object value = p.RawDefaultValue;
471 var ptype = types[i];
472 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeManager.IsReferenceType (ptype))) {
474 default_value = Constant.CreateConstant (ptype, null, Location.Null);
476 default_value = ImportParameterConstant (value);
479 default_value = new EnumConstant ((Constant) default_value, ptype);
482 } else if (value == Missing.Value) {
483 default_value = EmptyExpression.MissingValue;
484 } else if (value == null) {
485 default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
486 } else if (ptype.BuildinType == BuildinTypeSpec.Type.Decimal) {
487 default_value = ImportParameterConstant (value);
492 par[i] = new ParameterData (p.Name, mod, default_value);
496 par[par.Length - 1] = new ArglistParameter (Location.Null);
497 types[types.Length - 1] = InternalType.Arglist;
500 return method != null ?
501 new ParametersImported (par, types, varargs != 0, is_params) :
502 new ParametersImported (par, types, is_params);
506 // Returns null when the property is not valid C# property
508 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
511 AParametersCollection param = null;
512 TypeSpec type = null;
515 param = get.Parameters;
516 type = get.ReturnType;
519 bool is_valid_property = true;
521 if (set.ReturnType.Kind != MemberKind.Void)
522 is_valid_property = false;
524 var set_param_count = set.Parameters.Count - 1;
526 if (set_param_count < 0) {
528 is_valid_property = false;
531 var set_type = set.Parameters.Types[set_param_count];
534 AParametersCollection set_based_param;
536 if (set_param_count == 0) {
537 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
540 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
542 var data = new IParameterData[set_param_count];
543 var types = new TypeSpec[set_param_count];
544 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
545 Array.Copy (set.Parameters.Types, types, set_param_count);
546 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
550 param = set_based_param;
553 if (set_param_count != get.Parameters.Count)
554 is_valid_property = false;
556 if (get.ReturnType != set_type)
557 is_valid_property = false;
559 // Possible custom accessor modifiers
560 if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
561 var get_acc = mod & Modifiers.AccessibilityMask;
562 if (get_acc != Modifiers.PUBLIC) {
563 var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
564 // If the accessor modifiers are not same, do extra restriction checks
565 if (get_acc != set_acc) {
566 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
567 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
568 if (get_restr && set_restr) {
569 is_valid_property = false; // Neither is more restrictive
573 mod &= ~Modifiers.AccessibilityMask;
582 PropertySpec spec = null;
583 if (!param.IsEmpty) {
584 var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
585 if (index_name == null) {
586 is_valid_property = false;
590 is_valid_property = false;
591 if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
592 is_valid_property = false;
596 is_valid_property = false;
597 if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
598 is_valid_property = false;
602 if (is_valid_property)
603 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
607 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
609 if (!is_valid_property) {
610 spec.IsNotRealProperty = true;
622 public TypeSpec CreateType (MetaType type)
624 return CreateType (type, new DynamicTypeReader (), true);
627 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
629 return CreateType (type, declaringType, new DynamicTypeReader (type), false);
632 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
634 TypeSpec declaring_type;
635 if (type.IsNested && !type.IsGenericParameter)
636 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
638 declaring_type = null;
640 return CreateType (type, declaring_type, dtype, canImportBaseType);
643 TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
646 if (import_cache.TryGetValue (type, out spec)) {
647 if (spec.BuildinType == BuildinTypeSpec.Type.Object) {
648 if (dtype.IsDynamicObject (this))
649 return module.Compiler.BuildinTypes.Dynamic;
654 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
657 if (!dtype.HasDynamicAttribute (this))
660 // We've found same object in the cache but this one has a dynamic custom attribute
661 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
662 // Do type resolve process again in that case
664 // TODO: Handle cases where they still unify
667 if (IsMissingType (type)) {
668 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
669 spec.MemberCache = MemberCache.Empty;
670 import_cache.Add (type, spec);
674 if (type.IsGenericType && !type.IsGenericTypeDefinition) {
675 var type_def = type.GetGenericTypeDefinition ();
676 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
677 if (declaringType == null) {
678 // Simple case, no nesting
679 spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
680 spec = spec.MakeGenericType (module, targs);
683 // Nested type case, converting .NET types like
684 // A`1.B`1.C`1<int, long, string> to typespec like
685 // A<int>.B<long>.C<string>
687 var nested_hierarchy = new List<TypeSpec> ();
688 while (declaringType.IsNested) {
689 nested_hierarchy.Add (declaringType);
690 declaringType = declaringType.DeclaringType;
694 if (declaringType.Arity > 0) {
695 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
696 targs_pos = spec.Arity;
698 spec = declaringType;
701 for (int i = nested_hierarchy.Count; i != 0; --i) {
702 var t = nested_hierarchy [i - 1];
703 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
705 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
706 targs_pos += t.Arity;
710 string name = type.Name;
711 int index = name.IndexOf ('`');
713 name = name.Substring (0, index);
715 spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
716 if (spec.Arity > 0) {
717 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
721 // Don't add generic type with dynamic arguments, they can interfere with same type
722 // using object type arguments
723 if (!spec.HasDynamicElement) {
725 // Add to reading cache to speed up reading
726 if (!import_cache.ContainsKey (type))
727 import_cache.Add (type, spec);
736 var ma = type.Attributes;
737 switch (ma & TypeAttributes.VisibilityMask) {
738 case TypeAttributes.Public:
739 case TypeAttributes.NestedPublic:
740 mod = Modifiers.PUBLIC;
742 case TypeAttributes.NestedPrivate:
743 mod = Modifiers.PRIVATE;
745 case TypeAttributes.NestedFamily:
746 mod = Modifiers.PROTECTED;
748 case TypeAttributes.NestedFamORAssem:
749 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
752 mod = Modifiers.INTERNAL;
756 if ((ma & TypeAttributes.Interface) != 0) {
757 kind = MemberKind.Interface;
758 } else if (type.IsGenericParameter) {
759 kind = MemberKind.TypeParameter;
761 var base_type = type.BaseType;
762 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
763 kind = MemberKind.Class;
765 kind = DetermineKindFromBaseType (base_type);
766 if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
767 mod |= Modifiers.SEALED;
771 if (kind == MemberKind.Class) {
772 if ((ma & TypeAttributes.Sealed) != 0) {
773 mod |= Modifiers.SEALED;
774 if ((ma & TypeAttributes.Abstract) != 0)
775 mod |= Modifiers.STATIC;
776 } else if ((ma & TypeAttributes.Abstract) != 0) {
777 mod |= Modifiers.ABSTRACT;
782 var definition = new ImportedTypeDefinition (type, this);
785 if (kind == MemberKind.Enum) {
786 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
787 BindingFlags.Instance |
788 BindingFlags.Public | BindingFlags.NonPublic;
790 var type_members = type.GetFields (underlying_member);
791 foreach (var type_member in type_members) {
792 spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
797 kind = MemberKind.Class;
799 } else if (kind == MemberKind.TypeParameter) {
800 spec = CreateTypeParameter (type, declaringType);
801 } else if (type.IsGenericTypeDefinition) {
802 definition.TypeParameters = CreateGenericParameters (type, declaringType);
803 } else if (compiled_types.TryGetValue (type, out pt)) {
805 // Same type was found in inside compiled types. It's
806 // either build-in type or forward referenced typed
807 // which point into just compiled assembly.
810 BuildinTypeSpec bts = pt as BuildinTypeSpec;
812 bts.SetDefinition (definition, type, mod);
816 spec = new TypeSpec (kind, declaringType, definition, type, mod);
818 import_cache.Add (type, spec);
821 // Two stage setup as the base type can be inflated declaring type or
822 // another nested type inside same declaring type which has not been
823 // loaded, therefore we can import a base type of nested types once
824 // the types have been imported
826 if (canImportBaseType)
827 ImportTypeBase (spec, type);
832 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
834 IAssemblyDefinition found;
835 if (!assembly_2_definition.TryGetValue (assembly, out found)) {
837 // This can happen in dynamic context only
838 var def = new ImportedAssemblyDefinition (assembly, this);
839 assembly_2_definition.Add (assembly, def);
840 def.ReadAttributes ();
847 public void ImportTypeBase (MetaType type)
849 TypeSpec spec = import_cache[type];
851 ImportTypeBase (spec, type);
854 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
857 switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
858 case GenericParameterAttributes.Covariant:
859 variance = Variance.Covariant;
861 case GenericParameterAttributes.Contravariant:
862 variance = Variance.Contravariant;
865 variance = Variance.None;
869 SpecialConstraint special = SpecialConstraint.None;
870 var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
872 if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
873 special |= SpecialConstraint.Struct;
874 } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
875 special = SpecialConstraint.Constructor;
878 if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
879 special |= SpecialConstraint.Class;
882 TypeParameterSpec spec;
883 var def = new ImportedTypeParameterDefinition (type, this);
884 if (type.DeclaringMethod != null) {
885 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
887 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
894 // Test for a custom attribute type match. Custom attributes are not really predefined globaly
895 // they can be assembly specific therefore we do check based on names only
897 public bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
899 if (attributesData.Count == 0)
903 foreach (var attr in attributesData) {
904 GetCustomAttributeTypeName (attr, out ns, out name);
905 if (name == attrName && ns == attrNamespace)
912 void ImportTypeBase (TypeSpec spec, MetaType type)
914 if (spec.Kind == MemberKind.Interface)
915 spec.BaseType = module.Compiler.BuildinTypes.Object;
916 else if (type.BaseType != null) {
918 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
919 base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
921 base_type = CreateType (type.BaseType);
923 spec.BaseType = base_type;
928 ifaces = type.__GetDeclaredInterfaces ();
929 if (ifaces.Length != 0) {
930 foreach (var iface in ifaces) {
931 var it = CreateType (iface);
932 spec.AddInterface (it);
934 // Unfortunatelly not all languages inlcude inherited interfaces
935 var bifaces = it.Interfaces;
936 if (bifaces != null) {
937 foreach (var biface in bifaces) {
938 spec.AddInterface (biface);
944 if (spec.BaseType != null) {
945 var bifaces = spec.BaseType.Interfaces;
946 if (bifaces != null) {
947 foreach (var iface in bifaces)
948 spec.AddInterface (iface);
952 ifaces = type.GetInterfaces ();
954 if (ifaces.Length > 0) {
955 foreach (var iface in ifaces) {
956 spec.AddInterface (CreateType (iface));
961 if (spec.MemberDefinition.TypeParametersCount > 0) {
962 foreach (var tp in spec.MemberDefinition.TypeParameters) {
963 ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
969 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
971 Namespace ns = targetNamespace;
972 string prev_namespace = null;
973 foreach (var t in types) {
977 // Be careful not to trigger full parent type loading
978 if (t.MemberType == MemberTypes.NestedType)
981 if (t.Name[0] == '<')
984 var it = CreateType (t, null, new DynamicTypeReader (t), true);
988 if (prev_namespace != t.Namespace) {
989 ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
990 prev_namespace = t.Namespace;
995 if (it.IsStatic && hasExtensionTypes &&
996 HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
997 it.SetExtensionMethodContainer ();
1002 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1004 var constraints = type.GetGenericParameterConstraints ();
1005 List<TypeSpec> tparams = null;
1006 foreach (var ct in constraints) {
1007 if (ct.IsGenericParameter) {
1008 if (tparams == null)
1009 tparams = new List<TypeSpec> ();
1011 tparams.Add (CreateType (ct));
1015 if (!IsMissingType (ct) && ct.IsClass) {
1016 spec.BaseType = CreateType (ct);
1020 spec.AddInterface (CreateType (ct));
1023 if (spec.BaseType == null)
1024 spec.BaseType = module.Compiler.BuildinTypes.Object;
1026 if (tparams != null)
1027 spec.TypeArguments = tparams.ToArray ();
1030 Constant ImportParameterConstant (object value)
1033 // Get type of underlying value as int constant can be used for object
1034 // parameter type. This is not allowed in C# but other languages can do that
1036 var types = module.Compiler.BuildinTypes;
1037 switch (System.Type.GetTypeCode (value.GetType ())) {
1038 case TypeCode.Boolean:
1039 return new BoolConstant (types, (bool) value, Location.Null);
1041 return new ByteConstant (types, (byte) value, Location.Null);
1043 return new CharConstant (types, (char) value, Location.Null);
1044 case TypeCode.Decimal:
1045 return new DecimalConstant (types, (decimal) value, Location.Null);
1046 case TypeCode.Double:
1047 return new DoubleConstant (types, (double) value, Location.Null);
1048 case TypeCode.Int16:
1049 return new ShortConstant (types, (short) value, Location.Null);
1050 case TypeCode.Int32:
1051 return new IntConstant (types, (int) value, Location.Null);
1052 case TypeCode.Int64:
1053 return new LongConstant (types, (long) value, Location.Null);
1054 case TypeCode.SByte:
1055 return new SByteConstant (types, (sbyte) value, Location.Null);
1056 case TypeCode.Single:
1057 return new FloatConstant (types, (float) value, Location.Null);
1058 case TypeCode.String:
1059 return new StringConstant (types, (string) value, Location.Null);
1060 case TypeCode.UInt16:
1061 return new UShortConstant (types, (ushort) value, Location.Null);
1062 case TypeCode.UInt32:
1063 return new UIntConstant (types, (uint) value, Location.Null);
1064 case TypeCode.UInt64:
1065 return new ULongConstant (types, (ulong) value, Location.Null);
1068 throw new NotImplementedException (value.GetType ().ToString ());
1071 public TypeSpec ImportType (MetaType type)
1073 return ImportType (type, new DynamicTypeReader (type));
1076 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1078 if (type.HasElementType) {
1079 var element = type.GetElementType ();
1081 var spec = ImportType (element, dtype);
1084 return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1086 return ReferenceContainer.MakeType (module, spec);
1088 return PointerContainer.MakeType (module, spec);
1090 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1093 return CreateType (type, dtype, true);
1096 static bool IsMissingType (MetaType type)
1099 return type.__IsMissing;
1106 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1107 // as IsInitOnly ('readonly' in C# parlance). We get its value from the
1108 // DecimalConstantAttribute metadata.
1110 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1112 if (attrs.Count == 0)
1116 foreach (var ca in attrs) {
1117 GetCustomAttributeTypeName (ca, out ns, out name);
1118 if (name != "DecimalConstantAttribute" || ns != CompilerServicesNamespace)
1121 var value = new decimal (
1122 (int) (uint) ca.ConstructorArguments[4].Value,
1123 (int) (uint) ca.ConstructorArguments[3].Value,
1124 (int) (uint) ca.ConstructorArguments[2].Value,
1125 (byte) ca.ConstructorArguments[1].Value != 0,
1126 (byte) ca.ConstructorArguments[0].Value);
1128 return new DecimalConstant (module.Compiler.BuildinTypes, value, Location.Null);
1134 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1137 var ma = mb.Attributes;
1138 switch (ma & MethodAttributes.MemberAccessMask) {
1139 case MethodAttributes.Public:
1140 mod = Modifiers.PUBLIC;
1142 case MethodAttributes.Assembly:
1143 mod = Modifiers.INTERNAL;
1145 case MethodAttributes.Family:
1146 mod = Modifiers.PROTECTED;
1148 case MethodAttributes.FamORAssem:
1149 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1152 mod = Modifiers.PRIVATE;
1156 if ((ma & MethodAttributes.Static) != 0) {
1157 mod |= Modifiers.STATIC;
1160 if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1161 mod |= Modifiers.ABSTRACT;
1165 if ((ma & MethodAttributes.Final) != 0)
1166 mod |= Modifiers.SEALED;
1168 // It can be sealed and override
1169 if ((ma & MethodAttributes.Virtual) != 0) {
1170 if ((ma & MethodAttributes.NewSlot) != 0 || !declaringType.IsClass) {
1171 // No private virtual or sealed virtual
1172 if ((mod & (Modifiers.PRIVATE | Modifiers.SEALED)) == 0)
1173 mod |= Modifiers.VIRTUAL;
1175 mod |= Modifiers.OVERRIDE;
1183 abstract class ImportedDefinition : IMemberDefinition
1185 protected class AttributesBag
1187 public static readonly AttributesBag Default = new AttributesBag ();
1189 public AttributeUsageAttribute AttributeUsage;
1190 public ObsoleteAttribute Obsolete;
1191 public string[] Conditionals;
1192 public string DefaultIndexerName;
1193 public bool? CLSAttributeValue;
1194 public TypeSpec CoClass;
1196 public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1198 AttributesBag bag = null;
1199 List<string> conditionals = null;
1201 // It should not throw any loading exception
1202 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1205 foreach (var a in attrs) {
1206 importer.GetCustomAttributeTypeName (a, out ns, out name);
1207 if (name == "ObsoleteAttribute") {
1212 bag = new AttributesBag ();
1214 var args = a.ConstructorArguments;
1216 if (args.Count == 1) {
1217 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1218 } else if (args.Count == 2) {
1219 bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1221 bag.Obsolete = new ObsoleteAttribute ();
1227 if (name == "ConditionalAttribute") {
1228 if (ns != "System.Diagnostics")
1232 bag = new AttributesBag ();
1234 if (conditionals == null)
1235 conditionals = new List<string> (2);
1237 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1241 if (name == "CLSCompliantAttribute") {
1246 bag = new AttributesBag ();
1248 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1252 // Type only attributes
1253 if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1254 if (name == "DefaultMemberAttribute") {
1255 if (ns != "System.Reflection")
1259 bag = new AttributesBag ();
1261 bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1265 if (name == "AttributeUsageAttribute") {
1270 bag = new AttributesBag ();
1272 bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1273 foreach (var named in a.NamedArguments) {
1274 if (named.MemberInfo.Name == "AllowMultiple")
1275 bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1276 else if (named.MemberInfo.Name == "Inherited")
1277 bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1282 // Interface only attribute
1283 if (name == "CoClassAttribute") {
1284 if (ns != "System.Runtime.InteropServices")
1288 bag = new AttributesBag ();
1290 bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1299 if (conditionals != null)
1300 bag.Conditionals = conditionals.ToArray ();
1306 protected readonly MemberInfo provider;
1307 protected AttributesBag cattrs;
1308 protected readonly MetadataImporter importer;
1310 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1312 this.provider = provider;
1313 this.importer = importer;
1318 public bool IsImported {
1324 public virtual string Name {
1326 return provider.Name;
1332 public string[] ConditionalConditions ()
1337 return cattrs.Conditionals;
1340 public ObsoleteAttribute GetAttributeObsolete ()
1345 return cattrs.Obsolete;
1348 public bool? CLSAttributeValue {
1353 return cattrs.CLSAttributeValue;
1357 protected void ReadAttributes ()
1359 cattrs = AttributesBag.Read (provider, importer);
1362 public void SetIsAssigned ()
1364 // Unused for imported members
1367 public void SetIsUsed ()
1369 // Unused for imported members
1373 public class ImportedModuleDefinition
1375 readonly Module module;
1377 readonly MetadataImporter importer;
1379 public ImportedModuleDefinition (Module module, MetadataImporter importer)
1381 this.module = module;
1382 this.importer = importer;
1387 public bool IsCLSCompliant {
1389 return cls_compliant;
1393 public string Name {
1401 public void ReadAttributes ()
1403 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1406 foreach (var a in attrs) {
1407 importer.GetCustomAttributeTypeName (a, out ns, out name);
1408 if (name == "CLSCompliantAttribute") {
1412 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1419 // Reads assembly attributes which where attached to a special type because
1420 // module does have assembly manifest
1422 public List<Attribute> ReadAssemblyAttributes ()
1424 var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1428 var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1432 // TODO: implement, the idea is to fabricate specil Attribute class and
1433 // add it to OptAttributes before resolving the source code attributes
1434 // Need to build module location as well for correct error reporting
1436 //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1437 //var attrs = new List<Attribute> (assembly_attributes.Count);
1438 //foreach (var a in assembly_attributes)
1440 // var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1441 // var ctor = metaImporter.CreateMethod (a.Constructor, type);
1443 // foreach (var carg in a.ConstructorArguments) {
1447 // attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1454 public class ImportedAssemblyDefinition : IAssemblyDefinition
1456 readonly Assembly assembly;
1457 readonly AssemblyName aname;
1458 readonly MetadataImporter importer;
1460 bool contains_extension_methods;
1462 List<AssemblyName> internals_visible_to;
1463 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1465 public ImportedAssemblyDefinition (Assembly assembly, MetadataImporter importer)
1467 this.assembly = assembly;
1468 this.aname = assembly.GetName ();
1469 this.importer = importer;
1474 public Assembly Assembly {
1480 public string FullName {
1482 return aname.FullName;
1486 public bool HasExtensionMethod {
1488 return contains_extension_methods;
1492 public bool HasStrongName {
1494 return aname.GetPublicKey ().Length != 0;
1498 public bool IsMissing {
1501 return assembly.__IsMissing;
1508 public bool IsCLSCompliant {
1510 return cls_compliant;
1514 public string Location {
1516 return assembly.Location;
1520 public string Name {
1528 public byte[] GetPublicKeyToken ()
1530 return aname.GetPublicKeyToken ();
1533 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1535 return internals_visible_to_cache [assembly];
1538 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1540 if (internals_visible_to == null)
1543 AssemblyName is_visible = null;
1544 if (internals_visible_to_cache == null) {
1545 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1547 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1548 return is_visible != null;
1551 var token = assembly.GetPublicKeyToken ();
1552 if (token != null && token.Length == 0)
1555 foreach (var internals in internals_visible_to) {
1556 if (internals.Name != assembly.Name)
1559 if (token == null && assembly is AssemblyDefinition) {
1560 is_visible = internals;
1564 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1567 is_visible = internals;
1571 internals_visible_to_cache.Add (assembly, is_visible);
1572 return is_visible != null;
1575 public void ReadAttributes ()
1578 if (assembly.__IsMissing)
1582 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1585 foreach (var a in attrs) {
1586 importer.GetCustomAttributeTypeName (a, out ns, out name);
1588 if (name == "CLSCompliantAttribute") {
1589 if (ns == "System") {
1591 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1598 if (name == "InternalsVisibleToAttribute") {
1599 if (ns != MetadataImporter.CompilerServicesNamespace)
1604 s = a.ConstructorArguments[0].Value as string;
1612 var an = new AssemblyName (s);
1613 if (internals_visible_to == null)
1614 internals_visible_to = new List<AssemblyName> ();
1616 internals_visible_to.Add (an);
1620 if (name == "ExtensionAttribute") {
1621 if (ns == MetadataImporter.CompilerServicesNamespace)
1622 contains_extension_methods = true;
1629 public override string ToString ()
1635 class ImportedMemberDefinition : ImportedDefinition
1637 readonly TypeSpec type;
1639 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1640 : base (member, importer)
1647 public TypeSpec MemberType {
1656 class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1658 readonly AParametersCollection parameters;
1660 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1661 : base (provider, type, importer)
1663 this.parameters = parameters;
1666 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1667 : base (provider, type, importer)
1669 this.parameters = parameters;
1674 public AParametersCollection Parameters {
1683 class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1685 readonly TypeParameterSpec[] tparams;
1687 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1688 : base (provider, type, parameters, importer)
1690 this.tparams = tparams;
1695 public TypeParameterSpec[] TypeParameters {
1701 public int TypeParametersCount {
1703 return tparams.Length;
1710 class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1712 TypeParameterSpec[] tparams;
1715 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1716 : base (type, importer)
1722 public IAssemblyDefinition DeclaringAssembly {
1724 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1728 public override string Name {
1732 if (tparams != null) {
1733 int arity_start = name.IndexOf ('`');
1734 if (arity_start > 0)
1735 name = name.Substring (0, arity_start);
1743 public string Namespace {
1745 return ((MetaType) provider).Namespace;
1749 public int TypeParametersCount {
1751 return tparams == null ? 0 : tparams.Length;
1755 public TypeParameterSpec[] TypeParameters {
1766 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1769 // Report details about missing type and most likely cause of the problem.
1770 // csc reports 1683, 1684 as warnings but we report them only when used
1771 // or referenced from the user core in which case compilation error has to
1772 // be reported because compiler cannot continue anyway
1774 foreach (var t in types) {
1775 string name = t.GetSignatureForError ();
1777 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1778 ctx.Module.Compiler.Report.Error (1683, loc,
1779 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1781 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1782 ctx.Module.Compiler.Report.Error (12, loc,
1783 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1784 name, t.MemberDefinition.DeclaringAssembly.FullName);
1786 ctx.Module.Compiler.Report.Error (1684, loc,
1787 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1788 name, t.MemberDefinition.DeclaringAssembly.FullName);
1793 public TypeSpec GetAttributeCoClass ()
1798 return cattrs.CoClass;
1801 public string GetAttributeDefaultMember ()
1806 return cattrs.DefaultIndexerName;
1809 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1814 return cattrs.AttributeUsage;
1817 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1819 var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1820 return a == assembly || a.IsFriendAssemblyTo (assembly);
1823 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1826 // Not interested in members of nested private types unless the importer needs them
1828 if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1829 cache = MemberCache.Empty;
1833 var loading_type = (MetaType) provider;
1834 const BindingFlags all_members = BindingFlags.DeclaredOnly |
1835 BindingFlags.Static | BindingFlags.Instance |
1836 BindingFlags.Public | BindingFlags.NonPublic;
1838 const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1839 MethodAttributes.Virtual | MethodAttributes.HideBySig |
1840 MethodAttributes.Final;
1842 Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1843 List<EventSpec> imported_events = null;
1844 EventSpec event_spec;
1845 MemberSpec imported;
1849 all = loading_type.GetMembers (all_members);
1850 } catch (Exception e) {
1851 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1852 declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1855 if (cache == null) {
1856 cache = new MemberCache (all.Length);
1859 // Do the types first as they can be referenced by the members before
1860 // they are found or inflated
1862 foreach (var member in all) {
1863 if (member.MemberType != MemberTypes.NestedType)
1866 var t = (MetaType) member;
1868 // Ignore compiler generated types, mostly lambda containers
1869 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1872 imported = importer.CreateNestedType (t, declaringType);
1873 cache.AddMemberImported (imported);
1876 foreach (var member in all) {
1877 if (member.MemberType != MemberTypes.NestedType)
1880 var t = (MetaType) member;
1882 if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1885 importer.ImportTypeBase (t);
1891 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1893 foreach (var member in all) {
1894 switch (member.MemberType) {
1895 case MemberTypes.Constructor:
1896 case MemberTypes.Method:
1897 MethodBase mb = (MethodBase) member;
1898 var attrs = mb.Attributes;
1900 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1901 if (importer.IgnorePrivateMembers)
1904 // Ignore explicitly implemented members
1905 if ((attrs & explicit_impl) == explicit_impl)
1908 // Ignore compiler generated methods
1909 if (importer.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1913 imported = importer.CreateMethod (mb, declaringType);
1914 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1915 if (possible_accessors == null)
1916 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1918 // There are no metadata rules for accessors, we have to consider any method as possible candidate
1919 possible_accessors.Add (mb, (MethodSpec) imported);
1923 case MemberTypes.Property:
1924 if (possible_accessors == null)
1927 var p = (PropertyInfo) member;
1929 // Links possible accessors with property
1931 MethodSpec get, set;
1932 m = p.GetGetMethod (true);
1933 if (m == null || !possible_accessors.TryGetValue (m, out get))
1936 m = p.GetSetMethod (true);
1937 if (m == null || !possible_accessors.TryGetValue (m, out set))
1940 // No accessors registered (e.g. explicit implementation)
1941 if (get == null && set == null)
1944 imported = importer.CreateProperty (p, declaringType, get, set);
1945 if (imported == null)
1949 case MemberTypes.Event:
1950 if (possible_accessors == null)
1953 var e = (EventInfo) member;
1955 // Links accessors with event
1957 MethodSpec add, remove;
1958 m = e.GetAddMethod (true);
1959 if (m == null || !possible_accessors.TryGetValue (m, out add))
1962 m = e.GetRemoveMethod (true);
1963 if (m == null || !possible_accessors.TryGetValue (m, out remove))
1966 // Both accessors are required
1967 if (add == null || remove == null)
1970 event_spec = importer.CreateEvent (e, declaringType, add, remove);
1971 if (!importer.IgnorePrivateMembers) {
1972 if (imported_events == null)
1973 imported_events = new List<EventSpec> ();
1975 imported_events.Add (event_spec);
1978 imported = event_spec;
1980 case MemberTypes.Field:
1981 var fi = (FieldInfo) member;
1983 imported = importer.CreateField (fi, declaringType);
1984 if (imported == null)
1988 // For dynamic binder event has to be fully restored to allow operations
1989 // within the type container to work correctly
1991 if (imported_events != null) {
1992 // The backing event field should be private but it may not
1994 for (i = 0; i < imported_events.Count; ++i) {
1995 var ev = imported_events[i];
1996 if (ev.Name == fi.Name) {
1997 ev.BackingField = (FieldSpec) imported;
1998 imported_events.RemoveAt (i);
2009 case MemberTypes.NestedType:
2010 // Already in the cache from the first pass
2013 throw new NotImplementedException (member.ToString ());
2016 cache.AddMemberImported (imported);
2020 if (declaringType.IsInterface && declaringType.Interfaces != null) {
2021 foreach (var iface in declaringType.Interfaces) {
2022 cache.AddInterface (iface);
2028 class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2030 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2031 : base (type, importer)
2037 public IAssemblyDefinition DeclaringAssembly {
2039 throw new NotImplementedException ();
2043 public string Namespace {
2049 public int TypeParametersCount {
2055 public TypeParameterSpec[] TypeParameters {
2063 public TypeSpec GetAttributeCoClass ()
2068 public string GetAttributeDefaultMember ()
2070 throw new NotSupportedException ();
2073 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2075 throw new NotSupportedException ();
2078 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2080 throw new NotImplementedException ();
2083 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2085 throw new NotImplementedException ();