57afe77b004f424864eaba0104e9e04d1e99a764
[mono.git] / mcs / mcs / generic.cs
1 //
2 // generic.cs: Generics support
3 //
4 // Authors: Martin Baulig (martin@ximian.com)
5 //          Miguel de Icaza (miguel@ximian.com)
6 //          Marek Safar (marek.safar@gmail.com)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 //
14
15 using System;
16 using System.Collections.Generic;
17 using System.Text;
18 using System.Linq;
19
20 #if STATIC
21 using MetaType = IKVM.Reflection.Type;
22 using IKVM.Reflection;
23 using IKVM.Reflection.Emit;
24 #else
25 using MetaType = System.Type;
26 using System.Reflection;
27 using System.Reflection.Emit;
28 #endif
29
30 namespace Mono.CSharp {
31         public class VarianceDecl
32         {
33                 public VarianceDecl (Variance variance, Location loc)
34                 {
35                         this.Variance = variance;
36                         this.Location = loc;
37                 }
38
39                 public Variance Variance { get; private set; }
40                 public Location Location { get; private set; }
41
42                 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
43                 {
44                         var tp = t as TypeParameterSpec;
45                         if (tp != null) {
46                                 var v = tp.Variance;
47                                 if (expected == Variance.None && v != expected ||
48                                         expected == Variance.Covariant && v == Variance.Contravariant ||
49                                         expected == Variance.Contravariant && v == Variance.Covariant) {
50                                         ((TypeParameter) tp.MemberDefinition).ErrorInvalidVariance (member, expected);
51                                 }
52
53                                 return expected;
54                         }
55
56                         if (t.TypeArguments.Length > 0) {
57                                 var targs_definition = t.MemberDefinition.TypeParameters;
58                                 TypeSpec[] targs = TypeManager.GetTypeArguments (t);
59                                 for (int i = 0; i < targs.Length; ++i) {
60                                         var v = targs_definition[i].Variance;
61                                         CheckTypeVariance (targs[i], (Variance) ((int) v * (int) expected), member);
62                                 }
63
64                                 return expected;
65                         }
66
67                         var ac = t as ArrayContainer;
68                         if (ac != null)
69                                 return CheckTypeVariance (ac.Element, expected, member);
70
71                         return Variance.None;
72                 }
73         }
74
75         public enum Variance
76         {
77                 //
78                 // Don't add or modify internal values, they are used as -/+ calculation signs
79                 //
80                 None                    = 0,
81                 Covariant               = 1,
82                 Contravariant   = -1
83         }
84
85         [Flags]
86         public enum SpecialConstraint
87         {
88                 None            = 0,
89                 Constructor = 1 << 2,
90                 Class           = 1 << 3,
91                 Struct          = 1 << 4
92         }
93
94         public class SpecialContraintExpr : FullNamedExpression
95         {
96                 public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
97                 {
98                         this.loc = loc;
99                         this.Constraint = constraint;
100                 }
101
102                 public SpecialConstraint Constraint { get; private set; }
103
104                 protected override Expression DoResolve (ResolveContext rc)
105                 {
106                         throw new NotImplementedException ();
107                 }
108
109                 public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
110                 {
111                         throw new NotImplementedException ();
112                 }
113         }
114
115         //
116         // A set of parsed constraints for a type parameter
117         //
118         public class Constraints
119         {
120                 readonly SimpleMemberName tparam;
121                 readonly List<FullNamedExpression> constraints;
122                 readonly Location loc;
123                 bool resolved;
124                 bool resolving;
125                 
126                 public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
127                 {
128                         this.tparam = tparam;
129                         this.constraints = constraints;
130                         this.loc = loc;
131                 }
132
133                 #region Properties
134
135                 public List<FullNamedExpression> TypeExpressions {
136                         get {
137                                 return constraints;
138                         }
139                 }
140
141                 public Location Location {
142                         get {
143                                 return loc;
144                         }
145                 }
146
147                 public SimpleMemberName TypeParameter {
148                         get {
149                                 return tparam;
150                         }
151                 }
152
153                 #endregion
154
155                 public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
156                 {
157                         if (spec.HasSpecialClass && bb.IsStruct) {
158                                 context.Module.Compiler.Report.Error (455, loc,
159                                         "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
160                                         spec.Name, "class", bb.GetSignatureForError ());
161
162                                 return false;
163                         }
164
165                         return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
166                 }
167
168                 static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
169                 {
170                         if (ba == bb)
171                                 return true;
172
173                         if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
174                                 return true;
175
176                         Error_ConflictingConstraints (context, spec, ba, bb, loc);
177                         return false;
178                 }
179
180                 public static void Error_ConflictingConstraints (IMemberContext context, TypeParameterSpec tp, TypeSpec ba, TypeSpec bb, Location loc)
181                 {
182                         context.Module.Compiler.Report.Error (455, loc,
183                                 "Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
184                                 tp.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
185                 }
186
187                 public void CheckGenericConstraints (IMemberContext context, bool obsoleteCheck)
188                 {
189                         foreach (var c in constraints) {
190                                 if (c == null)
191                                         continue;
192
193                                 var t = c.Type;
194                                 if (t == null)
195                                         continue;
196
197                                 if (obsoleteCheck) {
198                                         ObsoleteAttribute obsolete_attr = t.GetAttributeObsolete ();
199                                         if (obsolete_attr != null)
200                                                 AttributeTester.Report_ObsoleteMessage (obsolete_attr, t.GetSignatureForError (), c.Location, context.Module.Compiler.Report);
201                                 }
202
203                                 ConstraintChecker.Check (context, t, c.Location);
204                         }
205                 }
206
207                 //
208                 // Resolve the constraints types with only possible early checks, return
209                 // value `false' is reserved for recursive failure
210                 //
211                 public bool Resolve (IMemberContext context, TypeParameter tp)
212                 {
213                         if (resolved)
214                                 return true;
215
216                         if (resolving)
217                                 return false;
218
219                         resolving = true;
220                         var spec = tp.Type;
221                         List<TypeParameterSpec> tparam_types = null;
222                         bool iface_found = false;
223
224                         spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
225
226                         for (int i = 0; i < constraints.Count; ++i) {
227                                 var constraint = constraints[i];
228
229                                 if (constraint is SpecialContraintExpr) {
230                                         spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
231                                         if (spec.HasSpecialStruct)
232                                                 spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
233
234                                         // Set to null as it does not have a type
235                                         constraints[i] = null;
236                                         continue;
237                                 }
238
239                                 var type = constraint.ResolveAsType (context);
240                                 if (type == null)
241                                         continue;
242
243                                 if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
244                                         context.Module.Compiler.Report.Error (1968, constraint.Location,
245                                                 "A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
246                                         continue;
247                                 }
248
249                                 if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
250                                         context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
251                                         context.Module.Compiler.Report.Error (703, loc,
252                                                 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
253                                                 type.GetSignatureForError (), context.GetSignatureForError ());
254                                 }
255
256                                 if (type.IsInterface) {
257                                         if (!spec.AddInterface (type)) {
258                                                 context.Module.Compiler.Report.Error (405, constraint.Location,
259                                                         "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
260                                         }
261
262                                         iface_found = true;
263                                         continue;
264                                 }
265                                         
266                                 var constraint_tp = type as TypeParameterSpec;
267                                 if (constraint_tp != null) {
268                                         if (tparam_types == null) {
269                                                 tparam_types = new List<TypeParameterSpec> (2);
270                                         } else if (tparam_types.Contains (constraint_tp)) {
271                                                 context.Module.Compiler.Report.Error (405, constraint.Location,
272                                                         "Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
273                                                 continue;
274                                         }
275
276                                         //
277                                         // Checks whether each generic method parameter constraint type
278                                         // is valid with respect to T
279                                         //
280                                         if (tp.IsMethodTypeParameter) {
281                                                 VarianceDecl.CheckTypeVariance (type, Variance.Contravariant, context);
282                                         }
283
284                                         var tp_def = constraint_tp.MemberDefinition as TypeParameter;
285                                         if (tp_def != null && !tp_def.ResolveConstraints (context)) {
286                                                 context.Module.Compiler.Report.Error (454, constraint.Location,
287                                                         "Circular constraint dependency involving `{0}' and `{1}'",
288                                                         constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
289                                                 continue;
290                                         }
291
292                                         //
293                                         // Checks whether there are no conflicts between type parameter constraints
294                                         //
295                                         // class Foo<T, U>
296                                         //      where T : A
297                                         //      where U : B, T
298                                         //
299                                         // A and B are not convertible and only 1 class constraint is allowed
300                                         //
301                                         if (constraint_tp.HasTypeConstraint) {
302                                                 if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
303                                                         if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
304                                                                 continue;
305                                                 } else {
306                                                         for (int ii = 0; ii < tparam_types.Count; ++ii) {
307                                                                 if (!tparam_types[ii].HasTypeConstraint)
308                                                                         continue;
309
310                                                                 if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
311                                                                         break;
312                                                         }
313                                                 }
314                                         }
315
316                                         if (constraint_tp.TypeArguments != null) {
317                                                 var eb = constraint_tp.GetEffectiveBase ();
318                                                 if (eb != null && !CheckConflictingInheritedConstraint (spec, eb, spec.BaseType, context, constraint.Location))
319                                                         break;
320                                         }
321
322                                         if (constraint_tp.HasSpecialStruct) {
323                                                 context.Module.Compiler.Report.Error (456, constraint.Location,
324                                                         "Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
325                                                         constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
326                                                 continue;
327                                         }
328
329                                         tparam_types.Add (constraint_tp);
330                                         continue;
331                                 }
332
333                                 if (iface_found || spec.HasTypeConstraint) {
334                                         context.Module.Compiler.Report.Error (406, constraint.Location,
335                                                 "The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
336                                                 type.GetSignatureForError ());
337                                 }
338
339                                 if (spec.HasSpecialStruct || spec.HasSpecialClass) {
340                                         context.Module.Compiler.Report.Error (450, constraint.Location,
341                                                 "`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
342                                                 type.GetSignatureForError ());
343                                 }
344
345                                 switch (type.BuiltinType) {
346                                 case BuiltinTypeSpec.Type.Array:
347                                 case BuiltinTypeSpec.Type.Delegate:
348                                 case BuiltinTypeSpec.Type.MulticastDelegate:
349                                 case BuiltinTypeSpec.Type.Enum:
350                                 case BuiltinTypeSpec.Type.ValueType:
351                                 case BuiltinTypeSpec.Type.Object:
352                                         context.Module.Compiler.Report.Error (702, constraint.Location,
353                                                 "A constraint cannot be special class `{0}'", type.GetSignatureForError ());
354                                         continue;
355                                 case BuiltinTypeSpec.Type.Dynamic:
356                                         context.Module.Compiler.Report.Error (1967, constraint.Location,
357                                                 "A constraint cannot be the dynamic type");
358                                         continue;
359                                 }
360
361                                 if (type.IsSealed || !type.IsClass) {
362                                         context.Module.Compiler.Report.Error (701, loc,
363                                                 "`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
364                                                 type.GetSignatureForError ());
365                                         continue;
366                                 }
367
368                                 if (type.IsStatic) {
369                                         context.Module.Compiler.Report.Error (717, constraint.Location,
370                                                 "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
371                                                 type.GetSignatureForError ());
372                                 }
373
374                                 spec.BaseType = type;
375                         }
376
377                         if (tparam_types != null)
378                                 spec.TypeArguments = tparam_types.ToArray ();
379
380                         resolving = false;
381                         resolved = true;
382                         return true;
383                 }
384
385                 public void VerifyClsCompliance (Report report)
386                 {
387                         foreach (var c in constraints)
388                         {
389                                 if (c == null)
390                                         continue;
391
392                                 if (!c.Type.IsCLSCompliant ()) {
393                                         report.SymbolRelatedToPreviousError (c.Type);
394                                         report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
395                                                 c.Type.GetSignatureForError ());
396                                 }
397                         }
398                 }
399         }
400
401         //
402         // A type parameter for a generic type or generic method definition
403         //
404         public class TypeParameter : MemberCore, ITypeDefinition
405         {
406                 static readonly string[] attribute_target = { "type parameter" };
407                 
408                 Constraints constraints;
409                 GenericTypeParameterBuilder builder;
410                 readonly TypeParameterSpec spec;
411
412                 public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance Variance)
413                         : base (null, name, attrs)
414                 {
415                         this.constraints = constraints;
416                         this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, Variance, null);
417                 }
418
419                 //
420                 // Used by parser
421                 //
422                 public TypeParameter (MemberName name, Attributes attrs, VarianceDecl variance)
423                         : base (null, name, attrs)
424                 {
425                         var var = variance == null ? Variance.None : variance.Variance;
426                         this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, var, null);
427                         this.VarianceDecl = variance;
428                 }
429                 
430                 public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
431                         : base (null, name, attrs)
432                 {
433                         this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
434                                 BaseType = spec.BaseType,
435                                 InterfacesDefined = spec.InterfacesDefined,
436                                 TypeArguments = spec.TypeArguments
437                         };
438                 }
439                 
440                 #region Properties
441
442                 public override AttributeTargets AttributeTargets {
443                         get {
444                                 return AttributeTargets.GenericParameter;
445                         }
446                 }
447
448                 public Constraints Constraints {
449                         get {
450                                 return constraints;
451                         }
452                         set {
453                                 constraints = value;
454                         }
455                 }
456
457                 public IAssemblyDefinition DeclaringAssembly {
458                         get     {
459                                 return Module.DeclaringAssembly;
460                         }
461                 }
462
463                 public override string DocCommentHeader {
464                         get {
465                                 throw new InvalidOperationException (
466                                         "Unexpected attempt to get doc comment from " + this.GetType ());
467                         }
468                 }
469
470                 bool ITypeDefinition.IsComImport {
471                         get {
472                                 return false;
473                         }
474                 }
475
476                 bool ITypeDefinition.IsPartial {
477                         get {
478                                 return false;
479                         }
480                 }
481
482                 public bool IsMethodTypeParameter {
483                         get {
484                                 return spec.IsMethodOwned;
485                         }
486                 }
487
488                 bool ITypeDefinition.IsTypeForwarder {
489                         get {
490                                 return false;
491                         }
492                 }
493
494                 bool ITypeDefinition.IsCyclicTypeForwarder {
495                         get {
496                                 return false;
497                         }
498                 }
499
500                 public string Name {
501                         get {
502                                 return MemberName.Name;
503                         }
504                 }
505
506                 public string Namespace {
507                         get {
508                                 return null;
509                         }
510                 }
511
512                 public TypeParameterSpec Type {
513                         get {
514                                 return spec;
515                         }
516                 }
517
518                 public int TypeParametersCount {
519                         get {
520                                 return 0;
521                         }
522                 }
523
524                 public TypeParameterSpec[] TypeParameters {
525                         get {
526                                 return null;
527                         }
528                 }
529
530                 public override string[] ValidAttributeTargets {
531                         get {
532                                 return attribute_target;
533                         }
534                 }
535
536                 public Variance Variance {
537                         get {
538                                 return spec.Variance;
539                         }
540                 }
541
542                 public VarianceDecl VarianceDecl { get; private set; }
543
544                 #endregion
545
546                 //
547                 // This is called for each part of a partial generic type definition.
548                 //
549                 // If partial type parameters constraints are not null and we don't
550                 // already have constraints they become our constraints. If we already
551                 // have constraints, we must check that they're same.
552                 //
553                 public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
554                 {
555                         if (builder == null)
556                                 throw new InvalidOperationException ();
557
558                         var new_constraints = tp.constraints;
559                         if (new_constraints == null)
560                                 return true;
561
562                         // TODO: could create spec only
563                         //tp.Define (null, -1, part.Definition);
564                         tp.spec.DeclaringType = part.Definition;
565                         if (!tp.ResolveConstraints (part))
566                                 return false;
567
568                         if (constraints != null)
569                                 return spec.HasSameConstraintsDefinition (tp.Type);
570
571                         // Copy constraint from resolved part to partial container
572                         spec.SpecialConstraint = tp.spec.SpecialConstraint;
573                         spec.InterfacesDefined = tp.spec.InterfacesDefined;
574                         spec.TypeArguments = tp.spec.TypeArguments;
575                         spec.BaseType = tp.spec.BaseType;
576                         
577                         return true;
578                 }
579
580                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
581                 {
582                         builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
583                 }
584
585                 public void CheckGenericConstraints (bool obsoleteCheck)
586                 {
587                         if (constraints != null)
588                                 constraints.CheckGenericConstraints (this, obsoleteCheck);
589                 }
590
591                 public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
592                 {
593                         return new TypeParameter (spec, declaringSpec, MemberName, null);
594                 }
595
596                 public override bool Define ()
597                 {
598                         return true;
599                 }
600
601                 //
602                 // This is the first method which is called during the resolving
603                 // process; we're called immediately after creating the type parameters
604                 // with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
605                 // MethodBuilder).
606                 //
607                 public void Create (TypeSpec declaringType, TypeContainer parent)
608                 {
609                         if (builder != null)
610                                 throw new InternalErrorException ();
611
612                         // Needed to get compiler reference
613                         this.Parent = parent;
614                         spec.DeclaringType = declaringType;
615                 }
616
617                 public void Define (GenericTypeParameterBuilder type)
618                 {
619                         this.builder = type;
620                         spec.SetMetaInfo (type);
621                 }
622
623                 public void Define (TypeParameter tp)
624                 {
625                         builder = tp.builder;
626                 }
627
628                 public void EmitConstraints (GenericTypeParameterBuilder builder)
629                 {
630                         var attr = GenericParameterAttributes.None;
631                         if (spec.Variance == Variance.Contravariant)
632                                 attr |= GenericParameterAttributes.Contravariant;
633                         else if (spec.Variance == Variance.Covariant)
634                                 attr |= GenericParameterAttributes.Covariant;
635
636                         if (spec.HasSpecialClass)
637                                 attr |= GenericParameterAttributes.ReferenceTypeConstraint;
638                         else if (spec.HasSpecialStruct)
639                                 attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
640
641                         if (spec.HasSpecialConstructor)
642                                 attr |= GenericParameterAttributes.DefaultConstructorConstraint;
643
644                         if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
645                                 builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
646
647                         if (spec.InterfacesDefined != null)
648                                 builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
649
650                         if (spec.TypeArguments != null) {
651                                 var meta_constraints = new List<MetaType> (spec.TypeArguments.Length);
652                                 foreach (var c in spec.TypeArguments) {
653                                         //
654                                         // Inflated type parameters can collide with special constraint types, don't
655                                         // emit any such type parameter.
656                                         //
657                                         if (c.BuiltinType == BuiltinTypeSpec.Type.Object || c.BuiltinType == BuiltinTypeSpec.Type.ValueType)
658                                                 continue;
659
660                                         meta_constraints.Add (c.GetMetaInfo ());
661                                 }
662
663                                 builder.SetInterfaceConstraints (meta_constraints.ToArray ());
664                         }
665
666                         builder.SetGenericParameterAttributes (attr);
667                 }
668
669                 public override void Emit ()
670                 {
671                         EmitConstraints (builder);
672
673                         if (OptAttributes != null)
674                                 OptAttributes.Emit ();
675
676                         base.Emit ();
677                 }
678
679                 public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
680                 {
681                         Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
682                         string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
683                         string gtype_variance;
684                         switch (expected) {
685                         case Variance.Contravariant: gtype_variance = "contravariantly"; break;
686                         case Variance.Covariant: gtype_variance = "covariantly"; break;
687                         default: gtype_variance = "invariantly"; break;
688                         }
689
690                         Delegate d = mc as Delegate;
691                         string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
692
693                         Report.Error (1961, Location,
694                                 "The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
695                                         GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
696                 }
697
698                 public TypeSpec GetAttributeCoClass ()
699                 {
700                         return null;
701                 }
702
703                 public string GetAttributeDefaultMember ()
704                 {
705                         throw new NotSupportedException ();
706                 }
707
708                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
709                 {
710                         throw new NotSupportedException ();
711                 }
712
713                 public override string GetSignatureForDocumentation ()
714                 {
715                         throw new NotImplementedException ();
716                 }
717
718                 public override string GetSignatureForError ()
719                 {
720                         return MemberName.Name;
721                 }
722
723                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
724                 {
725                         return spec.MemberDefinition.DeclaringAssembly == assembly;
726                 }
727
728                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
729                 {
730                         throw new NotSupportedException ("Not supported for compiled definition");
731                 }
732
733                 //
734                 // Resolves all type parameter constraints
735                 //
736                 public bool ResolveConstraints (IMemberContext context)
737                 {
738                         if (constraints != null)
739                                 return constraints.Resolve (context, this);
740
741                         if (spec.BaseType == null)
742                                 spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
743
744                         return true;
745                 }
746
747                 public override bool IsClsComplianceRequired ()
748                 {
749                         return false;
750                 }
751
752                 public new void VerifyClsCompliance ()
753                 {
754                         if (constraints != null)
755                                 constraints.VerifyClsCompliance (Report);
756                 }
757
758                 public void WarningParentNameConflict (TypeParameter conflict)
759                 {
760                         conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
761                         conflict.Report.Warning (693, 3, Location,
762                                 "Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
763                                 GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
764                 }
765         }
766
767         [System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
768         public class TypeParameterSpec : TypeSpec
769         {
770                 public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
771
772                 Variance variance;
773                 SpecialConstraint spec;
774                 int tp_pos;
775                 TypeSpec[] targs;
776                 TypeSpec[] ifaces_defined;
777                 TypeSpec effective_base;
778
779                 //
780                 // Creates type owned type parameter
781                 //
782                 public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
783                         : base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
784                 {
785                         this.variance = variance;
786                         this.spec = spec;
787                         state &= ~StateFlags.Obsolete_Undetected;
788                         tp_pos = index;
789                 }
790
791                 //
792                 // Creates method owned type parameter
793                 //
794                 public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
795                         : this (null, index, definition, spec, variance, info)
796                 {
797                 }
798
799                 #region Properties
800
801                 public int DeclaredPosition {
802                         get {
803                                 return tp_pos;
804                         }
805                         set {
806                                 tp_pos = value;
807                         }
808                 }
809
810                 public bool HasSpecialConstructor {
811                         get {
812                                 return (spec & SpecialConstraint.Constructor) != 0;
813                         }
814                 }
815
816                 public bool HasSpecialClass {
817                         get {
818                                 return (spec & SpecialConstraint.Class) != 0;
819                         }
820                 }
821
822                 public bool HasSpecialStruct {
823                         get {
824                                 return (spec & SpecialConstraint.Struct) != 0;
825                         }
826                 }
827
828                 public bool HasAnyTypeConstraint {
829                         get {
830                                 return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
831                         }
832                 }
833
834                 public bool HasTypeConstraint {
835                         get {
836                                 var bt = BaseType.BuiltinType;
837                                 return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
838                         }
839                 }
840
841                 public override IList<TypeSpec> Interfaces {
842                         get {
843                                 if ((state & StateFlags.InterfacesExpanded) == 0) {
844                                         if (ifaces != null) {
845                                                 if (ifaces_defined == null)
846                                                         ifaces_defined = ifaces.ToArray ();
847
848                                                 for (int i = 0; i < ifaces_defined.Length; ++i ) {
849                                                         var iface_type = ifaces_defined[i];
850                                                         var td = iface_type.MemberDefinition as TypeDefinition;
851                                                         if (td != null)
852                                                                 td.DoExpandBaseInterfaces ();
853
854                                                         if (iface_type.Interfaces != null) {
855                                                                 for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
856                                                                         var ii_iface_type = iface_type.Interfaces [ii];
857                                                                         AddInterface (ii_iface_type);
858                                                                 }
859                                                         }
860                                                 }
861                                         } else if (ifaces_defined == null) {
862                                                 ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
863                                         }
864
865                                         //
866                                         // Include all base type interfaces too, see ImportTypeBase for details
867                                         //
868                                         if (BaseType != null) {
869                                                 var td = BaseType.MemberDefinition as TypeDefinition;
870                                                 if (td != null)
871                                                         td.DoExpandBaseInterfaces ();
872
873                                                 if (BaseType.Interfaces != null) {
874                                                         foreach (var iface in BaseType.Interfaces) {
875                                                                 AddInterface (iface);
876                                                         }
877                                                 }
878                                         }
879
880                                         state |= StateFlags.InterfacesExpanded;
881                                 }
882
883                                 return ifaces;
884                         }
885                 }
886
887                 //
888                 // Unexpanded interfaces list
889                 //
890                 public TypeSpec[] InterfacesDefined {
891                         get {
892                                 if (ifaces_defined == null) {
893                                         ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
894                                 }
895
896                                 return ifaces_defined.Length == 0 ? null : ifaces_defined;
897                         }
898                         set {
899                                 ifaces_defined = value;
900                                 if (value != null && value.Length != 0)
901                                         ifaces = new List<TypeSpec> (value);
902                         }
903                 }
904
905                 public bool IsConstrained {
906                         get {
907                                 return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
908                         }
909                 }
910
911                 //
912                 // Returns whether the type parameter is known to be a reference type
913                 //
914                 public new bool IsReferenceType {
915                         get {
916                                 if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
917                                         return (spec & SpecialConstraint.Class) != 0;
918
919                                 //
920                                 // Full check is needed (see IsValueType for details)
921                                 //
922                                 if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
923                                         return true;
924
925                                 if (targs != null) {
926                                         foreach (var ta in targs) {
927                                                 //
928                                                 // Secondary special constraints are ignored (I am not sure why)
929                                                 //
930                                                 var tp = ta as TypeParameterSpec;
931                                                 if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
932                                                         continue;
933
934                                                 if (TypeSpec.IsReferenceType (ta))
935                                                         return true;
936                                         }
937                                 }
938
939                                 return false;
940                         }
941                 }
942
943                 //
944                 // Returns whether the type parameter is known to be a value type
945                 //
946                 public new bool IsValueType {
947                         get {
948                                 //
949                                 // Even if structs/enums cannot be used directly as constraints
950                                 // they can apear as constraint type when inheriting base constraint
951                                 // which has dependant type parameter constraint which has been
952                                 // inflated using value type
953                                 //
954                                 // class A : B<int> { override void Foo<U> () {} }
955                                 // class B<T> { virtual void Foo<U> () where U : T {} }
956                                 //
957                                 if (HasSpecialStruct)
958                                         return true;
959
960                                 if (targs != null) {
961                                         foreach (var ta in targs) {
962                                                 if (TypeSpec.IsValueType (ta))
963                                                         return true;
964                                         }
965                                 }
966
967                                 return false;
968                         }
969                 }
970
971                 public override string Name {
972                         get {
973                                 return definition.Name;
974                         }
975                 }
976
977                 public bool IsMethodOwned {
978                         get {
979                                 return DeclaringType == null;
980                         }
981                 }
982
983                 public SpecialConstraint SpecialConstraint {
984                         get {
985                                 return spec;
986                         }
987                         set {
988                                 spec = value;
989                         }
990                 }
991
992                 //
993                 // Types used to inflate the generic type
994                 //
995                 public new TypeSpec[] TypeArguments {
996                         get {
997                                 return targs;
998                         }
999                         set {
1000                                 targs = value;
1001                         }
1002                 }
1003
1004                 public Variance Variance {
1005                         get {
1006                                 return variance;
1007                         }
1008                 }
1009
1010                 #endregion
1011
1012                 public string DisplayDebugInfo ()
1013                 {
1014                         var s = GetSignatureForError ();
1015                         return IsMethodOwned ? s + "!!" : s + "!";
1016                 }
1017
1018                 //
1019                 // Finds effective base class. The effective base class is always a class-type
1020                 //
1021                 public TypeSpec GetEffectiveBase ()
1022                 {
1023                         if (HasSpecialStruct)
1024                                 return BaseType;
1025
1026                         //
1027                         // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
1028                         //
1029                         if (BaseType != null && targs == null) {
1030                                 //
1031                                 // If T has a constraint V that is a value-type, use instead the most specific base type of V that is a class-type.
1032                                 // 
1033                                 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
1034                                 //
1035                                 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
1036                                 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
1037                                 //
1038                                 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
1039                         }
1040
1041                         if (effective_base != null)
1042                                 return effective_base;
1043
1044                         var types = new TypeSpec [HasTypeConstraint ? targs.Length + 1 : targs.Length];
1045
1046                         for (int i = 0; i < targs.Length; ++i) {
1047                                 var t = targs [i];
1048
1049                                 // Same issue as above, inherited constraints can be of struct type
1050                                 if (t.IsStruct) {
1051                                         types [i] = t.BaseType;
1052                                         continue;
1053                                 }
1054
1055                                 types [i] = ((TypeParameterSpec)t).GetEffectiveBase ();
1056                         }
1057
1058                         if (HasTypeConstraint)
1059                                 types [types.Length - 1] = BaseType;
1060
1061                         return effective_base = Convert.FindMostEncompassedType (types);
1062                 }
1063
1064                 public override string GetSignatureForDocumentation ()
1065                 {
1066                         var prefix = IsMethodOwned ? "``" : "`";
1067                         return prefix + DeclaredPosition;
1068                 }
1069
1070                 public override string GetSignatureForError ()
1071                 {
1072                         return Name;
1073                 }
1074
1075                 //
1076                 // Constraints have to match by definition but not position, used by
1077                 // partial classes or methods
1078                 //
1079                 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
1080                 {
1081                         if (spec != other.spec)
1082                                 return false;
1083
1084                         if (BaseType != other.BaseType)
1085                                 return false;
1086
1087                         if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
1088                                 return false;
1089
1090                         if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
1091                                 return false;
1092
1093                         return true;
1094                 }
1095
1096                 //
1097                 // Constraints have to match by using same set of types, used by
1098                 // implicit interface implementation
1099                 //
1100                 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
1101                 {
1102                         if (spec != other.spec)
1103                                 return false;
1104
1105                         //
1106                         // It can be same base type or inflated type parameter
1107                         //
1108                         // interface I<T> { void Foo<U> where U : T; }
1109                         // class A : I<int> { void Foo<X> where X : int {} }
1110                         //
1111                         bool found;
1112                         if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
1113                                 if (other.targs == null)
1114                                         return false;
1115
1116                                 found = false;
1117                                 foreach (var otarg in other.targs) {
1118                                         if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1119                                                 found = true;
1120                                                 break;
1121                                         }
1122                                 }
1123
1124                                 if (!found)
1125                                         return false;
1126                         }
1127
1128                         // Check interfaces implementation -> definition
1129                         if (InterfacesDefined != null) {
1130                                 //
1131                                 // Iterate over inflated interfaces
1132                                 //
1133                                 foreach (var iface in Interfaces) {
1134                                         found = false;
1135                                         if (other.InterfacesDefined != null) {
1136                                                 foreach (var oiface in other.Interfaces) {
1137                                                         if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1138                                                                 found = true;
1139                                                                 break;
1140                                                         }
1141                                                 }
1142                                         }
1143
1144                                         if (found)
1145                                                 continue;
1146
1147                                         if (other.targs != null) {
1148                                                 foreach (var otarg in other.targs) {
1149                                                         if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1150                                                                 found = true;
1151                                                                 break;
1152                                                         }
1153                                                 }
1154                                         }
1155
1156                                         if (!found)
1157                                                 return false;
1158                                 }
1159                         }
1160
1161                         // Check interfaces implementation <- definition
1162                         if (other.InterfacesDefined != null) {
1163                                 if (InterfacesDefined == null)
1164                                         return false;
1165
1166                                 //
1167                                 // Iterate over inflated interfaces
1168                                 //
1169                                 foreach (var oiface in other.Interfaces) {
1170                                         found = false;
1171                                         foreach (var iface in Interfaces) {
1172                                                 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1173                                                         found = true;
1174                                                         break;
1175                                                 }
1176                                         }
1177
1178                                         if (!found)
1179                                                 return false;
1180                                 }
1181                         }
1182
1183                         // Check type parameters implementation -> definition
1184                         if (targs != null) {
1185                                 if (other.targs == null)
1186                                         return false;
1187
1188                                 foreach (var targ in targs) {
1189                                         found = false;
1190                                         foreach (var otarg in other.targs) {
1191                                                 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1192                                                         found = true;
1193                                                         break;
1194                                                 }
1195                                         }
1196
1197                                         if (!found)
1198                                                 return false;
1199                                 }
1200                         }
1201
1202                         // Check type parameters implementation <- definition
1203                         if (other.targs != null) {
1204                                 foreach (var otarg in other.targs) {
1205                                         // Ignore inflated type arguments, were checked above
1206                                         if (!otarg.IsGenericParameter)
1207                                                 continue;
1208
1209                                         if (targs == null)
1210                                                 return false;
1211
1212                                         found = false;
1213                                         foreach (var targ in targs) {
1214                                                 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1215                                                         found = true;
1216                                                         break;
1217                                                 }
1218                                         }
1219
1220                                         if (!found)
1221                                                 return false;
1222                                 }                               
1223                         }
1224
1225                         return true;
1226                 }
1227
1228                 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1229                 {
1230                         return InflateConstraints (tparams, l => l, inflator);
1231                 }
1232
1233                 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1234                 {
1235                         TypeParameterSpec[] constraints = null;
1236                         TypeParameterInflator? inflator = null;
1237
1238                         for (int i = 0; i < tparams.Length; ++i) {
1239                                 var tp = tparams[i];
1240                                 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1241                                         if (constraints == null) {
1242                                                 constraints = new TypeParameterSpec[tparams.Length];
1243                                                 Array.Copy (tparams, constraints, constraints.Length);
1244                                         }
1245
1246                                         //
1247                                         // Using a factory to avoid possibly expensive inflator build up
1248                                         //
1249                                         if (inflator == null)
1250                                                 inflator = inflatorFactory (arg);
1251
1252                                         constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1253                                 }
1254                         }
1255
1256                         if (constraints == null)
1257                                 constraints = tparams;
1258
1259                         return constraints;
1260                 }
1261
1262                 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1263                 {
1264                         tps.BaseType = inflator.Inflate (BaseType);
1265
1266                         var defined = InterfacesDefined;
1267                         if (defined != null) {
1268                                 tps.ifaces_defined = new TypeSpec[defined.Length];
1269                                 for (int i = 0; i < defined.Length; ++i)
1270                                         tps.ifaces_defined [i] = inflator.Inflate (defined[i]);
1271                         } else if (ifaces_defined == TypeSpec.EmptyTypes) {
1272                                 tps.ifaces_defined = TypeSpec.EmptyTypes;
1273                         }
1274
1275                         var ifaces = Interfaces;
1276                         if (ifaces != null) {
1277                                 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1278                                 for (int i = 0; i < ifaces.Count; ++i)
1279                                         tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1280                                 tps.state |= StateFlags.InterfacesExpanded;
1281                         }
1282
1283                         if (targs != null) {
1284                                 tps.targs = new TypeSpec[targs.Length];
1285                                 for (int i = 0; i < targs.Length; ++i)
1286                                         tps.targs[i] = inflator.Inflate (targs[i]);
1287                         }
1288                 }
1289
1290                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1291                 {
1292                         var tps = (TypeParameterSpec) MemberwiseClone ();
1293 #if DEBUG
1294                         tps.ID += 1000000;
1295 #endif
1296
1297                         InflateConstraints (inflator, tps);
1298                         return tps;
1299                 }
1300
1301                 //
1302                 // Populates type parameter members using type parameter constraints
1303                 // The trick here is to be called late enough but not too late to
1304                 // populate member cache with all members from other types
1305                 //
1306                 protected override void InitializeMemberCache (bool onlyTypes)
1307                 {
1308                         cache = new MemberCache ();
1309
1310                         //
1311                         // For a type parameter the membercache is the union of the sets of members of the types
1312                         // specified as a primary constraint or secondary constraint
1313                         //
1314                         if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1315                                 cache.AddBaseType (BaseType);
1316
1317                         if (InterfacesDefined != null) {
1318                                 foreach (var iface_type in InterfacesDefined) {
1319                                         cache.AddInterface (iface_type);
1320                                 }
1321                         }
1322
1323                         if (targs != null) {
1324                                 foreach (var ta in targs) {
1325                                         var tps = ta as TypeParameterSpec;
1326                                         IList<TypeSpec> ifaces;
1327                                         if (tps != null) {
1328                                                 var b_type = tps.GetEffectiveBase ();
1329                                                 if (b_type != null && b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1330                                                         cache.AddBaseType (b_type);
1331
1332                                                 ifaces = tps.InterfacesDefined;
1333                                         } else {
1334                                                 ifaces = ta.Interfaces;
1335                                         }
1336
1337                                         if (ifaces != null) {
1338                                                 foreach (var iface_type in ifaces) {
1339                                                         cache.AddInterface (iface_type);
1340                                                 }
1341                                         }
1342                                 }
1343                         }
1344                 }
1345
1346                 public bool IsConvertibleToInterface (TypeSpec iface)
1347                 {
1348                         if (Interfaces != null) {
1349                                 foreach (var t in Interfaces) {
1350                                         if (t == iface)
1351                                                 return true;
1352                                 }
1353                         }
1354
1355                         if (TypeArguments != null) {
1356                                 foreach (var t in TypeArguments) {
1357                                         var tps = t as TypeParameterSpec;
1358                                         if (tps != null) {
1359                                                 if (tps.IsConvertibleToInterface (iface))
1360                                                         return true;
1361
1362                                                 continue;
1363                                         }
1364
1365                                         if (t.ImplementsInterface (iface, false))
1366                                                 return true;
1367                                 }
1368                         }
1369
1370                         return false;
1371                 }
1372
1373                 public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
1374                 {
1375                         var tps = md.TypeParameters;
1376                         for (int i = 0; i < md.TypeParametersCount; ++i) {
1377                                 if (tps[i].HasAnyTypeConstraint) {
1378                                         return true;
1379                                 }
1380                         }
1381
1382                         return false;
1383                 }
1384
1385                 public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
1386                 {
1387                         var tps = md.TypeParameters;
1388                         for (int i = 0; i < md.TypeParametersCount; ++i) {
1389                                 if (tps[i].IsConstrained) {
1390                                         return true;
1391                                 }
1392                         }
1393
1394                         return false;
1395                 }
1396
1397                 public bool HasDependencyOn (TypeSpec type)
1398                 {
1399                         if (TypeArguments != null) {
1400                                 foreach (var targ in TypeArguments) {
1401                                         if (TypeSpecComparer.Override.IsEqual (targ, type))
1402                                                 return true;
1403
1404                                         var tps = targ as TypeParameterSpec;
1405                                         if (tps != null && tps.HasDependencyOn (type))
1406                                                 return true;
1407                                 }
1408                         }
1409
1410                         return false;
1411                 }
1412
1413                 public override TypeSpec Mutate (TypeParameterMutator mutator)
1414                 {
1415                         return mutator.Mutate (this);
1416                 }
1417         }
1418
1419         public struct TypeParameterInflator
1420         {
1421                 readonly TypeSpec type;
1422                 readonly TypeParameterSpec[] tparams;
1423                 readonly TypeSpec[] targs;
1424                 readonly IModuleContext context;
1425
1426                 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1427                         : this (nested.context, type, nested.tparams, nested.targs)
1428                 {
1429                 }
1430
1431                 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1432                 {
1433                         if (tparams.Length != targs.Length)
1434                                 throw new ArgumentException ("Invalid arguments");
1435
1436                         this.context = context;
1437                         this.tparams = tparams;
1438                         this.targs = targs;
1439                         this.type = type;
1440                 }
1441
1442                 #region Properties
1443
1444                 public IModuleContext Context {
1445                         get {
1446                                 return context;
1447                         }
1448                 }
1449
1450                 public TypeSpec TypeInstance {
1451                         get {
1452                                 return type;
1453                         }
1454                 }
1455
1456                 //
1457                 // Type parameters to inflate
1458                 //
1459                 public TypeParameterSpec[] TypeParameters {
1460                         get {
1461                                 return tparams;
1462                         }
1463                 }
1464
1465                 #endregion
1466
1467                 public TypeSpec Inflate (TypeSpec type)
1468                 {
1469                         var tp = type as TypeParameterSpec;
1470                         if (tp != null)
1471                                 return Inflate (tp);
1472
1473                         var ec = type as ElementTypeSpec;
1474                         if (ec != null) {
1475                                 var et = Inflate (ec.Element);
1476                                 if (et != ec.Element) {
1477                                         var ac = ec as ArrayContainer;
1478                                         if (ac != null)
1479                                                 return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1480
1481                                         throw new NotImplementedException ();
1482                                 }
1483
1484                                 return ec;
1485                         }
1486
1487                         if (type.Kind == MemberKind.MissingType)
1488                                 return type;
1489
1490                         //
1491                         // When inflating a nested type, inflate its parent first
1492                         // in case it's using same type parameters (was inflated within the type)
1493                         //
1494                         TypeSpec[] targs;
1495                         int i = 0;
1496                         if (type.IsNested) {
1497                                 var parent = Inflate (type.DeclaringType);
1498
1499                                 //
1500                                 // Keep the inflated type arguments
1501                                 // 
1502                                 targs = type.TypeArguments;
1503
1504                                 //
1505                                 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1506                                 // because the import cache helps us to catch it. However, that means we have to look at
1507                                 // type definition to get type argument (they are in fact type parameter in this case)
1508                                 //
1509                                 if (targs.Length == 0 && type.Arity > 0)
1510                                         targs = type.MemberDefinition.TypeParameters;
1511
1512                                 //
1513                                 // Parent was inflated, find the same type on inflated type
1514                                 // to use same cache for nested types on same generic parent
1515                                 //
1516                                 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1517
1518                                 //
1519                                 // Handle the tricky case where parent shares local type arguments
1520                                 // which means inflating inflated type
1521                                 //
1522                                 // class Test<T> {
1523                                 //              public static Nested<T> Foo () { return null; }
1524                                 //
1525                                 //              public class Nested<U> {}
1526                                 //      }
1527                                 //
1528                                 //  return type of Test<string>.Foo() has to be Test<string>.Nested<string> 
1529                                 //
1530                                 if (targs.Length > 0) {
1531                                         var inflated_targs = new TypeSpec[targs.Length];
1532                                         for (; i < targs.Length; ++i)
1533                                                 inflated_targs[i] = Inflate (targs[i]);
1534
1535                                         type = type.MakeGenericType (context, inflated_targs);
1536                                 }
1537
1538                                 return type;
1539                         }
1540
1541                         // Nothing to do for non-generic type
1542                         if (type.Arity == 0)
1543                                 return type;
1544
1545                         targs = new TypeSpec[type.Arity];
1546
1547                         //
1548                         // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1549                         //
1550                         if (type is InflatedTypeSpec) {
1551                                 for (; i < targs.Length; ++i)
1552                                         targs[i] = Inflate (type.TypeArguments[i]);
1553
1554                                 type = type.GetDefinition ();
1555                         } else {
1556                                 //
1557                                 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1558                                 //
1559                                 var args = type.MemberDefinition.TypeParameters;
1560                                 foreach (var ds_tp in args)
1561                                         targs[i++] = Inflate (ds_tp);
1562                         }
1563
1564                         return type.MakeGenericType (context, targs);
1565                 }
1566
1567                 public TypeSpec Inflate (TypeParameterSpec tp)
1568                 {
1569                         for (int i = 0; i < tparams.Length; ++i)
1570                                 if (tparams [i] == tp)
1571                                         return targs[i];
1572
1573                         // This can happen when inflating nested types
1574                         // without type arguments specified
1575                         return tp;
1576                 }
1577         }
1578
1579         //
1580         // Before emitting any code we have to change all MVAR references to VAR
1581         // when the method is of generic type and has hoisted variables
1582         //
1583         public class TypeParameterMutator
1584         {
1585                 readonly TypeParameters mvar;
1586                 readonly TypeParameters var;
1587                 readonly TypeParameterSpec[] src;
1588                 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1589
1590                 public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
1591                 {
1592                         if (mvar.Count != var.Count)
1593                                 throw new ArgumentException ();
1594
1595                         this.mvar = mvar;
1596                         this.var = var;
1597                 }
1598
1599                 public TypeParameterMutator (TypeParameterSpec[] srcVar, TypeParameters destVar)
1600                 {
1601                         if (srcVar.Length != destVar.Count)
1602                                 throw new ArgumentException ();
1603
1604                         this.src = srcVar;
1605                         this.var = destVar;
1606                 }
1607
1608                 #region Properties
1609
1610                 public TypeParameters MethodTypeParameters {
1611                         get {
1612                                 return mvar;
1613                         }
1614                 }
1615
1616                 #endregion
1617
1618                 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1619                 {
1620                         if (type is InflatedTypeSpec) {
1621                                 if (type.DeclaringType == null)
1622                                         return type.GetDefinition ();
1623
1624                                 var parent = GetMemberDeclaringType (type.DeclaringType);
1625                                 type = MemberCache.GetMember<TypeSpec> (parent, type);
1626                         }
1627
1628                         return type;
1629                 }
1630
1631                 public TypeSpec Mutate (TypeSpec ts)
1632                 {
1633                         TypeSpec value;
1634                         if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1635                                 return value;
1636
1637                         value = ts.Mutate (this);
1638                         if (mutated_typespec == null)
1639                                 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1640
1641                         mutated_typespec.Add (ts, value);
1642                         return value;
1643                 }
1644
1645                 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1646                 {
1647                         if (mvar != null) {
1648                                 for (int i = 0; i < mvar.Count; ++i) {
1649                                         if (mvar[i].Type == tp)
1650                                                 return var[i].Type;
1651                                 }
1652                         } else {
1653                                 for (int i = 0; i < src.Length; ++i) {
1654                                         if (src[i] == tp)
1655                                                 return var[i].Type;
1656                                 }
1657                         }
1658
1659                         return tp;
1660                 }
1661
1662                 public TypeSpec[] Mutate (TypeSpec[] targs)
1663                 {
1664                         TypeSpec[] mutated = new TypeSpec[targs.Length];
1665                         bool changed = false;
1666                         for (int i = 0; i < targs.Length; ++i) {
1667                                 mutated[i] = Mutate (targs[i]);
1668                                 changed |= targs[i] != mutated[i];
1669                         }
1670
1671                         return changed ? mutated : targs;
1672                 }
1673         }
1674
1675         /// <summary>
1676         ///   A TypeExpr which already resolved to a type parameter.
1677         /// </summary>
1678         public class TypeParameterExpr : TypeExpression
1679         {
1680                 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1681                         : base (type_parameter.Type, loc)
1682                 {
1683                         this.eclass = ExprClass.TypeParameter;
1684                 }
1685         }
1686
1687         public class InflatedTypeSpec : TypeSpec
1688         {
1689                 TypeSpec[] targs;
1690                 TypeParameterSpec[] constraints;
1691                 readonly TypeSpec open_type;
1692                 readonly IModuleContext context;
1693
1694                 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1695                         : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1696                 {
1697                         if (targs == null)
1698                                 throw new ArgumentNullException ("targs");
1699
1700                         this.state &= ~SharedStateFlags;
1701                         this.state |= (openType.state & SharedStateFlags);
1702
1703                         this.context = context;
1704                         this.open_type = openType;
1705                         this.targs = targs;
1706
1707                         foreach (var arg in targs) {
1708                                 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1709                                         state |= StateFlags.HasDynamicElement;
1710                                         break;
1711                                 }
1712                         }
1713
1714                         if (open_type.Kind == MemberKind.MissingType)
1715                                 MemberCache = MemberCache.Empty;
1716
1717                         if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1718                                 state |= StateFlags.ConstraintsChecked;
1719                 }
1720
1721                 #region Properties
1722
1723                 public override TypeSpec BaseType {
1724                         get {
1725                                 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1726                                         InitializeMemberCache (true);
1727
1728                                 return base.BaseType;
1729                         }
1730                 }
1731
1732                 //
1733                 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1734                 //
1735                 public TypeParameterSpec[] Constraints {
1736                         get {
1737                                 if (constraints == null) {
1738                                         constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1739                                 }
1740
1741                                 return constraints;
1742                         }
1743                 }
1744
1745                 //
1746                 // Used to cache expensive constraints validation on constructed types
1747                 //
1748                 public bool HasConstraintsChecked {
1749                         get {
1750                                 return (state & StateFlags.ConstraintsChecked) != 0;
1751                         }
1752                         set {
1753                                 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1754                         }
1755                 }
1756
1757                 public override IList<TypeSpec> Interfaces {
1758                         get {
1759                                 if (cache == null)
1760                                         InitializeMemberCache (true);
1761
1762                                 return base.Interfaces;
1763                         }
1764                 }
1765
1766                 public override bool IsExpressionTreeType {
1767                         get {
1768                                 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1769                         }
1770                 }
1771
1772                 public override bool IsArrayGenericInterface {
1773                         get {
1774                                 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1775                         }
1776                 }
1777
1778                 public override bool IsGenericTask {
1779                         get {
1780                                 return (open_type.state & StateFlags.GenericTask) != 0;
1781                         }
1782                 }
1783
1784                 public override bool IsNullableType {
1785                         get {
1786                                 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1787                         }
1788                 }
1789
1790                 //
1791                 // Types used to inflate the generic  type
1792                 //
1793                 public override TypeSpec[] TypeArguments {
1794                         get {
1795                                 return targs;
1796                         }
1797                 }
1798
1799                 #endregion
1800
1801                 public override bool AddInterface (TypeSpec iface)
1802                 {
1803                         var inflator = CreateLocalInflator (context);
1804                         iface = inflator.Inflate (iface);
1805                         if (iface == null)
1806                                 return false;
1807
1808                         return base.AddInterface (iface);
1809                 }
1810
1811                 public static bool ContainsTypeParameter (TypeSpec type)
1812                 {
1813                         if (type.Kind == MemberKind.TypeParameter)
1814                                 return true;
1815
1816                         var element_container = type as ElementTypeSpec;
1817                         if (element_container != null)
1818                                 return ContainsTypeParameter (element_container.Element);
1819
1820                         foreach (var t in type.TypeArguments) {
1821                                 if (ContainsTypeParameter (t)) {
1822                                         return true;
1823                                 }
1824                         }
1825
1826                         return false;
1827                 }
1828
1829                 public TypeParameterInflator CreateLocalInflator (IModuleContext context)
1830                 {
1831                         TypeParameterSpec[] tparams_full;
1832                         TypeSpec[] targs_full = targs;
1833                         if (IsNested) {
1834                                 //
1835                                 // Special case is needed when we are inflating an open type (nested type definition)
1836                                 // on inflated parent. Consider following case
1837                                 //
1838                                 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1839                                 //
1840                                 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1841                                 //
1842                                 List<TypeSpec> merged_targs = null;
1843                                 List<TypeParameterSpec> merged_tparams = null;
1844
1845                                 var type = DeclaringType;
1846
1847                                 do {
1848                                         if (type.TypeArguments.Length > 0) {
1849                                                 if (merged_targs == null) {
1850                                                         merged_targs = new List<TypeSpec> ();
1851                                                         merged_tparams = new List<TypeParameterSpec> ();
1852                                                         if (targs.Length > 0) {
1853                                                                 merged_targs.AddRange (targs);
1854                                                                 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1855                                                         }
1856                                                 }
1857                                                 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1858                                                 merged_targs.AddRange (type.TypeArguments);
1859                                         }
1860                                         type = type.DeclaringType;
1861                                 } while (type != null);
1862
1863                                 if (merged_targs != null) {
1864                                         // Type arguments are not in the right order but it should not matter in this case
1865                                         targs_full = merged_targs.ToArray ();
1866                                         tparams_full = merged_tparams.ToArray ();
1867                                 } else if (targs.Length == 0) {
1868                                         tparams_full = TypeParameterSpec.EmptyTypes;
1869                                 } else {
1870                                         tparams_full = open_type.MemberDefinition.TypeParameters;
1871                                 }
1872                         } else if (targs.Length == 0) {
1873                                 tparams_full = TypeParameterSpec.EmptyTypes;
1874                         } else {
1875                                 tparams_full = open_type.MemberDefinition.TypeParameters;
1876                         }
1877
1878                         return new TypeParameterInflator (context, this, tparams_full, targs_full);
1879                 }
1880
1881                 MetaType CreateMetaInfo ()
1882                 {
1883                         //
1884                         // Converts nested type arguments into right order
1885                         // Foo<string, bool>.Bar<int> => string, bool, int
1886                         //
1887                         var all = new List<MetaType> ();
1888                         TypeSpec type = this;
1889                         TypeSpec definition = type;
1890                         do {
1891                                 if (type.GetDefinition().IsGeneric) {
1892                                         all.InsertRange (0,
1893                                                 type.TypeArguments != TypeSpec.EmptyTypes ?
1894                                                 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1895                                                 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1896                                 }
1897
1898                                 definition = definition.GetDefinition ();
1899                                 type = type.DeclaringType;
1900                         } while (type != null);
1901
1902                         return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1903                 }
1904
1905                 public override ObsoleteAttribute GetAttributeObsolete ()
1906                 {
1907                         return open_type.GetAttributeObsolete ();
1908                 }
1909
1910                 protected override bool IsNotCLSCompliant (out bool attrValue)
1911                 {
1912                         if (base.IsNotCLSCompliant (out attrValue))
1913                                 return true;
1914
1915                         foreach (var ta in TypeArguments) {
1916                                 if (ta.MemberDefinition.CLSAttributeValue == false)
1917                                         return true;
1918                         }
1919
1920                         return false;
1921                 }
1922
1923                 public override TypeSpec GetDefinition ()
1924                 {
1925                         return open_type;
1926                 }
1927
1928                 public override MetaType GetMetaInfo ()
1929                 {
1930                         if (info == null)
1931                                 info = CreateMetaInfo ();
1932
1933                         return info;
1934                 }
1935
1936                 public override string GetSignatureForError ()
1937                 {
1938                         if (IsNullableType)
1939                                 return targs[0].GetSignatureForError () + "?";
1940
1941                         return base.GetSignatureForError ();
1942                 }
1943
1944                 protected override string GetTypeNameSignature ()
1945                 {
1946                         if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1947                                 return null;
1948
1949                         return "<" + TypeManager.CSharpName (targs) + ">";
1950                 }
1951
1952                 public bool HasDynamicArgument ()
1953                 {
1954                         for (int i = 0; i < targs.Length; ++i) {
1955                                 var item = targs[i];
1956
1957                                 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1958                                         return true;
1959
1960                                 if (item is InflatedTypeSpec) {
1961                                         if (((InflatedTypeSpec) item).HasDynamicArgument ())
1962                                                 return true;
1963
1964                                         continue;
1965                                 }
1966
1967                                 if (item.IsArray) {
1968                                         while (item.IsArray) {
1969                                                 item = ((ArrayContainer) item).Element;
1970                                         }
1971
1972                                         if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1973                                                 return true;
1974                                 }
1975                         }
1976
1977                         return false;
1978                 }
1979
1980                 protected override void InitializeMemberCache (bool onlyTypes)
1981                 {
1982                         if (cache == null) {
1983                                 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1984
1985                                 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1986                                 // for imported type parameter constraints referencing nested type of this declaration
1987                                 if (cache == null)
1988                                         cache = new MemberCache (open_cache);
1989                         }
1990
1991                         var inflator = CreateLocalInflator (context);
1992
1993                         //
1994                         // Two stage inflate due to possible nested types recursive
1995                         // references
1996                         //
1997                         // class A<T> {
1998                         //    B b;
1999                         //    class B {
2000                         //      T Value;
2001                         //    }
2002                         // }
2003                         //
2004                         // When resolving type of `b' members of `B' cannot be 
2005                         // inflated because are not yet available in membercache
2006                         //
2007                         if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
2008                                 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
2009
2010                                 //
2011                                 // Inflate any implemented interfaces
2012                                 //
2013                                 if (open_type.Interfaces != null) {
2014                                         ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
2015                                         foreach (var iface in open_type.Interfaces) {
2016                                                 var iface_inflated = inflator.Inflate (iface);
2017                                                 if (iface_inflated == null)
2018                                                         continue;
2019
2020                                                 base.AddInterface (iface_inflated);
2021                                         }
2022                                 }
2023
2024                                 //
2025                                 // Handles the tricky case of recursive nested base generic type
2026                                 //
2027                                 // class A<T> : Base<A<T>.Nested> {
2028                                 //    class Nested {}
2029                                 // }
2030                                 //
2031                                 // When inflating A<T>. base type is not yet known, secondary
2032                                 // inflation is required (not common case) once base scope
2033                                 // is known
2034                                 //
2035                                 if (open_type.BaseType == null) {
2036                                         if (IsClass)
2037                                                 state |= StateFlags.PendingBaseTypeInflate;
2038                                 } else {
2039                                         BaseType = inflator.Inflate (open_type.BaseType);
2040                                 }
2041                         } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2042                                 //
2043                                 // It can happen when resolving base type without being defined
2044                                 // which is not allowed to happen and will always lead to an error
2045                                 //
2046                                 // class B { class N {} }
2047                                 // class A<T> : A<B.N> {}
2048                                 //
2049                                 if (open_type.BaseType == null)
2050                                         return;
2051
2052                                 BaseType = inflator.Inflate (open_type.BaseType);
2053                                 state &= ~StateFlags.PendingBaseTypeInflate;
2054                         }
2055
2056                         if (onlyTypes) {
2057                                 state |= StateFlags.PendingMemberCacheMembers;
2058                                 return;
2059                         }
2060
2061                         var tc = open_type.MemberDefinition as TypeDefinition;
2062                         if (tc != null && !tc.HasMembersDefined) {
2063                                 //
2064                                 // Inflating MemberCache with undefined members
2065                                 //
2066                                 return;
2067                         }
2068
2069                         if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
2070                                 BaseType = inflator.Inflate (open_type.BaseType);
2071                                 state &= ~StateFlags.PendingBaseTypeInflate;
2072                         }
2073
2074                         state &= ~StateFlags.PendingMemberCacheMembers;
2075                         open_type.MemberCache.InflateMembers (cache, open_type, inflator);
2076                 }
2077
2078                 public override TypeSpec Mutate (TypeParameterMutator mutator)
2079                 {
2080                         var targs = TypeArguments;
2081                         if (targs != null)
2082                                 targs = mutator.Mutate (targs);
2083
2084                         var decl = DeclaringType;
2085                         if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
2086                                 decl = mutator.Mutate (decl);
2087
2088                         if (targs == TypeArguments && decl == DeclaringType)
2089                                 return this;
2090
2091                         var mutated = (InflatedTypeSpec) MemberwiseClone ();
2092                         if (decl != DeclaringType) {
2093                                 // Gets back MethodInfo in case of metaInfo was inflated
2094                                 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
2095
2096                                 mutated.declaringType = decl;
2097                                 mutated.state |= StateFlags.PendingMetaInflate;
2098                         }
2099
2100                         if (targs != null) {
2101                                 mutated.targs = targs;
2102                                 mutated.info = null;
2103                         }
2104
2105                         return mutated;
2106                 }
2107         }
2108
2109
2110         //
2111         // Tracks the type arguments when instantiating a generic type. It's used
2112         // by both type arguments and type parameters
2113         //
2114         public class TypeArguments
2115         {
2116                 List<FullNamedExpression> args;
2117                 TypeSpec[] atypes;
2118
2119                 public TypeArguments (params FullNamedExpression[] types)
2120                 {
2121                         this.args = new List<FullNamedExpression> (types);
2122                 }
2123
2124                 public void Add (FullNamedExpression type)
2125                 {
2126                         args.Add (type);
2127                 }
2128
2129                 /// <summary>
2130                 ///   We may only be used after Resolve() is called and return the fully
2131                 ///   resolved types.
2132                 /// </summary>
2133                 // TODO: Not needed, just return type from resolve
2134                 public TypeSpec[] Arguments {
2135                         get {
2136                                 return atypes;
2137                         }
2138                         set {
2139                                 atypes = value;
2140                         }
2141                 }
2142
2143                 public int Count {
2144                         get {
2145                                 return args.Count;
2146                         }
2147                 }
2148
2149                 public virtual bool IsEmpty {
2150                         get {
2151                                 return false;
2152                         }
2153                 }
2154
2155                 public List<FullNamedExpression> TypeExpressions {
2156                         get {
2157                                 return this.args;
2158                         }
2159                 }
2160
2161                 public string GetSignatureForError()
2162                 {
2163                         StringBuilder sb = new StringBuilder ();
2164                         for (int i = 0; i < Count; ++i) {
2165                                 var expr = args[i];
2166                                 if (expr != null)
2167                                         sb.Append (expr.GetSignatureForError ());
2168
2169                                 if (i + 1 < Count)
2170                                         sb.Append (',');
2171                         }
2172
2173                         return sb.ToString ();
2174                 }
2175
2176                 /// <summary>
2177                 ///   Resolve the type arguments.
2178                 /// </summary>
2179                 public virtual bool Resolve (IMemberContext ec)
2180                 {
2181                         if (atypes != null)
2182                             return true;
2183
2184                         int count = args.Count;
2185                         bool ok = true;
2186
2187                         atypes = new TypeSpec [count];
2188
2189                         var errors = ec.Module.Compiler.Report.Errors;
2190
2191                         for (int i = 0; i < count; i++){
2192                                 var te = args[i].ResolveAsType (ec);
2193                                 if (te == null) {
2194                                         ok = false;
2195                                         continue;
2196                                 }
2197
2198                                 atypes[i] = te;
2199
2200                                 if (te.IsStatic) {
2201                                         ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
2202                                                 te.GetSignatureForError ());
2203                                         ok = false;
2204                                 }
2205
2206                                 if (te.IsPointer || te.IsSpecialRuntimeType) {
2207                                         ec.Module.Compiler.Report.Error (306, args[i].Location,
2208                                                 "The type `{0}' may not be used as a type argument",
2209                                                 te.GetSignatureForError ());
2210                                         ok = false;
2211                                 }
2212                         }
2213
2214                         if (!ok || errors != ec.Module.Compiler.Report.Errors)
2215                                 atypes = null;
2216
2217                         return ok;
2218                 }
2219
2220                 public TypeArguments Clone ()
2221                 {
2222                         TypeArguments copy = new TypeArguments ();
2223                         foreach (var ta in args)
2224                                 copy.args.Add (ta);
2225
2226                         return copy;
2227                 }
2228         }
2229
2230         public class UnboundTypeArguments : TypeArguments
2231         {
2232                 public UnboundTypeArguments (int arity)
2233                         : base (new FullNamedExpression[arity])
2234                 {
2235                 }
2236
2237                 public override bool IsEmpty {
2238                         get {
2239                                 return true;
2240                         }
2241                 }
2242
2243                 public override bool Resolve (IMemberContext ec)
2244                 {
2245                         // Nothing to be resolved
2246                         return true;
2247                 }
2248         }
2249
2250         public class TypeParameters
2251         {
2252                 List<TypeParameter> names;
2253                 TypeParameterSpec[] types;
2254
2255                 public TypeParameters ()
2256                 {
2257                         names = new List<TypeParameter> ();
2258                 }
2259
2260                 public TypeParameters (int count)
2261                 {
2262                         names = new List<TypeParameter> (count);
2263                 }
2264
2265                 #region Properties
2266
2267                 public int Count {
2268                         get {
2269                                 return names.Count;
2270                         }
2271                 }
2272
2273                 public TypeParameterSpec[] Types {
2274                         get {
2275                                 return types;
2276                         }
2277                 }
2278
2279                 #endregion
2280
2281                 public void Add (TypeParameter tparam)
2282                 {
2283                         names.Add (tparam);
2284                 }
2285
2286                 public void Add (TypeParameters tparams)
2287                 {
2288                         names.AddRange (tparams.names);
2289                 }
2290
2291                 public void Create (TypeSpec declaringType, int parentOffset, TypeContainer parent)
2292                 {
2293                         types = new TypeParameterSpec[Count];
2294                         for (int i = 0; i < types.Length; ++i) {
2295                                 var tp = names[i];
2296
2297                                 tp.Create (declaringType, parent);
2298                                 types[i] = tp.Type;
2299                                 types[i].DeclaredPosition = i + parentOffset;
2300
2301                                 if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
2302                                         parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
2303                                 }
2304                         }
2305                 }
2306
2307                 public void Define (GenericTypeParameterBuilder[] builders)
2308                 {
2309                         for (int i = 0; i < types.Length; ++i) {
2310                                 var tp = names[i];
2311                                 tp.Define (builders [types [i].DeclaredPosition]);
2312                         }
2313                 }
2314
2315                 public TypeParameter this[int index] {
2316                         get {
2317                                 return names [index];
2318                         }
2319                         set {
2320                                 names[index] = value;
2321                         }
2322                 }
2323
2324                 public TypeParameter Find (string name)
2325                 {
2326                         foreach (var tp in names) {
2327                                 if (tp.Name == name)
2328                                         return tp;
2329                         }
2330
2331                         return null;
2332                 }
2333
2334                 public string[] GetAllNames ()
2335                 {
2336                         return names.Select (l => l.Name).ToArray ();
2337                 }
2338
2339                 public string GetSignatureForError ()
2340                 {
2341                         StringBuilder sb = new StringBuilder ();
2342                         for (int i = 0; i < Count; ++i) {
2343                                 if (i > 0)
2344                                         sb.Append (',');
2345
2346                                 var name = names[i];
2347                                 if (name != null)
2348                                         sb.Append (name.GetSignatureForError ());
2349                         }
2350
2351                         return sb.ToString ();
2352                 }
2353
2354
2355                 public void CheckPartialConstraints (Method part)
2356                 {
2357                         var partTypeParameters = part.CurrentTypeParameters;
2358
2359                         for (int i = 0; i < Count; i++) {
2360                                 var tp_a = names[i];
2361                                 var tp_b = partTypeParameters [i];
2362                                 if (tp_a.Constraints == null) {
2363                                         if (tp_b.Constraints == null)
2364                                                 continue;
2365                                 } else if (tp_b.Constraints != null && tp_a.Type.HasSameConstraintsDefinition (tp_b.Type)) {
2366                                         continue;
2367                                 }
2368
2369                                 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition.Location, "");
2370                                 part.Compiler.Report.Error (761, part.Location,
2371                                         "Partial method declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2372                                         part.GetSignatureForError (), partTypeParameters[i].GetSignatureForError ());
2373                         }
2374                 }
2375
2376                 public void UpdateConstraints (TypeDefinition part)
2377                 {
2378                         var partTypeParameters = part.MemberName.TypeParameters;
2379
2380                         for (int i = 0; i < Count; i++) {
2381                                 var tp = names [i];
2382                                 if (tp.AddPartialConstraints (part, partTypeParameters [i]))
2383                                         continue;
2384
2385                                 part.Compiler.Report.SymbolRelatedToPreviousError (this[i].CurrentMemberDefinition);
2386                                 part.Compiler.Report.Error (265, part.Location,
2387                                         "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
2388                                         part.GetSignatureForError (), tp.GetSignatureForError ());
2389                         }
2390                 }
2391
2392                 public void VerifyClsCompliance ()
2393                 {
2394                         foreach (var tp in names) {
2395                                 tp.VerifyClsCompliance ();
2396                         }
2397                 }
2398         }
2399
2400         //
2401         // A type expression of generic type with type arguments
2402         //
2403         class GenericTypeExpr : TypeExpr
2404         {
2405                 TypeArguments args;
2406                 TypeSpec open_type;
2407
2408                 /// <summary>
2409                 ///   Instantiate the generic type `t' with the type arguments `args'.
2410                 ///   Use this constructor if you already know the fully resolved
2411                 ///   generic type.
2412                 /// </summary>          
2413                 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2414                 {
2415                         this.open_type = open_type;
2416                         loc = l;
2417                         this.args = args;
2418                 }
2419
2420                 public override string GetSignatureForError ()
2421                 {
2422                         return type.GetSignatureForError ();
2423                 }
2424
2425                 public override TypeSpec ResolveAsType (IMemberContext mc)
2426                 {
2427                         if (eclass != ExprClass.Unresolved)
2428                                 return type;
2429
2430                         if (!args.Resolve (mc))
2431                                 return null;
2432
2433                         TypeSpec[] atypes = args.Arguments;
2434                         if (atypes == null)
2435                                 return null;
2436
2437                         //
2438                         // Now bind the parameters
2439                         //
2440                         var inflated = open_type.MakeGenericType (mc, atypes);
2441                         type = inflated;
2442                         eclass = ExprClass.Type;
2443
2444                         //
2445                         // The constraints can be checked only when full type hierarchy is known
2446                         //
2447                         if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2448                                 var constraints = inflated.Constraints;
2449                                 if (constraints != null) {
2450                                         var cc = new ConstraintChecker (mc);
2451                                         if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2452                                                 inflated.HasConstraintsChecked = true;
2453                                         }
2454                                 }
2455                         }
2456
2457                         return type;
2458                 }
2459
2460                 public override bool Equals (object obj)
2461                 {
2462                         GenericTypeExpr cobj = obj as GenericTypeExpr;
2463                         if (cobj == null)
2464                                 return false;
2465
2466                         if ((type == null) || (cobj.type == null))
2467                                 return false;
2468
2469                         return type == cobj.type;
2470                 }
2471
2472                 public override int GetHashCode ()
2473                 {
2474                         return base.GetHashCode ();
2475                 }
2476         }
2477
2478         //
2479         // Generic type with unbound type arguments, used for typeof (G<,,>)
2480         //
2481         class GenericOpenTypeExpr : TypeExpression
2482         {
2483                 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2484                         : base (type.GetDefinition (), loc)
2485                 {
2486                 }
2487         }
2488
2489         struct ConstraintChecker
2490         {
2491                 IMemberContext mc;
2492                 bool recursive_checks;
2493
2494                 public ConstraintChecker (IMemberContext ctx)
2495                 {
2496                         this.mc = ctx;
2497                         recursive_checks = false;
2498                 }
2499
2500                 //
2501                 // Checks the constraints of open generic type against type
2502                 // arguments. This version is used for types which could not be
2503                 // checked immediatelly during construction because the type
2504                 // hierarchy was not yet fully setup (before Emit phase)
2505                 //
2506                 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2507                 {
2508                         //
2509                         // Check declaring type first if there is any
2510                         //
2511                         if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2512                                 return false;
2513
2514                         while (type is ElementTypeSpec)
2515                                 type = ((ElementTypeSpec) type).Element;
2516
2517                         if (type.Arity == 0)
2518                                 return true;
2519
2520                         var gtype = type as InflatedTypeSpec;
2521                         if (gtype == null)
2522                                 return true;
2523
2524                         var constraints = gtype.Constraints;
2525                         if (constraints == null)
2526                                 return true;
2527
2528                         if (gtype.HasConstraintsChecked)
2529                                 return true;
2530
2531                         var cc = new ConstraintChecker (mc);
2532                         cc.recursive_checks = true;
2533
2534                         if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2535                                 gtype.HasConstraintsChecked = true;
2536                                 return true;
2537                         }
2538
2539                         return false;
2540                 }
2541
2542                 //
2543                 // Checks all type arguments againts type parameters constraints
2544                 // NOTE: It can run in probing mode when `this.mc' is null
2545                 //
2546                 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2547                 {
2548                         for (int i = 0; i < tparams.Length; i++) {
2549                                 var targ = targs[i];
2550                                 if (!CheckConstraint (context, targ, tparams [i], loc))
2551                                         return false;
2552
2553                                 if (!recursive_checks)
2554                                         continue;
2555
2556                                 if (!Check (mc, targ, loc))
2557                                         return false;
2558                         }
2559
2560                         return true;
2561                 }
2562
2563                 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2564                 {
2565                         //
2566                         // First, check the `class' and `struct' constraints.
2567                         //
2568                         if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2569                                 if (mc != null) {
2570                                         mc.Module.Compiler.Report.Error (452, loc,
2571                                                 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2572                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2573                                 }
2574
2575                                 return false;
2576                         }
2577
2578                         if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2579                                 if (mc != null) {
2580                                         mc.Module.Compiler.Report.Error (453, loc,
2581                                                 "The type `{0}' must be a non-nullable value type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2582                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2583                                 }
2584
2585                                 return false;
2586                         }
2587
2588                         bool ok = true;
2589
2590                         //
2591                         // Check the class constraint
2592                         //
2593                         if (tparam.HasTypeConstraint) {
2594                                 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2595                                         if (mc == null)
2596                                                 return false;
2597
2598                                         ok = false;
2599                                 }
2600                         }
2601
2602                         //
2603                         // Check the interfaces constraints
2604                         //
2605                         if (tparam.InterfacesDefined != null) {
2606                                 foreach (TypeSpec iface in tparam.InterfacesDefined) {
2607                                         if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2608                                                 if (mc == null)
2609                                                         return false;
2610
2611                                                 ok = false;
2612                                                 break;
2613                                         }
2614                                 }
2615                         }
2616
2617                         //
2618                         // Check the type parameter constraint
2619                         //
2620                         if (tparam.TypeArguments != null) {
2621                                 foreach (var ta in tparam.TypeArguments) {
2622                                         if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2623                                                 if (mc == null)
2624                                                         return false;
2625
2626                                                 ok = false;
2627                                                 break;
2628                                         }
2629                                 }
2630                         }
2631
2632                         //
2633                         // Finally, check the constructor constraint.
2634                         //
2635                         if (!tparam.HasSpecialConstructor)
2636                                 return ok;
2637
2638                         if (!HasDefaultConstructor (atype)) {
2639                                 if (mc != null) {
2640                                         mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2641                                         mc.Module.Compiler.Report.Error (310, loc,
2642                                                 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2643                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2644                                 }
2645                                 return false;
2646                         }
2647
2648                         return ok;
2649                 }
2650
2651                 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2652                 {
2653                         for (int i = 0; i < targs.Length; ++i) {
2654                                 var targ = targs [i];
2655                                 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2656                                         return true;
2657
2658                                 if (HasDynamicTypeArgument (targ.TypeArguments))
2659                                         return true;
2660                         }
2661
2662                         return false;
2663                 }
2664
2665                 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2666                 {
2667                         if (atype == ttype)
2668                                 return true;
2669
2670                         if (atype.IsGenericParameter) {
2671                                 var tps = (TypeParameterSpec) atype;
2672                                 if (tps.HasDependencyOn (ttype))
2673                                         return true;
2674
2675                                 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2676                                         return true;
2677
2678                         } else if (TypeSpec.IsValueType (atype)) {
2679                                 if (atype.IsNullableType) {
2680                                         //
2681                                         // LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
2682                                         //
2683                                         if (TypeSpec.IsBaseClass (atype, ttype, false))
2684                                                 return true;
2685                                 } else {
2686                                         if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2687                                                 return true;
2688                                 }
2689                         } else {
2690                                 if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2691                                         return true;
2692                         }
2693
2694                         if (mc != null) {
2695                                 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2696                                 if (atype.IsGenericParameter) {
2697                                         mc.Module.Compiler.Report.Error (314, loc,
2698                                                 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing or type parameter conversion from `{0}' to `{3}'",
2699                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2700                                 } else if (TypeSpec.IsValueType (atype)) {
2701                                         if (atype.IsNullableType) {
2702                                                 if (ttype.IsInterface) {
2703                                                         mc.Module.Compiler.Report.Error (313, loc,
2704                                                                 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' never satisfies interface constraint `{3}'",
2705                                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2706                                                 } else {
2707                                                         mc.Module.Compiler.Report.Error (312, loc,
2708                                                                 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' does not satisfy constraint `{3}'",
2709                                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2710                                                 }
2711                                         } else {
2712                                                 mc.Module.Compiler.Report.Error (315, loc,
2713                                                         "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no boxing conversion from `{0}' to `{3}'",
2714                                                         atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2715                                         }
2716                                 } else {
2717                                         mc.Module.Compiler.Report.Error (311, loc,
2718                                                 "The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. There is no implicit reference conversion from `{0}' to `{3}'",
2719                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2720                                 }
2721                         }
2722
2723                         return false;
2724                 }
2725
2726                 static bool HasDefaultConstructor (TypeSpec atype)
2727                 {
2728                         var tp = atype as TypeParameterSpec;
2729                         if (tp != null) {
2730                                 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2731                         }
2732
2733                         if (atype.IsStruct || atype.IsEnum)
2734                                 return true;
2735
2736                         if (atype.IsAbstract)
2737                                 return false;
2738
2739                         var tdef = atype.GetDefinition ();
2740
2741                         var found = MemberCache.FindMember (tdef,
2742                                 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2743                                 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2744
2745                         return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2746                 }
2747         }
2748
2749         //
2750         // Implements C# type inference
2751         //
2752         class TypeInference
2753         {
2754                 //
2755                 // Tracks successful rate of type inference
2756                 //
2757                 int score = int.MaxValue;
2758                 readonly Arguments arguments;
2759                 readonly int arg_count;
2760
2761                 public TypeInference (Arguments arguments)
2762                 {
2763                         this.arguments = arguments;
2764                         if (arguments != null)
2765                                 arg_count = arguments.Count;
2766                 }
2767
2768                 public int InferenceScore {
2769                         get {
2770                                 return score;
2771                         }
2772                 }
2773
2774                 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2775                 {
2776                         var method_generic_args = method.GenericDefinition.TypeParameters;
2777                         TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2778                         if (!context.UnfixedVariableExists)
2779                                 return TypeSpec.EmptyTypes;
2780
2781                         AParametersCollection pd = method.Parameters;
2782                         if (!InferInPhases (ec, context, pd))
2783                                 return null;
2784
2785                         return context.InferredTypeArguments;
2786                 }
2787
2788                 //
2789                 // Implements method type arguments inference
2790                 //
2791                 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2792                 {
2793                         int params_arguments_start;
2794                         if (methodParameters.HasParams) {
2795                                 params_arguments_start = methodParameters.Count - 1;
2796                         } else {
2797                                 params_arguments_start = arg_count;
2798                         }
2799
2800                         TypeSpec [] ptypes = methodParameters.Types;
2801                         
2802                         //
2803                         // The first inference phase
2804                         //
2805                         TypeSpec method_parameter = null;
2806                         for (int i = 0; i < arg_count; i++) {
2807                                 Argument a = arguments [i];
2808                                 if (a == null)
2809                                         continue;
2810                                 
2811                                 if (i < params_arguments_start) {
2812                                         method_parameter = methodParameters.Types [i];
2813                                 } else if (i == params_arguments_start) {
2814                                         if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2815                                                 method_parameter = methodParameters.Types [params_arguments_start];
2816                                         else
2817                                                 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2818
2819                                         ptypes = (TypeSpec[]) ptypes.Clone ();
2820                                         ptypes [i] = method_parameter;
2821                                 }
2822
2823                                 //
2824                                 // When a lambda expression, an anonymous method
2825                                 // is used an explicit argument type inference takes a place
2826                                 //
2827                                 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2828                                 if (am != null) {
2829                                         if (am.ExplicitTypeInference (tic, method_parameter))
2830                                                 --score; 
2831                                         continue;
2832                                 }
2833
2834                                 if (a.IsByRef) {
2835                                         score -= tic.ExactInference (a.Type, method_parameter);
2836                                         continue;
2837                                 }
2838
2839                                 if (a.Expr.Type == InternalType.NullLiteral)
2840                                         continue;
2841
2842                                 if (TypeSpec.IsValueType (method_parameter)) {
2843                                         score -= tic.LowerBoundInference (a.Type, method_parameter);
2844                                         continue;
2845                                 }
2846
2847                                 //
2848                                 // Otherwise an output type inference is made
2849                                 //
2850                                 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2851                         }
2852
2853                         //
2854                         // Part of the second phase but because it happens only once
2855                         // we don't need to call it in cycle
2856                         //
2857                         bool fixed_any = false;
2858                         if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2859                                 return false;
2860
2861                         return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2862                 }
2863
2864                 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2865                 {
2866                         bool fixed_any = false;
2867                         if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2868                                 return false;
2869
2870                         // If no further unfixed type variables exist, type inference succeeds
2871                         if (!tic.UnfixedVariableExists)
2872                                 return true;
2873
2874                         if (!fixed_any && fixDependent)
2875                                 return false;
2876                         
2877                         // For all arguments where the corresponding argument output types
2878                         // contain unfixed type variables but the input types do not,
2879                         // an output type inference is made
2880                         for (int i = 0; i < arg_count; i++) {
2881                                 
2882                                 // Align params arguments
2883                                 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2884                                 
2885                                 if (!t_i.IsDelegate) {
2886                                         if (!t_i.IsExpressionTreeType)
2887                                                 continue;
2888
2889                                         t_i = TypeManager.GetTypeArguments (t_i) [0];
2890                                 }
2891
2892                                 var mi = Delegate.GetInvokeMethod (t_i);
2893                                 TypeSpec rtype = mi.ReturnType;
2894
2895                                 if (tic.IsReturnTypeNonDependent (mi, rtype)) {
2896                                         // It can be null for default arguments
2897                                         if (arguments[i] == null)
2898                                                 continue;
2899
2900                                         score -= tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
2901                                 }
2902                         }
2903
2904
2905                         return DoSecondPhase (ec, tic, methodParameters, true);
2906                 }
2907         }
2908
2909         public class TypeInferenceContext
2910         {
2911                 protected enum BoundKind
2912                 {
2913                         Exact   = 0,
2914                         Lower   = 1,
2915                         Upper   = 2
2916                 }
2917
2918                 struct BoundInfo : IEquatable<BoundInfo>
2919                 {
2920                         public readonly TypeSpec Type;
2921                         public readonly BoundKind Kind;
2922
2923                         public BoundInfo (TypeSpec type, BoundKind kind)
2924                         {
2925                                 this.Type = type;
2926                                 this.Kind = kind;
2927                         }
2928                         
2929                         public override int GetHashCode ()
2930                         {
2931                                 return Type.GetHashCode ();
2932                         }
2933
2934                         public Expression GetTypeExpression ()
2935                         {
2936                                 return new TypeExpression (Type, Location.Null);
2937                         }
2938
2939                         #region IEquatable<BoundInfo> Members
2940
2941                         public bool Equals (BoundInfo other)
2942                         {
2943                                 return Type == other.Type && Kind == other.Kind;
2944                         }
2945
2946                         #endregion
2947                 }
2948
2949                 readonly TypeSpec[] tp_args;
2950                 readonly TypeSpec[] fixed_types;
2951                 readonly List<BoundInfo>[] bounds;
2952
2953                 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2954                 public TypeInferenceContext (TypeSpec[] typeArguments)
2955                 {
2956                         if (typeArguments.Length == 0)
2957                                 throw new ArgumentException ("Empty generic arguments");
2958
2959                         fixed_types = new TypeSpec [typeArguments.Length];
2960                         for (int i = 0; i < typeArguments.Length; ++i) {
2961                                 if (typeArguments [i].IsGenericParameter) {
2962                                         if (bounds == null) {
2963                                                 bounds = new List<BoundInfo> [typeArguments.Length];
2964                                                 tp_args = new TypeSpec [typeArguments.Length];
2965                                         }
2966                                         tp_args [i] = typeArguments [i];
2967                                 } else {
2968                                         fixed_types [i] = typeArguments [i];
2969                                 }
2970                         }
2971                 }
2972
2973                 // 
2974                 // Used together with AddCommonTypeBound fo implement
2975                 // 7.4.2.13 Finding the best common type of a set of expressions
2976                 //
2977                 public TypeInferenceContext ()
2978                 {
2979                         fixed_types = new TypeSpec [1];
2980                         tp_args = new TypeSpec [1];
2981                         tp_args[0] = InternalType.Arglist; // it can be any internal type
2982                         bounds = new List<BoundInfo> [1];
2983                 }
2984
2985                 public TypeSpec[] InferredTypeArguments {
2986                         get {
2987                                 return fixed_types;
2988                         }
2989                 }
2990
2991                 public void AddCommonTypeBound (TypeSpec type)
2992                 {
2993                         AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, false);
2994                 }
2995
2996                 public void AddCommonTypeBoundAsync (TypeSpec type)
2997                 {
2998                         AddToBounds (new BoundInfo (type, BoundKind.Lower), 0, true);
2999                 }
3000
3001                 void AddToBounds (BoundInfo bound, int index, bool voidAllowed)
3002                 {
3003                         //
3004                         // Some types cannot be used as type arguments
3005                         //
3006                         if ((bound.Type.Kind == MemberKind.Void && !voidAllowed) || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
3007                                 bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
3008                                 return;
3009
3010                         var a = bounds [index];
3011                         if (a == null) {
3012                                 a = new List<BoundInfo> (2);
3013                                 a.Add (bound);
3014                                 bounds [index] = a;
3015                                 return;
3016                         }
3017
3018                         if (a.Contains (bound))
3019                                 return;
3020
3021                         a.Add (bound);
3022                 }
3023                 
3024                 bool AllTypesAreFixed (TypeSpec[] types)
3025                 {
3026                         foreach (TypeSpec t in types) {
3027                                 if (t.IsGenericParameter) {
3028                                         if (!IsFixed (t))
3029                                                 return false;
3030                                         continue;
3031                                 }
3032
3033                                 if (TypeManager.IsGenericType (t))
3034                                         return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
3035                         }
3036                         
3037                         return true;
3038                 }               
3039
3040                 //
3041                 // 26.3.3.8 Exact Inference
3042                 //
3043                 public int ExactInference (TypeSpec u, TypeSpec v)
3044                 {
3045                         // If V is an array type
3046                         if (v.IsArray) {
3047                                 if (!u.IsArray)
3048                                         return 0;
3049
3050                                 var ac_u = (ArrayContainer) u;
3051                                 var ac_v = (ArrayContainer) v;
3052                                 if (ac_u.Rank != ac_v.Rank)
3053                                         return 0;
3054
3055                                 return ExactInference (ac_u.Element, ac_v.Element);
3056                         }
3057
3058                         // If V is constructed type and U is constructed type
3059                         if (TypeManager.IsGenericType (v)) {
3060                                 if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
3061                                         return 0;
3062
3063                                 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
3064                                 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
3065                                 if (ga_u.Length != ga_v.Length)
3066                                         return 0;
3067
3068                                 int score = 0;
3069                                 for (int i = 0; i < ga_u.Length; ++i)
3070                                         score += ExactInference (ga_u [i], ga_v [i]);
3071
3072                                 return System.Math.Min (1, score);
3073                         }
3074
3075                         // If V is one of the unfixed type arguments
3076                         int pos = IsUnfixed (v);
3077                         if (pos == -1)
3078                                 return 0;
3079
3080                         AddToBounds (new BoundInfo (u, BoundKind.Exact), pos, false);
3081                         return 1;
3082                 }
3083
3084                 public bool FixAllTypes (ResolveContext ec)
3085                 {
3086                         for (int i = 0; i < tp_args.Length; ++i) {
3087                                 if (!FixType (ec, i))
3088                                         return false;
3089                         }
3090                         return true;
3091                 }
3092
3093                 //
3094                 // All unfixed type variables Xi are fixed for which all of the following hold:
3095                 // a, There is at least one type variable Xj that depends on Xi
3096                 // b, Xi has a non-empty set of bounds
3097                 // 
3098                 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
3099                 {
3100                         for (int i = 0; i < tp_args.Length; ++i) {
3101                                 if (fixed_types[i] != null)
3102                                         continue;
3103
3104                                 if (bounds[i] == null)
3105                                         continue;
3106
3107                                 if (!FixType (ec, i))
3108                                         return false;
3109                                 
3110                                 fixed_any = true;
3111                         }
3112
3113                         return true;
3114                 }
3115
3116                 //
3117                 // All unfixed type variables Xi which depend on no Xj are fixed
3118                 //
3119                 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
3120                 {
3121                         var types_to_fix = new List<TypeSpec> (tp_args);
3122                         for (int i = 0; i < methodParameters.Length; ++i) {
3123                                 TypeSpec t = methodParameters[i];
3124
3125                                 if (!t.IsDelegate) {
3126                                         if (!t.IsExpressionTreeType)
3127                                                 continue;
3128
3129                                         t =  TypeManager.GetTypeArguments (t) [0];
3130                                 }
3131
3132                                 if (t.IsGenericParameter)
3133                                         continue;
3134
3135                                 var invoke = Delegate.GetInvokeMethod (t);
3136                                 TypeSpec rtype = invoke.ReturnType;
3137                                 while (rtype.IsArray)
3138                                         rtype = ((ArrayContainer) rtype).Element;
3139
3140                                 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3141                                         continue;
3142
3143                                 // Remove dependent types, they cannot be fixed yet
3144                                 RemoveDependentTypes (types_to_fix, rtype);
3145                         }
3146
3147                         foreach (TypeSpec t in types_to_fix) {
3148                                 if (t == null)
3149                                         continue;
3150
3151                                 int idx = IsUnfixed (t);
3152                                 if (idx >= 0 && !FixType (ec, idx)) {
3153                                         return false;
3154                                 }
3155                         }
3156
3157                         fixed_any = types_to_fix.Count > 0;
3158                         return true;
3159                 }
3160
3161                 //
3162                 // 26.3.3.10 Fixing
3163                 //
3164                 public bool FixType (ResolveContext ec, int i)
3165                 {
3166                         // It's already fixed
3167                         if (fixed_types[i] != null)
3168                                 throw new InternalErrorException ("Type argument has been already fixed");
3169
3170                         var candidates = bounds [i];
3171                         if (candidates == null)
3172                                 return false;
3173
3174                         if (candidates.Count == 1) {
3175                                 TypeSpec t = candidates[0].Type;
3176                                 if (t == InternalType.NullLiteral)
3177                                         return false;
3178
3179                                 fixed_types [i] = t;
3180                                 return true;
3181                         }
3182
3183                         //
3184                         // The set of candidate types Uj starts out as the set of
3185                         // all types in the set of bounds for Xi
3186                         //
3187                         var applicable = new bool [candidates.Count];
3188                         for (int ci = 0; ci < applicable.Length; ++ci)
3189                                 applicable [ci] = true;
3190
3191                         for (int ci = 0; ci < applicable.Length; ++ci) {
3192                                 var bound = candidates [ci];
3193                                 int cii = 0;
3194
3195                                 switch (bound.Kind) {
3196                                 case BoundKind.Exact:
3197                                         for (; cii != applicable.Length; ++cii) {
3198                                                 if (ci == cii)
3199                                                         continue;
3200
3201                                                 if (!applicable[cii])
3202                                                         break;
3203
3204                                                 //
3205                                                 // For each exact bound U of Xi all types Uj which are not identical
3206                                                 // to U are removed from the candidate set
3207                                                 //
3208                                                 if (candidates [cii].Type != bound.Type)
3209                                                         applicable[cii] = false;
3210                                         }
3211
3212                                         break;
3213                                 case BoundKind.Lower:
3214                                         for (; cii != applicable.Length; ++cii) {
3215                                                 if (ci == cii)
3216                                                         continue;
3217
3218                                                 if (!applicable[cii])
3219                                                         break;
3220
3221                                                 //
3222                                                 // For each lower bound U of Xi all types Uj to which there is not an implicit conversion
3223                                                 // from U are removed from the candidate set
3224                                                 //
3225                                                 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), candidates [cii].Type)) {
3226                                                         applicable[cii] = false;
3227                                                 }
3228                                         }
3229
3230                                         break;
3231
3232                                 case BoundKind.Upper:
3233                                         for (; cii != applicable.Length; ++cii) {
3234                                                 if (ci == cii)
3235                                                         continue;
3236
3237                                                 if (!applicable[cii])
3238                                                         break;
3239
3240                                                 //
3241                                                 // For each upper bound U of Xi all types Uj from which there is not an implicit conversion
3242                                                 // to U are removed from the candidate set
3243                                                 //
3244                                                 if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3245                                                         applicable[cii] = false;
3246                                         }
3247
3248                                         break;
3249                                 }
3250                         }
3251
3252                         TypeSpec best_candidate = null;
3253                         for (int ci = 0; ci < applicable.Length; ++ci) {
3254                                 if (!applicable[ci])
3255                                         continue;
3256
3257                                 var bound = candidates [ci];
3258                                 if (bound.Type == best_candidate)
3259                                         continue;
3260
3261                                 int cii = 0;
3262                                 for (; cii < applicable.Length; ++cii) {
3263                                         if (ci == cii)
3264                                                 continue;
3265
3266                                         if (!applicable[cii])
3267                                                 continue;
3268
3269                                         if (!Convert.ImplicitConversionExists (ec, candidates[cii].GetTypeExpression (), bound.Type))
3270                                                 break;
3271                                 }
3272
3273                                 if (cii != applicable.Length)
3274                                         continue;
3275
3276                                 //
3277                                 // We already have the best candidate, break if it's different (non-unique)
3278                                 //
3279                                 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3280                                 //
3281                                 if (best_candidate != null) {
3282
3283                                         if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3284                                                 continue;
3285
3286                                         if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3287                                                 return false;
3288                                 }
3289
3290                                 best_candidate = bound.Type;
3291                         }
3292
3293                         if (best_candidate == null)
3294                                 return false;
3295
3296                         fixed_types[i] = best_candidate;
3297                         return true;
3298                 }
3299
3300                 public bool HasBounds (int pos)
3301                 {
3302                         return bounds[pos] != null;
3303                 }
3304                 
3305                 //
3306                 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3307                 // null when type parameter has not been fixed
3308                 //
3309                 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3310                 {
3311                         var tp = parameter as TypeParameterSpec;
3312                         if (tp != null) {
3313                                 //
3314                                 // Type inference works on generic arguments (MVAR) only
3315                                 //
3316                                 if (!tp.IsMethodOwned)
3317                                         return parameter;
3318
3319                                 //
3320                                 // Ensure the type parameter belongs to same container
3321                                 //
3322                                 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3323                                         return fixed_types[tp.DeclaredPosition] ?? parameter;
3324
3325                                 return parameter;
3326                         }
3327
3328                         var gt = parameter as InflatedTypeSpec;
3329                         if (gt != null) {
3330                                 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3331                                 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3332                                         var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3333                                         if (inflated == null)
3334                                                 return null;
3335
3336                                         inflated_targs[ii] = inflated;
3337                                 }
3338
3339                                 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3340                         }
3341
3342                         var ac = parameter as ArrayContainer;
3343                         if (ac != null) {
3344                                 var inflated = InflateGenericArgument (context, ac.Element);
3345                                 if (inflated != ac.Element)
3346                                         return ArrayContainer.MakeType (context.Module, inflated);
3347                         }
3348
3349                         return parameter;
3350                 }
3351                 
3352                 //
3353                 // Tests whether all delegate input arguments are fixed and generic output type
3354                 // requires output type inference 
3355                 //
3356                 public bool IsReturnTypeNonDependent (MethodSpec invoke, TypeSpec returnType)
3357                 {
3358                         AParametersCollection d_parameters = invoke.Parameters;
3359
3360                         if (d_parameters.IsEmpty)
3361                                 return true;
3362
3363                         while (returnType.IsArray)
3364                                 returnType = ((ArrayContainer) returnType).Element;
3365
3366                         if (returnType.IsGenericParameter) {
3367                                 if (IsFixed (returnType))
3368                                     return false;
3369                         } else if (TypeManager.IsGenericType (returnType)) {
3370                                 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3371                                 
3372                                 // At least one unfixed return type has to exist 
3373                                 if (AllTypesAreFixed (g_args))
3374                                         return false;
3375                         } else {
3376                                 return false;
3377                         }
3378
3379                         // All generic input arguments have to be fixed
3380                         return AllTypesAreFixed (d_parameters.Types);
3381                 }
3382
3383                 bool IsFixed (TypeSpec type)
3384                 {
3385                         return IsUnfixed (type) == -1;
3386                 }               
3387
3388                 int IsUnfixed (TypeSpec type)
3389                 {
3390                         if (!type.IsGenericParameter)
3391                                 return -1;
3392
3393                         for (int i = 0; i < tp_args.Length; ++i) {
3394                                 if (tp_args[i] == type) {
3395                                         if (fixed_types[i] != null)
3396                                                 break;
3397
3398                                         return i;
3399                                 }
3400                         }
3401
3402                         return -1;
3403                 }
3404
3405                 //
3406                 // 26.3.3.9 Lower-bound Inference
3407                 //
3408                 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3409                 {
3410                         return LowerBoundInference (u, v, false);
3411                 }
3412
3413                 //
3414                 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3415                 //
3416                 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3417                 {
3418                         // If V is one of the unfixed type arguments
3419                         int pos = IsUnfixed (v);
3420                         if (pos != -1) {
3421                                 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos, false);
3422                                 return 1;
3423                         }                       
3424
3425                         // If U is an array type
3426                         var u_ac = u as ArrayContainer;
3427                         if (u_ac != null) {
3428                                 var v_ac = v as ArrayContainer;
3429                                 if (v_ac != null) {
3430                                         if (u_ac.Rank != v_ac.Rank)
3431                                                 return 0;
3432
3433                                         if (TypeSpec.IsValueType (u_ac.Element))
3434                                                 return ExactInference (u_ac.Element, v_ac.Element);
3435
3436                                         return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3437                                 }
3438
3439                                 if (u_ac.Rank != 1 || !v.IsArrayGenericInterface)
3440                                         return 0;
3441
3442                                 var v_i = TypeManager.GetTypeArguments (v) [0];
3443                                 if (TypeSpec.IsValueType (u_ac.Element))
3444                                         return ExactInference (u_ac.Element, v_i);
3445
3446                                 return LowerBoundInference (u_ac.Element, v_i);
3447                         }
3448                         
3449                         if (v.IsGenericOrParentIsGeneric) {
3450                                 //
3451                                 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3452                                 // such that U is identical to, inherits from (directly or indirectly),
3453                                 // or implements (directly or indirectly) C<U1..Uk>
3454                                 //
3455                                 var u_candidates = new List<TypeSpec> ();
3456                                 var open_v = v.MemberDefinition;
3457
3458                                 for (TypeSpec t = u; t != null; t = t.BaseType) {
3459                                         if (open_v == t.MemberDefinition)
3460                                                 u_candidates.Add (t);
3461
3462                                         //
3463                                         // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3464                                         // that would complicate the process a lot, instead I treat them as dynamic
3465                                         //
3466                                         if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3467                                                 u_candidates.Add (t);
3468                                 }
3469
3470                                 if (u.Interfaces != null) {
3471                                         foreach (var iface in u.Interfaces) {
3472                                                 if (open_v == iface.MemberDefinition)
3473                                                         u_candidates.Add (iface);
3474                                         }
3475                                 }
3476
3477                                 TypeSpec[] unique_candidate_targs = null;
3478                                 var ga_v = TypeSpec.GetAllTypeArguments (v);
3479                                 foreach (TypeSpec u_candidate in u_candidates) {
3480                                         //
3481                                         // The unique set of types U1..Uk means that if we have an interface I<T>,
3482                                         // class U : I<int>, I<long> then no type inference is made when inferring
3483                                         // type I<T> by applying type U because T could be int or long
3484                                         //
3485                                         if (unique_candidate_targs != null) {
3486                                                 TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3487                                                 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3488                                                         unique_candidate_targs = second_unique_candidate_targs;
3489                                                         continue;
3490                                                 }
3491
3492                                                 //
3493                                                 // Break when candidate arguments are ambiguous
3494                                                 //
3495                                                 return 0;
3496                                         }
3497
3498                                         //
3499                                         // A candidate is dynamic type expression, to simplify things use dynamic
3500                                         // for all type parameter of this type. For methods like this one
3501                                         // 
3502                                         // void M<T, U> (IList<T>, IList<U[]>)
3503                                         //
3504                                         // dynamic becomes both T and U when the arguments are of dynamic type
3505                                         //
3506                                         if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3507                                                 unique_candidate_targs = new TypeSpec[ga_v.Length];
3508                                                 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3509                                                         unique_candidate_targs[i] = u_candidate;
3510                                         } else {
3511                                                 unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3512                                         }
3513                                 }
3514
3515                                 if (unique_candidate_targs != null) {
3516                                         int score = 0;
3517                                         int tp_index = -1;
3518                                         TypeParameterSpec[] tps = null;
3519
3520                                         for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3521                                                 if (tp_index < 0) {
3522                                                         while (v.Arity == 0)
3523                                                                 v = v.DeclaringType;
3524
3525                                                         tps = v.MemberDefinition.TypeParameters;
3526                                                         tp_index = tps.Length - 1;
3527                                                 }
3528
3529                                                 Variance variance = tps [tp_index--].Variance;
3530
3531                                                 TypeSpec u_i = unique_candidate_targs [i];
3532                                                 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3533                                                         if (ExactInference (u_i, ga_v [i]) == 0)
3534                                                                 ++score;
3535                                                 } else {
3536                                                         bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3537                                                                 (variance == Variance.Covariant && inversed);
3538
3539                                                         if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3540                                                                 ++score;
3541                                                 }
3542                                         }
3543
3544                                         return score;
3545                                 }
3546                         }
3547
3548                         return 0;
3549                 }
3550
3551                 //
3552                 // 26.3.3.6 Output Type Inference
3553                 //
3554                 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3555                 {
3556                         // If e is a lambda or anonymous method with inferred return type
3557                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3558                         if (ame != null) {
3559                                 TypeSpec rt = ame.InferReturnType (ec, this, t);
3560                                 var invoke = Delegate.GetInvokeMethod (t);
3561
3562                                 if (rt == null) {
3563                                         AParametersCollection pd = invoke.Parameters;
3564                                         return ame.Parameters.Count == pd.Count ? 1 : 0;
3565                                 }
3566
3567                                 TypeSpec rtype = invoke.ReturnType;
3568                                 return LowerBoundInference (rt, rtype) + 1;
3569                         }
3570
3571                         //
3572                         // if E is a method group and T is a delegate type or expression tree type
3573                         // return type Tb with parameter types T1..Tk and return type Tb, and overload
3574                         // resolution of E with the types T1..Tk yields a single method with return type U,
3575                         // then a lower-bound inference is made from U for Tb.
3576                         //
3577                         if (e is MethodGroupExpr) {
3578                                 if (!t.IsDelegate) {
3579                                         if (!t.IsExpressionTreeType)
3580                                                 return 0;
3581
3582                                         t = TypeManager.GetTypeArguments (t)[0];
3583                                 }
3584
3585                                 var invoke = Delegate.GetInvokeMethod (t);
3586                                 TypeSpec rtype = invoke.ReturnType;
3587
3588                                 if (!IsReturnTypeNonDependent (invoke, rtype))
3589                                         return 0;
3590
3591                                 // LAMESPEC: Standard does not specify that all methodgroup arguments
3592                                 // has to be fixed but it does not specify how to do recursive type inference
3593                                 // either. We choose the simple option and infer return type only
3594                                 // if all delegate generic arguments are fixed.
3595                                 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3596                                 for (int i = 0; i < param_types.Length; ++i) {
3597                                         var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3598                                         if (inflated == null)
3599                                                 return 0;
3600
3601                                         param_types[i] = inflated;
3602                                 }
3603
3604                                 MethodGroupExpr mg = (MethodGroupExpr) e;
3605                                 Arguments args = DelegateCreation.CreateDelegateMethodArguments (ec, invoke.Parameters, param_types, e.Location);
3606                                 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3607                                 if (mg == null)
3608                                         return 0;
3609
3610                                 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3611                         }
3612
3613                         //
3614                         // if e is an expression with type U, then
3615                         // a lower-bound inference is made from U for T
3616                         //
3617                         return LowerBoundInference (e.Type, t) * 2;
3618                 }
3619
3620                 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3621                 {
3622                         int idx = IsUnfixed (returnType);
3623                         if (idx >= 0) {
3624                                 types [idx] = null;
3625                                 return;
3626                         }
3627
3628                         if (TypeManager.IsGenericType (returnType)) {
3629                                 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3630                                         RemoveDependentTypes (types, t);
3631                                 }
3632                         }
3633                 }
3634
3635                 public bool UnfixedVariableExists {
3636                         get {
3637                                 foreach (TypeSpec ut in fixed_types) {
3638                                         if (ut == null)
3639                                                 return true;
3640                                 }
3641
3642                                 return false;
3643                         }
3644                 }
3645         }
3646 }