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