Reorder fields to improve object layout since the runtime can't do it for corlib...
[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.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. The effective base class is always a class-type
859                 //
860                 public TypeSpec GetEffectiveBase ()
861                 {
862                         if (HasSpecialStruct)
863                                 return BaseType;
864
865                         //
866                         // If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
867                         //
868                         if (BaseType != null && targs == null) {
869                                 //
870                                 // If T has a constraint V that is a value-type, use instead the most specific base type of V that is a class-type.
871                                 // 
872                                 // LAMESPEC: Is System.ValueType always the most specific base type in this case?
873                                 //
874                                 // Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
875                                 // are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
876                                 //
877                                 return BaseType.IsStruct ? BaseType.BaseType : BaseType;
878                         }
879
880                         var types = targs;
881                         if (HasTypeConstraint) {
882                                 Array.Resize (ref types, types.Length + 1);
883                                 types[types.Length - 1] = BaseType;
884                         }
885
886                         if (types != null)
887                                 return Convert.FindMostEncompassedType (types.Select (l => l.BaseType));
888
889                         return BaseType;
890                 }
891
892                 public override string GetSignatureForDocumentation ()
893                 {
894                         int c = 0;
895                         var type = DeclaringType;
896                         while (type != null && type.DeclaringType != null) {
897                                 type = type.DeclaringType;
898                                 c += type.MemberDefinition.TypeParametersCount;
899                         }
900
901                         var prefix = IsMethodOwned ? "``" : "`";
902                         return prefix + (c + DeclaredPosition);
903                 }
904
905                 public override string GetSignatureForError ()
906                 {
907                         return Name;
908                 }
909
910                 //
911                 // Constraints have to match by definition but not position, used by
912                 // partial classes or methods
913                 //
914                 public bool HasSameConstraintsDefinition (TypeParameterSpec other)
915                 {
916                         if (spec != other.spec)
917                                 return false;
918
919                         if (BaseType != other.BaseType)
920                                 return false;
921
922                         if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
923                                 return false;
924
925                         if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
926                                 return false;
927
928                         return true;
929                 }
930
931                 //
932                 // Constraints have to match by using same set of types, used by
933                 // implicit interface implementation
934                 //
935                 public bool HasSameConstraintsImplementation (TypeParameterSpec other)
936                 {
937                         if (spec != other.spec)
938                                 return false;
939
940                         //
941                         // It can be same base type or inflated type parameter
942                         //
943                         // interface I<T> { void Foo<U> where U : T; }
944                         // class A : I<int> { void Foo<X> where X : int {} }
945                         //
946                         bool found;
947                         if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
948                                 if (other.targs == null)
949                                         return false;
950
951                                 found = false;
952                                 foreach (var otarg in other.targs) {
953                                         if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
954                                                 found = true;
955                                                 break;
956                                         }
957                                 }
958
959                                 if (!found)
960                                         return false;
961                         }
962
963                         // Check interfaces implementation -> definition
964                         if (InterfacesDefined != null) {
965                                 foreach (var iface in InterfacesDefined) {
966                                         found = false;
967                                         if (other.InterfacesDefined != null) {
968                                                 foreach (var oiface in other.InterfacesDefined) {
969                                                         if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
970                                                                 found = true;
971                                                                 break;
972                                                         }
973                                                 }
974                                         }
975
976                                         if (found)
977                                                 continue;
978
979                                         if (other.targs != null) {
980                                                 foreach (var otarg in other.targs) {
981                                                         if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
982                                                                 found = true;
983                                                                 break;
984                                                         }
985                                                 }
986                                         }
987
988                                         if (!found)
989                                                 return false;
990                                 }
991                         }
992
993                         // Check interfaces implementation <- definition
994                         if (other.InterfacesDefined != null) {
995                                 if (InterfacesDefined == null)
996                                         return false;
997
998                                 foreach (var oiface in other.InterfacesDefined) {
999                                         found = false;
1000                                         foreach (var iface in InterfacesDefined) {
1001                                                 if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1002                                                         found = true;
1003                                                         break;
1004                                                 }
1005                                         }
1006
1007                                         if (!found)
1008                                                 return false;
1009                                 }
1010                         }
1011
1012                         // Check type parameters implementation -> definition
1013                         if (targs != null) {
1014                                 if (other.targs == null)
1015                                         return false;
1016
1017                                 foreach (var targ in targs) {
1018                                         found = false;
1019                                         foreach (var otarg in other.targs) {
1020                                                 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1021                                                         found = true;
1022                                                         break;
1023                                                 }
1024                                         }
1025
1026                                         if (!found)
1027                                                 return false;
1028                                 }
1029                         }
1030
1031                         // Check type parameters implementation <- definition
1032                         if (other.targs != null) {
1033                                 foreach (var otarg in other.targs) {
1034                                         // Ignore inflated type arguments, were checked above
1035                                         if (!otarg.IsGenericParameter)
1036                                                 continue;
1037
1038                                         if (targs == null)
1039                                                 return false;
1040
1041                                         found = false;
1042                                         foreach (var targ in targs) {
1043                                                 if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1044                                                         found = true;
1045                                                         break;
1046                                                 }
1047                                         }
1048
1049                                         if (!found)
1050                                                 return false;
1051                                 }                               
1052                         }
1053
1054                         return true;
1055                 }
1056
1057                 public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1058                 {
1059                         return InflateConstraints (tparams, l => l, inflator);
1060                 }
1061
1062                 public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1063                 {
1064                         TypeParameterSpec[] constraints = null;
1065                         TypeParameterInflator? inflator = null;
1066
1067                         for (int i = 0; i < tparams.Length; ++i) {
1068                                 var tp = tparams[i];
1069                                 if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1070                                         if (constraints == null) {
1071                                                 constraints = new TypeParameterSpec[tparams.Length];
1072                                                 Array.Copy (tparams, constraints, constraints.Length);
1073                                         }
1074
1075                                         //
1076                                         // Using a factory to avoid possibly expensive inflator build up
1077                                         //
1078                                         if (inflator == null)
1079                                                 inflator = inflatorFactory (arg);
1080
1081                                         constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1082                                 }
1083                         }
1084
1085                         if (constraints == null)
1086                                 constraints = tparams;
1087
1088                         return constraints;
1089                 }
1090
1091                 public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1092                 {
1093                         tps.BaseType = inflator.Inflate (BaseType);
1094                         if (ifaces != null) {
1095                                 tps.ifaces = new List<TypeSpec> (ifaces.Count);
1096                                 for (int i = 0; i < ifaces.Count; ++i)
1097                                         tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1098                         }
1099
1100                         if (targs != null) {
1101                                 tps.targs = new TypeSpec[targs.Length];
1102                                 for (int i = 0; i < targs.Length; ++i)
1103                                         tps.targs[i] = inflator.Inflate (targs[i]);
1104                         }
1105                 }
1106
1107                 public override MemberSpec InflateMember (TypeParameterInflator inflator)
1108                 {
1109                         var tps = (TypeParameterSpec) MemberwiseClone ();
1110                         InflateConstraints (inflator, tps);
1111                         return tps;
1112                 }
1113
1114                 //
1115                 // Populates type parameter members using type parameter constraints
1116                 // The trick here is to be called late enough but not too late to
1117                 // populate member cache with all members from other types
1118                 //
1119                 protected override void InitializeMemberCache (bool onlyTypes)
1120                 {
1121                         cache = new MemberCache ();
1122
1123                         //
1124                         // For a type parameter the membercache is the union of the sets of members of the types
1125                         // specified as a primary constraint or secondary constraint
1126                         //
1127                         if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1128                                 cache.AddBaseType (BaseType);
1129
1130                         if (ifaces != null) {
1131                                 foreach (var iface_type in Interfaces) {
1132                                         cache.AddInterface (iface_type);
1133                                 }
1134                         }
1135
1136                         if (targs != null) {
1137                                 foreach (var ta in targs) {
1138                                         var b_type = ta.BaseType;
1139                                         if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1140                                                 cache.AddBaseType (b_type);
1141
1142                                         if (ta.Interfaces != null) {
1143                                                 foreach (var iface_type in ta.Interfaces) {
1144                                                         cache.AddInterface (iface_type);
1145                                                 }
1146                                         }
1147                                 }
1148                         }
1149                 }
1150
1151                 public bool IsConvertibleToInterface (TypeSpec iface)
1152                 {
1153                         if (Interfaces != null) {
1154                                 foreach (var t in Interfaces) {
1155                                         if (t == iface)
1156                                                 return true;
1157                                 }
1158                         }
1159
1160                         if (TypeArguments != null) {
1161                                 foreach (var t in TypeArguments) {
1162                                         if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1163                                                 return true;
1164                                 }
1165                         }
1166
1167                         return false;
1168                 }
1169
1170                 public override TypeSpec Mutate (TypeParameterMutator mutator)
1171                 {
1172                         return mutator.Mutate (this);
1173                 }
1174         }
1175
1176         public struct TypeParameterInflator
1177         {
1178                 readonly TypeSpec type;
1179                 readonly TypeParameterSpec[] tparams;
1180                 readonly TypeSpec[] targs;
1181                 readonly IModuleContext context;
1182
1183                 public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1184                         : this (nested.context, type, nested.tparams, nested.targs)
1185                 {
1186                 }
1187
1188                 public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1189                 {
1190                         if (tparams.Length != targs.Length)
1191                                 throw new ArgumentException ("Invalid arguments");
1192
1193                         this.context = context;
1194                         this.tparams = tparams;
1195                         this.targs = targs;
1196                         this.type = type;
1197                 }
1198
1199                 #region Properties
1200
1201                 public IModuleContext Context {
1202                         get {
1203                                 return context;
1204                         }
1205                 }
1206
1207                 public TypeSpec TypeInstance {
1208                         get {
1209                                 return type;
1210                         }
1211                 }
1212
1213                 //
1214                 // Type parameters to inflate
1215                 //
1216                 public TypeParameterSpec[] TypeParameters {
1217                         get {
1218                                 return tparams;
1219                         }
1220                 }
1221
1222                 #endregion
1223
1224                 public TypeSpec Inflate (TypeSpec type)
1225                 {
1226                         var tp = type as TypeParameterSpec;
1227                         if (tp != null)
1228                                 return Inflate (tp);
1229
1230                         var ac = type as ArrayContainer;
1231                         if (ac != null) {
1232                                 var et = Inflate (ac.Element);
1233                                 if (et != ac.Element)
1234                                         return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1235
1236                                 return ac;
1237                         }
1238
1239                         //
1240                         // When inflating a nested type, inflate its parent first
1241                         // in case it's using same type parameters (was inflated within the type)
1242                         //
1243                         TypeSpec[] targs;
1244                         int i = 0;
1245                         if (type.IsNested) {
1246                                 var parent = Inflate (type.DeclaringType);
1247
1248                                 //
1249                                 // Keep the inflated type arguments
1250                                 // 
1251                                 targs = type.TypeArguments;
1252
1253                                 //
1254                                 // When inflating imported nested type used inside same declaring type, we get TypeSpec
1255                                 // because the import cache helps us to catch it. However, that means we have to look at
1256                                 // type definition to get type argument (they are in fact type parameter in this case)
1257                                 //
1258                                 if (targs.Length == 0 && type.Arity > 0)
1259                                         targs = type.MemberDefinition.TypeParameters;
1260
1261                                 //
1262                                 // Parent was inflated, find the same type on inflated type
1263                                 // to use same cache for nested types on same generic parent
1264                                 //
1265                                 type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1266
1267                                 //
1268                                 // Handle the tricky case where parent shares local type arguments
1269                                 // which means inflating inflated type
1270                                 //
1271                                 // class Test<T> {
1272                                 //              public static Nested<T> Foo () { return null; }
1273                                 //
1274                                 //              public class Nested<U> {}
1275                                 //      }
1276                                 //
1277                                 //  return type of Test<string>.Foo() has to be Test<string>.Nested<string> 
1278                                 //
1279                                 if (targs.Length > 0) {
1280                                         var inflated_targs = new TypeSpec[targs.Length];
1281                                         for (; i < targs.Length; ++i)
1282                                                 inflated_targs[i] = Inflate (targs[i]);
1283
1284                                         type = type.MakeGenericType (context, inflated_targs);
1285                                 }
1286
1287                                 return type;
1288                         }
1289
1290                         // Nothing to do for non-generic type
1291                         if (type.Arity == 0)
1292                                 return type;
1293
1294                         targs = new TypeSpec[type.Arity];
1295
1296                         //
1297                         // Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1298                         //
1299                         if (type is InflatedTypeSpec) {
1300                                 for (; i < targs.Length; ++i)
1301                                         targs[i] = Inflate (type.TypeArguments[i]);
1302
1303                                 type = type.GetDefinition ();
1304                         } else {
1305                                 //
1306                                 // Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1307                                 //
1308                                 var args = type.MemberDefinition.TypeParameters;
1309                                 foreach (var ds_tp in args)
1310                                         targs[i++] = Inflate (ds_tp);
1311                         }
1312
1313                         return type.MakeGenericType (context, targs);
1314                 }
1315
1316                 public TypeSpec Inflate (TypeParameterSpec tp)
1317                 {
1318                         for (int i = 0; i < tparams.Length; ++i)
1319                                 if (tparams [i] == tp)
1320                                         return targs[i];
1321
1322                         // This can happen when inflating nested types
1323                         // without type arguments specified
1324                         return tp;
1325                 }
1326         }
1327
1328         //
1329         // Before emitting any code we have to change all MVAR references to VAR
1330         // when the method is of generic type and has hoisted variables
1331         //
1332         public class TypeParameterMutator
1333         {
1334                 readonly TypeParameter[] mvar;
1335                 readonly TypeParameter[] var;
1336                 Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1337
1338                 public TypeParameterMutator (TypeParameter[] mvar, TypeParameter[] var)
1339                 {
1340                         if (mvar.Length != var.Length)
1341                                 throw new ArgumentException ();
1342
1343                         this.mvar = mvar;
1344                         this.var = var;
1345                 }
1346
1347                 #region Properties
1348
1349                 public TypeParameter[] MethodTypeParameters {
1350                         get {
1351                                 return mvar;
1352                         }
1353                 }
1354
1355                 #endregion
1356
1357                 public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1358                 {
1359                         if (type is InflatedTypeSpec) {
1360                                 if (type.DeclaringType == null)
1361                                         return type.GetDefinition ();
1362
1363                                 var parent = GetMemberDeclaringType (type.DeclaringType);
1364                                 type = MemberCache.GetMember<TypeSpec> (parent, type);
1365                         }
1366
1367                         return type;
1368                 }
1369
1370                 public TypeSpec Mutate (TypeSpec ts)
1371                 {
1372                         TypeSpec value;
1373                         if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1374                                 return value;
1375
1376                         value = ts.Mutate (this);
1377                         if (mutated_typespec == null)
1378                                 mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1379
1380                         mutated_typespec.Add (ts, value);
1381                         return value;
1382                 }
1383
1384                 public TypeParameterSpec Mutate (TypeParameterSpec tp)
1385                 {
1386                         for (int i = 0; i < mvar.Length; ++i) {
1387                                 if (mvar[i].Type == tp)
1388                                         return var[i].Type;
1389                         }
1390
1391                         return tp;
1392                 }
1393
1394                 public TypeSpec[] Mutate (TypeSpec[] targs)
1395                 {
1396                         TypeSpec[] mutated = new TypeSpec[targs.Length];
1397                         bool changed = false;
1398                         for (int i = 0; i < targs.Length; ++i) {
1399                                 mutated[i] = Mutate (targs[i]);
1400                                 changed |= targs[i] != mutated[i];
1401                         }
1402
1403                         return changed ? mutated : targs;
1404                 }
1405         }
1406
1407         /// <summary>
1408         ///   A TypeExpr which already resolved to a type parameter.
1409         /// </summary>
1410         public class TypeParameterExpr : TypeExpression
1411         {
1412                 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1413                         : base (type_parameter.Type, loc)
1414                 {
1415                         this.eclass = ExprClass.TypeParameter;
1416                 }
1417         }
1418
1419         public class InflatedTypeSpec : TypeSpec
1420         {
1421                 TypeSpec[] targs;
1422                 TypeParameterSpec[] constraints;
1423                 readonly TypeSpec open_type;
1424                 readonly IModuleContext context;
1425
1426                 public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1427                         : base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1428                 {
1429                         if (targs == null)
1430                                 throw new ArgumentNullException ("targs");
1431
1432 //                      this.state = openType.state;
1433                         this.context = context;
1434                         this.open_type = openType;
1435                         this.targs = targs;
1436
1437                         foreach (var arg in targs) {
1438                                 if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1439                                         state |= StateFlags.HasDynamicElement;
1440                                         break;
1441                                 }
1442                         }
1443
1444                         if (open_type.Kind == MemberKind.MissingType)
1445                                 MemberCache = MemberCache.Empty;
1446
1447                         if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1448                                 state |= StateFlags.ConstraintsChecked;
1449                 }
1450
1451                 #region Properties
1452
1453                 public override TypeSpec BaseType {
1454                         get {
1455                                 if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1456                                         InitializeMemberCache (true);
1457
1458                                 return base.BaseType;
1459                         }
1460                 }
1461
1462                 //
1463                 // Inflated type parameters with constraints array, mapping with type arguments is based on index
1464                 //
1465                 public TypeParameterSpec[] Constraints {
1466                         get {
1467                                 if (constraints == null) {
1468                                         constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1469                                 }
1470
1471                                 return constraints;
1472                         }
1473                 }
1474
1475                 //
1476                 // Used to cache expensive constraints validation on constructed types
1477                 //
1478                 public bool HasConstraintsChecked {
1479                         get {
1480                                 return (state & StateFlags.ConstraintsChecked) != 0;
1481                         }
1482                         set {
1483                                 state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1484                         }
1485                 }
1486
1487                 public override IList<TypeSpec> Interfaces {
1488                         get {
1489                                 if (cache == null)
1490                                         InitializeMemberCache (true);
1491
1492                                 return base.Interfaces;
1493                         }
1494                 }
1495
1496                 public override bool IsExpressionTreeType {
1497                         get {
1498                                 return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1499                         }
1500                 }
1501
1502                 public override bool IsGenericIterateInterface {
1503                         get {
1504                                 return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1505                         }
1506                 }
1507
1508                 public override bool IsNullableType {
1509                         get {
1510                                 return (open_type.state & StateFlags.InflatedNullableType) != 0;
1511                         }
1512                 }
1513
1514                 //
1515                 // Types used to inflate the generic  type
1516                 //
1517                 public override TypeSpec[] TypeArguments {
1518                         get {
1519                                 return targs;
1520                         }
1521                 }
1522
1523                 #endregion
1524
1525                 public static bool ContainsTypeParameter (TypeSpec type)
1526                 {
1527                         if (type.Kind == MemberKind.TypeParameter)
1528                                 return true;
1529
1530                         var element_container = type as ElementTypeSpec;
1531                         if (element_container != null)
1532                                 return ContainsTypeParameter (element_container.Element);
1533
1534                         foreach (var t in type.TypeArguments) {
1535                                 if (ContainsTypeParameter (t)) {
1536                                         return true;
1537                                 }
1538                         }
1539
1540                         return false;
1541                 }
1542
1543                 TypeParameterInflator CreateLocalInflator (IModuleContext context)
1544                 {
1545                         TypeParameterSpec[] tparams_full;
1546                         TypeSpec[] targs_full = targs;
1547                         if (IsNested) {
1548                                 //
1549                                 // Special case is needed when we are inflating an open type (nested type definition)
1550                                 // on inflated parent. Consider following case
1551                                 //
1552                                 // Foo<T>.Bar<U> => Foo<string>.Bar<U>
1553                                 //
1554                                 // Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1555                                 //
1556                                 List<TypeSpec> merged_targs = null;
1557                                 List<TypeParameterSpec> merged_tparams = null;
1558
1559                                 var type = DeclaringType;
1560
1561                                 do {
1562                                         if (type.TypeArguments.Length > 0) {
1563                                                 if (merged_targs == null) {
1564                                                         merged_targs = new List<TypeSpec> ();
1565                                                         merged_tparams = new List<TypeParameterSpec> ();
1566                                                         if (targs.Length > 0) {
1567                                                                 merged_targs.AddRange (targs);
1568                                                                 merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1569                                                         }
1570                                                 }
1571                                                 merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1572                                                 merged_targs.AddRange (type.TypeArguments);
1573                                         }
1574                                         type = type.DeclaringType;
1575                                 } while (type != null);
1576
1577                                 if (merged_targs != null) {
1578                                         // Type arguments are not in the right order but it should not matter in this case
1579                                         targs_full = merged_targs.ToArray ();
1580                                         tparams_full = merged_tparams.ToArray ();
1581                                 } else if (targs.Length == 0) {
1582                                         tparams_full = TypeParameterSpec.EmptyTypes;
1583                                 } else {
1584                                         tparams_full = open_type.MemberDefinition.TypeParameters;
1585                                 }
1586                         } else if (targs.Length == 0) {
1587                                 tparams_full = TypeParameterSpec.EmptyTypes;
1588                         } else {
1589                                 tparams_full = open_type.MemberDefinition.TypeParameters;
1590                         }
1591
1592                         return new TypeParameterInflator (context, this, tparams_full, targs_full);
1593                 }
1594
1595                 MetaType CreateMetaInfo (TypeParameterMutator mutator)
1596                 {
1597                         //
1598                         // Converts nested type arguments into right order
1599                         // Foo<string, bool>.Bar<int> => string, bool, int
1600                         //
1601                         var all = new List<MetaType> ();
1602                         TypeSpec type = this;
1603                         TypeSpec definition = type;
1604                         do {
1605                                 if (type.GetDefinition().IsGeneric) {
1606                                         all.InsertRange (0,
1607                                                 type.TypeArguments != TypeSpec.EmptyTypes ?
1608                                                 type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1609                                                 type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1610                                 }
1611
1612                                 definition = definition.GetDefinition ();
1613                                 type = type.DeclaringType;
1614                         } while (type != null);
1615
1616                         return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1617                 }
1618
1619                 public override ObsoleteAttribute GetAttributeObsolete ()
1620                 {
1621                         return open_type.GetAttributeObsolete ();
1622                 }
1623
1624                 protected override bool IsNotCLSCompliant (out bool attrValue)
1625                 {
1626                         if (base.IsNotCLSCompliant (out attrValue))
1627                                 return true;
1628
1629                         foreach (var ta in TypeArguments) {
1630                                 if (ta.MemberDefinition.CLSAttributeValue == false)
1631                                         return true;
1632                         }
1633
1634                         return false;
1635                 }
1636
1637                 public override TypeSpec GetDefinition ()
1638                 {
1639                         return open_type;
1640                 }
1641
1642                 public override MetaType GetMetaInfo ()
1643                 {
1644                         if (info == null)
1645                                 info = CreateMetaInfo (null);
1646
1647                         return info;
1648                 }
1649
1650                 public override string GetSignatureForError ()
1651                 {
1652                         if (IsNullableType)
1653                                 return targs[0].GetSignatureForError () + "?";
1654
1655                         return base.GetSignatureForError ();
1656                 }
1657
1658                 protected override string GetTypeNameSignature ()
1659                 {
1660                         if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1661                                 return null;
1662
1663                         return "<" + TypeManager.CSharpName (targs) + ">";
1664                 }
1665
1666                 public bool HasDynamicArgument ()
1667                 {
1668                         for (int i = 0; i < targs.Length; ++i) {
1669                                 var item = targs[i];
1670
1671                                 if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1672                                         return true;
1673
1674                                 if (item is InflatedTypeSpec) {
1675                                         if (((InflatedTypeSpec) item).HasDynamicArgument ())
1676                                                 return true;
1677
1678                                         continue;
1679                                 }
1680
1681                                 if (item.IsArray) {
1682                                         while (item.IsArray) {
1683                                                 item = ((ArrayContainer) item).Element;
1684                                         }
1685
1686                                         if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1687                                                 return true;
1688                                 }
1689                         }
1690
1691                         return false;
1692                 }
1693
1694                 protected override void InitializeMemberCache (bool onlyTypes)
1695                 {
1696                         if (cache == null) {
1697                                 var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1698
1699                                 // Surprisingly, calling MemberCache on open type could meantime create cache on this type
1700                                 // for imported type parameter constraints referencing nested type of this declaration
1701                                 if (cache == null)
1702                                         cache = new MemberCache (open_cache);
1703                         }
1704
1705                         var inflator = CreateLocalInflator (context);
1706
1707                         //
1708                         // Two stage inflate due to possible nested types recursive
1709                         // references
1710                         //
1711                         // class A<T> {
1712                         //    B b;
1713                         //    class B {
1714                         //      T Value;
1715                         //    }
1716                         // }
1717                         //
1718                         // When resolving type of `b' members of `B' cannot be 
1719                         // inflated because are not yet available in membercache
1720                         //
1721                         if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1722                                 open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1723
1724                                 //
1725                                 // Inflate any implemented interfaces
1726                                 //
1727                                 if (open_type.Interfaces != null) {
1728                                         ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1729                                         foreach (var iface in open_type.Interfaces) {
1730                                                 var iface_inflated = inflator.Inflate (iface);
1731                                                 if (iface_inflated == null)
1732                                                         continue;
1733
1734                                                 AddInterface (iface_inflated);
1735                                         }
1736                                 }
1737
1738                                 //
1739                                 // Handles the tricky case of recursive nested base generic type
1740                                 //
1741                                 // class A<T> : Base<A<T>.Nested> {
1742                                 //    class Nested {}
1743                                 // }
1744                                 //
1745                                 // When inflating A<T>. base type is not yet known, secondary
1746                                 // inflation is required (not common case) once base scope
1747                                 // is known
1748                                 //
1749                                 if (open_type.BaseType == null) {
1750                                         if (IsClass)
1751                                                 state |= StateFlags.PendingBaseTypeInflate;
1752                                 } else {
1753                                         BaseType = inflator.Inflate (open_type.BaseType);
1754                                 }
1755                         } else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1756                                 BaseType = inflator.Inflate (open_type.BaseType);
1757                                 state &= ~StateFlags.PendingBaseTypeInflate;
1758                         }
1759
1760                         if (onlyTypes) {
1761                                 state |= StateFlags.PendingMemberCacheMembers;
1762                                 return;
1763                         }
1764
1765                         var tc = open_type.MemberDefinition as TypeContainer;
1766                         if (tc != null && !tc.HasMembersDefined)
1767                                 throw new InternalErrorException ("Inflating MemberCache with undefined members");
1768
1769                         if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1770                                 BaseType = inflator.Inflate (open_type.BaseType);
1771                                 state &= ~StateFlags.PendingBaseTypeInflate;
1772                         }
1773
1774                         state &= ~StateFlags.PendingMemberCacheMembers;
1775                         open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1776                 }
1777
1778                 public override TypeSpec Mutate (TypeParameterMutator mutator)
1779                 {
1780                         var targs = TypeArguments;
1781                         if (targs != null)
1782                                 targs = mutator.Mutate (targs);
1783
1784                         var decl = DeclaringType;
1785                         if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1786                                 decl = mutator.Mutate (decl);
1787
1788                         if (targs == TypeArguments && decl == DeclaringType)
1789                                 return this;
1790
1791                         var mutated = (InflatedTypeSpec) MemberwiseClone ();
1792                         if (decl != DeclaringType) {
1793                                 // Gets back MethodInfo in case of metaInfo was inflated
1794                                 //mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1795
1796                                 mutated.declaringType = decl;
1797                                 mutated.state |= StateFlags.PendingMetaInflate;
1798                         }
1799
1800                         if (targs != null) {
1801                                 mutated.targs = targs;
1802                                 mutated.info = null;
1803                         }
1804
1805                         return mutated;
1806                 }
1807         }
1808
1809
1810         //
1811         // Tracks the type arguments when instantiating a generic type. It's used
1812         // by both type arguments and type parameters
1813         //
1814         public class TypeArguments
1815         {
1816                 List<FullNamedExpression> args;
1817                 TypeSpec[] atypes;
1818
1819                 public TypeArguments (params FullNamedExpression[] types)
1820                 {
1821                         this.args = new List<FullNamedExpression> (types);
1822                 }
1823
1824                 public void Add (FullNamedExpression type)
1825                 {
1826                         args.Add (type);
1827                 }
1828
1829                 // TODO: Kill this monster
1830                 public TypeParameterName[] GetDeclarations ()
1831                 {
1832                         return args.ConvertAll (i => (TypeParameterName) i).ToArray ();
1833                 }
1834
1835                 /// <summary>
1836                 ///   We may only be used after Resolve() is called and return the fully
1837                 ///   resolved types.
1838                 /// </summary>
1839                 // TODO: Not needed, just return type from resolve
1840                 public TypeSpec[] Arguments {
1841                         get {
1842                                 return atypes;
1843                         }
1844                         set {
1845                                 atypes = value;
1846                         }
1847                 }
1848
1849                 public int Count {
1850                         get {
1851                                 return args.Count;
1852                         }
1853                 }
1854
1855                 public virtual bool IsEmpty {
1856                         get {
1857                                 return false;
1858                         }
1859                 }
1860
1861                 public string GetSignatureForError()
1862                 {
1863                         StringBuilder sb = new StringBuilder ();
1864                         for (int i = 0; i < Count; ++i) {
1865                                 var expr = args[i];
1866                                 if (expr != null)
1867                                         sb.Append (expr.GetSignatureForError ());
1868
1869                                 if (i + 1 < Count)
1870                                         sb.Append (',');
1871                         }
1872
1873                         return sb.ToString ();
1874                 }
1875
1876                 /// <summary>
1877                 ///   Resolve the type arguments.
1878                 /// </summary>
1879                 public virtual bool Resolve (IMemberContext ec)
1880                 {
1881                         if (atypes != null)
1882                             return atypes.Length != 0;
1883
1884                         int count = args.Count;
1885                         bool ok = true;
1886
1887                         atypes = new TypeSpec [count];
1888
1889                         for (int i = 0; i < count; i++){
1890                                 var te = args[i].ResolveAsType (ec);
1891                                 if (te == null) {
1892                                         ok = false;
1893                                         continue;
1894                                 }
1895
1896                                 atypes[i] = te;
1897
1898                                 if (te.IsStatic) {
1899                                         ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
1900                                                 te.GetSignatureForError ());
1901                                         ok = false;
1902                                 }
1903
1904                                 if (te.IsPointer || te.IsSpecialRuntimeType) {
1905                                         ec.Module.Compiler.Report.Error (306, args[i].Location,
1906                                                 "The type `{0}' may not be used as a type argument",
1907                                                 te.GetSignatureForError ());
1908                                         ok = false;
1909                                 }
1910                         }
1911
1912                         if (!ok)
1913                                 atypes = TypeSpec.EmptyTypes;
1914
1915                         return ok;
1916                 }
1917
1918                 public TypeArguments Clone ()
1919                 {
1920                         TypeArguments copy = new TypeArguments ();
1921                         foreach (var ta in args)
1922                                 copy.args.Add (ta);
1923
1924                         return copy;
1925                 }
1926         }
1927
1928         public class UnboundTypeArguments : TypeArguments
1929         {
1930                 public UnboundTypeArguments (int arity)
1931                         : base (new FullNamedExpression[arity])
1932                 {
1933                 }
1934
1935                 public override bool IsEmpty {
1936                         get {
1937                                 return true;
1938                         }
1939                 }
1940
1941                 public override bool Resolve (IMemberContext ec)
1942                 {
1943                         // Nothing to be resolved
1944                         return true;
1945                 }
1946         }
1947
1948         public class TypeParameterName : SimpleName
1949         {
1950                 Attributes attributes;
1951                 Variance variance;
1952
1953                 public TypeParameterName (string name, Attributes attrs, Location loc)
1954                         : this (name, attrs, Variance.None, loc)
1955                 {
1956                 }
1957
1958                 public TypeParameterName (string name, Attributes attrs, Variance variance, Location loc)
1959                         : base (name, loc)
1960                 {
1961                         attributes = attrs;
1962                         this.variance = variance;
1963                 }
1964
1965                 public Attributes OptAttributes {
1966                         get {
1967                                 return attributes;
1968                         }
1969                 }
1970
1971                 public Variance Variance {
1972                         get {
1973                                 return variance;
1974                         }
1975                 }
1976         }
1977
1978         //
1979         // A type expression of generic type with type arguments
1980         //
1981         class GenericTypeExpr : TypeExpr
1982         {
1983                 TypeArguments args;
1984                 TypeSpec open_type;
1985
1986                 /// <summary>
1987                 ///   Instantiate the generic type `t' with the type arguments `args'.
1988                 ///   Use this constructor if you already know the fully resolved
1989                 ///   generic type.
1990                 /// </summary>          
1991                 public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
1992                 {
1993                         this.open_type = open_type;
1994                         loc = l;
1995                         this.args = args;
1996                 }
1997
1998                 public TypeArguments TypeArguments {
1999                         get { return args; }
2000                 }
2001
2002                 public override string GetSignatureForError ()
2003                 {
2004                         return TypeManager.CSharpName (type);
2005                 }
2006
2007                 public override TypeSpec ResolveAsType (IMemberContext mc)
2008                 {
2009                         if (eclass != ExprClass.Unresolved)
2010                                 return type;
2011
2012                         if (!args.Resolve (mc))
2013                                 return null;
2014
2015                         TypeSpec[] atypes = args.Arguments;
2016
2017                         //
2018                         // Now bind the parameters
2019                         //
2020                         var inflated = open_type.MakeGenericType (mc, atypes);
2021                         type = inflated;
2022                         eclass = ExprClass.Type;
2023
2024                         //
2025                         // The constraints can be checked only when full type hierarchy is known
2026                         //
2027                         if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2028                                 var constraints = inflated.Constraints;
2029                                 if (constraints != null) {
2030                                         var cc = new ConstraintChecker (mc);
2031                                         if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2032                                                 inflated.HasConstraintsChecked = true;
2033                                         }
2034                                 }
2035                         }
2036
2037                         return type;
2038                 }
2039
2040                 public override bool Equals (object obj)
2041                 {
2042                         GenericTypeExpr cobj = obj as GenericTypeExpr;
2043                         if (cobj == null)
2044                                 return false;
2045
2046                         if ((type == null) || (cobj.type == null))
2047                                 return false;
2048
2049                         return type == cobj.type;
2050                 }
2051
2052                 public override int GetHashCode ()
2053                 {
2054                         return base.GetHashCode ();
2055                 }
2056         }
2057
2058         //
2059         // Generic type with unbound type arguments, used for typeof (G<,,>)
2060         //
2061         class GenericOpenTypeExpr : TypeExpression
2062         {
2063                 public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2064                         : base (type.GetDefinition (), loc)
2065                 {
2066                 }
2067         }
2068
2069         struct ConstraintChecker
2070         {
2071                 IMemberContext mc;
2072                 bool ignore_inferred_dynamic;
2073                 bool recursive_checks;
2074
2075                 public ConstraintChecker (IMemberContext ctx)
2076                 {
2077                         this.mc = ctx;
2078                         ignore_inferred_dynamic = false;
2079                         recursive_checks = false;
2080                 }
2081
2082                 #region Properties
2083
2084                 public bool IgnoreInferredDynamic {
2085                         get {
2086                                 return ignore_inferred_dynamic;
2087                         }
2088                         set {
2089                                 ignore_inferred_dynamic = value;
2090                         }
2091                 }
2092
2093                 #endregion
2094
2095                 //
2096                 // Checks the constraints of open generic type against type
2097                 // arguments. This version is used for types which could not be
2098                 // checked immediatelly during construction because the type
2099                 // hierarchy was not yet fully setup (before Emit phase)
2100                 //
2101                 public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2102                 {
2103                         //
2104                         // Check declaring type first if there is any
2105                         //
2106                         if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2107                                 return false;
2108
2109                         while (type is ElementTypeSpec)
2110                                 type = ((ElementTypeSpec) type).Element;
2111
2112                         if (type.Arity == 0)
2113                                 return true;
2114
2115                         var gtype = type as InflatedTypeSpec;
2116                         if (gtype == null)
2117                                 return true;
2118
2119                         var constraints = gtype.Constraints;
2120                         if (constraints == null)
2121                                 return true;
2122
2123                         if (gtype.HasConstraintsChecked)
2124                                 return true;
2125
2126                         var cc = new ConstraintChecker (mc);
2127                         cc.recursive_checks = true;
2128
2129                         if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2130                                 gtype.HasConstraintsChecked = true;
2131                                 return true;
2132                         }
2133
2134                         return false;
2135                 }
2136
2137                 //
2138                 // Checks all type arguments againts type parameters constraints
2139                 // NOTE: It can run in probing mode when `mc' is null
2140                 //
2141                 public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2142                 {
2143                         for (int i = 0; i < tparams.Length; i++) {
2144                                 if (ignore_inferred_dynamic && targs[i].BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2145                                         continue;
2146
2147                                 var targ = targs[i];
2148                                 if (!CheckConstraint (context, targ, tparams [i], loc))
2149                                         return false;
2150
2151                                 if (!recursive_checks)
2152                                         continue;
2153
2154                                 if (!Check (mc, targ, loc))
2155                                         return false;
2156                         }
2157
2158                         return true;
2159                 }
2160
2161                 bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2162                 {
2163                         //
2164                         // First, check the `class' and `struct' constraints.
2165                         //
2166                         if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2167                                 if (mc != null) {
2168                                         mc.Module.Compiler.Report.Error (452, loc,
2169                                                 "The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2170                                                 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2171                                 }
2172
2173                                 return false;
2174                         }
2175
2176                         if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2177                                 if (mc != null) {
2178                                         mc.Module.Compiler.Report.Error (453, loc,
2179                                                 "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}'",
2180                                                 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2181                                 }
2182
2183                                 return false;
2184                         }
2185
2186                         bool ok = true;
2187
2188                         //
2189                         // Check the class constraint
2190                         //
2191                         if (tparam.HasTypeConstraint) {
2192                                 var dep = tparam.BaseType.GetMissingDependencies ();
2193                                 if (dep != null) {
2194                                         if (mc == null)
2195                                                 return false;
2196
2197                                         ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2198                                         ok = false;
2199                                 }
2200
2201                                 if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2202                                         if (mc == null)
2203                                                 return false;
2204
2205                                         ok = false;
2206                                 }
2207                         }
2208
2209                         //
2210                         // Check the interfaces constraints
2211                         //
2212                         if (tparam.Interfaces != null) {
2213                                 if (atype.IsNullableType) {
2214                                         if (mc == null)
2215                                                 return false;
2216
2217                                         mc.Module.Compiler.Report.Error (313, loc,
2218                                                 "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",
2219                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError ());
2220                                         ok = false;
2221                                 } else {
2222                                         foreach (TypeSpec iface in tparam.Interfaces) {
2223                                                 var dep = iface.GetMissingDependencies ();
2224                                                 if (dep != null) {
2225                                                         if (mc == null)
2226                                                                 return false;
2227
2228                                                         ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
2229                                                         ok = false;
2230
2231                                                         // return immediately to avoid duplicate errors because we are scanning
2232                                                         // expanded interface list
2233                                                         return false;
2234                                                 }
2235
2236                                                 if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2237                                                         if (mc == null)
2238                                                                 return false;
2239
2240                                                         ok = false;
2241                                                 }
2242                                         }
2243                                 }
2244                         }
2245
2246                         //
2247                         // Check the type parameter constraint
2248                         //
2249                         if (tparam.TypeArguments != null) {
2250                                 foreach (var ta in tparam.TypeArguments) {
2251                                         if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2252                                                 if (mc == null)
2253                                                         return false;
2254
2255                                                 ok = false;
2256                                         }
2257                                 }
2258                         }
2259
2260                         //
2261                         // Finally, check the constructor constraint.
2262                         //
2263                         if (!tparam.HasSpecialConstructor)
2264                                 return ok;
2265
2266                         if (!HasDefaultConstructor (atype)) {
2267                                 if (mc != null) {
2268                                         mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2269                                         mc.Module.Compiler.Report.Error (310, loc,
2270                                                 "The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2271                                                 TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2272                                 }
2273                                 return false;
2274                         }
2275
2276                         return ok;
2277                 }
2278
2279                 static bool HasDynamicTypeArgument (TypeSpec[] targs)
2280                 {
2281                         for (int i = 0; i < targs.Length; ++i) {
2282                                 var targ = targs [i];
2283                                 if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2284                                         return true;
2285
2286                                 if (HasDynamicTypeArgument (targ.TypeArguments))
2287                                         return true;
2288                         }
2289
2290                         return false;
2291                 }
2292
2293                 bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2294                 {
2295                         if (atype == ttype)
2296                                 return true;
2297
2298                         if (atype.IsGenericParameter) {
2299                                 var tps = (TypeParameterSpec) atype;
2300                                 if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2301                                         return true;
2302
2303                                 //
2304                                 // LAMESPEC: Identity conversion with inflated type parameter
2305                                 // It's not clear from the spec what rule should apply to inherited
2306                                 // inflated type parameter. The specification allows only type parameter
2307                                 // conversion but that's clearly not enough
2308                                 //
2309                                 if (tps.HasTypeConstraint && tps.BaseType == ttype)
2310                                         return true;
2311
2312                         } else if (TypeSpec.IsValueType (atype)) {
2313                                 if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2314                                         return true;
2315                         } else {
2316                                 var expr = new EmptyExpression (atype);
2317                                 if (Convert.ImplicitStandardConversionExists (expr, ttype))
2318                                         return true;
2319                         }
2320
2321                         //
2322                         // When partial/full type inference finds a dynamic type argument delay
2323                         // the constraint check to runtime, it can succeed for real underlying
2324                         // dynamic type
2325                         //
2326                         if (ignore_inferred_dynamic && HasDynamicTypeArgument (ttype.TypeArguments))
2327                                 return true;
2328
2329                         if (mc != null) {
2330                                 mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2331                                 if (atype.IsGenericParameter) {
2332                                         mc.Module.Compiler.Report.Error (314, loc,
2333                                                 "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}'",
2334                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2335                                 } else if (TypeSpec.IsValueType (atype)) {
2336                                         mc.Module.Compiler.Report.Error (315, loc,
2337                                                 "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}'",
2338                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2339                                 } else {
2340                                         mc.Module.Compiler.Report.Error (311, loc,
2341                                                 "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}'",
2342                                                 atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2343                                 }
2344                         }
2345
2346                         return false;
2347                 }
2348
2349                 bool HasDefaultConstructor (TypeSpec atype)
2350                 {
2351                         var tp = atype as TypeParameterSpec;
2352                         if (tp != null) {
2353                                 return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2354                         }
2355
2356                         if (atype.IsStruct || atype.IsEnum)
2357                                 return true;
2358
2359                         if (atype.IsAbstract)
2360                                 return false;
2361
2362                         var tdef = atype.GetDefinition ();
2363
2364                         var found = MemberCache.FindMember (tdef,
2365                                 MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2366                                 BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2367
2368                         return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2369                 }
2370         }
2371
2372         /// <summary>
2373         ///   A generic method definition.
2374         /// </summary>
2375         public class GenericMethod : DeclSpace
2376         {
2377                 ParametersCompiled parameters;
2378
2379                 public GenericMethod (NamespaceContainer ns, DeclSpace parent, MemberName name,
2380                                       FullNamedExpression return_type, ParametersCompiled parameters)
2381                         : base (ns, parent, name, null)
2382                 {
2383                         this.parameters = parameters;
2384                 }
2385
2386                 public GenericMethod (NamespaceContainer ns, DeclSpace parent, MemberName name, TypeParameter[] tparams,
2387                                           FullNamedExpression return_type, ParametersCompiled parameters)
2388                         : this (ns, parent, name, return_type, parameters)
2389                 {
2390                         this.type_params = tparams;
2391                 }
2392
2393                 public override TypeParameter[] CurrentTypeParameters {
2394                         get {
2395                                 return base.type_params;
2396                         }
2397                 }
2398
2399                 protected override TypeAttributes TypeAttr {
2400                         get {
2401                                 throw new NotSupportedException ();
2402                         }
2403                 }
2404
2405                 public override void DefineType ()
2406                 {
2407                         throw new Exception ();
2408                 }
2409
2410                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2411                 {
2412                         throw new NotSupportedException ();
2413                 }
2414
2415                 public override bool Define ()
2416                 {
2417                         throw new NotSupportedException ();
2418                 }
2419
2420                 /// <summary>
2421                 ///   Define and resolve the type parameters.
2422                 ///   We're called from Method.Define().
2423                 /// </summary>
2424                 public bool Define (MethodOrOperator m)
2425                 {
2426                         TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
2427                         string[] snames = new string [names.Length];
2428                         var block = m.Block;
2429                         for (int i = 0; i < names.Length; i++) {
2430                                 string type_argument_name = names[i].Name;
2431
2432                                 if (block == null) {
2433                                         int idx = parameters.GetParameterIndexByName (type_argument_name);
2434                                         if (idx >= 0) {
2435                                                 var b = m.Block;
2436                                                 if (b == null)
2437                                                         b = new ToplevelBlock (Compiler, Location);
2438
2439                                                 b.Error_AlreadyDeclaredTypeParameter (type_argument_name, parameters[i].Location);
2440                                         }
2441                                 } else {
2442                                         INamedBlockVariable variable = null;
2443                                         block.GetLocalName (type_argument_name, m.Block, ref variable);
2444                                         if (variable != null)
2445                                                 variable.Block.Error_AlreadyDeclaredTypeParameter (type_argument_name, variable.Location);
2446                                 }
2447
2448                                 snames[i] = type_argument_name;
2449                         }
2450
2451                         GenericTypeParameterBuilder[] gen_params = m.MethodBuilder.DefineGenericParameters (snames);
2452                         for (int i = 0; i < TypeParameters.Length; i++)
2453                                 TypeParameters [i].Define (gen_params [i], null);
2454
2455                         return true;
2456                 }
2457
2458                 public void EmitAttributes ()
2459                 {
2460                         if (OptAttributes != null)
2461                                 OptAttributes.Emit ();
2462                 }
2463
2464                 public override string GetSignatureForError ()
2465                 {
2466                         return base.GetSignatureForError () + parameters.GetSignatureForError ();
2467                 }
2468
2469                 public override AttributeTargets AttributeTargets {
2470                         get {
2471                                 return AttributeTargets.Method | AttributeTargets.ReturnValue;
2472                         }
2473                 }
2474
2475                 public override string DocCommentHeader {
2476                         get { return "M:"; }
2477                 }
2478
2479                 public new void VerifyClsCompliance ()
2480                 {
2481                         foreach (TypeParameter tp in TypeParameters) {
2482                                 tp.VerifyClsCompliance ();
2483                         }
2484                 }
2485         }
2486
2487         public partial class TypeManager
2488         {
2489                 public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2490                 {
2491                         var tp = t as TypeParameterSpec;
2492                         if (tp != null) {
2493                                 Variance v = tp.Variance;
2494                                 if (expected == Variance.None && v != expected ||
2495                                         expected == Variance.Covariant && v == Variance.Contravariant ||
2496                                         expected == Variance.Contravariant && v == Variance.Covariant) {
2497                                         ((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2498                                 }
2499
2500                                 return expected;
2501                         }
2502
2503                         if (t.TypeArguments.Length > 0) {
2504                                 var targs_definition = t.MemberDefinition.TypeParameters;
2505                                 TypeSpec[] targs = GetTypeArguments (t);
2506                                 for (int i = 0; i < targs.Length; ++i) {
2507                                         Variance v = targs_definition[i].Variance;
2508                                         CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2509                                 }
2510
2511                                 return expected;
2512                         }
2513
2514                         if (t.IsArray)
2515                                 return CheckTypeVariance (GetElementType (t), expected, member);
2516
2517                         return Variance.None;
2518                 }
2519         }
2520
2521         //
2522         // Implements C# type inference
2523         //
2524         class TypeInference
2525         {
2526                 //
2527                 // Tracks successful rate of type inference
2528                 //
2529                 int score = int.MaxValue;
2530                 readonly Arguments arguments;
2531                 readonly int arg_count;
2532
2533                 public TypeInference (Arguments arguments)
2534                 {
2535                         this.arguments = arguments;
2536                         if (arguments != null)
2537                                 arg_count = arguments.Count;
2538                 }
2539
2540                 public int InferenceScore {
2541                         get {
2542                                 return score;
2543                         }
2544                 }
2545
2546                 public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2547                 {
2548                         var method_generic_args = method.GenericDefinition.TypeParameters;
2549                         TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2550                         if (!context.UnfixedVariableExists)
2551                                 return TypeSpec.EmptyTypes;
2552
2553                         AParametersCollection pd = method.Parameters;
2554                         if (!InferInPhases (ec, context, pd))
2555                                 return null;
2556
2557                         return context.InferredTypeArguments;
2558                 }
2559
2560                 //
2561                 // Implements method type arguments inference
2562                 //
2563                 bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2564                 {
2565                         int params_arguments_start;
2566                         if (methodParameters.HasParams) {
2567                                 params_arguments_start = methodParameters.Count - 1;
2568                         } else {
2569                                 params_arguments_start = arg_count;
2570                         }
2571
2572                         TypeSpec [] ptypes = methodParameters.Types;
2573                         
2574                         //
2575                         // The first inference phase
2576                         //
2577                         TypeSpec method_parameter = null;
2578                         for (int i = 0; i < arg_count; i++) {
2579                                 Argument a = arguments [i];
2580                                 if (a == null)
2581                                         continue;
2582                                 
2583                                 if (i < params_arguments_start) {
2584                                         method_parameter = methodParameters.Types [i];
2585                                 } else if (i == params_arguments_start) {
2586                                         if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2587                                                 method_parameter = methodParameters.Types [params_arguments_start];
2588                                         else
2589                                                 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2590
2591                                         ptypes = (TypeSpec[]) ptypes.Clone ();
2592                                         ptypes [i] = method_parameter;
2593                                 }
2594
2595                                 //
2596                                 // When a lambda expression, an anonymous method
2597                                 // is used an explicit argument type inference takes a place
2598                                 //
2599                                 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2600                                 if (am != null) {
2601                                         if (am.ExplicitTypeInference (ec, tic, method_parameter))
2602                                                 --score; 
2603                                         continue;
2604                                 }
2605
2606                                 if (a.IsByRef) {
2607                                         score -= tic.ExactInference (a.Type, method_parameter);
2608                                         continue;
2609                                 }
2610
2611                                 if (a.Expr.Type == InternalType.NullLiteral)
2612                                         continue;
2613
2614                                 if (TypeSpec.IsValueType (method_parameter)) {
2615                                         score -= tic.LowerBoundInference (a.Type, method_parameter);
2616                                         continue;
2617                                 }
2618
2619                                 //
2620                                 // Otherwise an output type inference is made
2621                                 //
2622                                 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2623                         }
2624
2625                         //
2626                         // Part of the second phase but because it happens only once
2627                         // we don't need to call it in cycle
2628                         //
2629                         bool fixed_any = false;
2630                         if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2631                                 return false;
2632
2633                         return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2634                 }
2635
2636                 bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2637                 {
2638                         bool fixed_any = false;
2639                         if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2640                                 return false;
2641
2642                         // If no further unfixed type variables exist, type inference succeeds
2643                         if (!tic.UnfixedVariableExists)
2644                                 return true;
2645
2646                         if (!fixed_any && fixDependent)
2647                                 return false;
2648                         
2649                         // For all arguments where the corresponding argument output types
2650                         // contain unfixed type variables but the input types do not,
2651                         // an output type inference is made
2652                         for (int i = 0; i < arg_count; i++) {
2653                                 
2654                                 // Align params arguments
2655                                 TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2656                                 
2657                                 if (!TypeManager.IsDelegateType (t_i)) {
2658                                         if (!t_i.IsExpressionTreeType)
2659                                                 continue;
2660
2661                                         t_i = TypeManager.GetTypeArguments (t_i) [0];
2662                                 }
2663
2664                                 var mi = Delegate.GetInvokeMethod (t_i);
2665                                 TypeSpec rtype = mi.ReturnType;
2666
2667                                 if (tic.IsReturnTypeNonDependent (ec, mi, rtype))
2668                                         score -= tic.OutputTypeInference (ec, arguments [i].Expr, t_i);
2669                         }
2670
2671
2672                         return DoSecondPhase (ec, tic, methodParameters, true);
2673                 }
2674         }
2675
2676         public class TypeInferenceContext
2677         {
2678                 protected enum BoundKind
2679                 {
2680                         Exact   = 0,
2681                         Lower   = 1,
2682                         Upper   = 2
2683                 }
2684
2685                 protected class BoundInfo : IEquatable<BoundInfo>
2686                 {
2687                         public readonly TypeSpec Type;
2688                         public readonly BoundKind Kind;
2689
2690                         public BoundInfo (TypeSpec type, BoundKind kind)
2691                         {
2692                                 this.Type = type;
2693                                 this.Kind = kind;
2694                         }
2695                         
2696                         public override int GetHashCode ()
2697                         {
2698                                 return Type.GetHashCode ();
2699                         }
2700
2701                         public virtual Expression GetTypeExpression ()
2702                         {
2703                                 return new TypeExpression (Type, Location.Null);
2704                         }
2705
2706                         #region IEquatable<BoundInfo> Members
2707
2708                         public virtual bool Equals (BoundInfo other)
2709                         {
2710                                 return Type == other.Type && Kind == other.Kind;
2711                         }
2712
2713                         #endregion
2714                 }
2715
2716                 readonly TypeSpec[] tp_args;
2717                 readonly TypeSpec[] fixed_types;
2718                 readonly List<BoundInfo>[] bounds;
2719                 bool failed;
2720
2721                 // TODO MemberCache: Could it be TypeParameterSpec[] ??
2722                 public TypeInferenceContext (TypeSpec[] typeArguments)
2723                 {
2724                         if (typeArguments.Length == 0)
2725                                 throw new ArgumentException ("Empty generic arguments");
2726
2727                         fixed_types = new TypeSpec [typeArguments.Length];
2728                         for (int i = 0; i < typeArguments.Length; ++i) {
2729                                 if (typeArguments [i].IsGenericParameter) {
2730                                         if (bounds == null) {
2731                                                 bounds = new List<BoundInfo> [typeArguments.Length];
2732                                                 tp_args = new TypeSpec [typeArguments.Length];
2733                                         }
2734                                         tp_args [i] = typeArguments [i];
2735                                 } else {
2736                                         fixed_types [i] = typeArguments [i];
2737                                 }
2738                         }
2739                 }
2740
2741                 // 
2742                 // Used together with AddCommonTypeBound fo implement
2743                 // 7.4.2.13 Finding the best common type of a set of expressions
2744                 //
2745                 public TypeInferenceContext ()
2746                 {
2747                         fixed_types = new TypeSpec [1];
2748                         tp_args = new TypeSpec [1];
2749                         tp_args[0] = InternalType.Arglist; // it can be any internal type
2750                         bounds = new List<BoundInfo> [1];
2751                 }
2752
2753                 public TypeSpec[] InferredTypeArguments {
2754                         get {
2755                                 return fixed_types;
2756                         }
2757                 }
2758
2759                 public void AddCommonTypeBound (TypeSpec type)
2760                 {
2761                         AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2762                 }
2763
2764                 protected void AddToBounds (BoundInfo bound, int index)
2765                 {
2766                         //
2767                         // Some types cannot be used as type arguments
2768                         //
2769                         if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType)
2770                                 return;
2771
2772                         var a = bounds [index];
2773                         if (a == null) {
2774                                 a = new List<BoundInfo> (2);
2775                                 a.Add (bound);
2776                                 bounds [index] = a;
2777                                 return;
2778                         }
2779
2780                         if (a.Contains (bound))
2781                                 return;
2782
2783                         a.Add (bound);
2784                 }
2785                 
2786                 bool AllTypesAreFixed (TypeSpec[] types)
2787                 {
2788                         foreach (TypeSpec t in types) {
2789                                 if (t.IsGenericParameter) {
2790                                         if (!IsFixed (t))
2791                                                 return false;
2792                                         continue;
2793                                 }
2794
2795                                 if (TypeManager.IsGenericType (t))
2796                                         return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2797                         }
2798                         
2799                         return true;
2800                 }               
2801
2802                 //
2803                 // 26.3.3.8 Exact Inference
2804                 //
2805                 public int ExactInference (TypeSpec u, TypeSpec v)
2806                 {
2807                         // If V is an array type
2808                         if (v.IsArray) {
2809                                 if (!u.IsArray)
2810                                         return 0;
2811
2812                                 // TODO MemberCache: GetMetaInfo ()
2813                                 if (u.GetMetaInfo ().GetArrayRank () != v.GetMetaInfo ().GetArrayRank ())
2814                                         return 0;
2815
2816                                 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2817                         }
2818
2819                         // If V is constructed type and U is constructed type
2820                         if (TypeManager.IsGenericType (v)) {
2821                                 if (!TypeManager.IsGenericType (u))
2822                                         return 0;
2823
2824                                 TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2825                                 TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2826                                 if (ga_u.Length != ga_v.Length)
2827                                         return 0;
2828
2829                                 int score = 0;
2830                                 for (int i = 0; i < ga_u.Length; ++i)
2831                                         score += ExactInference (ga_u [i], ga_v [i]);
2832
2833                                 return score > 0 ? 1 : 0;
2834                         }
2835
2836                         // If V is one of the unfixed type arguments
2837                         int pos = IsUnfixed (v);
2838                         if (pos == -1)
2839                                 return 0;
2840
2841                         AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2842                         return 1;
2843                 }
2844
2845                 public bool FixAllTypes (ResolveContext ec)
2846                 {
2847                         for (int i = 0; i < tp_args.Length; ++i) {
2848                                 if (!FixType (ec, i))
2849                                         return false;
2850                         }
2851                         return true;
2852                 }
2853
2854                 //
2855                 // All unfixed type variables Xi are fixed for which all of the following hold:
2856                 // a, There is at least one type variable Xj that depends on Xi
2857                 // b, Xi has a non-empty set of bounds
2858                 // 
2859                 public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2860                 {
2861                         for (int i = 0; i < tp_args.Length; ++i) {
2862                                 if (fixed_types[i] != null)
2863                                         continue;
2864
2865                                 if (bounds[i] == null)
2866                                         continue;
2867
2868                                 if (!FixType (ec, i))
2869                                         return false;
2870                                 
2871                                 fixed_any = true;
2872                         }
2873
2874                         return true;
2875                 }
2876
2877                 //
2878                 // All unfixed type variables Xi which depend on no Xj are fixed
2879                 //
2880                 public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
2881                 {
2882                         var types_to_fix = new List<TypeSpec> (tp_args);
2883                         for (int i = 0; i < methodParameters.Length; ++i) {
2884                                 TypeSpec t = methodParameters[i];
2885
2886                                 if (!TypeManager.IsDelegateType (t)) {
2887                                         if (!t.IsExpressionTreeType)
2888                                                 continue;
2889
2890                                         t =  TypeManager.GetTypeArguments (t) [0];
2891                                 }
2892
2893                                 if (t.IsGenericParameter)
2894                                         continue;
2895
2896                                 var invoke = Delegate.GetInvokeMethod (t);
2897                                 TypeSpec rtype = invoke.ReturnType;
2898                                 while (rtype.IsArray)
2899                                         rtype = ((ArrayContainer) rtype).Element;
2900
2901                                 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
2902                                         continue;
2903
2904                                 // Remove dependent types, they cannot be fixed yet
2905                                 RemoveDependentTypes (types_to_fix, rtype);
2906                         }
2907
2908                         foreach (TypeSpec t in types_to_fix) {
2909                                 if (t == null)
2910                                         continue;
2911
2912                                 int idx = IsUnfixed (t);
2913                                 if (idx >= 0 && !FixType (ec, idx)) {
2914                                         return false;
2915                                 }
2916                         }
2917
2918                         fixed_any = types_to_fix.Count > 0;
2919                         return true;
2920                 }
2921
2922                 //
2923                 // 26.3.3.10 Fixing
2924                 //
2925                 public bool FixType (ResolveContext ec, int i)
2926                 {
2927                         // It's already fixed
2928                         if (fixed_types[i] != null)
2929                                 throw new InternalErrorException ("Type argument has been already fixed");
2930
2931                         if (failed)
2932                                 return false;
2933
2934                         var candidates = bounds [i];
2935                         if (candidates == null)
2936                                 return false;
2937
2938                         if (candidates.Count == 1) {
2939                                 TypeSpec t = candidates[0].Type;
2940                                 if (t == InternalType.NullLiteral)
2941                                         return false;
2942
2943                                 fixed_types [i] = t;
2944                                 return true;
2945                         }
2946
2947                         //
2948                         // Determines a unique type from which there is
2949                         // a standard implicit conversion to all the other
2950                         // candidate types.
2951                         //
2952                         TypeSpec best_candidate = null;
2953                         int cii;
2954                         int candidates_count = candidates.Count;
2955                         for (int ci = 0; ci < candidates_count; ++ci) {
2956                                 BoundInfo bound = candidates [ci];
2957                                 for (cii = 0; cii < candidates_count; ++cii) {
2958                                         if (cii == ci)
2959                                                 continue;
2960
2961                                         BoundInfo cbound = candidates[cii];
2962                                         
2963                                         // Same type parameters with different bounds
2964                                         if (cbound.Type == bound.Type) {
2965                                                 if (bound.Kind != BoundKind.Exact)
2966                                                         bound = cbound;
2967
2968                                                 continue;
2969                                         }
2970
2971                                         if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
2972                                                 if (cbound.Kind == BoundKind.Lower) {
2973                                                         if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
2974                                                                 break;
2975                                                         }
2976
2977                                                         continue;
2978                                                 }
2979                                                 if (cbound.Kind == BoundKind.Upper) {
2980                                                         if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2981                                                                 break;
2982                                                         }
2983
2984                                                         continue;
2985                                                 }
2986                                                 
2987                                                 if (bound.Kind != BoundKind.Exact) {
2988                                                         if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
2989                                                                 break;
2990                                                         }
2991
2992                                                         bound = cbound;
2993                                                         continue;
2994                                                 }
2995                                                 
2996                                                 break;
2997                                         }
2998
2999                                         if (bound.Kind == BoundKind.Lower) {
3000                                                 if (cbound.Kind == BoundKind.Lower) {
3001                                                         if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3002                                                                 break;
3003                                                         }
3004                                                 } else {
3005                                                         if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3006                                                                 break;
3007                                                         }
3008
3009                                                         bound = cbound;
3010                                                 }
3011
3012                                                 continue;
3013                                         }
3014
3015                                         if (bound.Kind == BoundKind.Upper) {
3016                                                 if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3017                                                         break;
3018                                                 }
3019                                         } else {
3020                                                 throw new NotImplementedException ("variance conversion");
3021                                         }
3022                                 }
3023
3024                                 if (cii != candidates_count)
3025                                         continue;
3026
3027                                 //
3028                                 // We already have the best candidate, break if thet are different
3029                                 //
3030                                 // Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3031                                 //
3032                                 if (best_candidate != null) {
3033
3034                                         if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3035                                                 continue;
3036
3037                                         if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3038                                                 return false;
3039                                 }
3040
3041                                 best_candidate = bound.Type;
3042                         }
3043
3044                         if (best_candidate == null)
3045                                 return false;
3046
3047                         fixed_types[i] = best_candidate;
3048                         return true;
3049                 }
3050                 
3051                 //
3052                 // Uses inferred or partially infered types to inflate delegate type argument. Returns
3053                 // null when type parameter has not been fixed
3054                 //
3055                 public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3056                 {
3057                         var tp = parameter as TypeParameterSpec;
3058                         if (tp != null) {
3059                                 //
3060                                 // Type inference works on generic arguments (MVAR) only
3061                                 //
3062                                 if (!tp.IsMethodOwned)
3063                                         return parameter;
3064
3065                                 //
3066                                 // Ensure the type parameter belongs to same container
3067                                 //
3068                                 if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3069                                         return fixed_types[tp.DeclaredPosition] ?? parameter;
3070
3071                                 return parameter;
3072                         }
3073
3074                         var gt = parameter as InflatedTypeSpec;
3075                         if (gt != null) {
3076                                 var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3077                                 for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3078                                         var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3079                                         if (inflated == null)
3080                                                 return null;
3081
3082                                         inflated_targs[ii] = inflated;
3083                                 }
3084
3085                                 return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3086                         }
3087
3088                         return parameter;
3089                 }
3090                 
3091                 //
3092                 // Tests whether all delegate input arguments are fixed and generic output type
3093                 // requires output type inference 
3094                 //
3095                 public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
3096                 {
3097                         while (returnType.IsArray)
3098                                 returnType = ((ArrayContainer) returnType).Element;
3099
3100                         if (returnType.IsGenericParameter) {
3101                                 if (IsFixed (returnType))
3102                                     return false;
3103                         } else if (TypeManager.IsGenericType (returnType)) {
3104                                 if (TypeManager.IsDelegateType (returnType)) {
3105                                         invoke = Delegate.GetInvokeMethod (returnType);
3106                                         return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
3107                                 }
3108                                         
3109                                 TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3110                                 
3111                                 // At least one unfixed return type has to exist 
3112                                 if (AllTypesAreFixed (g_args))
3113                                         return false;
3114                         } else {
3115                                 return false;
3116                         }
3117
3118                         // All generic input arguments have to be fixed
3119                         AParametersCollection d_parameters = invoke.Parameters;
3120                         return AllTypesAreFixed (d_parameters.Types);
3121                 }
3122                 
3123                 bool IsFixed (TypeSpec type)
3124                 {
3125                         return IsUnfixed (type) == -1;
3126                 }               
3127
3128                 int IsUnfixed (TypeSpec type)
3129                 {
3130                         if (!type.IsGenericParameter)
3131                                 return -1;
3132
3133                         for (int i = 0; i < tp_args.Length; ++i) {
3134                                 if (tp_args[i] == type) {
3135                                         if (fixed_types[i] != null)
3136                                                 break;
3137
3138                                         return i;
3139                                 }
3140                         }
3141
3142                         return -1;
3143                 }
3144
3145                 //
3146                 // 26.3.3.9 Lower-bound Inference
3147                 //
3148                 public int LowerBoundInference (TypeSpec u, TypeSpec v)
3149                 {
3150                         return LowerBoundInference (u, v, false);
3151                 }
3152
3153                 //
3154                 // Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3155                 //
3156                 int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3157                 {
3158                         // If V is one of the unfixed type arguments
3159                         int pos = IsUnfixed (v);
3160                         if (pos != -1) {
3161                                 AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3162                                 return 1;
3163                         }                       
3164
3165                         // If U is an array type
3166                         var u_ac = u as ArrayContainer;
3167                         if (u_ac != null) {
3168                                 var v_ac = v as ArrayContainer;
3169                                 if (v_ac != null) {
3170                                         if (u_ac.Rank != v_ac.Rank)
3171                                                 return 0;
3172
3173                                         if (TypeSpec.IsValueType (u_ac.Element))
3174                                                 return ExactInference (u_ac.Element, v_ac.Element);
3175
3176                                         return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3177                                 }
3178
3179                                 if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
3180                                         return 0;
3181
3182                                 var v_i = TypeManager.GetTypeArguments (v) [0];
3183                                 if (TypeSpec.IsValueType (u_ac.Element))
3184                                         return ExactInference (u_ac.Element, v_i);
3185
3186                                 return LowerBoundInference (u_ac.Element, v_i);
3187                         }
3188                         
3189                         if (TypeManager.IsGenericType (v)) {
3190                                 //
3191                                 // if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3192                                 // such that U is identical to, inherits from (directly or indirectly),
3193                                 // or implements (directly or indirectly) C<U1..Uk>
3194                                 //
3195                                 var u_candidates = new List<TypeSpec> ();
3196                                 var open_v = v.MemberDefinition;
3197
3198                                 for (TypeSpec t = u; t != null; t = t.BaseType) {
3199                                         if (open_v == t.MemberDefinition)
3200                                                 u_candidates.Add (t);
3201
3202                                         //
3203                                         // Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3204                                         // that would complicate the process a lot, instead I treat them as dynamic
3205                                         //
3206                                         if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3207                                                 u_candidates.Add (t);
3208
3209                                         if (t.Interfaces != null) {
3210                                                 foreach (var iface in t.Interfaces) {
3211                                                         if (open_v == iface.MemberDefinition)
3212                                                                 u_candidates.Add (iface);
3213                                                 }
3214                                         }
3215                                 }
3216
3217                                 TypeSpec [] unique_candidate_targs = null;
3218                                 TypeSpec[] ga_v = TypeManager.GetTypeArguments (v);
3219                                 foreach (TypeSpec u_candidate in u_candidates) {
3220                                         //
3221                                         // The unique set of types U1..Uk means that if we have an interface I<T>,
3222                                         // class U : I<int>, I<long> then no type inference is made when inferring
3223                                         // type I<T> by applying type U because T could be int or long
3224                                         //
3225                                         if (unique_candidate_targs != null) {
3226                                                 TypeSpec[] second_unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3227                                                 if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3228                                                         unique_candidate_targs = second_unique_candidate_targs;
3229                                                         continue;
3230                                                 }
3231
3232                                                 //
3233                                                 // This should always cause type inference failure
3234                                                 //
3235                                                 failed = true;
3236                                                 return 1;
3237                                         }
3238
3239                                         //
3240                                         // A candidate is dynamic type expression, to simplify things use dynamic
3241                                         // for all type parameter of this type. For methods like this one
3242                                         // 
3243                                         // void M<T, U> (IList<T>, IList<U[]>)
3244                                         //
3245                                         // dynamic becomes both T and U when the arguments are of dynamic type
3246                                         //
3247                                         if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3248                                                 unique_candidate_targs = new TypeSpec[ga_v.Length];
3249                                                 for (int i = 0; i < unique_candidate_targs.Length; ++i)
3250                                                         unique_candidate_targs[i] = u_candidate;
3251                                         } else {
3252                                                 unique_candidate_targs = TypeManager.GetTypeArguments (u_candidate);
3253                                         }
3254                                 }
3255
3256                                 if (unique_candidate_targs != null) {
3257                                         var ga_open_v = open_v.TypeParameters;
3258                                         int score = 0;
3259                                         for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3260                                                 Variance variance = ga_open_v [i].Variance;
3261
3262                                                 TypeSpec u_i = unique_candidate_targs [i];
3263                                                 if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3264                                                         if (ExactInference (u_i, ga_v [i]) == 0)
3265                                                                 ++score;
3266                                                 } else {
3267                                                         bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3268                                                                 (variance == Variance.Covariant && inversed);
3269
3270                                                         if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3271                                                                 ++score;
3272                                                 }
3273                                         }
3274                                         return score;
3275                                 }
3276                         }
3277
3278                         return 0;
3279                 }
3280
3281                 //
3282                 // 26.3.3.6 Output Type Inference
3283                 //
3284                 public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3285                 {
3286                         // If e is a lambda or anonymous method with inferred return type
3287                         AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3288                         if (ame != null) {
3289                                 TypeSpec rt = ame.InferReturnType (ec, this, t);
3290                                 var invoke = Delegate.GetInvokeMethod (t);
3291
3292                                 if (rt == null) {
3293                                         AParametersCollection pd = invoke.Parameters;
3294                                         return ame.Parameters.Count == pd.Count ? 1 : 0;
3295                                 }
3296
3297                                 TypeSpec rtype = invoke.ReturnType;
3298                                 return LowerBoundInference (rt, rtype) + 1;
3299                         }
3300
3301                         //
3302                         // if E is a method group and T is a delegate type or expression tree type
3303                         // return type Tb with parameter types T1..Tk and return type Tb, and overload
3304                         // resolution of E with the types T1..Tk yields a single method with return type U,
3305                         // then a lower-bound inference is made from U for Tb.
3306                         //
3307                         if (e is MethodGroupExpr) {
3308                                 if (!TypeManager.IsDelegateType (t)) {
3309                                         if (!t.IsExpressionTreeType)
3310                                                 return 0;
3311
3312                                         t = TypeManager.GetTypeArguments (t)[0];
3313                                 }
3314
3315                                 var invoke = Delegate.GetInvokeMethod (t);
3316                                 TypeSpec rtype = invoke.ReturnType;
3317
3318                                 if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3319                                         return 0;
3320
3321                                 // LAMESPEC: Standard does not specify that all methodgroup arguments
3322                                 // has to be fixed but it does not specify how to do recursive type inference
3323                                 // either. We choose the simple option and infer return type only
3324                                 // if all delegate generic arguments are fixed.
3325                                 TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3326                                 for (int i = 0; i < param_types.Length; ++i) {
3327                                         var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3328                                         if (inflated == null)
3329                                                 return 0;
3330
3331                                         if (IsUnfixed (inflated) >= 0)
3332                                                 return 0;
3333
3334                                         param_types[i] = inflated;
3335                                 }
3336
3337                                 MethodGroupExpr mg = (MethodGroupExpr) e;
3338                                 Arguments args = DelegateCreation.CreateDelegateMethodArguments (invoke.Parameters, param_types, e.Location);
3339                                 mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3340                                 if (mg == null)
3341                                         return 0;
3342
3343                                 return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3344                         }
3345
3346                         //
3347                         // if e is an expression with type U, then
3348                         // a lower-bound inference is made from U for T
3349                         //
3350                         return LowerBoundInference (e.Type, t) * 2;
3351                 }
3352
3353                 void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3354                 {
3355                         int idx = IsUnfixed (returnType);
3356                         if (idx >= 0) {
3357                                 types [idx] = null;
3358                                 return;
3359                         }
3360
3361                         if (TypeManager.IsGenericType (returnType)) {
3362                                 foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3363                                         RemoveDependentTypes (types, t);
3364                                 }
3365                         }
3366                 }
3367
3368                 public bool UnfixedVariableExists {
3369                         get {
3370                                 foreach (TypeSpec ut in fixed_types) {
3371                                         if (ut == null)
3372                                                 return true;
3373                                 }
3374
3375                                 return false;
3376                         }
3377                 }
3378         }
3379 }