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