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