Free cookie consent management tool by TermsFeed Policy Generator

source: branches/CodeEditor/HeuristicLab.ExtLibs/HeuristicLab.NRefactory/5.5.0/NRefactory.CSharp-5.5.0/Parser/mcs/import.cs @ 11700

Last change on this file since 11700 was 11700, checked in by jkarder, 9 years ago

#2077: created branch and added first version

File size: 65.3 KB
Line 
1//
2// import.cs: System.Reflection conversions
3//
4// Authors: Marek Safar (marek.safar@gmail.com)
5//
6// Dual licensed under the terms of the MIT X11 or GNU GPL
7//
8// Copyright 2009-2011 Novell, Inc
9// Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
10//
11
12using System;
13using System.Runtime.CompilerServices;
14using System.Linq;
15using System.Collections.Generic;
16
17#if STATIC
18using MetaType = IKVM.Reflection.Type;
19using IKVM.Reflection;
20using IKVM.Reflection.Emit;
21#else
22using MetaType = System.Type;
23using System.Reflection;
24using System.Reflection.Emit;
25#endif
26
27namespace Mono.CSharp
28{
29  public abstract class MetadataImporter
30  {
31    //
32    // Dynamic types reader with additional logic to reconstruct a dynamic
33    // type using DynamicAttribute values
34    //
35    protected struct DynamicTypeReader
36    {
37      static readonly bool[] single_attribute = { true };
38
39      public int Position;
40      bool[] flags;
41
42      // There is no common type for CustomAttributeData and we cannot
43      // use ICustomAttributeProvider
44      object provider;
45
46      //
47      // A member provider which can be used to get CustomAttributeData
48      //
49      public DynamicTypeReader (object provider)
50      {
51        Position = 0;
52        flags = null;
53        this.provider = provider;
54      }
55
56      //
57      // Returns true when object at local position has dynamic attribute flag
58      //
59      public bool IsDynamicObject ()
60      {
61        if (provider != null)
62          ReadAttribute ();
63
64        return flags != null && Position < flags.Length && flags[Position];
65      }
66
67      //
68      // Returns true when DynamicAttribute exists
69      //
70      public bool HasDynamicAttribute ()
71      {
72        if (provider != null)
73          ReadAttribute ();
74
75        return flags != null;
76      }
77
78      IList<CustomAttributeData> GetCustomAttributes ()
79      {
80        var mi = provider as MemberInfo;
81        if (mi != null)
82          return CustomAttributeData.GetCustomAttributes (mi);
83
84        var pi = provider as ParameterInfo;
85        if (pi != null)
86          return CustomAttributeData.GetCustomAttributes (pi);
87
88        provider = null;
89        return null;
90      }
91
92      void ReadAttribute ()
93      {
94        var cad = GetCustomAttributes ();
95        if (cad == null) {
96          return;
97        }
98
99        if (cad.Count > 0) {
100          foreach (var ca in cad) {
101            var dt = ca.Constructor.DeclaringType;
102            if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace)
103              continue;
104
105            if (ca.ConstructorArguments.Count == 0) {
106              flags = single_attribute;
107              break;
108            }
109
110            var arg_type = ca.ConstructorArguments[0].ArgumentType;
111
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;
118              }
119
120              break;
121            }
122          }
123        }
124
125        provider = null;
126      }
127    }
128
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;
133
134    public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
135
136    protected MetadataImporter (ModuleContainer module)
137    {
138      this.module = module;
139
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;
144    }
145
146    #region Properties
147
148    public ICollection<IAssemblyDefinition> Assemblies {
149      get {
150        return assembly_2_definition.Values;
151      }
152    }
153
154    public bool IgnorePrivateMembers { get; set; }
155
156    #endregion
157
158    public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
159    protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
160    protected abstract bool HasVolatileModifier (MetaType[] modifiers);
161
162    public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
163    {
164      Modifiers mod;
165      var fa = fi.Attributes;
166      switch (fa & FieldAttributes.FieldAccessMask) {
167        case FieldAttributes.Public:
168          mod = Modifiers.PUBLIC;
169          break;
170        case FieldAttributes.Assembly:
171          mod = Modifiers.INTERNAL;
172          break;
173        case FieldAttributes.Family:
174          mod = Modifiers.PROTECTED;
175          break;
176        case FieldAttributes.FamORAssem:
177          mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
178          break;
179        default:
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))
183            return null;
184
185          mod = Modifiers.PRIVATE;
186          break;
187      }
188
189      TypeSpec field_type;
190
191      try {
192        field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
193
194        //
195        // Private field has private type which is not fixed buffer
196        //
197        if (field_type == null)
198          return 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);
204      }
205
206      var definition = new ImportedMemberDefinition (fi, field_type, this);
207
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);
213      }
214
215      if ((fa & FieldAttributes.InitOnly) != 0) {
216        if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
217          var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
218          if (dc != null)
219            return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
220        }
221
222        mod |= Modifiers.READONLY;
223      } else {
224        var req_mod = fi.GetRequiredCustomModifiers ();
225        if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
226          mod |= Modifiers.VOLATILE;
227      }
228
229      if ((fa & FieldAttributes.Static) != 0) {
230        mod |= Modifiers.STATIC;
231      } else {
232        // Fixed buffers cannot be static
233        if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
234          HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
235
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);
239        }
240      }
241
242      return new FieldSpec (declaringType, definition, field_type, fi, mod);
243    }
244
245    public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
246    {
247      add.IsAccessor = true;
248      remove.IsAccessor = true;
249
250      if (add.Modifiers != remove.Modifiers)
251        throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
252
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);
256    }
257
258    TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
259    {
260      var tparams = type.GetGenericArguments ();
261
262      int parent_owned_count;
263      if (type.IsNested) {
264        parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
265
266        //
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
272        //
273        if (declaringType != null && parent_owned_count > 0) {
274          int read_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]);
282              }
283            }
284
285            declaringType = declaringType.DeclaringType;
286          }
287        }     
288      } else {
289        parent_owned_count = 0;
290      }
291
292      if (tparams.Length - parent_owned_count == 0)
293        return null;
294
295      return CreateGenericParameters (parent_owned_count, tparams);
296    }
297
298    TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
299    {
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;
304
305        tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
306      }
307
308      return tspec;
309    }
310
311    TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
312    {
313      ++dtype.Position;
314
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;
319
320        TypeSpec spec;
321        if (type.HasElementType) {
322          var element = type.GetElementType ();
323          ++dtype.Position;
324          spec = ImportType (element, dtype);
325
326          if (!type.IsArray) {
327            throw new NotImplementedException ("Unknown element type " + type.ToString ());
328          }
329
330          spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
331        } else {
332          spec = CreateType (type, dtype, true);
333
334          //
335          // We treat nested generic types as inflated internally where
336          // reflection uses type definition
337          //
338          // class A<T> {
339          //    IFoo<A<T>> foo; // A<T> is definition in this case
340          // }
341          //
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);
346          }
347        }
348
349        if (spec == null)
350          return null;
351
352        ++dtype.Position;
353        tspec[index] = spec;
354      }
355
356      return tspec;
357    }
358
359    public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
360    {
361      Modifiers mod = ReadMethodModifiers (mb, declaringType);
362      TypeParameterSpec[] tparams;
363
364      var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
365
366      if (mb.IsGenericMethod) {
367        if (!mb.IsGenericMethodDefinition)
368          throw new NotSupportedException ("assert");
369
370        tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
371      } else {
372        tparams = null;
373      }
374
375      MemberKind kind;
376      TypeSpec returnType;
377      if (mb.MemberType == MemberTypes.Constructor) {
378        kind = MemberKind.Constructor;
379        returnType = module.Compiler.BuiltinTypes.Void;
380      } else {
381        //
382        // Detect operators and destructors
383        //
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;
392              }
393            }
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;
399            }
400          }
401        }
402
403        var mi = (MethodInfo) mb;
404        returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
405
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);
416
417              //
418              // For imported class method do additional validation to be sure that metadata
419              // override flag was correct
420              //
421              // Difference between protected internal and protected is ok
422              //
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;
426              }
427            }
428          }
429
430          if (!is_real_override) {
431            mod &= ~Modifiers.OVERRIDE;
432            if ((mod & Modifiers.SEALED) != 0)
433              mod &= ~Modifiers.SEALED;
434            else
435              mod |= Modifiers.VIRTUAL;
436          }
437        } else if (parameters.HasExtensionMethodType) {
438          mod |= Modifiers.METHOD_EXTENSION;
439        }
440      }
441
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 ());
447        }
448
449        definition = gmd;
450      } else {
451        definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
452      }
453
454      MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
455      if (tparams != null)
456        ms.IsGeneric = true;
457
458      return ms;
459    }
460
461    bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
462    {
463      switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
464      case Modifiers.PUBLIC:
465        return true;
466      case Modifiers.INTERNAL:
467        //
468        // Check whether imported method in base type is accessible from compiled
469        // context
470        //
471        return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
472      case Modifiers.PRIVATE:
473        return false;
474      default:
475        // protected
476        // protected internal
477        //
478        // Method accessibility checks will be done later based on context
479        // where the method is called (CS0122 error will be reported for inaccessible)
480        //
481        return true;
482      }
483    }
484
485    //
486    // Imports System.Reflection parameters
487    //
488    AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
489    {
490      int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
491
492      if (pi.Length == 0 && varargs == 0)
493        return ParametersCompiled.EmptyReadOnlyParameters;
494
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;
505          else
506            mod = Parameter.Modifier.REF;
507
508          //
509          // Strip reference wrapping
510          //
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));
517        } else {
518          types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
519
520          if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
521            if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
522              mod = Parameter.Modifier.PARAMS;
523              is_params = true;
524            }
525          }
526
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))) {
531              if (value == null) {
532                default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
533              } else {
534                default_value = ImportParameterConstant (value);
535
536                if (ptype.IsEnum) {
537                  default_value = new EnumConstant ((Constant) default_value, ptype);
538                }
539              }
540
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)
546                  continue;
547
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;
554              }
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);
561            }
562          }
563        }
564
565        par[i] = new ParameterData (p.Name, mod, default_value);
566      }
567
568      if (varargs != 0) {
569        par[par.Length - 1] = new ArglistParameter (Location.Null);
570        types[types.Length - 1] = InternalType.Arglist;
571      }
572
573      return method != null ?
574        new ParametersImported (par, types, varargs != 0, is_params) :
575        new ParametersImported (par, types, is_params);
576    }
577
578    //
579    // Returns null when the property is not valid C# property
580    //
581    public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
582    {
583      Modifiers mod = 0;
584      AParametersCollection param = null;
585      TypeSpec type = null;
586      if (get != null) {
587        mod = get.Modifiers;
588        param = get.Parameters;
589        type = get.ReturnType;
590      }
591
592      bool is_valid_property = true;
593      if (set != null) {
594        if (set.ReturnType.Kind != MemberKind.Void)
595          is_valid_property = false;
596
597        var set_param_count = set.Parameters.Count - 1;
598
599        if (set_param_count < 0) {
600          set_param_count = 0;
601          is_valid_property = false;
602        }
603
604        var set_type = set.Parameters.Types[set_param_count];
605
606        if (mod == 0) {
607          AParametersCollection set_based_param;
608
609          if (set_param_count == 0) {
610            set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
611          } else {
612            //
613            // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
614            //
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);
620          }
621
622          mod = set.Modifiers;
623          param = set_based_param;
624          type = set_type;
625        } else {
626          if (set_param_count != get.Parameters.Count)
627            is_valid_property = false;
628
629          if (get.ReturnType != set_type)
630            is_valid_property = false;
631
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
643                }
644
645                if (get_restr) {
646                  mod &= ~Modifiers.AccessibilityMask;
647                  mod |= set_acc;
648                }
649              }
650            }
651          }
652        }
653      }
654
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;
661          } else {
662            if (get != null) {
663              if (get.IsStatic)
664                is_valid_property = false;
665              if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
666                is_valid_property = false;
667            }
668            if (set != null) {
669              if (set.IsStatic)
670                is_valid_property = false;
671              if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
672                is_valid_property = false;
673            }
674          }
675
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) {
679            //
680            // Enables support for properties with parameters (must have default value) of COM-imported types
681            //
682            is_valid_property = true;
683
684            for (int i = 0; i < param.FixedParameters.Length; ++i) {
685              if (!param.FixedParameters[i].HasDefaultValue) {
686                is_valid_property = false;
687                break;
688              }
689            }
690          }
691        }
692      }
693
694      if (spec == null)
695        spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
696
697      if (!is_valid_property) {
698        spec.IsNotCSharpCompatible = true;
699        return spec;
700      }
701
702      if (set != null)
703        spec.Set = set;
704      if (get != null)
705        spec.Get = get;
706
707      return spec;
708    }
709
710    public TypeSpec CreateType (MetaType type)
711    {
712      return CreateType (type, new DynamicTypeReader (), true);
713    }
714
715    public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
716    {
717      return CreateType (type, declaringType, new DynamicTypeReader (type), false);
718    }
719
720    TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
721    {
722      TypeSpec declaring_type;
723      if (type.IsNested && !type.IsGenericParameter)
724        declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
725      else
726        declaring_type = null;
727
728      return CreateType (type, declaring_type, dtype, canImportBaseType);
729    }
730
731    protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
732    {
733      TypeSpec spec;
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;
738
739          return spec;
740        }
741
742        if (!spec.IsGeneric || type.IsGenericTypeDefinition)
743          return spec;
744
745        if (!dtype.HasDynamicAttribute ())
746          return spec;
747
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
751
752        // TODO: Handle cases where they still unify
753      }
754
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);
759        return spec;
760      }
761
762      if (type.IsGenericType && !type.IsGenericTypeDefinition) {
763        var type_def = type.GetGenericTypeDefinition ();
764
765        // Generic type definition can also be forwarded
766        if (compiled_types.TryGetValue (type_def, out spec))
767          return spec;
768
769        var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
770        if (targs == null)
771          return null;
772        if (declaringType == null) {
773          // Simple case, no nesting
774          spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
775          spec = spec.MakeGenericType (module, targs);
776        } else {
777          //
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>
781          //
782          var nested_hierarchy = new List<TypeSpec> ();
783          while (declaringType.IsNested) {
784            nested_hierarchy.Add (declaringType);
785            declaringType = declaringType.DeclaringType;
786          }
787
788          int targs_pos = 0;
789          if (declaringType.Arity > 0) {
790            spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
791            targs_pos = spec.Arity;
792          } else {
793            spec = declaringType;
794          }
795
796          for (int i = nested_hierarchy.Count; i != 0; --i) {
797            var t = nested_hierarchy [i - 1];
798            if (t.Kind == MemberKind.MissingType)
799              spec = t;
800            else
801              spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
802
803            if (t.Arity > 0) {
804              spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
805              targs_pos += t.Arity;
806            }
807          }
808
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;
812          } else {
813            if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
814              return null;
815
816            string name = type.Name;
817            int index = name.IndexOf ('`');
818            if (index > 0)
819              name = name.Substring (0, index);
820
821            spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
822
823            if (spec.Arity > 0) {
824              spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
825            }
826          }
827        }
828
829        // Don't add generic type with dynamic arguments, they can interfere with same type
830        // using object type arguments
831        if (!spec.HasDynamicElement) {
832
833          // Add to reading cache to speed up reading
834          if (!import_cache.ContainsKey (type))
835            import_cache.Add (type, spec);
836        }
837
838        return spec;
839      }
840
841      Modifiers mod;
842      MemberKind kind;
843
844      var ma = type.Attributes;
845      switch (ma & TypeAttributes.VisibilityMask) {
846      case TypeAttributes.Public:
847      case TypeAttributes.NestedPublic:
848        mod = Modifiers.PUBLIC;
849        break;
850      case TypeAttributes.NestedPrivate:
851        mod = Modifiers.PRIVATE;
852        break;
853      case TypeAttributes.NestedFamily:
854        mod = Modifiers.PROTECTED;
855        break;
856      case TypeAttributes.NestedFamORAssem:
857        mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
858        break;
859      default:
860        mod = Modifiers.INTERNAL;
861        break;
862      }
863
864      if ((ma & TypeAttributes.Interface) != 0) {
865        kind = MemberKind.Interface;
866      } else if (type.IsGenericParameter) {
867        kind = MemberKind.TypeParameter;
868      } else {
869        var base_type = type.BaseType;
870        if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
871          kind = MemberKind.Class;
872        } else {
873          kind = DetermineKindFromBaseType (base_type);
874          if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
875            mod |= Modifiers.SEALED;
876          }
877        }
878
879        if (kind == MemberKind.Class) {
880          if ((ma & TypeAttributes.Sealed) != 0) {
881            if ((ma & TypeAttributes.Abstract) != 0)
882              mod |= Modifiers.STATIC;
883            else
884              mod |= Modifiers.SEALED;
885          } else if ((ma & TypeAttributes.Abstract) != 0) {
886            mod |= Modifiers.ABSTRACT;
887          }
888        }
889      }
890
891      var definition = new ImportedTypeDefinition (type, this);
892      TypeSpec pt;
893
894      if (kind == MemberKind.Enum) {
895        const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
896          BindingFlags.Instance |
897          BindingFlags.Public | BindingFlags.NonPublic;
898
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);
902          break;
903        }
904
905        if (spec == null)
906          kind = MemberKind.Class;
907
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)) {
913        //
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.
917        //
918        spec = pt;
919        BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
920        if (bts != null)
921          bts.SetDefinition (definition, type, mod);
922      }
923
924      if (spec == null)
925        spec = new TypeSpec (kind, declaringType, definition, type, mod);
926
927      import_cache.Add (type, spec);
928
929      if (kind == MemberKind.TypeParameter) {
930        if (canImportBaseType)
931          ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
932
933        return spec;
934      }
935
936      //
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
941      //
942      if (canImportBaseType)
943        ImportTypeBase (spec, type);
944
945      return spec;
946    }
947
948    public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
949    {
950      IAssemblyDefinition found;
951      if (!assembly_2_definition.TryGetValue (assembly, out found)) {
952
953        // This can happen in dynamic context only
954        var def = new ImportedAssemblyDefinition (assembly);
955        assembly_2_definition.Add (assembly, def);
956        def.ReadAttributes ();
957        found = def;
958      }
959
960      return found;
961    }
962
963    public void ImportTypeBase (MetaType type)
964    {
965      TypeSpec spec = import_cache[type];
966      if (spec != null)
967        ImportTypeBase (spec, type);
968    }
969
970    TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
971    {
972      Variance variance;
973      switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
974      case GenericParameterAttributes.Covariant:
975        variance = Variance.Covariant;
976        break;
977      case GenericParameterAttributes.Contravariant:
978        variance = Variance.Contravariant;
979        break;
980      default:
981        variance = Variance.None;
982        break;
983      }
984
985      SpecialConstraint special = SpecialConstraint.None;
986      var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
987
988      if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
989        special |= SpecialConstraint.Struct;
990      } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
991        special = SpecialConstraint.Constructor;
992      }
993
994      if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
995        special |= SpecialConstraint.Class;
996      }
997
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);
1002      } else {
1003        spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
1004      }
1005
1006      return spec;
1007    }
1008
1009    //
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
1012    //
1013    public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
1014    {
1015      if (attributesData.Count == 0)
1016        return false;
1017
1018      foreach (var attr in attributesData) {
1019        var dt = attr.Constructor.DeclaringType;
1020        if (dt.Name == attrName && dt.Namespace == attrNamespace)
1021          return true;
1022      }
1023
1024      return false;
1025    }
1026
1027    void ImportTypeBase (TypeSpec spec, MetaType type)
1028    {
1029      if (spec.Kind == MemberKind.Interface)
1030        spec.BaseType = module.Compiler.BuiltinTypes.Object;
1031      else if (type.BaseType != null) {
1032        TypeSpec base_type;
1033        if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1034          base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1035        else
1036          base_type = CreateType (type.BaseType);
1037
1038        spec.BaseType = base_type;
1039      }
1040
1041      if (spec.MemberDefinition.TypeParametersCount > 0) {
1042        foreach (var tp in spec.MemberDefinition.TypeParameters) {
1043          ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1044        }
1045      }
1046    }
1047
1048    protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1049    {
1050      Namespace ns = targetNamespace;
1051      string prev_namespace = null;
1052      foreach (var t in types) {
1053        if (t == null)
1054          continue;
1055
1056        // Be careful not to trigger full parent type loading
1057        if (t.MemberType == MemberTypes.NestedType)
1058          continue;
1059
1060        if (t.Name[0] == '<')
1061          continue;
1062
1063        var it = CreateType (t, null, new DynamicTypeReader (t), true);
1064        if (it == null)
1065          continue;
1066
1067        if (prev_namespace != t.Namespace) {
1068          ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1069          prev_namespace = t.Namespace;
1070        }
1071
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 ();
1077        }
1078
1079        ns.AddType (module, it);
1080      }
1081    }
1082
1083    void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1084    {
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> ();
1091
1092          tparams.Add (CreateType (ct));
1093          continue;
1094        }
1095
1096        var constraint_type = CreateType (ct);
1097        if (constraint_type.IsClass) {
1098          spec.BaseType = constraint_type;
1099          continue;
1100        }
1101
1102        spec.AddInterface (constraint_type);
1103      }
1104
1105      if (spec.BaseType == null)
1106        spec.BaseType = module.Compiler.BuiltinTypes.Object;
1107
1108      if (tparams != null)
1109        spec.TypeArguments = tparams.ToArray ();
1110    }
1111
1112    Constant ImportParameterConstant (object value)
1113    {
1114      //
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
1117      //
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);
1122      case TypeCode.Byte:
1123        return new ByteConstant (types, (byte) value, Location.Null);
1124      case TypeCode.Char:
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);
1148      }
1149
1150      throw new NotImplementedException (value.GetType ().ToString ());
1151    }
1152
1153    public TypeSpec ImportType (MetaType type)
1154    {
1155      return ImportType (type, new DynamicTypeReader (type));
1156    }
1157
1158    TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1159    {
1160      if (type.HasElementType) {
1161        var element = type.GetElementType ();
1162        ++dtype.Position;
1163        var spec = ImportType (element, dtype);
1164
1165        if (type.IsArray)
1166          return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1167        if (type.IsByRef)
1168          return ReferenceContainer.MakeType (module, spec);
1169        if (type.IsPointer)
1170          return PointerContainer.MakeType (module, spec);
1171
1172        throw new NotImplementedException ("Unknown element type " + type.ToString ());
1173      }
1174
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;
1179
1180        return compiled_type;
1181      }
1182
1183      return CreateType (type, dtype, true);
1184    }
1185
1186    static bool IsMissingType (MetaType type)
1187    {
1188#if STATIC
1189      return type.__IsMissing;
1190#else
1191      return false;
1192#endif
1193    }
1194
1195    //
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.
1199    //
1200    Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1201    {
1202      if (attrs.Count == 0)
1203        return null;
1204
1205      foreach (var ca in attrs) {
1206        var dt = ca.Constructor.DeclaringType;
1207        if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1208          continue;
1209
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);
1216
1217        return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1218      }
1219
1220      return null;
1221    }
1222
1223    static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1224    {
1225      Modifiers mod;
1226      var ma = mb.Attributes;
1227      switch (ma & MethodAttributes.MemberAccessMask) {
1228      case MethodAttributes.Public:
1229        mod = Modifiers.PUBLIC;
1230        break;
1231      case MethodAttributes.Assembly:
1232        mod = Modifiers.INTERNAL;
1233        break;
1234      case MethodAttributes.Family:
1235        mod = Modifiers.PROTECTED;
1236        break;
1237      case MethodAttributes.FamORAssem:
1238        mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1239        break;
1240      default:
1241        mod = Modifiers.PRIVATE;
1242        break;
1243      }
1244
1245      if ((ma & MethodAttributes.Static) != 0) {
1246        mod |= Modifiers.STATIC;
1247        return mod;
1248      }
1249      if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1250        mod |= Modifiers.ABSTRACT;
1251        return mod;
1252      }
1253
1254      // It can be sealed and override
1255      if ((ma & MethodAttributes.Final) != 0)
1256        mod |= Modifiers.SEALED;
1257
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
1262        // later
1263        if ((ma & MethodAttributes.NewSlot) != 0) {
1264          if ((mod & Modifiers.SEALED) != 0) {
1265            mod &= ~Modifiers.SEALED;
1266          } else {
1267            mod |= Modifiers.VIRTUAL;
1268          }
1269        } else {
1270          mod |= Modifiers.OVERRIDE;
1271        }
1272      }
1273
1274      return mod;
1275    }
1276  }
1277
1278  abstract class ImportedDefinition : IMemberDefinition
1279  {
1280    protected class AttributesBag
1281    {
1282      public static readonly AttributesBag Default = new AttributesBag ();
1283
1284      public AttributeUsageAttribute AttributeUsage;
1285      public ObsoleteAttribute Obsolete;
1286      public string[] Conditionals;
1287      public string DefaultIndexerName;
1288      public bool? CLSAttributeValue;
1289      public TypeSpec CoClass;
1290
1291      static bool HasMissingType (ConstructorInfo ctor)
1292      {
1293#if STATIC
1294        //
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
1298        //
1299        foreach (var p in ctor.GetParameters ()) {
1300          if (p.ParameterType.__ContainsMissingType)
1301            return true;
1302        }
1303#endif
1304
1305        return false;
1306      }
1307     
1308      public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1309      {
1310        AttributesBag bag = null;
1311        List<string> conditionals = null;
1312
1313        // It should not throw any loading exception
1314        IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1315
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")
1321              continue;
1322
1323            if (bag == null)
1324              bag = new AttributesBag ();
1325
1326            var args = a.ConstructorArguments;
1327
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);
1332            } else {
1333              bag.Obsolete = new ObsoleteAttribute ();
1334            }
1335
1336            continue;
1337          }
1338
1339          if (name == "ConditionalAttribute") {
1340            if (dt.Namespace != "System.Diagnostics")
1341              continue;
1342
1343            if (bag == null)
1344              bag = new AttributesBag ();
1345
1346            if (conditionals == null)
1347              conditionals = new List<string> (2);
1348
1349            conditionals.Add ((string) a.ConstructorArguments[0].Value);
1350            continue;
1351          }
1352
1353          if (name == "CLSCompliantAttribute") {
1354            if (dt.Namespace != "System")
1355              continue;
1356
1357            if (bag == null)
1358              bag = new AttributesBag ();
1359
1360            bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1361            continue;
1362          }
1363
1364          // Type only attributes
1365          if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1366            if (name == "DefaultMemberAttribute") {
1367              if (dt.Namespace != "System.Reflection")
1368                continue;
1369
1370              if (bag == null)
1371                bag = new AttributesBag ();
1372
1373              bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1374              continue;
1375            }
1376
1377            if (name == "AttributeUsageAttribute") {
1378              if (dt.Namespace != "System")
1379                continue;
1380
1381              if (HasMissingType (a.Constructor))
1382                continue;
1383
1384              if (bag == null)
1385                bag = new AttributesBag ();
1386
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;
1393              }
1394              continue;
1395            }
1396
1397            // Interface only attribute
1398            if (name == "CoClassAttribute") {
1399              if (dt.Namespace != "System.Runtime.InteropServices")
1400                continue;
1401
1402              if (HasMissingType (a.Constructor))
1403                continue;
1404
1405              if (bag == null)
1406                bag = new AttributesBag ();
1407
1408              bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1409              continue;
1410            }
1411          }
1412        }
1413
1414        if (bag == null)
1415          return Default;
1416
1417        if (conditionals != null)
1418          bag.Conditionals = conditionals.ToArray ();
1419       
1420        return bag;
1421      }
1422    }
1423
1424    protected readonly MemberInfo provider;
1425    protected AttributesBag cattrs;
1426    protected readonly MetadataImporter importer;
1427
1428    protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1429    {
1430      this.provider = provider;
1431      this.importer = importer;
1432    }
1433
1434    #region Properties
1435
1436    public bool IsImported {
1437      get {
1438        return true;
1439      }
1440    }
1441
1442    public virtual string Name {
1443      get {
1444        return provider.Name;
1445      }
1446    }
1447
1448    #endregion
1449
1450    public string[] ConditionalConditions ()
1451    {
1452      if (cattrs == null)
1453        ReadAttributes ();
1454
1455      return cattrs.Conditionals;
1456    }
1457
1458    public ObsoleteAttribute GetAttributeObsolete ()
1459    {
1460      if (cattrs == null)
1461        ReadAttributes ();
1462
1463      return cattrs.Obsolete;
1464    }
1465
1466    public bool? CLSAttributeValue {
1467      get {
1468        if (cattrs == null)
1469          ReadAttributes ();
1470
1471        return cattrs.CLSAttributeValue;
1472      }
1473    }
1474
1475    protected void ReadAttributes ()
1476    {
1477      cattrs = AttributesBag.Read (provider, importer);
1478    }
1479
1480    public void SetIsAssigned ()
1481    {
1482      // Unused for imported members
1483    }
1484
1485    public void SetIsUsed ()
1486    {
1487      // Unused for imported members
1488    }
1489  }
1490
1491  public class ImportedModuleDefinition
1492  {
1493    readonly Module module;
1494    bool cls_compliant;
1495   
1496    public ImportedModuleDefinition (Module module)
1497    {
1498      this.module = module;
1499    }
1500
1501    #region Properties
1502
1503    public bool IsCLSCompliant {
1504      get {
1505        return cls_compliant;
1506      }
1507    }
1508
1509    public string Name {
1510      get {
1511        return module.Name;
1512      }
1513    }
1514
1515    #endregion
1516
1517    public void ReadAttributes ()
1518    {
1519      IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1520
1521      foreach (var a in attrs) {
1522        var dt = a.Constructor.DeclaringType;
1523        if (dt.Name == "CLSCompliantAttribute") {
1524          if (dt.Namespace != "System")
1525            continue;
1526
1527          cls_compliant = (bool) a.ConstructorArguments[0].Value;
1528          continue;
1529        }
1530      }
1531    }
1532
1533    //
1534    // Reads assembly attributes which where attached to a special type because
1535    // module does have assembly manifest
1536    //
1537    public List<Attribute> ReadAssemblyAttributes ()
1538    {
1539      var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1540      if (t == null)
1541        return null;
1542
1543      var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1544      if (field == null)
1545        return null;
1546
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
1550
1551      //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1552      //var attrs = new List<Attribute> (assembly_attributes.Count);
1553      //foreach (var a in assembly_attributes)
1554      //{
1555      //    var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1556      //    var ctor = metaImporter.CreateMethod (a.Constructor, type);
1557
1558      //    foreach (var carg in a.ConstructorArguments) {
1559      //        carg.Value
1560      //    }
1561
1562      //    attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1563      //}
1564
1565      return null;
1566    }
1567  }
1568
1569  public class ImportedAssemblyDefinition : IAssemblyDefinition
1570  {
1571    readonly Assembly assembly;
1572    readonly AssemblyName aname;
1573    bool cls_compliant;
1574
1575    List<AssemblyName> internals_visible_to;
1576    Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1577
1578    public ImportedAssemblyDefinition (Assembly assembly)
1579    {
1580      this.assembly = assembly;
1581      this.aname = assembly.GetName ();
1582    }
1583
1584    #region Properties
1585
1586    public Assembly Assembly {
1587      get {
1588        return assembly;
1589      }
1590    }
1591
1592    public string FullName {
1593      get {
1594        return aname.FullName;
1595      }
1596    }
1597
1598    public bool HasStrongName {
1599      get {
1600        return aname.GetPublicKey ().Length != 0;
1601      }
1602    }
1603
1604    public bool IsMissing {
1605      get {
1606#if STATIC
1607        return assembly.__IsMissing;
1608#else
1609        return false;
1610#endif
1611      }
1612    }
1613
1614    public bool IsCLSCompliant {
1615      get {
1616        return cls_compliant;
1617      }
1618    }
1619
1620    public string Location {
1621      get {
1622        return assembly.Location;
1623      }
1624    }
1625
1626    public string Name {
1627      get {
1628        return aname.Name;
1629      }
1630    }
1631
1632    #endregion
1633
1634    public byte[] GetPublicKeyToken ()
1635    {
1636      return aname.GetPublicKeyToken ();
1637    }
1638
1639    public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1640    {
1641      return internals_visible_to_cache [assembly];
1642    }
1643
1644    public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1645    {
1646      if (internals_visible_to == null)
1647        return false;
1648
1649      AssemblyName is_visible = null;
1650      if (internals_visible_to_cache == null) {
1651        internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1652      } else {
1653        if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1654          return is_visible != null;
1655      }
1656
1657      var token = assembly.GetPublicKeyToken ();
1658      if (token != null && token.Length == 0)
1659        token = null;
1660
1661      foreach (var internals in internals_visible_to) {
1662        if (internals.Name != assembly.Name)
1663          continue;
1664
1665        if (token == null && assembly is AssemblyDefinition) {
1666          is_visible = internals;
1667          break;
1668        }
1669
1670        if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1671          continue;
1672
1673        is_visible = internals;
1674        break;
1675      }
1676
1677      internals_visible_to_cache.Add (assembly, is_visible);
1678      return is_visible != null;
1679    }
1680
1681    public void ReadAttributes ()
1682    {
1683#if STATIC
1684      if (assembly.__IsMissing)
1685        return;
1686#endif
1687
1688      IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1689
1690      foreach (var a in attrs) {
1691        var dt = a.Constructor.DeclaringType;
1692        var name = dt.Name;
1693        if (name == "CLSCompliantAttribute") {
1694          if (dt.Namespace == "System") {
1695            cls_compliant = (bool) a.ConstructorArguments[0].Value;
1696          }
1697          continue;
1698        }
1699
1700        if (name == "InternalsVisibleToAttribute") {
1701          if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1702            continue;
1703
1704          string s = a.ConstructorArguments[0].Value as string;
1705          if (s == null)
1706            continue;
1707
1708          var an = new AssemblyName (s);
1709          if (internals_visible_to == null)
1710            internals_visible_to = new List<AssemblyName> ();
1711
1712          internals_visible_to.Add (an);
1713          continue;
1714        }
1715      }
1716    }
1717
1718    public override string ToString ()
1719    {
1720      return FullName;
1721    }
1722  }
1723
1724  class ImportedMemberDefinition : ImportedDefinition
1725  {
1726    readonly TypeSpec type;
1727
1728    public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1729      : base (member, importer)
1730    {
1731      this.type = type;
1732    }
1733
1734    #region Properties
1735
1736    public TypeSpec MemberType {
1737      get {
1738        return type;
1739      }
1740    }
1741
1742    #endregion
1743  }
1744
1745  class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1746  {
1747    readonly AParametersCollection parameters;
1748
1749    protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1750      : base (provider, type, importer)
1751    {
1752      this.parameters = parameters;
1753    }
1754
1755    public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1756      : base (provider, type, importer)
1757    {
1758      this.parameters = parameters;
1759    }
1760
1761    #region Properties
1762
1763    public AParametersCollection Parameters {
1764      get {
1765        return parameters;
1766      }
1767    }
1768
1769    #endregion
1770  }
1771
1772  class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1773  {
1774    public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1775      : base (provider, type, parameters, importer)
1776    {
1777    }
1778
1779    MethodBase IMethodDefinition.Metadata {
1780      get {
1781        return (MethodBase) provider;
1782      }
1783    }
1784  }
1785
1786  class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1787  {
1788    readonly TypeParameterSpec[] tparams;
1789
1790    public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1791      : base (provider, type, parameters, importer)
1792    {
1793      this.tparams = tparams;
1794    }
1795
1796    #region Properties
1797
1798    public TypeParameterSpec[] TypeParameters {
1799      get {
1800        return tparams;
1801      }
1802    }
1803
1804    public int TypeParametersCount {
1805      get {
1806        return tparams.Length;
1807      }
1808    }
1809
1810    #endregion
1811  }
1812
1813  class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1814  {
1815    TypeParameterSpec[] tparams;
1816    string name;
1817
1818    public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1819      : base (type, importer)
1820    {
1821    }
1822
1823    #region Properties
1824
1825    public IAssemblyDefinition DeclaringAssembly {
1826      get {
1827        return importer.GetAssemblyDefinition (provider.Module.Assembly);
1828      }
1829    }
1830
1831    bool ITypeDefinition.IsComImport {
1832      get {
1833        return ((MetaType) provider).IsImport;
1834      }
1835    }
1836
1837
1838    bool ITypeDefinition.IsPartial {
1839      get {
1840        return false;
1841      }
1842    }
1843
1844    bool ITypeDefinition.IsTypeForwarder {
1845      get {
1846#if STATIC
1847        return ((MetaType) provider).__IsTypeForwarder;
1848#else
1849        return false;
1850#endif
1851      }
1852    }
1853
1854    bool ITypeDefinition.IsCyclicTypeForwarder {
1855      get {
1856#if STATIC
1857        return ((MetaType) provider).__IsCyclicTypeForwarder;
1858#else
1859        return false;
1860#endif
1861      }
1862    }
1863
1864    public override string Name {
1865      get {
1866        if (name == null) {
1867          name = base.Name;
1868          if (tparams != null) {
1869            int arity_start = name.IndexOf ('`');
1870            if (arity_start > 0)
1871              name = name.Substring (0, arity_start);
1872          }
1873        }
1874
1875        return name;
1876      }
1877    }
1878
1879    public string Namespace {
1880      get {
1881        return ((MetaType) provider).Namespace;
1882      }
1883    }
1884
1885    public int TypeParametersCount {
1886      get {
1887        return tparams == null ? 0 : tparams.Length;
1888      }
1889    }
1890
1891    public TypeParameterSpec[] TypeParameters {
1892      get {
1893        return tparams;
1894      }
1895      set {
1896        tparams = value;
1897      }
1898    }
1899
1900    #endregion
1901
1902    public void DefineInterfaces (TypeSpec spec)
1903    {
1904      var type = (MetaType) provider;
1905      MetaType[] ifaces;
1906#if STATIC
1907      ifaces = type.__GetDeclaredInterfaces ();
1908      if (ifaces.Length != 0) {
1909        foreach (var iface in ifaces) {
1910          var it = importer.CreateType (iface);
1911          if (it == null)
1912            continue;
1913
1914          spec.AddInterfaceDefined (it);
1915
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);
1921            }
1922          }
1923        }
1924      }
1925     
1926      //
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
1930      //
1931      if (spec.BaseType != null) {
1932        var bifaces = spec.BaseType.Interfaces;
1933        if (bifaces != null) {
1934          //
1935          // Before adding base class interfaces close defined interfaces
1936          // on type parameter
1937          //
1938          var tp = spec as TypeParameterSpec;
1939          if (tp != null && tp.InterfacesDefined == null) {
1940            tp.InterfacesDefined = TypeSpec.EmptyTypes;
1941          }
1942
1943          foreach (var iface in bifaces)
1944            spec.AddInterfaceDefined (iface);
1945        }
1946      }
1947#else
1948      ifaces = type.GetInterfaces ();
1949
1950      if (ifaces.Length > 0) {
1951        foreach (var iface in ifaces) {
1952          spec.AddInterface (importer.CreateType (iface));
1953        }
1954      }
1955#endif
1956
1957    }
1958
1959    public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
1960    {
1961      //
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
1966      //
1967
1968      var report = ctx.Module.Compiler.Report;
1969
1970      for (int i = 0; i < missing.Count; ++i) {
1971        var t = missing [i].Type;
1972
1973        //
1974        // Report missing types only once
1975        //
1976        if (report.Printer.MissingTypeReported (t.MemberDefinition))
1977          continue;
1978
1979        string name = t.GetSignatureForError ();
1980
1981        var caller = missing[i].Caller;
1982        if (caller.Kind != MemberKind.MissingType)
1983          report.SymbolRelatedToPreviousError (caller);
1984
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",
1989            name);
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);
1995          } else {
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);
1999          }
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);
2003        } else {
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);
2007        }
2008      }
2009    }
2010
2011    public TypeSpec GetAttributeCoClass ()
2012    {
2013      if (cattrs == null)
2014        ReadAttributes ();
2015
2016      return cattrs.CoClass;
2017    }
2018
2019    public string GetAttributeDefaultMember ()
2020    {
2021      if (cattrs == null)
2022        ReadAttributes ();
2023
2024      return cattrs.DefaultIndexerName;
2025    }
2026
2027    public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2028    {
2029      if (cattrs == null)
2030        ReadAttributes ();
2031
2032      return cattrs.AttributeUsage;
2033    }
2034
2035    bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2036    {
2037      var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
2038      return a == assembly || a.IsFriendAssemblyTo (assembly);
2039    }
2040
2041    public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2042    {
2043      //
2044      // Not interested in members of nested private types unless the importer needs them
2045      //
2046      if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
2047        cache = MemberCache.Empty;
2048        return;
2049      }
2050
2051      var loading_type = (MetaType) provider;
2052      const BindingFlags all_members = BindingFlags.DeclaredOnly |
2053        BindingFlags.Static | BindingFlags.Instance |
2054        BindingFlags.Public | BindingFlags.NonPublic;
2055
2056      const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
2057          MethodAttributes.Virtual | MethodAttributes.HideBySig |
2058          MethodAttributes.Final;
2059
2060      Dictionary<MethodBase, MethodSpec> possible_accessors = null;
2061      List<EventSpec> imported_events = null;
2062      EventSpec event_spec;
2063      MemberSpec imported;
2064      MethodInfo m;
2065      MemberInfo[] all;
2066      try {
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);
2071      }
2072
2073      if (cache == null) {
2074        cache = new MemberCache (all.Length);
2075
2076        //
2077        // Do the types first as they can be referenced by the members before
2078        // they are found or inflated
2079        //
2080        foreach (var member in all) {
2081          if (member.MemberType != MemberTypes.NestedType)
2082            continue;
2083
2084          var t = (MetaType) member;
2085
2086          // Ignore compiler generated types, mostly lambda containers
2087          if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2088            continue;
2089
2090          try {
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);
2095          }
2096
2097          cache.AddMemberImported (imported);
2098        }
2099
2100        foreach (var member in all) {
2101          if (member.MemberType != MemberTypes.NestedType)
2102            continue;
2103
2104          var t = (MetaType) member;
2105
2106          if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2107            continue;
2108
2109          importer.ImportTypeBase (t);
2110        }
2111      }
2112
2113      //
2114      // Load base interfaces first to minic behaviour of compiled members
2115      //
2116      if (declaringType.IsInterface && declaringType.Interfaces != null) {
2117        foreach (var iface in declaringType.Interfaces) {
2118          cache.AddInterface (iface);
2119        }
2120      }
2121
2122      if (!onlyTypes) {
2123        //
2124        // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2125        //
2126        foreach (var member in all) {
2127          switch (member.MemberType) {
2128          case MemberTypes.Constructor:
2129            if (declaringType.IsInterface)
2130              continue;
2131
2132            goto case MemberTypes.Method;
2133          case MemberTypes.Method:
2134            MethodBase mb = (MethodBase) member;
2135            var attrs = mb.Attributes;
2136
2137            if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2138              if (importer.IgnorePrivateMembers)
2139                continue;
2140
2141              // Ignore explicitly implemented members
2142              if ((attrs & explicit_impl) == explicit_impl)
2143                continue;
2144
2145              // Ignore compiler generated methods
2146              if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2147                continue;
2148            }
2149
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);
2154
2155              // There are no metadata rules for accessors, we have to consider any method as possible candidate
2156              possible_accessors.Add (mb, (MethodSpec) imported);
2157            }
2158
2159            break;
2160          case MemberTypes.Property:
2161            if (possible_accessors == null)
2162              continue;
2163
2164            var p = (PropertyInfo) member;
2165            //
2166            // Links possible accessors with property
2167            //
2168            MethodSpec get, set;
2169            m = p.GetGetMethod (true);
2170            if (m == null || !possible_accessors.TryGetValue (m, out get))
2171              get = null;
2172
2173            m = p.GetSetMethod (true);
2174            if (m == null || !possible_accessors.TryGetValue (m, out set))
2175              set = null;
2176
2177            // No accessors registered (e.g. explicit implementation)
2178            if (get == null && set == null)
2179              continue;
2180
2181            try {
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 ());
2186            }
2187
2188            if (imported == null)
2189              continue;
2190
2191            break;
2192          case MemberTypes.Event:
2193            if (possible_accessors == null)
2194              continue;
2195
2196            var e = (EventInfo) member;
2197            //
2198            // Links accessors with event
2199            //
2200            MethodSpec add, remove;
2201            m = e.GetAddMethod (true);
2202            if (m == null || !possible_accessors.TryGetValue (m, out add))
2203              add = null;
2204
2205            m = e.GetRemoveMethod (true);
2206            if (m == null || !possible_accessors.TryGetValue (m, out remove))
2207              remove = null;
2208
2209            // Both accessors are required
2210            if (add == null || remove == null)
2211              continue;
2212
2213            event_spec = importer.CreateEvent (e, declaringType, add, remove);
2214            if (!importer.IgnorePrivateMembers) {
2215              if (imported_events == null)
2216                imported_events = new List<EventSpec> ();
2217
2218              imported_events.Add (event_spec);
2219            }
2220
2221            imported = event_spec;
2222            break;
2223          case MemberTypes.Field:
2224            var fi = (FieldInfo) member;
2225
2226            imported = importer.CreateField (fi, declaringType);
2227            if (imported == null)
2228              continue;
2229
2230            //
2231            // For dynamic binder event has to be fully restored to allow operations
2232            // within the type container to work correctly
2233            //
2234            if (imported_events != null) {
2235              // The backing event field should be private but it may not
2236              int i;
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);
2242                  i = -1;
2243                  break;
2244                }
2245              }
2246
2247              if (i < 0)
2248                continue;
2249            }
2250
2251            break;
2252          case MemberTypes.NestedType:
2253            // Already in the cache from the first pass
2254            continue;
2255          default:
2256            throw new NotImplementedException (member.ToString ());
2257          }
2258
2259          if (imported.IsStatic && declaringType.IsInterface)
2260            continue;
2261
2262          cache.AddMemberImported (imported);
2263        }
2264      }
2265    }
2266  }
2267
2268  class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2269  {
2270    public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2271      : base (type, importer)
2272    {
2273    }
2274
2275    #region Properties
2276
2277    public IAssemblyDefinition DeclaringAssembly {
2278      get {
2279        throw new NotImplementedException ();
2280      }
2281    }
2282
2283    bool ITypeDefinition.IsComImport {
2284      get {
2285        return false;
2286      }
2287    }
2288
2289    bool ITypeDefinition.IsPartial {
2290      get {
2291        return false;
2292      }
2293    }
2294
2295    bool ITypeDefinition.IsTypeForwarder {
2296      get {
2297        return false;
2298      }
2299    }
2300
2301    bool ITypeDefinition.IsCyclicTypeForwarder {
2302      get {
2303        return false;
2304      }
2305    }
2306
2307    public string Namespace {
2308      get {
2309        return null;
2310      }
2311    }
2312
2313    public int TypeParametersCount {
2314      get {
2315        return 0;
2316      }
2317    }
2318
2319    public TypeParameterSpec[] TypeParameters {
2320      get {
2321        return null;
2322      }
2323    }
2324
2325    #endregion
2326
2327    public TypeSpec GetAttributeCoClass ()
2328    {
2329      return null;
2330    }
2331
2332    public string GetAttributeDefaultMember ()
2333    {
2334      throw new NotSupportedException ();
2335    }
2336
2337    public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2338    {
2339      throw new NotSupportedException ();
2340    }
2341
2342    bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2343    {
2344      throw new NotImplementedException ();
2345    }
2346
2347    public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2348    {
2349      throw new NotImplementedException ();
2350    }
2351  }
2352}
Note: See TracBrowser for help on using the repository browser.