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