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