2
// generic.cs: Generics support
4
// Authors: Martin Baulig (martin@ximian.com)
5
// Miguel de Icaza (miguel@ximian.com)
6
// Marek Safar (marek.safar@gmail.com)
8
// Dual licensed under the terms of the MIT X11 or GNU GPL
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)
16
using System.Collections.Generic;
21
using MetaType = IKVM.Reflection.Type;
22
using IKVM.Reflection;
23
using IKVM.Reflection.Emit;
25
using MetaType = System.Type;
26
using System.Reflection;
27
using System.Reflection.Emit;
30
namespace Mono.CSharp {
34
// Don't add or modify internal values, they are used as -/+ calculation signs
42
public enum SpecialConstraint
50
public class SpecialContraintExpr : FullNamedExpression
52
public SpecialContraintExpr (SpecialConstraint constraint, Location loc)
55
this.Constraint = constraint;
58
public SpecialConstraint Constraint { get; private set; }
60
protected override Expression DoResolve (ResolveContext rc)
62
throw new NotImplementedException ();
65
public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext ec)
67
throw new NotImplementedException ();
72
// A set of parsed constraints for a type parameter
74
public class Constraints
76
SimpleMemberName tparam;
77
List<FullNamedExpression> constraints;
82
public IEnumerable<FullNamedExpression> ConstraintExpressions {
88
public Constraints (SimpleMemberName tparam, List<FullNamedExpression> constraints, Location loc)
91
this.constraints = constraints;
97
public List<FullNamedExpression> TypeExpressions {
103
public Location Location {
109
public SimpleMemberName TypeParameter {
117
public static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec bb, IMemberContext context, Location loc)
119
if (spec.HasSpecialClass && bb.IsStruct) {
120
context.Module.Compiler.Report.Error (455, loc,
121
"Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
122
spec.Name, "class", bb.GetSignatureForError ());
127
return CheckConflictingInheritedConstraint (spec, spec.BaseType, bb, context, loc);
130
static bool CheckConflictingInheritedConstraint (TypeParameterSpec spec, TypeSpec ba, TypeSpec bb, IMemberContext context, Location loc)
135
if (TypeSpec.IsBaseClass (ba, bb, false) || TypeSpec.IsBaseClass (bb, ba, false))
138
Error_ConflictingConstraints (context, spec, ba, bb, loc);
142
public static void Error_ConflictingConstraints (IMemberContext context, TypeParameterSpec tp, TypeSpec ba, TypeSpec bb, Location loc)
144
context.Module.Compiler.Report.Error (455, loc,
145
"Type parameter `{0}' inherits conflicting constraints `{1}' and `{2}'",
146
tp.Name, ba.GetSignatureForError (), bb.GetSignatureForError ());
149
public void CheckGenericConstraints (IMemberContext context, bool obsoleteCheck)
151
foreach (var c in constraints) {
160
ObsoleteAttribute obsolete_attr = t.GetAttributeObsolete ();
161
if (obsolete_attr != null)
162
AttributeTester.Report_ObsoleteMessage (obsolete_attr, t.GetSignatureForError (), c.Location, context.Module.Compiler.Report);
165
ConstraintChecker.Check (context, t, c.Location);
170
// Resolve the constraints types with only possible early checks, return
171
// value `false' is reserved for recursive failure
173
public bool Resolve (IMemberContext context, TypeParameter tp)
183
List<TypeParameterSpec> tparam_types = null;
184
bool iface_found = false;
186
spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
188
for (int i = 0; i < constraints.Count; ++i) {
189
var constraint = constraints[i];
191
if (constraint is SpecialContraintExpr) {
192
spec.SpecialConstraint |= ((SpecialContraintExpr) constraint).Constraint;
193
if (spec.HasSpecialStruct)
194
spec.BaseType = context.Module.Compiler.BuiltinTypes.ValueType;
196
// Set to null as it does not have a type
197
constraints[i] = null;
201
var type = constraint.ResolveAsType (context);
205
if (type.Arity > 0 && ((InflatedTypeSpec) type).HasDynamicArgument ()) {
206
context.Module.Compiler.Report.Error (1968, constraint.Location,
207
"A constraint cannot be the dynamic type `{0}'", type.GetSignatureForError ());
211
if (!context.CurrentMemberDefinition.IsAccessibleAs (type)) {
212
context.Module.Compiler.Report.SymbolRelatedToPreviousError (type);
213
context.Module.Compiler.Report.Error (703, loc,
214
"Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
215
type.GetSignatureForError (), context.GetSignatureForError ());
218
if (type.IsInterface) {
219
if (!spec.AddInterface (type)) {
220
context.Module.Compiler.Report.Error (405, constraint.Location,
221
"Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
229
var constraint_tp = type as TypeParameterSpec;
230
if (constraint_tp != null) {
231
if (tparam_types == null) {
232
tparam_types = new List<TypeParameterSpec> (2);
233
} else if (tparam_types.Contains (constraint_tp)) {
234
context.Module.Compiler.Report.Error (405, constraint.Location,
235
"Duplicate constraint `{0}' for type parameter `{1}'", type.GetSignatureForError (), tparam.Value);
240
// Checks whether each generic method parameter constraint type
241
// is valid with respect to T
243
if (tp.IsMethodTypeParameter) {
244
TypeManager.CheckTypeVariance (type, Variance.Contravariant, context);
247
var tp_def = constraint_tp.MemberDefinition as TypeParameter;
248
if (tp_def != null && !tp_def.ResolveConstraints (context)) {
249
context.Module.Compiler.Report.Error (454, constraint.Location,
250
"Circular constraint dependency involving `{0}' and `{1}'",
251
constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
256
// Checks whether there are no conflicts between type parameter constraints
262
// A and B are not convertible and only 1 class constraint is allowed
264
if (constraint_tp.HasTypeConstraint) {
265
if (spec.HasTypeConstraint || spec.HasSpecialStruct) {
266
if (!CheckConflictingInheritedConstraint (spec, constraint_tp.BaseType, context, constraint.Location))
269
for (int ii = 0; ii < tparam_types.Count; ++ii) {
270
if (!tparam_types[ii].HasTypeConstraint)
273
if (!CheckConflictingInheritedConstraint (spec, tparam_types[ii].BaseType, constraint_tp.BaseType, context, constraint.Location))
279
if (constraint_tp.HasSpecialStruct) {
280
context.Module.Compiler.Report.Error (456, constraint.Location,
281
"Type parameter `{0}' has the `struct' constraint, so it cannot be used as a constraint for `{1}'",
282
constraint_tp.GetSignatureForError (), tp.GetSignatureForError ());
286
tparam_types.Add (constraint_tp);
290
if (iface_found || spec.HasTypeConstraint) {
291
context.Module.Compiler.Report.Error (406, constraint.Location,
292
"The class type constraint `{0}' must be listed before any other constraints. Consider moving type constraint to the beginning of the constraint list",
293
type.GetSignatureForError ());
296
if (spec.HasSpecialStruct || spec.HasSpecialClass) {
297
context.Module.Compiler.Report.Error (450, constraint.Location,
298
"`{0}': cannot specify both a constraint class and the `class' or `struct' constraint",
299
type.GetSignatureForError ());
302
switch (type.BuiltinType) {
303
case BuiltinTypeSpec.Type.Array:
304
case BuiltinTypeSpec.Type.Delegate:
305
case BuiltinTypeSpec.Type.MulticastDelegate:
306
case BuiltinTypeSpec.Type.Enum:
307
case BuiltinTypeSpec.Type.ValueType:
308
case BuiltinTypeSpec.Type.Object:
309
context.Module.Compiler.Report.Error (702, constraint.Location,
310
"A constraint cannot be special class `{0}'", type.GetSignatureForError ());
312
case BuiltinTypeSpec.Type.Dynamic:
313
context.Module.Compiler.Report.Error (1967, constraint.Location,
314
"A constraint cannot be the dynamic type");
318
if (type.IsSealed || !type.IsClass) {
319
context.Module.Compiler.Report.Error (701, loc,
320
"`{0}' is not a valid constraint. A constraint must be an interface, a non-sealed class or a type parameter",
321
TypeManager.CSharpName (type));
326
context.Module.Compiler.Report.Error (717, constraint.Location,
327
"`{0}' is not a valid constraint. Static classes cannot be used as constraints",
328
type.GetSignatureForError ());
331
spec.BaseType = type;
334
if (tparam_types != null)
335
spec.TypeArguments = tparam_types.ToArray ();
342
public void VerifyClsCompliance (Report report)
344
foreach (var c in constraints)
349
if (!c.Type.IsCLSCompliant ()) {
350
report.SymbolRelatedToPreviousError (c.Type);
351
report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
352
c.Type.GetSignatureForError ());
359
// A type parameter for a generic type or generic method definition
361
public class TypeParameter : MemberCore, ITypeDefinition
363
static readonly string[] attribute_target = new string [] { "type parameter" };
365
Constraints constraints;
366
GenericTypeParameterBuilder builder;
367
readonly TypeParameterSpec spec;
369
public TypeParameter (int index, MemberName name, Constraints constraints, Attributes attrs, Variance variance)
370
: base (null, name, attrs)
372
this.constraints = constraints;
373
this.spec = new TypeParameterSpec (null, index, this, SpecialConstraint.None, variance, null);
379
public TypeParameter (MemberName name, Attributes attrs, Variance variance)
380
: base (null, name, attrs)
382
this.spec = new TypeParameterSpec (null, -1, this, SpecialConstraint.None, variance, null);
385
public TypeParameter (TypeParameterSpec spec, TypeSpec parentSpec, MemberName name, Attributes attrs)
386
: base (null, name, attrs)
388
this.spec = new TypeParameterSpec (parentSpec, spec.DeclaredPosition, spec.MemberDefinition, spec.SpecialConstraint, spec.Variance, null) {
389
BaseType = spec.BaseType,
390
InterfacesDefined = spec.InterfacesDefined,
391
TypeArguments = spec.TypeArguments
397
public override AttributeTargets AttributeTargets {
399
return AttributeTargets.GenericParameter;
403
public Constraints Constraints {
412
public IAssemblyDefinition DeclaringAssembly {
414
return Module.DeclaringAssembly;
418
public override string DocCommentHeader {
420
throw new InvalidOperationException (
421
"Unexpected attempt to get doc comment from " + this.GetType ());
425
bool ITypeDefinition.IsComImport {
431
bool ITypeDefinition.IsPartial {
437
public bool IsMethodTypeParameter {
439
return spec.IsMethodOwned;
443
bool ITypeDefinition.IsTypeForwarder {
451
return MemberName.Name;
455
public string Namespace {
461
public TypeParameterSpec Type {
467
public int TypeParametersCount {
473
public TypeParameterSpec[] TypeParameters {
479
public override string[] ValidAttributeTargets {
481
return attribute_target;
485
public Variance Variance {
487
return spec.Variance;
494
// This is called for each part of a partial generic type definition.
496
// If partial type parameters constraints are not null and we don't
497
// already have constraints they become our constraints. If we already
498
// have constraints, we must check that they're the same.
500
public bool AddPartialConstraints (TypeDefinition part, TypeParameter tp)
503
throw new InvalidOperationException ();
505
var new_constraints = tp.constraints;
506
if (new_constraints == null)
509
// TODO: could create spec only
510
//tp.Define (null, -1, part.Definition);
511
tp.spec.DeclaringType = part.Definition;
512
if (!tp.ResolveConstraints (part))
515
if (constraints != null)
516
return spec.HasSameConstraintsDefinition (tp.Type);
518
// Copy constraint from resolved part to partial container
519
spec.SpecialConstraint = tp.spec.SpecialConstraint;
520
spec.Interfaces = tp.spec.Interfaces;
521
spec.TypeArguments = tp.spec.TypeArguments;
522
spec.BaseType = tp.spec.BaseType;
527
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
529
builder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
532
public void CheckGenericConstraints (bool obsoleteCheck)
534
if (constraints != null)
535
constraints.CheckGenericConstraints (this, obsoleteCheck);
538
public TypeParameter CreateHoistedCopy (TypeSpec declaringSpec)
540
return new TypeParameter (spec, declaringSpec, MemberName, null);
543
public override bool Define ()
549
// This is the first method which is called during the resolving
550
// process; we're called immediately after creating the type parameters
551
// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
554
public void Define (GenericTypeParameterBuilder type, TypeSpec declaringType, TypeContainer parent)
557
throw new InternalErrorException ();
559
// Needed to get compiler reference
560
this.Parent = parent;
562
spec.DeclaringType = declaringType;
563
spec.SetMetaInfo (type);
566
public void EmitConstraints (GenericTypeParameterBuilder builder)
568
var attr = GenericParameterAttributes.None;
569
if (spec.Variance == Variance.Contravariant)
570
attr |= GenericParameterAttributes.Contravariant;
571
else if (spec.Variance == Variance.Covariant)
572
attr |= GenericParameterAttributes.Covariant;
574
if (spec.HasSpecialClass)
575
attr |= GenericParameterAttributes.ReferenceTypeConstraint;
576
else if (spec.HasSpecialStruct)
577
attr |= GenericParameterAttributes.NotNullableValueTypeConstraint | GenericParameterAttributes.DefaultConstructorConstraint;
579
if (spec.HasSpecialConstructor)
580
attr |= GenericParameterAttributes.DefaultConstructorConstraint;
582
if (spec.BaseType.BuiltinType != BuiltinTypeSpec.Type.Object)
583
builder.SetBaseTypeConstraint (spec.BaseType.GetMetaInfo ());
585
if (spec.InterfacesDefined != null)
586
builder.SetInterfaceConstraints (spec.InterfacesDefined.Select (l => l.GetMetaInfo ()).ToArray ());
588
if (spec.TypeArguments != null)
589
builder.SetInterfaceConstraints (spec.TypeArguments.Select (l => l.GetMetaInfo ()).ToArray ());
591
builder.SetGenericParameterAttributes (attr);
594
public override void Emit ()
596
EmitConstraints (builder);
598
if (OptAttributes != null)
599
OptAttributes.Emit ();
604
public void ErrorInvalidVariance (IMemberContext mc, Variance expected)
606
Report.SymbolRelatedToPreviousError (mc.CurrentMemberDefinition);
607
string input_variance = Variance == Variance.Contravariant ? "contravariant" : "covariant";
608
string gtype_variance;
610
case Variance.Contravariant: gtype_variance = "contravariantly"; break;
611
case Variance.Covariant: gtype_variance = "covariantly"; break;
612
default: gtype_variance = "invariantly"; break;
615
Delegate d = mc as Delegate;
616
string parameters = d != null ? d.Parameters.GetSignatureForError () : "";
618
Report.Error (1961, Location,
619
"The {2} type parameter `{0}' must be {3} valid on `{1}{4}'",
620
GetSignatureForError (), mc.GetSignatureForError (), input_variance, gtype_variance, parameters);
623
public TypeSpec GetAttributeCoClass ()
628
public string GetAttributeDefaultMember ()
630
throw new NotSupportedException ();
633
public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
635
throw new NotSupportedException ();
638
public override string GetSignatureForDocumentation ()
640
throw new NotImplementedException ();
643
public override string GetSignatureForError ()
645
return MemberName.Name;
648
bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
650
return spec.MemberDefinition.DeclaringAssembly == assembly;
653
public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
655
throw new NotSupportedException ("Not supported for compiled definition");
659
// Resolves all type parameter constraints
661
public bool ResolveConstraints (IMemberContext context)
663
if (constraints != null)
664
return constraints.Resolve (context, this);
666
if (spec.BaseType == null)
667
spec.BaseType = context.Module.Compiler.BuiltinTypes.Object;
672
public override bool IsClsComplianceRequired ()
677
public new void VerifyClsCompliance ()
679
if (constraints != null)
680
constraints.VerifyClsCompliance (Report);
683
public void WarningParentNameConflict (TypeParameter conflict)
685
conflict.Report.SymbolRelatedToPreviousError (conflict.Location, null);
686
conflict.Report.Warning (693, 3, Location,
687
"Type parameter `{0}' has the same name as the type parameter from outer type `{1}'",
688
GetSignatureForError (), conflict.CurrentType.GetSignatureForError ());
692
[System.Diagnostics.DebuggerDisplay ("{DisplayDebugInfo()}")]
693
public class TypeParameterSpec : TypeSpec
695
public static readonly new TypeParameterSpec[] EmptyTypes = new TypeParameterSpec[0];
698
SpecialConstraint spec;
701
TypeSpec[] ifaces_defined;
704
// Creates type owned type parameter
706
public TypeParameterSpec (TypeSpec declaringType, int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
707
: base (MemberKind.TypeParameter, declaringType, definition, info, Modifiers.PUBLIC)
709
this.variance = variance;
711
state &= ~StateFlags.Obsolete_Undetected;
716
// Creates method owned type parameter
718
public TypeParameterSpec (int index, ITypeDefinition definition, SpecialConstraint spec, Variance variance, MetaType info)
719
: this (null, index, definition, spec, variance, info)
725
public int DeclaredPosition {
734
public bool HasSpecialConstructor {
736
return (spec & SpecialConstraint.Constructor) != 0;
740
public bool HasSpecialClass {
742
return (spec & SpecialConstraint.Class) != 0;
746
public bool HasSpecialStruct {
748
return (spec & SpecialConstraint.Struct) != 0;
752
public bool HasAnyTypeConstraint {
754
return (spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0 || ifaces != null || targs != null || HasTypeConstraint;
758
public bool HasTypeConstraint {
760
var bt = BaseType.BuiltinType;
761
return bt != BuiltinTypeSpec.Type.Object && bt != BuiltinTypeSpec.Type.ValueType;
765
public override IList<TypeSpec> Interfaces {
767
if ((state & StateFlags.InterfacesExpanded) == 0) {
768
if (ifaces != null) {
769
if (ifaces_defined == null)
770
ifaces_defined = ifaces.ToArray ();
772
for (int i = 0; i < ifaces_defined.Length; ++i ) {
773
var iface_type = ifaces_defined[i];
774
var td = iface_type.MemberDefinition as TypeDefinition;
776
td.DoExpandBaseInterfaces ();
778
if (iface_type.Interfaces != null) {
779
for (int ii = 0; ii < iface_type.Interfaces.Count; ++ii) {
780
var ii_iface_type = iface_type.Interfaces [ii];
781
AddInterface (ii_iface_type);
785
} else if (ifaces_defined == null) {
786
ifaces_defined = ifaces == null ? TypeSpec.EmptyTypes : ifaces.ToArray ();
790
// Include all base type interfaces too, see ImportTypeBase for details
792
if (BaseType != null) {
793
var td = BaseType.MemberDefinition as TypeDefinition;
795
td.DoExpandBaseInterfaces ();
797
if (BaseType.Interfaces != null) {
798
foreach (var iface in BaseType.Interfaces) {
799
AddInterface (iface);
804
state |= StateFlags.InterfacesExpanded;
812
// Unexpanded interfaces list
814
public TypeSpec[] InterfacesDefined {
816
if (ifaces_defined == null) {
820
ifaces_defined = ifaces.ToArray ();
823
return ifaces_defined.Length == 0 ? null : ifaces_defined;
826
ifaces_defined = value;
827
if (value != null && value.Length != 0)
828
ifaces = new List<TypeSpec> (value);
832
public bool IsConstrained {
834
return spec != SpecialConstraint.None || ifaces != null || targs != null || HasTypeConstraint;
839
// Returns whether the type parameter is known to be a reference type
841
public new bool IsReferenceType {
843
if ((spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
844
return (spec & SpecialConstraint.Class) != 0;
847
// Full check is needed (see IsValueType for details)
849
if (HasTypeConstraint && TypeSpec.IsReferenceType (BaseType))
853
foreach (var ta in targs) {
855
// Secondary special constraints are ignored (I am not sure why)
857
var tp = ta as TypeParameterSpec;
858
if (tp != null && (tp.spec & (SpecialConstraint.Class | SpecialConstraint.Struct)) != 0)
861
if (TypeSpec.IsReferenceType (ta))
871
// Returns whether the type parameter is known to be a value type
873
public new bool IsValueType {
876
// Even if structs/enums cannot be used directly as constraints
877
// they can apear as constraint type when inheriting base constraint
878
// which has dependant type parameter constraint which has been
879
// inflated using value type
881
// class A : B<int> { override void Foo<U> () {} }
882
// class B<T> { virtual void Foo<U> () where U : T {} }
884
if (HasSpecialStruct)
888
foreach (var ta in targs) {
889
if (TypeSpec.IsValueType (ta))
898
public override string Name {
900
return definition.Name;
904
public bool IsMethodOwned {
906
return DeclaringType == null;
910
public SpecialConstraint SpecialConstraint {
920
// Types used to inflate the generic type
922
public new TypeSpec[] TypeArguments {
931
public Variance Variance {
939
public string DisplayDebugInfo ()
941
var s = GetSignatureForError ();
942
return IsMethodOwned ? s + "!!" : s + "!";
946
// Finds effective base class. The effective base class is always a class-type
948
public TypeSpec GetEffectiveBase ()
950
if (HasSpecialStruct)
954
// If T has a class-type constraint C but no type-parameter constraints, its effective base class is C
956
if (BaseType != null && targs == null) {
958
// 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.
960
// LAMESPEC: Is System.ValueType always the most specific base type in this case?
962
// Note: This can never happen in an explicitly given constraint, but may occur when the constraints of a generic method
963
// are implicitly inherited by an overriding method declaration or an explicit implementation of an interface method.
965
return BaseType.IsStruct ? BaseType.BaseType : BaseType;
969
if (HasTypeConstraint) {
970
Array.Resize (ref types, types.Length + 1);
972
for (int i = 0; i < types.Length - 1; ++i) {
973
types[i] = types[i].BaseType;
976
types[types.Length - 1] = BaseType;
978
types = types.Select (l => l.BaseType).ToArray ();
982
return Convert.FindMostEncompassedType (types);
987
public override string GetSignatureForDocumentation ()
989
var prefix = IsMethodOwned ? "``" : "`";
990
return prefix + DeclaredPosition;
993
public override string GetSignatureForError ()
999
// Constraints have to match by definition but not position, used by
1000
// partial classes or methods
1002
public bool HasSameConstraintsDefinition (TypeParameterSpec other)
1004
if (spec != other.spec)
1007
if (BaseType != other.BaseType)
1010
if (!TypeSpecComparer.Override.IsSame (InterfacesDefined, other.InterfacesDefined))
1013
if (!TypeSpecComparer.Override.IsSame (targs, other.targs))
1020
// Constraints have to match by using same set of types, used by
1021
// implicit interface implementation
1023
public bool HasSameConstraintsImplementation (TypeParameterSpec other)
1025
if (spec != other.spec)
1029
// It can be same base type or inflated type parameter
1031
// interface I<T> { void Foo<U> where U : T; }
1032
// class A : I<int> { void Foo<X> where X : int {} }
1035
if (!TypeSpecComparer.Override.IsEqual (BaseType, other.BaseType)) {
1036
if (other.targs == null)
1040
foreach (var otarg in other.targs) {
1041
if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1051
// Check interfaces implementation -> definition
1052
if (InterfacesDefined != null) {
1054
// Iterate over inflated interfaces
1056
foreach (var iface in Interfaces) {
1058
if (other.InterfacesDefined != null) {
1059
foreach (var oiface in other.Interfaces) {
1060
if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1070
if (other.targs != null) {
1071
foreach (var otarg in other.targs) {
1072
if (TypeSpecComparer.Override.IsEqual (BaseType, otarg)) {
1084
// Check interfaces implementation <- definition
1085
if (other.InterfacesDefined != null) {
1086
if (InterfacesDefined == null)
1090
// Iterate over inflated interfaces
1092
foreach (var oiface in other.Interfaces) {
1094
foreach (var iface in Interfaces) {
1095
if (TypeSpecComparer.Override.IsEqual (iface, oiface)) {
1106
// Check type parameters implementation -> definition
1107
if (targs != null) {
1108
if (other.targs == null)
1111
foreach (var targ in targs) {
1113
foreach (var otarg in other.targs) {
1114
if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1125
// Check type parameters implementation <- definition
1126
if (other.targs != null) {
1127
foreach (var otarg in other.targs) {
1128
// Ignore inflated type arguments, were checked above
1129
if (!otarg.IsGenericParameter)
1136
foreach (var targ in targs) {
1137
if (TypeSpecComparer.Override.IsEqual (targ, otarg)) {
1151
public static TypeParameterSpec[] InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec[] tparams)
1153
return InflateConstraints (tparams, l => l, inflator);
1156
public static TypeParameterSpec[] InflateConstraints<T> (TypeParameterSpec[] tparams, Func<T, TypeParameterInflator> inflatorFactory, T arg)
1158
TypeParameterSpec[] constraints = null;
1159
TypeParameterInflator? inflator = null;
1161
for (int i = 0; i < tparams.Length; ++i) {
1162
var tp = tparams[i];
1163
if (tp.HasTypeConstraint || tp.InterfacesDefined != null || tp.TypeArguments != null) {
1164
if (constraints == null) {
1165
constraints = new TypeParameterSpec[tparams.Length];
1166
Array.Copy (tparams, constraints, constraints.Length);
1170
// Using a factory to avoid possibly expensive inflator build up
1172
if (inflator == null)
1173
inflator = inflatorFactory (arg);
1175
constraints[i] = (TypeParameterSpec) constraints[i].InflateMember (inflator.Value);
1179
if (constraints == null)
1180
constraints = tparams;
1185
public void InflateConstraints (TypeParameterInflator inflator, TypeParameterSpec tps)
1187
tps.BaseType = inflator.Inflate (BaseType);
1189
var defined = InterfacesDefined;
1190
if (defined != null) {
1191
tps.ifaces_defined = new TypeSpec[defined.Length];
1192
for (int i = 0; i < defined.Length; ++i)
1193
tps.ifaces_defined [i] = inflator.Inflate (defined[i]);
1196
var ifaces = Interfaces;
1197
if (ifaces != null) {
1198
tps.ifaces = new List<TypeSpec> (ifaces.Count);
1199
for (int i = 0; i < ifaces.Count; ++i)
1200
tps.ifaces.Add (inflator.Inflate (ifaces[i]));
1203
if (targs != null) {
1204
tps.targs = new TypeSpec[targs.Length];
1205
for (int i = 0; i < targs.Length; ++i)
1206
tps.targs[i] = inflator.Inflate (targs[i]);
1210
public override MemberSpec InflateMember (TypeParameterInflator inflator)
1212
var tps = (TypeParameterSpec) MemberwiseClone ();
1213
InflateConstraints (inflator, tps);
1218
// Populates type parameter members using type parameter constraints
1219
// The trick here is to be called late enough but not too late to
1220
// populate member cache with all members from other types
1222
protected override void InitializeMemberCache (bool onlyTypes)
1224
cache = new MemberCache ();
1227
// For a type parameter the membercache is the union of the sets of members of the types
1228
// specified as a primary constraint or secondary constraint
1230
if (BaseType.BuiltinType != BuiltinTypeSpec.Type.Object && BaseType.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1231
cache.AddBaseType (BaseType);
1233
if (InterfacesDefined != null) {
1234
foreach (var iface_type in InterfacesDefined) {
1235
cache.AddInterface (iface_type);
1239
if (targs != null) {
1240
foreach (var ta in targs) {
1241
var b_type = ta.BaseType;
1242
if (b_type.BuiltinType != BuiltinTypeSpec.Type.Object && b_type.BuiltinType != BuiltinTypeSpec.Type.ValueType)
1243
cache.AddBaseType (b_type);
1245
var tps = ta as TypeParameterSpec;
1246
var ifaces = tps != null ? tps.InterfacesDefined : ta.Interfaces;
1248
if (ifaces != null) {
1249
foreach (var iface_type in ifaces) {
1250
cache.AddInterface (iface_type);
1257
public bool IsConvertibleToInterface (TypeSpec iface)
1259
if (Interfaces != null) {
1260
foreach (var t in Interfaces) {
1266
if (TypeArguments != null) {
1267
foreach (var t in TypeArguments) {
1268
if (((TypeParameterSpec) t).IsConvertibleToInterface (iface))
1276
public static bool HasAnyTypeParameterTypeConstrained (IGenericMethodDefinition md)
1278
var tps = md.TypeParameters;
1279
for (int i = 0; i < md.TypeParametersCount; ++i) {
1280
if (tps[i].HasAnyTypeConstraint) {
1288
public static bool HasAnyTypeParameterConstrained (IGenericMethodDefinition md)
1290
var tps = md.TypeParameters;
1291
for (int i = 0; i < md.TypeParametersCount; ++i) {
1292
if (tps[i].IsConstrained) {
1300
public bool HasDependencyOn (TypeSpec type)
1302
if (TypeArguments != null) {
1303
foreach (var targ in TypeArguments) {
1304
if (TypeSpecComparer.Override.IsEqual (targ, type))
1307
var tps = targ as TypeParameterSpec;
1308
if (tps != null && tps.HasDependencyOn (type))
1316
public override TypeSpec Mutate (TypeParameterMutator mutator)
1318
return mutator.Mutate (this);
1322
public struct TypeParameterInflator
1324
readonly TypeSpec type;
1325
readonly TypeParameterSpec[] tparams;
1326
readonly TypeSpec[] targs;
1327
readonly IModuleContext context;
1329
public TypeParameterInflator (TypeParameterInflator nested, TypeSpec type)
1330
: this (nested.context, type, nested.tparams, nested.targs)
1334
public TypeParameterInflator (IModuleContext context, TypeSpec type, TypeParameterSpec[] tparams, TypeSpec[] targs)
1336
if (tparams.Length != targs.Length)
1337
throw new ArgumentException ("Invalid arguments");
1339
this.context = context;
1340
this.tparams = tparams;
1347
public IModuleContext Context {
1353
public TypeSpec TypeInstance {
1360
// Type parameters to inflate
1362
public TypeParameterSpec[] TypeParameters {
1370
public TypeSpec Inflate (TypeSpec type)
1372
var tp = type as TypeParameterSpec;
1374
return Inflate (tp);
1376
var ac = type as ArrayContainer;
1378
var et = Inflate (ac.Element);
1379
if (et != ac.Element)
1380
return ArrayContainer.MakeType (context.Module, et, ac.Rank);
1386
// When inflating a nested type, inflate its parent first
1387
// in case it's using same type parameters (was inflated within the type)
1391
if (type.IsNested) {
1392
var parent = Inflate (type.DeclaringType);
1395
// Keep the inflated type arguments
1397
targs = type.TypeArguments;
1400
// When inflating imported nested type used inside same declaring type, we get TypeSpec
1401
// because the import cache helps us to catch it. However, that means we have to look at
1402
// type definition to get type argument (they are in fact type parameter in this case)
1404
if (targs.Length == 0 && type.Arity > 0)
1405
targs = type.MemberDefinition.TypeParameters;
1408
// Parent was inflated, find the same type on inflated type
1409
// to use same cache for nested types on same generic parent
1411
type = MemberCache.FindNestedType (parent, type.Name, type.Arity);
1414
// Handle the tricky case where parent shares local type arguments
1415
// which means inflating inflated type
1418
// public static Nested<T> Foo () { return null; }
1420
// public class Nested<U> {}
1423
// return type of Test<string>.Foo() has to be Test<string>.Nested<string>
1425
if (targs.Length > 0) {
1426
var inflated_targs = new TypeSpec[targs.Length];
1427
for (; i < targs.Length; ++i)
1428
inflated_targs[i] = Inflate (targs[i]);
1430
type = type.MakeGenericType (context, inflated_targs);
1436
// Nothing to do for non-generic type
1437
if (type.Arity == 0)
1440
targs = new TypeSpec[type.Arity];
1443
// Inflating using outside type arguments, var v = new Foo<int> (), class Foo<T> {}
1445
if (type is InflatedTypeSpec) {
1446
for (; i < targs.Length; ++i)
1447
targs[i] = Inflate (type.TypeArguments[i]);
1449
type = type.GetDefinition ();
1452
// Inflating parent using inside type arguments, class Foo<T> { ITest<T> foo; }
1454
var args = type.MemberDefinition.TypeParameters;
1455
foreach (var ds_tp in args)
1456
targs[i++] = Inflate (ds_tp);
1459
return type.MakeGenericType (context, targs);
1462
public TypeSpec Inflate (TypeParameterSpec tp)
1464
for (int i = 0; i < tparams.Length; ++i)
1465
if (tparams [i] == tp)
1468
// This can happen when inflating nested types
1469
// without type arguments specified
1475
// Before emitting any code we have to change all MVAR references to VAR
1476
// when the method is of generic type and has hoisted variables
1478
public class TypeParameterMutator
1480
readonly TypeParameters mvar;
1481
readonly TypeParameters var;
1482
readonly TypeParameterSpec[] src;
1483
Dictionary<TypeSpec, TypeSpec> mutated_typespec;
1485
public TypeParameterMutator (TypeParameters mvar, TypeParameters var)
1487
if (mvar.Count != var.Count)
1488
throw new ArgumentException ();
1494
public TypeParameterMutator (TypeParameterSpec[] srcVar, TypeParameters destVar)
1496
if (srcVar.Length != destVar.Count)
1497
throw new ArgumentException ();
1505
public TypeParameters MethodTypeParameters {
1513
public static TypeSpec GetMemberDeclaringType (TypeSpec type)
1515
if (type is InflatedTypeSpec) {
1516
if (type.DeclaringType == null)
1517
return type.GetDefinition ();
1519
var parent = GetMemberDeclaringType (type.DeclaringType);
1520
type = MemberCache.GetMember<TypeSpec> (parent, type);
1526
public TypeSpec Mutate (TypeSpec ts)
1529
if (mutated_typespec != null && mutated_typespec.TryGetValue (ts, out value))
1532
value = ts.Mutate (this);
1533
if (mutated_typespec == null)
1534
mutated_typespec = new Dictionary<TypeSpec, TypeSpec> ();
1536
mutated_typespec.Add (ts, value);
1540
public TypeParameterSpec Mutate (TypeParameterSpec tp)
1543
for (int i = 0; i < mvar.Count; ++i) {
1544
if (mvar[i].Type == tp)
1548
for (int i = 0; i < src.Length; ++i) {
1557
public TypeSpec[] Mutate (TypeSpec[] targs)
1559
TypeSpec[] mutated = new TypeSpec[targs.Length];
1560
bool changed = false;
1561
for (int i = 0; i < targs.Length; ++i) {
1562
mutated[i] = Mutate (targs[i]);
1563
changed |= targs[i] != mutated[i];
1566
return changed ? mutated : targs;
1571
/// A TypeExpr which already resolved to a type parameter.
1573
public class TypeParameterExpr : TypeExpression
1575
public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1576
: base (type_parameter.Type, loc)
1578
this.eclass = ExprClass.TypeParameter;
1582
public class InflatedTypeSpec : TypeSpec
1585
TypeParameterSpec[] constraints;
1586
readonly TypeSpec open_type;
1587
readonly IModuleContext context;
1589
public InflatedTypeSpec (IModuleContext context, TypeSpec openType, TypeSpec declaringType, TypeSpec[] targs)
1590
: base (openType.Kind, declaringType, openType.MemberDefinition, null, openType.Modifiers)
1593
throw new ArgumentNullException ("targs");
1595
this.state &= ~SharedStateFlags;
1596
this.state |= (openType.state & SharedStateFlags);
1598
this.context = context;
1599
this.open_type = openType;
1602
foreach (var arg in targs) {
1603
if (arg.HasDynamicElement || arg.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
1604
state |= StateFlags.HasDynamicElement;
1609
if (open_type.Kind == MemberKind.MissingType)
1610
MemberCache = MemberCache.Empty;
1612
if ((open_type.Modifiers & Modifiers.COMPILER_GENERATED) != 0)
1613
state |= StateFlags.ConstraintsChecked;
1618
public override TypeSpec BaseType {
1620
if (cache == null || (state & StateFlags.PendingBaseTypeInflate) != 0)
1621
InitializeMemberCache (true);
1623
return base.BaseType;
1628
// Inflated type parameters with constraints array, mapping with type arguments is based on index
1630
public TypeParameterSpec[] Constraints {
1632
if (constraints == null) {
1633
constraints = TypeParameterSpec.InflateConstraints (MemberDefinition.TypeParameters, l => l.CreateLocalInflator (context), this);
1641
// Used to cache expensive constraints validation on constructed types
1643
public bool HasConstraintsChecked {
1645
return (state & StateFlags.ConstraintsChecked) != 0;
1648
state = value ? state | StateFlags.ConstraintsChecked : state & ~StateFlags.ConstraintsChecked;
1652
public override IList<TypeSpec> Interfaces {
1655
InitializeMemberCache (true);
1657
return base.Interfaces;
1661
public override bool IsExpressionTreeType {
1663
return (open_type.state & StateFlags.InflatedExpressionType) != 0;
1667
public override bool IsGenericIterateInterface {
1669
return (open_type.state & StateFlags.GenericIterateInterface) != 0;
1673
public override bool IsGenericTask {
1675
return (open_type.state & StateFlags.GenericTask) != 0;
1679
public override bool IsNullableType {
1681
return (open_type.state & StateFlags.InflatedNullableType) != 0;
1686
// Types used to inflate the generic type
1688
public override TypeSpec[] TypeArguments {
1696
public override bool AddInterface (TypeSpec iface)
1698
var inflator = CreateLocalInflator (context);
1699
iface = inflator.Inflate (iface);
1703
return base.AddInterface (iface);
1706
public static bool ContainsTypeParameter (TypeSpec type)
1708
if (type.Kind == MemberKind.TypeParameter)
1711
var element_container = type as ElementTypeSpec;
1712
if (element_container != null)
1713
return ContainsTypeParameter (element_container.Element);
1715
foreach (var t in type.TypeArguments) {
1716
if (ContainsTypeParameter (t)) {
1724
TypeParameterInflator CreateLocalInflator (IModuleContext context)
1726
TypeParameterSpec[] tparams_full;
1727
TypeSpec[] targs_full = targs;
1730
// Special case is needed when we are inflating an open type (nested type definition)
1731
// on inflated parent. Consider following case
1733
// Foo<T>.Bar<U> => Foo<string>.Bar<U>
1735
// Any later inflation of Foo<string>.Bar<U> has to also inflate T if used inside Bar<U>
1737
List<TypeSpec> merged_targs = null;
1738
List<TypeParameterSpec> merged_tparams = null;
1740
var type = DeclaringType;
1743
if (type.TypeArguments.Length > 0) {
1744
if (merged_targs == null) {
1745
merged_targs = new List<TypeSpec> ();
1746
merged_tparams = new List<TypeParameterSpec> ();
1747
if (targs.Length > 0) {
1748
merged_targs.AddRange (targs);
1749
merged_tparams.AddRange (open_type.MemberDefinition.TypeParameters);
1752
merged_tparams.AddRange (type.MemberDefinition.TypeParameters);
1753
merged_targs.AddRange (type.TypeArguments);
1755
type = type.DeclaringType;
1756
} while (type != null);
1758
if (merged_targs != null) {
1759
// Type arguments are not in the right order but it should not matter in this case
1760
targs_full = merged_targs.ToArray ();
1761
tparams_full = merged_tparams.ToArray ();
1762
} else if (targs.Length == 0) {
1763
tparams_full = TypeParameterSpec.EmptyTypes;
1765
tparams_full = open_type.MemberDefinition.TypeParameters;
1767
} else if (targs.Length == 0) {
1768
tparams_full = TypeParameterSpec.EmptyTypes;
1770
tparams_full = open_type.MemberDefinition.TypeParameters;
1773
return new TypeParameterInflator (context, this, tparams_full, targs_full);
1776
MetaType CreateMetaInfo (TypeParameterMutator mutator)
1779
// Converts nested type arguments into right order
1780
// Foo<string, bool>.Bar<int> => string, bool, int
1782
var all = new List<MetaType> ();
1783
TypeSpec type = this;
1784
TypeSpec definition = type;
1786
if (type.GetDefinition().IsGeneric) {
1788
type.TypeArguments != TypeSpec.EmptyTypes ?
1789
type.TypeArguments.Select (l => l.GetMetaInfo ()) :
1790
type.MemberDefinition.TypeParameters.Select (l => l.GetMetaInfo ()));
1793
definition = definition.GetDefinition ();
1794
type = type.DeclaringType;
1795
} while (type != null);
1797
return definition.GetMetaInfo ().MakeGenericType (all.ToArray ());
1800
public override ObsoleteAttribute GetAttributeObsolete ()
1802
return open_type.GetAttributeObsolete ();
1805
protected override bool IsNotCLSCompliant (out bool attrValue)
1807
if (base.IsNotCLSCompliant (out attrValue))
1810
foreach (var ta in TypeArguments) {
1811
if (ta.MemberDefinition.CLSAttributeValue == false)
1818
public override TypeSpec GetDefinition ()
1823
public override MetaType GetMetaInfo ()
1826
info = CreateMetaInfo (null);
1831
public override string GetSignatureForError ()
1834
return targs[0].GetSignatureForError () + "?";
1836
return base.GetSignatureForError ();
1839
protected override string GetTypeNameSignature ()
1841
if (targs.Length == 0 || MemberDefinition is AnonymousTypeClass)
1844
return "<" + TypeManager.CSharpName (targs) + ">";
1847
public bool HasDynamicArgument ()
1849
for (int i = 0; i < targs.Length; ++i) {
1850
var item = targs[i];
1852
if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1855
if (item is InflatedTypeSpec) {
1856
if (((InflatedTypeSpec) item).HasDynamicArgument ())
1863
while (item.IsArray) {
1864
item = ((ArrayContainer) item).Element;
1867
if (item.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
1875
protected override void InitializeMemberCache (bool onlyTypes)
1877
if (cache == null) {
1878
var open_cache = onlyTypes ? open_type.MemberCacheTypes : open_type.MemberCache;
1880
// Surprisingly, calling MemberCache on open type could meantime create cache on this type
1881
// for imported type parameter constraints referencing nested type of this declaration
1883
cache = new MemberCache (open_cache);
1886
var inflator = CreateLocalInflator (context);
1889
// Two stage inflate due to possible nested types recursive
1899
// When resolving type of `b' members of `B' cannot be
1900
// inflated because are not yet available in membercache
1902
if ((state & StateFlags.PendingMemberCacheMembers) == 0) {
1903
open_type.MemberCacheTypes.InflateTypes (cache, inflator);
1906
// Inflate any implemented interfaces
1908
if (open_type.Interfaces != null) {
1909
ifaces = new List<TypeSpec> (open_type.Interfaces.Count);
1910
foreach (var iface in open_type.Interfaces) {
1911
var iface_inflated = inflator.Inflate (iface);
1912
if (iface_inflated == null)
1915
base.AddInterface (iface_inflated);
1920
// Handles the tricky case of recursive nested base generic type
1922
// class A<T> : Base<A<T>.Nested> {
1926
// When inflating A<T>. base type is not yet known, secondary
1927
// inflation is required (not common case) once base scope
1930
if (open_type.BaseType == null) {
1932
state |= StateFlags.PendingBaseTypeInflate;
1934
BaseType = inflator.Inflate (open_type.BaseType);
1936
} else if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1938
// It can happen when resolving base type without being defined
1939
// which is not allowed to happen and will always lead to an error
1941
// class B { class N {} }
1942
// class A<T> : A<B.N> {}
1944
if (open_type.BaseType == null)
1947
BaseType = inflator.Inflate (open_type.BaseType);
1948
state &= ~StateFlags.PendingBaseTypeInflate;
1952
state |= StateFlags.PendingMemberCacheMembers;
1956
var tc = open_type.MemberDefinition as TypeDefinition;
1957
if (tc != null && !tc.HasMembersDefined) {
1959
// Inflating MemberCache with undefined members
1964
if ((state & StateFlags.PendingBaseTypeInflate) != 0) {
1965
BaseType = inflator.Inflate (open_type.BaseType);
1966
state &= ~StateFlags.PendingBaseTypeInflate;
1969
state &= ~StateFlags.PendingMemberCacheMembers;
1970
open_type.MemberCache.InflateMembers (cache, open_type, inflator);
1973
public override TypeSpec Mutate (TypeParameterMutator mutator)
1975
var targs = TypeArguments;
1977
targs = mutator.Mutate (targs);
1979
var decl = DeclaringType;
1980
if (IsNested && DeclaringType.IsGenericOrParentIsGeneric)
1981
decl = mutator.Mutate (decl);
1983
if (targs == TypeArguments && decl == DeclaringType)
1986
var mutated = (InflatedTypeSpec) MemberwiseClone ();
1987
if (decl != DeclaringType) {
1988
// Gets back MethodInfo in case of metaInfo was inflated
1989
//mutated.info = MemberCache.GetMember<TypeSpec> (DeclaringType.GetDefinition (), this).info;
1991
mutated.declaringType = decl;
1992
mutated.state |= StateFlags.PendingMetaInflate;
1995
if (targs != null) {
1996
mutated.targs = targs;
1997
mutated.info = null;
2006
// Tracks the type arguments when instantiating a generic type. It's used
2007
// by both type arguments and type parameters
2009
public class TypeArguments
2011
List<FullNamedExpression> args;
2014
public List<FullNamedExpression> Args {
2015
get { return this.args; }
2018
public TypeArguments (params FullNamedExpression[] types)
2020
this.args = new List<FullNamedExpression> (types);
2023
public void Add (FullNamedExpression type)
2029
/// We may only be used after Resolve() is called and return the fully
2032
// TODO: Not needed, just return type from resolve
2033
public TypeSpec[] Arguments {
2048
public virtual bool IsEmpty {
2054
public List<FullNamedExpression> TypeExpressions {
2060
public string GetSignatureForError()
2062
StringBuilder sb = new StringBuilder ();
2063
for (int i = 0; i < Count; ++i) {
2066
sb.Append (expr.GetSignatureForError ());
2072
return sb.ToString ();
2076
/// Resolve the type arguments.
2078
public virtual bool Resolve (IMemberContext ec)
2081
return atypes.Length != 0;
2083
int count = args.Count;
2086
atypes = new TypeSpec [count];
2088
for (int i = 0; i < count; i++){
2089
var te = args[i].ResolveAsType (ec);
2098
ec.Module.Compiler.Report.Error (718, args[i].Location, "`{0}': static classes cannot be used as generic arguments",
2099
te.GetSignatureForError ());
2103
if (te.IsPointer || te.IsSpecialRuntimeType) {
2104
ec.Module.Compiler.Report.Error (306, args[i].Location,
2105
"The type `{0}' may not be used as a type argument",
2106
te.GetSignatureForError ());
2112
atypes = TypeSpec.EmptyTypes;
2117
public TypeArguments Clone ()
2119
TypeArguments copy = new TypeArguments ();
2120
foreach (var ta in args)
2127
public class UnboundTypeArguments : TypeArguments
2129
public UnboundTypeArguments (int arity)
2130
: base (new FullNamedExpression[arity])
2134
public override bool IsEmpty {
2140
public override bool Resolve (IMemberContext ec)
2142
// Nothing to be resolved
2147
public class TypeParameters
2149
List<TypeParameter> names;
2150
TypeParameterSpec[] types;
2152
public TypeParameters ()
2154
names = new List<TypeParameter> ();
2157
public TypeParameters (int count)
2159
names = new List<TypeParameter> (count);
2170
public TypeParameterSpec[] Types {
2178
public void Add (TypeParameter tparam)
2183
public void Add (TypeParameters tparams)
2185
names.AddRange (tparams.names);
2188
public void Define (GenericTypeParameterBuilder[] buiders, TypeSpec declaringType, int parentOffset, TypeContainer parent)
2190
types = new TypeParameterSpec[Count];
2191
for (int i = 0; i < types.Length; ++i) {
2194
tp.Define (buiders[i + parentOffset], declaringType, parent);
2196
types[i].DeclaredPosition = i + parentOffset;
2198
if (tp.Variance != Variance.None && !(declaringType != null && (declaringType.Kind == MemberKind.Interface || declaringType.Kind == MemberKind.Delegate))) {
2199
parent.Compiler.Report.Error (1960, tp.Location, "Variant type parameters can only be used with interfaces and delegates");
2204
public TypeParameter this[int index] {
2206
return names [index];
2209
names[index] = value;
2213
public TypeParameter Find (string name)
2215
foreach (var tp in names) {
2216
if (tp.Name == name)
2223
public string[] GetAllNames ()
2225
return names.Select (l => l.Name).ToArray ();
2228
public string GetSignatureForError ()
2230
StringBuilder sb = new StringBuilder ();
2231
for (int i = 0; i < Count; ++i) {
2235
var name = names[i];
2237
sb.Append (name.GetSignatureForError ());
2240
return sb.ToString ();
2243
public void VerifyClsCompliance ()
2245
foreach (var tp in names) {
2246
tp.VerifyClsCompliance ();
2252
// A type expression of generic type with type arguments
2254
class GenericTypeExpr : TypeExpr
2260
/// Instantiate the generic type `t' with the type arguments `args'.
2261
/// Use this constructor if you already know the fully resolved
2264
public GenericTypeExpr (TypeSpec open_type, TypeArguments args, Location l)
2266
this.open_type = open_type;
2271
public override string GetSignatureForError ()
2273
return TypeManager.CSharpName (type);
2276
public override TypeSpec ResolveAsType (IMemberContext mc)
2278
if (eclass != ExprClass.Unresolved)
2281
if (!args.Resolve (mc))
2284
TypeSpec[] atypes = args.Arguments;
2287
// Now bind the parameters
2289
var inflated = open_type.MakeGenericType (mc, atypes);
2291
eclass = ExprClass.Type;
2294
// The constraints can be checked only when full type hierarchy is known
2296
if (!inflated.HasConstraintsChecked && mc.Module.HasTypesFullyDefined) {
2297
var constraints = inflated.Constraints;
2298
if (constraints != null) {
2299
var cc = new ConstraintChecker (mc);
2300
if (cc.CheckAll (open_type, atypes, constraints, loc)) {
2301
inflated.HasConstraintsChecked = true;
2309
public override bool Equals (object obj)
2311
GenericTypeExpr cobj = obj as GenericTypeExpr;
2315
if ((type == null) || (cobj.type == null))
2318
return type == cobj.type;
2321
public override int GetHashCode ()
2323
return base.GetHashCode ();
2328
// Generic type with unbound type arguments, used for typeof (G<,,>)
2330
class GenericOpenTypeExpr : TypeExpression
2332
public GenericOpenTypeExpr (TypeSpec type, /*UnboundTypeArguments args,*/ Location loc)
2333
: base (type.GetDefinition (), loc)
2338
struct ConstraintChecker
2341
bool recursive_checks;
2343
public ConstraintChecker (IMemberContext ctx)
2346
recursive_checks = false;
2350
// Checks the constraints of open generic type against type
2351
// arguments. This version is used for types which could not be
2352
// checked immediatelly during construction because the type
2353
// hierarchy was not yet fully setup (before Emit phase)
2355
public static bool Check (IMemberContext mc, TypeSpec type, Location loc)
2358
// Check declaring type first if there is any
2360
if (type.DeclaringType != null && !Check (mc, type.DeclaringType, loc))
2363
while (type is ElementTypeSpec)
2364
type = ((ElementTypeSpec) type).Element;
2366
if (type.Arity == 0)
2369
var gtype = type as InflatedTypeSpec;
2373
var constraints = gtype.Constraints;
2374
if (constraints == null)
2377
if (gtype.HasConstraintsChecked)
2380
var cc = new ConstraintChecker (mc);
2381
cc.recursive_checks = true;
2383
if (cc.CheckAll (gtype.GetDefinition (), type.TypeArguments, constraints, loc)) {
2384
gtype.HasConstraintsChecked = true;
2392
// Checks all type arguments againts type parameters constraints
2393
// NOTE: It can run in probing mode when `this.mc' is null
2395
public bool CheckAll (MemberSpec context, TypeSpec[] targs, TypeParameterSpec[] tparams, Location loc)
2397
for (int i = 0; i < tparams.Length; i++) {
2398
var targ = targs[i];
2399
if (!CheckConstraint (context, targ, tparams [i], loc))
2402
if (!recursive_checks)
2405
if (!Check (mc, targ, loc))
2412
bool CheckConstraint (MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, Location loc)
2415
// First, check the `class' and `struct' constraints.
2417
if (tparam.HasSpecialClass && !TypeSpec.IsReferenceType (atype)) {
2419
mc.Module.Compiler.Report.Error (452, loc,
2420
"The type `{0}' must be a reference type in order to use it as type parameter `{1}' in the generic type or method `{2}'",
2421
TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2427
if (tparam.HasSpecialStruct && (!TypeSpec.IsValueType (atype) || atype.IsNullableType)) {
2429
mc.Module.Compiler.Report.Error (453, loc,
2430
"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}'",
2431
TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2440
// Check the class constraint
2442
if (tparam.HasTypeConstraint) {
2443
if (!CheckConversion (mc, context, atype, tparam, tparam.BaseType, loc)) {
2452
// Check the interfaces constraints
2454
if (tparam.Interfaces != null) {
2455
foreach (TypeSpec iface in tparam.Interfaces) {
2456
if (!CheckConversion (mc, context, atype, tparam, iface, loc)) {
2467
// Check the type parameter constraint
2469
if (tparam.TypeArguments != null) {
2470
foreach (var ta in tparam.TypeArguments) {
2471
if (!CheckConversion (mc, context, atype, tparam, ta, loc)) {
2482
// Finally, check the constructor constraint.
2484
if (!tparam.HasSpecialConstructor)
2487
if (!HasDefaultConstructor (atype)) {
2489
mc.Module.Compiler.Report.SymbolRelatedToPreviousError (atype);
2490
mc.Module.Compiler.Report.Error (310, loc,
2491
"The type `{0}' must have a public parameterless constructor in order to use it as parameter `{1}' in the generic type or method `{2}'",
2492
TypeManager.CSharpName (atype), tparam.GetSignatureForError (), context.GetSignatureForError ());
2500
static bool HasDynamicTypeArgument (TypeSpec[] targs)
2502
for (int i = 0; i < targs.Length; ++i) {
2503
var targ = targs [i];
2504
if (targ.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
2507
if (HasDynamicTypeArgument (targ.TypeArguments))
2514
bool CheckConversion (IMemberContext mc, MemberSpec context, TypeSpec atype, TypeParameterSpec tparam, TypeSpec ttype, Location loc)
2519
if (atype.IsGenericParameter) {
2520
var tps = (TypeParameterSpec) atype;
2521
if (tps.HasDependencyOn (ttype))
2524
if (Convert.ImplicitTypeParameterConversion (null, tps, ttype) != null)
2527
} else if (TypeSpec.IsValueType (atype)) {
2528
if (atype.IsNullableType) {
2530
// LAMESPEC: Only identity or base type ValueType or Object satisfy nullable type
2532
if (TypeSpec.IsBaseClass (atype, ttype, false))
2535
if (Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2539
if (Convert.ImplicitReferenceConversionExists (atype, ttype) || Convert.ImplicitBoxingConversion (null, atype, ttype) != null)
2544
mc.Module.Compiler.Report.SymbolRelatedToPreviousError (tparam);
2545
if (atype.IsGenericParameter) {
2546
mc.Module.Compiler.Report.Error (314, loc,
2547
"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}'",
2548
atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2549
} else if (TypeSpec.IsValueType (atype)) {
2550
if (atype.IsNullableType) {
2551
if (ttype.IsInterface) {
2552
mc.Module.Compiler.Report.Error (313, loc,
2553
"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' never satisfies interface constraint `{3}'",
2554
atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2556
mc.Module.Compiler.Report.Error (312, loc,
2557
"The type `{0}' cannot be used as type parameter `{1}' in the generic type or method `{2}'. The nullable type `{0}' does not satisfy constraint `{3}'",
2558
atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2561
mc.Module.Compiler.Report.Error (315, loc,
2562
"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}'",
2563
atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2566
mc.Module.Compiler.Report.Error (311, loc,
2567
"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}'",
2568
atype.GetSignatureForError (), tparam.GetSignatureForError (), context.GetSignatureForError (), ttype.GetSignatureForError ());
2575
static bool HasDefaultConstructor (TypeSpec atype)
2577
var tp = atype as TypeParameterSpec;
2579
return tp.HasSpecialConstructor || tp.HasSpecialStruct;
2582
if (atype.IsStruct || atype.IsEnum)
2585
if (atype.IsAbstract)
2588
var tdef = atype.GetDefinition ();
2590
var found = MemberCache.FindMember (tdef,
2591
MemberFilter.Constructor (ParametersCompiled.EmptyReadOnlyParameters),
2592
BindingRestriction.DeclaredOnly | BindingRestriction.InstanceOnly);
2594
return found != null && (found.Modifiers & Modifiers.PUBLIC) != 0;
2598
public partial class TypeManager
2600
public static Variance CheckTypeVariance (TypeSpec t, Variance expected, IMemberContext member)
2602
var tp = t as TypeParameterSpec;
2604
Variance v = tp.Variance;
2605
if (expected == Variance.None && v != expected ||
2606
expected == Variance.Covariant && v == Variance.Contravariant ||
2607
expected == Variance.Contravariant && v == Variance.Covariant) {
2608
((TypeParameter)tp.MemberDefinition).ErrorInvalidVariance (member, expected);
2614
if (t.TypeArguments.Length > 0) {
2615
var targs_definition = t.MemberDefinition.TypeParameters;
2616
TypeSpec[] targs = GetTypeArguments (t);
2617
for (int i = 0; i < targs.Length; ++i) {
2618
Variance v = targs_definition[i].Variance;
2619
CheckTypeVariance (targs[i], (Variance) ((int)v * (int)expected), member);
2626
return CheckTypeVariance (GetElementType (t), expected, member);
2628
return Variance.None;
2633
// Implements C# type inference
2638
// Tracks successful rate of type inference
2640
int score = int.MaxValue;
2641
readonly Arguments arguments;
2642
readonly int arg_count;
2644
public TypeInference (Arguments arguments)
2646
this.arguments = arguments;
2647
if (arguments != null)
2648
arg_count = arguments.Count;
2651
public int InferenceScore {
2657
public TypeSpec[] InferMethodArguments (ResolveContext ec, MethodSpec method)
2659
var method_generic_args = method.GenericDefinition.TypeParameters;
2660
TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2661
if (!context.UnfixedVariableExists)
2662
return TypeSpec.EmptyTypes;
2664
AParametersCollection pd = method.Parameters;
2665
if (!InferInPhases (ec, context, pd))
2668
return context.InferredTypeArguments;
2672
// Implements method type arguments inference
2674
bool InferInPhases (ResolveContext ec, TypeInferenceContext tic, AParametersCollection methodParameters)
2676
int params_arguments_start;
2677
if (methodParameters.HasParams) {
2678
params_arguments_start = methodParameters.Count - 1;
2680
params_arguments_start = arg_count;
2683
TypeSpec [] ptypes = methodParameters.Types;
2686
// The first inference phase
2688
TypeSpec method_parameter = null;
2689
for (int i = 0; i < arg_count; i++) {
2690
Argument a = arguments [i];
2694
if (i < params_arguments_start) {
2695
method_parameter = methodParameters.Types [i];
2696
} else if (i == params_arguments_start) {
2697
if (arg_count == params_arguments_start + 1 && TypeManager.HasElementType (a.Type))
2698
method_parameter = methodParameters.Types [params_arguments_start];
2700
method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2702
ptypes = (TypeSpec[]) ptypes.Clone ();
2703
ptypes [i] = method_parameter;
2707
// When a lambda expression, an anonymous method
2708
// is used an explicit argument type inference takes a place
2710
AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2712
if (am.ExplicitTypeInference (ec, tic, method_parameter))
2718
score -= tic.ExactInference (a.Type, method_parameter);
2722
if (a.Expr.Type == InternalType.NullLiteral)
2725
if (TypeSpec.IsValueType (method_parameter)) {
2726
score -= tic.LowerBoundInference (a.Type, method_parameter);
2731
// Otherwise an output type inference is made
2733
score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2737
// Part of the second phase but because it happens only once
2738
// we don't need to call it in cycle
2740
bool fixed_any = false;
2741
if (!tic.FixIndependentTypeArguments (ec, ptypes, ref fixed_any))
2744
return DoSecondPhase (ec, tic, ptypes, !fixed_any);
2747
bool DoSecondPhase (ResolveContext ec, TypeInferenceContext tic, TypeSpec[] methodParameters, bool fixDependent)
2749
bool fixed_any = false;
2750
if (fixDependent && !tic.FixDependentTypes (ec, ref fixed_any))
2753
// If no further unfixed type variables exist, type inference succeeds
2754
if (!tic.UnfixedVariableExists)
2757
if (!fixed_any && fixDependent)
2760
// For all arguments where the corresponding argument output types
2761
// contain unfixed type variables but the input types do not,
2762
// an output type inference is made
2763
for (int i = 0; i < arg_count; i++) {
2765
// Align params arguments
2766
TypeSpec t_i = methodParameters [i >= methodParameters.Length ? methodParameters.Length - 1: i];
2768
if (!t_i.IsDelegate) {
2769
if (!t_i.IsExpressionTreeType)
2772
t_i = TypeManager.GetTypeArguments (t_i) [0];
2775
var mi = Delegate.GetInvokeMethod (t_i);
2776
TypeSpec rtype = mi.ReturnType;
2778
if (tic.IsReturnTypeNonDependent (ec, mi, rtype)) {
2779
// It can be null for default arguments
2780
if (arguments[i] == null)
2783
score -= tic.OutputTypeInference (ec, arguments[i].Expr, t_i);
2788
return DoSecondPhase (ec, tic, methodParameters, true);
2792
public class TypeInferenceContext
2794
protected enum BoundKind
2801
struct BoundInfo : IEquatable<BoundInfo>
2803
public readonly TypeSpec Type;
2804
public readonly BoundKind Kind;
2806
public BoundInfo (TypeSpec type, BoundKind kind)
2812
public override int GetHashCode ()
2814
return Type.GetHashCode ();
2817
public Expression GetTypeExpression ()
2819
return new TypeExpression (Type, Location.Null);
2822
#region IEquatable<BoundInfo> Members
2824
public bool Equals (BoundInfo other)
2826
return Type == other.Type && Kind == other.Kind;
2832
readonly TypeSpec[] tp_args;
2833
readonly TypeSpec[] fixed_types;
2834
readonly List<BoundInfo>[] bounds;
2837
// TODO MemberCache: Could it be TypeParameterSpec[] ??
2838
public TypeInferenceContext (TypeSpec[] typeArguments)
2840
if (typeArguments.Length == 0)
2841
throw new ArgumentException ("Empty generic arguments");
2843
fixed_types = new TypeSpec [typeArguments.Length];
2844
for (int i = 0; i < typeArguments.Length; ++i) {
2845
if (typeArguments [i].IsGenericParameter) {
2846
if (bounds == null) {
2847
bounds = new List<BoundInfo> [typeArguments.Length];
2848
tp_args = new TypeSpec [typeArguments.Length];
2850
tp_args [i] = typeArguments [i];
2852
fixed_types [i] = typeArguments [i];
2858
// Used together with AddCommonTypeBound fo implement
2859
// 7.4.2.13 Finding the best common type of a set of expressions
2861
public TypeInferenceContext ()
2863
fixed_types = new TypeSpec [1];
2864
tp_args = new TypeSpec [1];
2865
tp_args[0] = InternalType.Arglist; // it can be any internal type
2866
bounds = new List<BoundInfo> [1];
2869
public TypeSpec[] InferredTypeArguments {
2875
public void AddCommonTypeBound (TypeSpec type)
2877
AddToBounds (new BoundInfo (type, BoundKind.Lower), 0);
2880
void AddToBounds (BoundInfo bound, int index)
2883
// Some types cannot be used as type arguments
2885
if (bound.Type.Kind == MemberKind.Void || bound.Type.IsPointer || bound.Type.IsSpecialRuntimeType ||
2886
bound.Type == InternalType.MethodGroup || bound.Type == InternalType.AnonymousMethod)
2889
var a = bounds [index];
2891
a = new List<BoundInfo> (2);
2897
if (a.Contains (bound))
2903
bool AllTypesAreFixed (TypeSpec[] types)
2905
foreach (TypeSpec t in types) {
2906
if (t.IsGenericParameter) {
2912
if (TypeManager.IsGenericType (t))
2913
return AllTypesAreFixed (TypeManager.GetTypeArguments (t));
2920
// 26.3.3.8 Exact Inference
2922
public int ExactInference (TypeSpec u, TypeSpec v)
2924
// If V is an array type
2929
var ac_u = (ArrayContainer) u;
2930
var ac_v = (ArrayContainer) v;
2931
if (ac_u.Rank != ac_v.Rank)
2934
return ExactInference (ac_u.Element, ac_v.Element);
2937
// If V is constructed type and U is constructed type
2938
if (TypeManager.IsGenericType (v)) {
2939
if (!TypeManager.IsGenericType (u) || v.MemberDefinition != u.MemberDefinition)
2942
TypeSpec [] ga_u = TypeManager.GetTypeArguments (u);
2943
TypeSpec [] ga_v = TypeManager.GetTypeArguments (v);
2944
if (ga_u.Length != ga_v.Length)
2948
for (int i = 0; i < ga_u.Length; ++i)
2949
score += ExactInference (ga_u [i], ga_v [i]);
2951
return System.Math.Min (1, score);
2954
// If V is one of the unfixed type arguments
2955
int pos = IsUnfixed (v);
2959
AddToBounds (new BoundInfo (u, BoundKind.Exact), pos);
2963
public bool FixAllTypes (ResolveContext ec)
2965
for (int i = 0; i < tp_args.Length; ++i) {
2966
if (!FixType (ec, i))
2973
// All unfixed type variables Xi are fixed for which all of the following hold:
2974
// a, There is at least one type variable Xj that depends on Xi
2975
// b, Xi has a non-empty set of bounds
2977
public bool FixDependentTypes (ResolveContext ec, ref bool fixed_any)
2979
for (int i = 0; i < tp_args.Length; ++i) {
2980
if (fixed_types[i] != null)
2983
if (bounds[i] == null)
2986
if (!FixType (ec, i))
2996
// All unfixed type variables Xi which depend on no Xj are fixed
2998
public bool FixIndependentTypeArguments (ResolveContext ec, TypeSpec[] methodParameters, ref bool fixed_any)
3000
var types_to_fix = new List<TypeSpec> (tp_args);
3001
for (int i = 0; i < methodParameters.Length; ++i) {
3002
TypeSpec t = methodParameters[i];
3004
if (!t.IsDelegate) {
3005
if (!t.IsExpressionTreeType)
3008
t = TypeManager.GetTypeArguments (t) [0];
3011
if (t.IsGenericParameter)
3014
var invoke = Delegate.GetInvokeMethod (t);
3015
TypeSpec rtype = invoke.ReturnType;
3016
while (rtype.IsArray)
3017
rtype = ((ArrayContainer) rtype).Element;
3019
if (!rtype.IsGenericParameter && !TypeManager.IsGenericType (rtype))
3022
// Remove dependent types, they cannot be fixed yet
3023
RemoveDependentTypes (types_to_fix, rtype);
3026
foreach (TypeSpec t in types_to_fix) {
3030
int idx = IsUnfixed (t);
3031
if (idx >= 0 && !FixType (ec, idx)) {
3036
fixed_any = types_to_fix.Count > 0;
3043
public bool FixType (ResolveContext ec, int i)
3045
// It's already fixed
3046
if (fixed_types[i] != null)
3047
throw new InternalErrorException ("Type argument has been already fixed");
3052
var candidates = bounds [i];
3053
if (candidates == null)
3056
if (candidates.Count == 1) {
3057
TypeSpec t = candidates[0].Type;
3058
if (t == InternalType.NullLiteral)
3061
fixed_types [i] = t;
3066
// Determines a unique type from which there is
3067
// a standard implicit conversion to all the other
3070
TypeSpec best_candidate = null;
3072
int candidates_count = candidates.Count;
3073
for (int ci = 0; ci < candidates_count; ++ci) {
3074
BoundInfo bound = candidates [ci];
3075
for (cii = 0; cii < candidates_count; ++cii) {
3079
BoundInfo cbound = candidates[cii];
3081
// Same type parameters with different bounds
3082
if (cbound.Type == bound.Type) {
3083
if (bound.Kind != BoundKind.Exact)
3089
if (bound.Kind == BoundKind.Exact || cbound.Kind == BoundKind.Exact) {
3090
if (cbound.Kind == BoundKind.Lower) {
3091
if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3097
if (cbound.Kind == BoundKind.Upper) {
3098
if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3105
if (bound.Kind != BoundKind.Exact) {
3106
if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3117
if (bound.Kind == BoundKind.Lower) {
3118
if (cbound.Kind == BoundKind.Lower) {
3119
if (!Convert.ImplicitConversionExists (ec, cbound.GetTypeExpression (), bound.Type)) {
3123
if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3133
if (bound.Kind == BoundKind.Upper) {
3134
if (!Convert.ImplicitConversionExists (ec, bound.GetTypeExpression (), cbound.Type)) {
3138
throw new NotImplementedException ("variance conversion");
3142
if (cii != candidates_count)
3146
// We already have the best candidate, break if thet are different
3148
// Dynamic is never ambiguous as we prefer dynamic over other best candidate types
3150
if (best_candidate != null) {
3152
if (best_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3155
if (bound.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic && best_candidate != bound.Type)
3159
best_candidate = bound.Type;
3162
if (best_candidate == null)
3165
fixed_types[i] = best_candidate;
3169
public bool HasBounds (int pos)
3171
return bounds[pos] != null;
3175
// Uses inferred or partially infered types to inflate delegate type argument. Returns
3176
// null when type parameter has not been fixed
3178
public TypeSpec InflateGenericArgument (IModuleContext context, TypeSpec parameter)
3180
var tp = parameter as TypeParameterSpec;
3183
// Type inference works on generic arguments (MVAR) only
3185
if (!tp.IsMethodOwned)
3189
// Ensure the type parameter belongs to same container
3191
if (tp.DeclaredPosition < tp_args.Length && tp_args[tp.DeclaredPosition] == parameter)
3192
return fixed_types[tp.DeclaredPosition] ?? parameter;
3197
var gt = parameter as InflatedTypeSpec;
3199
var inflated_targs = new TypeSpec [gt.TypeArguments.Length];
3200
for (int ii = 0; ii < inflated_targs.Length; ++ii) {
3201
var inflated = InflateGenericArgument (context, gt.TypeArguments [ii]);
3202
if (inflated == null)
3205
inflated_targs[ii] = inflated;
3208
return gt.GetDefinition ().MakeGenericType (context, inflated_targs);
3211
var ac = parameter as ArrayContainer;
3213
var inflated = InflateGenericArgument (context, ac.Element);
3214
if (inflated != ac.Element)
3215
return ArrayContainer.MakeType (context.Module, inflated);
3222
// Tests whether all delegate input arguments are fixed and generic output type
3223
// requires output type inference
3225
public bool IsReturnTypeNonDependent (ResolveContext ec, MethodSpec invoke, TypeSpec returnType)
3227
while (returnType.IsArray)
3228
returnType = ((ArrayContainer) returnType).Element;
3230
if (returnType.IsGenericParameter) {
3231
if (IsFixed (returnType))
3233
} else if (TypeManager.IsGenericType (returnType)) {
3234
if (returnType.IsDelegate) {
3235
invoke = Delegate.GetInvokeMethod (returnType);
3236
return IsReturnTypeNonDependent (ec, invoke, invoke.ReturnType);
3239
TypeSpec[] g_args = TypeManager.GetTypeArguments (returnType);
3241
// At least one unfixed return type has to exist
3242
if (AllTypesAreFixed (g_args))
3248
// All generic input arguments have to be fixed
3249
AParametersCollection d_parameters = invoke.Parameters;
3250
return AllTypesAreFixed (d_parameters.Types);
3253
bool IsFixed (TypeSpec type)
3255
return IsUnfixed (type) == -1;
3258
int IsUnfixed (TypeSpec type)
3260
if (!type.IsGenericParameter)
3263
for (int i = 0; i < tp_args.Length; ++i) {
3264
if (tp_args[i] == type) {
3265
if (fixed_types[i] != null)
3276
// 26.3.3.9 Lower-bound Inference
3278
public int LowerBoundInference (TypeSpec u, TypeSpec v)
3280
return LowerBoundInference (u, v, false);
3284
// Lower-bound (false) or Upper-bound (true) inference based on inversed argument
3286
int LowerBoundInference (TypeSpec u, TypeSpec v, bool inversed)
3288
// If V is one of the unfixed type arguments
3289
int pos = IsUnfixed (v);
3291
AddToBounds (new BoundInfo (u, inversed ? BoundKind.Upper : BoundKind.Lower), pos);
3295
// If U is an array type
3296
var u_ac = u as ArrayContainer;
3298
var v_ac = v as ArrayContainer;
3300
if (u_ac.Rank != v_ac.Rank)
3303
if (TypeSpec.IsValueType (u_ac.Element))
3304
return ExactInference (u_ac.Element, v_ac.Element);
3306
return LowerBoundInference (u_ac.Element, v_ac.Element, inversed);
3309
if (u_ac.Rank != 1 || !v.IsGenericIterateInterface)
3312
var v_i = TypeManager.GetTypeArguments (v) [0];
3313
if (TypeSpec.IsValueType (u_ac.Element))
3314
return ExactInference (u_ac.Element, v_i);
3316
return LowerBoundInference (u_ac.Element, v_i);
3319
if (v.IsGenericOrParentIsGeneric) {
3321
// if V is a constructed type C<V1..Vk> and there is a unique type C<U1..Uk>
3322
// such that U is identical to, inherits from (directly or indirectly),
3323
// or implements (directly or indirectly) C<U1..Uk>
3325
var u_candidates = new List<TypeSpec> ();
3326
var open_v = v.MemberDefinition;
3328
for (TypeSpec t = u; t != null; t = t.BaseType) {
3329
if (open_v == t.MemberDefinition)
3330
u_candidates.Add (t);
3333
// Using this trick for dynamic type inference, the spec says the type arguments are "unknown" but
3334
// that would complicate the process a lot, instead I treat them as dynamic
3336
if (t.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
3337
u_candidates.Add (t);
3340
if (u.Interfaces != null) {
3341
foreach (var iface in u.Interfaces) {
3342
if (open_v == iface.MemberDefinition)
3343
u_candidates.Add (iface);
3347
TypeSpec[] unique_candidate_targs = null;
3348
var ga_v = TypeSpec.GetAllTypeArguments (v);
3349
foreach (TypeSpec u_candidate in u_candidates) {
3351
// The unique set of types U1..Uk means that if we have an interface I<T>,
3352
// class U : I<int>, I<long> then no type inference is made when inferring
3353
// type I<T> by applying type U because T could be int or long
3355
if (unique_candidate_targs != null) {
3356
TypeSpec[] second_unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3357
if (TypeSpecComparer.Equals (unique_candidate_targs, second_unique_candidate_targs)) {
3358
unique_candidate_targs = second_unique_candidate_targs;
3363
// This should always cause type inference failure
3370
// A candidate is dynamic type expression, to simplify things use dynamic
3371
// for all type parameter of this type. For methods like this one
3373
// void M<T, U> (IList<T>, IList<U[]>)
3375
// dynamic becomes both T and U when the arguments are of dynamic type
3377
if (u_candidate.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
3378
unique_candidate_targs = new TypeSpec[ga_v.Length];
3379
for (int i = 0; i < unique_candidate_targs.Length; ++i)
3380
unique_candidate_targs[i] = u_candidate;
3382
unique_candidate_targs = TypeSpec.GetAllTypeArguments (u_candidate);
3386
if (unique_candidate_targs != null) {
3389
TypeParameterSpec[] tps = null;
3391
for (int i = 0; i < unique_candidate_targs.Length; ++i) {
3393
while (v.Arity == 0)
3394
v = v.DeclaringType;
3396
tps = v.MemberDefinition.TypeParameters;
3397
tp_index = tps.Length - 1;
3400
Variance variance = tps [tp_index--].Variance;
3402
TypeSpec u_i = unique_candidate_targs [i];
3403
if (variance == Variance.None || TypeSpec.IsValueType (u_i)) {
3404
if (ExactInference (u_i, ga_v [i]) == 0)
3407
bool upper_bound = (variance == Variance.Contravariant && !inversed) ||
3408
(variance == Variance.Covariant && inversed);
3410
if (LowerBoundInference (u_i, ga_v [i], upper_bound) == 0)
3423
// 26.3.3.6 Output Type Inference
3425
public int OutputTypeInference (ResolveContext ec, Expression e, TypeSpec t)
3427
// If e is a lambda or anonymous method with inferred return type
3428
AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3430
TypeSpec rt = ame.InferReturnType (ec, this, t);
3431
var invoke = Delegate.GetInvokeMethod (t);
3434
AParametersCollection pd = invoke.Parameters;
3435
return ame.Parameters.Count == pd.Count ? 1 : 0;
3438
TypeSpec rtype = invoke.ReturnType;
3439
return LowerBoundInference (rt, rtype) + 1;
3443
// if E is a method group and T is a delegate type or expression tree type
3444
// return type Tb with parameter types T1..Tk and return type Tb, and overload
3445
// resolution of E with the types T1..Tk yields a single method with return type U,
3446
// then a lower-bound inference is made from U for Tb.
3448
if (e is MethodGroupExpr) {
3449
if (!t.IsDelegate) {
3450
if (!t.IsExpressionTreeType)
3453
t = TypeManager.GetTypeArguments (t)[0];
3456
var invoke = Delegate.GetInvokeMethod (t);
3457
TypeSpec rtype = invoke.ReturnType;
3459
if (!IsReturnTypeNonDependent (ec, invoke, rtype))
3462
// LAMESPEC: Standard does not specify that all methodgroup arguments
3463
// has to be fixed but it does not specify how to do recursive type inference
3464
// either. We choose the simple option and infer return type only
3465
// if all delegate generic arguments are fixed.
3466
TypeSpec[] param_types = new TypeSpec [invoke.Parameters.Count];
3467
for (int i = 0; i < param_types.Length; ++i) {
3468
var inflated = InflateGenericArgument (ec, invoke.Parameters.Types[i]);
3469
if (inflated == null)
3472
param_types[i] = inflated;
3475
MethodGroupExpr mg = (MethodGroupExpr) e;
3476
Arguments args = DelegateCreation.CreateDelegateMethodArguments (ec, invoke.Parameters, param_types, e.Location);
3477
mg = mg.OverloadResolve (ec, ref args, null, OverloadResolver.Restrictions.CovariantDelegate | OverloadResolver.Restrictions.ProbingOnly);
3481
return LowerBoundInference (mg.BestCandidateReturnType, rtype) + 1;
3485
// if e is an expression with type U, then
3486
// a lower-bound inference is made from U for T
3488
return LowerBoundInference (e.Type, t) * 2;
3491
void RemoveDependentTypes (List<TypeSpec> types, TypeSpec returnType)
3493
int idx = IsUnfixed (returnType);
3499
if (TypeManager.IsGenericType (returnType)) {
3500
foreach (TypeSpec t in TypeManager.GetTypeArguments (returnType)) {
3501
RemoveDependentTypes (types, t);
3506
public bool UnfixedVariableExists {
3508
foreach (TypeSpec ut in fixed_types) {