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 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Globalization;
17 using System.Collections;
19 using System.Text.RegularExpressions;
21 namespace Mono.CSharp {
24 /// Abstract base class for type parameter constraints.
25 /// The type parameter can come from a generic type definition or from reflection.
27 public abstract class GenericConstraints {
28 public abstract string TypeParameter {
32 public abstract GenericParameterAttributes Attributes {
36 public bool HasConstructorConstraint {
37 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
40 public bool HasReferenceTypeConstraint {
41 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
44 public bool HasValueTypeConstraint {
45 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
48 public virtual bool HasClassConstraint {
49 get { return ClassConstraint != null; }
52 public abstract Type ClassConstraint {
56 public abstract Type[] InterfaceConstraints {
60 public abstract Type EffectiveBaseClass {
65 // Returns whether the type parameter is "known to be a reference type".
67 public virtual bool IsReferenceType {
69 if (HasReferenceTypeConstraint)
71 if (HasValueTypeConstraint)
74 if (ClassConstraint != null) {
75 if (ClassConstraint.IsValueType)
78 if (ClassConstraint != TypeManager.object_type)
82 foreach (Type t in InterfaceConstraints) {
83 if (!t.IsGenericParameter)
86 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
87 if ((gc != null) && gc.IsReferenceType)
96 // Returns whether the type parameter is "known to be a value type".
98 public virtual bool IsValueType {
100 if (HasValueTypeConstraint)
102 if (HasReferenceTypeConstraint)
105 if (ClassConstraint != null) {
106 if (!ClassConstraint.IsValueType)
109 if (ClassConstraint != TypeManager.value_type)
113 foreach (Type t in InterfaceConstraints) {
114 if (!t.IsGenericParameter)
117 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
118 if ((gc != null) && gc.IsValueType)
127 public enum SpecialConstraint
135 /// Tracks the constraints for a type parameter from a generic type definition.
137 public class Constraints : GenericConstraints {
139 ArrayList constraints;
143 // name is the identifier, constraints is an arraylist of
144 // Expressions (with types) or `true' for the constructor constraint.
146 public Constraints (string name, ArrayList constraints,
150 this.constraints = constraints;
154 public override string TypeParameter {
160 public Constraints Clone ()
162 return new Constraints (name, constraints, loc);
165 GenericParameterAttributes attrs;
166 TypeExpr class_constraint;
167 ArrayList iface_constraints;
168 ArrayList type_param_constraints;
170 Type class_constraint_type;
171 Type[] iface_constraint_types;
172 Type effective_base_type;
177 /// Resolve the constraints - but only resolve things into Expression's, not
178 /// into actual types.
180 public bool Resolve (IResolveContext ec)
185 iface_constraints = new ArrayList ();
186 type_param_constraints = new ArrayList ();
188 foreach (object obj in constraints) {
189 if (HasConstructorConstraint) {
190 Report.Error (401, loc,
191 "The new() constraint must be the last constraint specified");
195 if (obj is SpecialConstraint) {
196 SpecialConstraint sc = (SpecialConstraint) obj;
198 if (sc == SpecialConstraint.Constructor) {
199 if (!HasValueTypeConstraint) {
200 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
204 Report.Error (451, loc, "The `new()' constraint " +
205 "cannot be used with the `struct' constraint");
209 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
210 Report.Error (449, loc, "The `class' or `struct' " +
211 "constraint must be the first constraint specified");
215 if (sc == SpecialConstraint.ReferenceType)
216 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
218 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
222 int errors = Report.Errors;
223 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
226 if (errors != Report.Errors)
229 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
234 ConstructedType cexpr = fn as ConstructedType;
236 if (!cexpr.ResolveConstructedType (ec))
241 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
243 if ((expr == null) || (expr.Type == null))
246 // TODO: It's aleady done in ResolveAsBaseTerminal
247 if (!ec.GenericDeclContainer.AsAccessible (fn.Type, ec.GenericDeclContainer.ModFlags)) {
248 Report.SymbolRelatedToPreviousError (fn.Type);
249 Report.Error (703, loc,
250 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
251 fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
255 TypeParameterExpr texpr = expr as TypeParameterExpr;
257 type_param_constraints.Add (expr);
258 else if (expr.IsInterface)
259 iface_constraints.Add (expr);
260 else if (class_constraint != null) {
261 Report.Error (406, loc,
262 "`{0}': the class constraint for `{1}' " +
263 "must come before any other constraints.",
266 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
267 Report.Error (450, loc, "`{0}': cannot specify both " +
268 "a constraint class and the `class' " +
269 "or `struct' constraint", expr.GetSignatureForError ());
272 class_constraint = expr;
277 ArrayList list = new ArrayList ();
278 foreach (TypeExpr iface_constraint in iface_constraints) {
279 foreach (Type type in list) {
280 if (!type.Equals (iface_constraint.Type))
283 Report.Error (405, loc,
284 "Duplicate constraint `{0}' for type " +
285 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
290 list.Add (iface_constraint.Type);
293 foreach (TypeParameterExpr expr in type_param_constraints) {
294 foreach (Type type in list) {
295 if (!type.Equals (expr.Type))
298 Report.Error (405, loc,
299 "Duplicate constraint `{0}' for type " +
300 "parameter `{1}'.", expr.GetSignatureForError (), name);
304 list.Add (expr.Type);
307 iface_constraint_types = new Type [list.Count];
308 list.CopyTo (iface_constraint_types, 0);
310 if (class_constraint != null) {
311 class_constraint_type = class_constraint.Type;
312 if (class_constraint_type == null)
315 if (class_constraint_type.IsSealed) {
316 if (class_constraint_type.IsAbstract)
318 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
319 TypeManager.CSharpName (class_constraint_type));
323 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
324 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
329 if ((class_constraint_type == TypeManager.array_type) ||
330 (class_constraint_type == TypeManager.delegate_type) ||
331 (class_constraint_type == TypeManager.enum_type) ||
332 (class_constraint_type == TypeManager.value_type) ||
333 (class_constraint_type == TypeManager.object_type) ||
334 class_constraint_type == TypeManager.multicast_delegate_type) {
335 Report.Error (702, loc,
336 "A constraint cannot be special class `{0}'",
337 TypeManager.CSharpName (class_constraint_type));
342 if (class_constraint_type != null)
343 effective_base_type = class_constraint_type;
344 else if (HasValueTypeConstraint)
345 effective_base_type = TypeManager.value_type;
347 effective_base_type = TypeManager.object_type;
353 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
355 seen.Add (tparam, true);
357 Constraints constraints = tparam.Constraints;
358 if (constraints == null)
361 if (constraints.HasValueTypeConstraint) {
362 Report.Error (456, loc, "Type parameter `{0}' has " +
363 "the `struct' constraint, so it cannot " +
364 "be used as a constraint for `{1}'",
369 if (constraints.type_param_constraints == null)
372 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
373 if (seen.Contains (expr.TypeParameter)) {
374 Report.Error (454, loc, "Circular constraint " +
375 "dependency involving `{0}' and `{1}'",
376 tparam.Name, expr.Name);
380 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
388 /// Resolve the constraints into actual types.
390 public bool ResolveTypes (IResolveContext ec)
395 resolved_types = true;
397 foreach (object obj in constraints) {
398 ConstructedType cexpr = obj as ConstructedType;
402 if (!cexpr.CheckConstraints (ec))
406 foreach (TypeParameterExpr expr in type_param_constraints) {
407 Hashtable seen = new Hashtable ();
408 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
412 for (int i = 0; i < iface_constraints.Count; ++i) {
413 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
414 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
415 if (iface_constraint == null)
417 iface_constraints [i] = iface_constraint;
420 if (class_constraint != null) {
421 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
422 if (class_constraint == null)
430 /// Check whether there are no conflicts in our type parameter constraints.
432 /// This is an example:
436 /// where U : T, struct
438 public bool CheckDependencies ()
440 foreach (TypeParameterExpr expr in type_param_constraints) {
441 if (!CheckDependencies (expr.TypeParameter))
448 bool CheckDependencies (TypeParameter tparam)
450 Constraints constraints = tparam.Constraints;
451 if (constraints == null)
454 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
455 Report.Error (455, loc, "Type parameter `{0}' inherits " +
456 "conflicting constraints `{1}' and `{2}'",
457 name, TypeManager.CSharpName (constraints.ClassConstraint),
462 if (HasClassConstraint && constraints.HasClassConstraint) {
463 Type t1 = ClassConstraint;
464 TypeExpr e1 = class_constraint;
465 Type t2 = constraints.ClassConstraint;
466 TypeExpr e2 = constraints.class_constraint;
468 if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
469 !Convert.ImplicitReferenceConversionExists (e2, t1)) {
470 Report.Error (455, loc,
471 "Type parameter `{0}' inherits " +
472 "conflicting constraints `{1}' and `{2}'",
473 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
478 if (constraints.type_param_constraints == null)
481 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
482 if (!CheckDependencies (expr.TypeParameter))
489 public override GenericParameterAttributes Attributes {
490 get { return attrs; }
493 public override bool HasClassConstraint {
494 get { return class_constraint != null; }
497 public override Type ClassConstraint {
498 get { return class_constraint_type; }
501 public override Type[] InterfaceConstraints {
502 get { return iface_constraint_types; }
505 public override Type EffectiveBaseClass {
506 get { return effective_base_type; }
509 public bool IsSubclassOf (Type t)
511 if ((class_constraint_type != null) &&
512 class_constraint_type.IsSubclassOf (t))
515 if (iface_constraint_types == null)
518 foreach (Type iface in iface_constraint_types) {
519 if (TypeManager.IsSubclassOf (iface, t))
526 public Location Location {
533 /// This is used when we're implementing a generic interface method.
534 /// Each method type parameter in implementing method must have the same
535 /// constraints than the corresponding type parameter in the interface
536 /// method. To do that, we're called on each of the implementing method's
539 public bool CheckInterfaceMethod (GenericConstraints gc)
541 if (gc.Attributes != attrs)
544 if (HasClassConstraint != gc.HasClassConstraint)
546 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
549 int gc_icount = gc.InterfaceConstraints != null ?
550 gc.InterfaceConstraints.Length : 0;
551 int icount = InterfaceConstraints != null ?
552 InterfaceConstraints.Length : 0;
554 if (gc_icount != icount)
557 for (int i = 0; i < gc.InterfaceConstraints.Length; ++i) {
558 Type iface = gc.InterfaceConstraints [i];
559 if (iface.IsGenericType)
560 iface = iface.GetGenericTypeDefinition ();
563 for (int ii = 0; i < InterfaceConstraints.Length; ++ii) {
564 Type check = InterfaceConstraints [ii];
565 if (check.IsGenericType)
566 check = check.GetGenericTypeDefinition ();
568 if (TypeManager.IsEqual (iface, check)) {
581 public void VerifyClsCompliance ()
583 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
584 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
586 if (iface_constraint_types != null) {
587 for (int i = 0; i < iface_constraint_types.Length; ++i) {
588 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
589 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
590 ((TypeExpr)iface_constraints [i]).Location);
595 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
597 Report.SymbolRelatedToPreviousError (t);
598 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
599 TypeManager.CSharpName (t));
604 /// A type parameter from a generic type definition.
606 public class TypeParameter : MemberCore, IMemberContainer
610 GenericConstraints gc;
611 Constraints constraints;
613 GenericTypeParameterBuilder type;
614 MemberCache member_cache;
616 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
617 Constraints constraints, Attributes attrs, Location loc)
618 : base (parent, new MemberName (name, loc), attrs)
622 this.constraints = constraints;
626 public GenericConstraints GenericConstraints {
627 get { return gc != null ? gc : constraints; }
630 public Constraints Constraints {
631 get { return constraints; }
634 public DeclSpace DeclSpace {
643 /// This is the first method which is called during the resolving
644 /// process; we're called immediately after creating the type parameters
645 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
648 /// We're either called from TypeContainer.DefineType() or from
649 /// GenericMethod.Define() (called from Method.Define()).
651 public void Define (GenericTypeParameterBuilder type)
653 if (this.type != null)
654 throw new InvalidOperationException ();
657 TypeManager.AddTypeParameter (type, this);
661 /// This is the second method which is called during the resolving
662 /// process - in case of class type parameters, we're called from
663 /// TypeContainer.ResolveType() - after it resolved the class'es
664 /// base class and interfaces. For method type parameters, we're
665 /// called immediately after Define().
667 /// We're just resolving the constraints into expressions here, we
668 /// don't resolve them into actual types.
670 /// Note that in the special case of partial generic classes, we may be
671 /// called _before_ Define() and we may also be called multiple types.
673 public bool Resolve (DeclSpace ds)
675 if (constraints != null) {
676 if (!constraints.Resolve (ds)) {
686 /// This is the third method which is called during the resolving
687 /// process. We're called immediately after calling DefineConstraints()
688 /// on all of the current class'es type parameters.
690 /// Our job is to resolve the constraints to actual types.
692 /// Note that we may have circular dependencies on type parameters - this
693 /// is why Resolve() and ResolveType() are separate.
695 public bool ResolveType (IResolveContext ec)
697 if (constraints != null) {
698 if (!constraints.ResolveTypes (ec)) {
708 /// This is the fourth and last method which is called during the resolving
709 /// process. We're called after everything is fully resolved and actually
710 /// register the constraints with SRE and the TypeManager.
712 public bool DefineType (IResolveContext ec)
714 return DefineType (ec, null, null, false);
718 /// This is the fith and last method which is called during the resolving
719 /// process. We're called after everything is fully resolved and actually
720 /// register the constraints with SRE and the TypeManager.
722 /// The `builder', `implementing' and `is_override' arguments are only
723 /// applicable to method type parameters.
725 public bool DefineType (IResolveContext ec, MethodBuilder builder,
726 MethodInfo implementing, bool is_override)
728 if (!ResolveType (ec))
731 if (implementing != null) {
732 if (is_override && (constraints != null)) {
733 Report.Error (460, loc,
734 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
735 TypeManager.CSharpSignature (builder));
739 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
741 int pos = type.GenericParameterPosition;
742 Type mparam = mb.GetGenericArguments () [pos];
743 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
746 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
747 else if (constraints != null)
748 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
751 if (constraints != null) {
754 else if (!constraints.CheckInterfaceMethod (gc))
757 if (!is_override && (temp_gc != null))
762 Report.SymbolRelatedToPreviousError (implementing);
765 425, loc, "The constraints for type " +
766 "parameter `{0}' of method `{1}' must match " +
767 "the constraints for type parameter `{2}' " +
768 "of interface method `{3}'. Consider using " +
769 "an explicit interface implementation instead",
770 Name, TypeManager.CSharpSignature (builder),
771 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
774 } else if (DeclSpace is CompilerGeneratedClass) {
775 TypeParameter[] tparams = DeclSpace.TypeParameters;
776 Type[] types = new Type [tparams.Length];
777 for (int i = 0; i < tparams.Length; i++)
778 types [i] = tparams [i].Type;
780 if (constraints != null)
781 gc = new InflatedConstraints (constraints, types);
783 gc = (GenericConstraints) constraints;
789 if (gc.HasClassConstraint)
790 type.SetBaseTypeConstraint (gc.ClassConstraint);
792 type.SetInterfaceConstraints (gc.InterfaceConstraints);
793 type.SetGenericParameterAttributes (gc.Attributes);
794 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
800 /// Check whether there are no conflicts in our type parameter constraints.
802 /// This is an example:
806 /// where U : T, struct
808 public bool CheckDependencies ()
810 if (constraints != null)
811 return constraints.CheckDependencies ();
817 /// This is called for each part of a partial generic type definition.
819 /// If `new_constraints' is not null and we don't already have constraints,
820 /// they become our constraints. If we already have constraints, we must
821 /// check that they're the same.
824 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
827 throw new InvalidOperationException ();
829 if (new_constraints == null)
832 if (!new_constraints.Resolve (ec))
834 if (!new_constraints.ResolveTypes (ec))
837 if (constraints != null)
838 return constraints.CheckInterfaceMethod (new_constraints);
840 constraints = new_constraints;
844 public override void Emit ()
846 if (OptAttributes != null)
847 OptAttributes.Emit ();
852 public override string DocCommentHeader {
854 throw new InvalidOperationException (
855 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
863 public override bool Define ()
868 public override void ApplyAttributeBuilder (Attribute a,
869 CustomAttributeBuilder cb)
871 type.SetCustomAttribute (cb);
874 public override AttributeTargets AttributeTargets {
876 return (AttributeTargets) AttributeTargets.GenericParameter;
880 public override string[] ValidAttributeTargets {
882 return new string [] { "type parameter" };
890 string IMemberContainer.Name {
894 MemberCache IMemberContainer.BaseCache {
899 if (gc.EffectiveBaseClass.BaseType == null)
902 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
906 bool IMemberContainer.IsInterface {
907 get { return false; }
910 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
912 return FindMembers (mt, bf, null, null);
915 public MemberCache MemberCache {
917 if (member_cache != null)
923 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
924 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
930 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
931 MemberFilter filter, object criteria)
934 return MemberList.Empty;
936 ArrayList members = new ArrayList ();
938 if (gc.HasClassConstraint) {
939 MemberList list = TypeManager.FindMembers (
940 gc.ClassConstraint, mt, bf, filter, criteria);
942 members.AddRange (list);
945 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
946 foreach (Type t in ifaces) {
947 MemberList list = TypeManager.FindMembers (
948 t, mt, bf, filter, criteria);
950 members.AddRange (list);
953 return new MemberList (members);
956 public bool IsSubclassOf (Type t)
961 if (constraints != null)
962 return constraints.IsSubclassOf (t);
967 public override string ToString ()
969 return "TypeParameter[" + name + "]";
972 public static string GetSignatureForError (TypeParameter[] tp)
974 if (tp == null || tp.Length == 0)
977 StringBuilder sb = new StringBuilder ("<");
978 for (int i = 0; i < tp.Length; ++i) {
981 sb.Append (tp[i].GetSignatureForError ());
984 return sb.ToString ();
987 public void InflateConstraints (Type declaring)
989 if (constraints != null)
990 gc = new InflatedConstraints (constraints, declaring);
993 public override bool IsClsComplianceRequired ()
998 protected class InflatedConstraints : GenericConstraints
1000 GenericConstraints gc;
1002 Type class_constraint;
1003 Type[] iface_constraints;
1006 public InflatedConstraints (GenericConstraints gc, Type declaring)
1007 : this (gc, TypeManager.GetTypeArguments (declaring))
1010 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
1015 ArrayList list = new ArrayList ();
1016 if (gc.HasClassConstraint)
1017 list.Add (inflate (gc.ClassConstraint));
1018 foreach (Type iface in gc.InterfaceConstraints)
1019 list.Add (inflate (iface));
1021 bool has_class_constr = false;
1022 if (list.Count > 0) {
1023 Type first = (Type) list [0];
1024 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
1027 if ((list.Count > 0) && has_class_constr) {
1028 class_constraint = (Type) list [0];
1029 iface_constraints = new Type [list.Count - 1];
1030 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1032 iface_constraints = new Type [list.Count];
1033 list.CopyTo (iface_constraints, 0);
1036 if (HasValueTypeConstraint)
1037 base_type = TypeManager.value_type;
1038 else if (class_constraint != null)
1039 base_type = class_constraint;
1041 base_type = TypeManager.object_type;
1044 Type inflate (Type t)
1048 if (t.IsGenericParameter)
1049 return dargs [t.GenericParameterPosition];
1050 if (t.IsGenericType) {
1051 Type[] args = t.GetGenericArguments ();
1052 Type[] inflated = new Type [args.Length];
1054 for (int i = 0; i < args.Length; i++)
1055 inflated [i] = inflate (args [i]);
1057 t = t.GetGenericTypeDefinition ();
1058 t = t.MakeGenericType (inflated);
1064 public override string TypeParameter {
1065 get { return gc.TypeParameter; }
1068 public override GenericParameterAttributes Attributes {
1069 get { return gc.Attributes; }
1072 public override Type ClassConstraint {
1073 get { return class_constraint; }
1076 public override Type EffectiveBaseClass {
1077 get { return base_type; }
1080 public override Type[] InterfaceConstraints {
1081 get { return iface_constraints; }
1087 /// A TypeExpr which already resolved to a type parameter.
1089 public class TypeParameterExpr : TypeExpr {
1090 TypeParameter type_parameter;
1092 public override string Name {
1094 return type_parameter.Name;
1098 public override string FullName {
1100 return type_parameter.Name;
1104 public TypeParameter TypeParameter {
1106 return type_parameter;
1110 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1112 this.type_parameter = type_parameter;
1116 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1118 type = type_parameter.Type;
1123 public override bool IsInterface {
1124 get { return false; }
1127 public override bool CheckAccessLevel (DeclSpace ds)
1132 public void Error_CannotUseAsUnmanagedType (Location loc)
1134 Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
1139 /// Tracks the type arguments when instantiating a generic type. We're used in
1140 /// ConstructedType.
1142 public class TypeArguments {
1143 public readonly Location Location;
1150 public TypeArguments (Location loc)
1152 args = new ArrayList ();
1153 this.Location = loc;
1156 public TypeArguments (Location loc, params Expression[] types)
1158 this.Location = loc;
1159 this.args = new ArrayList (types);
1162 public TypeArguments (int dimension, Location loc)
1164 this.dimension = dimension;
1165 this.Location = loc;
1168 public void Add (Expression type)
1171 throw new InvalidOperationException ();
1176 public void Add (TypeArguments new_args)
1179 throw new InvalidOperationException ();
1181 args.AddRange (new_args.args);
1185 /// We're used during the parsing process: the parser can't distinguish
1186 /// between type parameters and type arguments. Because of that, the
1187 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1188 /// in case of a generic type definition, we call GetDeclarations().
1190 public TypeParameterName[] GetDeclarations ()
1192 TypeParameterName[] ret = new TypeParameterName [args.Count];
1193 for (int i = 0; i < args.Count; i++) {
1194 TypeParameterName name = args [i] as TypeParameterName;
1199 SimpleName sn = args [i] as SimpleName;
1201 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1205 Report.Error (81, Location, "Type parameter declaration " +
1206 "must be an identifier not a type");
1213 /// We may only be used after Resolve() is called and return the fully
1216 public Type[] Arguments {
1222 public bool HasTypeArguments {
1224 return has_type_args;
1237 public bool IsUnbound {
1239 return dimension > 0;
1243 public override string ToString ()
1245 StringBuilder s = new StringBuilder ();
1248 for (int i = 0; i < count; i++){
1250 // FIXME: Use TypeManager.CSharpname once we have the type
1253 s.Append (args [i].ToString ());
1257 return s.ToString ();
1260 public string GetSignatureForError()
1262 StringBuilder sb = new StringBuilder();
1263 for (int i = 0; i < Count; ++i)
1265 Expression expr = (Expression)args [i];
1266 sb.Append(expr.GetSignatureForError());
1270 return sb.ToString();
1274 /// Resolve the type arguments.
1276 public bool Resolve (IResolveContext ec)
1278 int count = args.Count;
1281 atypes = new Type [count];
1283 for (int i = 0; i < count; i++){
1284 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1290 atypes[i] = te.Type;
1291 if (te.Type.IsGenericParameter) {
1292 if (te is TypeParameterExpr)
1293 has_type_args = true;
1297 if (te.Type.IsSealed && te.Type.IsAbstract) {
1298 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1299 te.GetSignatureForError ());
1303 if (te.Type.IsPointer) {
1304 Report.Error (306, Location, "The type `{0}' may not be used " +
1305 "as a type argument", TypeManager.CSharpName (te.Type));
1309 if (te.Type == TypeManager.void_type) {
1310 Expression.Error_VoidInvalidInTheContext (Location);
1317 public TypeArguments Clone ()
1319 TypeArguments copy = new TypeArguments (Location);
1320 foreach (Expression ta in args)
1327 public class TypeParameterName : SimpleName
1329 Attributes attributes;
1331 public TypeParameterName (string name, Attributes attrs, Location loc)
1337 public Attributes OptAttributes {
1345 /// An instantiation of a generic type.
1347 public class ConstructedType : TypeExpr {
1349 FullNamedExpression name;
1351 Type[] gen_params, atypes;
1355 /// Instantiate the generic type `fname' with the type arguments `args'.
1357 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1363 eclass = ExprClass.Type;
1364 full_name = name + "<" + args.ToString () + ">";
1367 protected ConstructedType (TypeArguments args, Location l)
1372 eclass = ExprClass.Type;
1375 protected ConstructedType (TypeParameter[] type_params, Location l)
1379 args = new TypeArguments (l);
1380 foreach (TypeParameter type_param in type_params)
1381 args.Add (new TypeParameterExpr (type_param, l));
1383 eclass = ExprClass.Type;
1387 /// This is used to construct the `this' type inside a generic type definition.
1389 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1390 : this (type_params, l)
1392 gt = t.GetGenericTypeDefinition ();
1394 this.name = new TypeExpression (gt, l);
1395 full_name = gt.FullName + "<" + args.ToString () + ">";
1399 /// Instantiate the generic type `t' with the type arguments `args'.
1400 /// Use this constructor if you already know the fully resolved
1403 public ConstructedType (Type t, TypeArguments args, Location l)
1406 gt = t.GetGenericTypeDefinition ();
1408 this.name = new TypeExpression (gt, l);
1409 full_name = gt.FullName + "<" + args.ToString () + ">";
1412 public TypeArguments TypeArguments {
1413 get { return args; }
1416 public override string GetSignatureForError ()
1418 return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1421 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1423 if (!ResolveConstructedType (ec))
1430 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1431 /// after fully resolving the constructed type.
1433 public bool CheckConstraints (IResolveContext ec)
1435 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1439 /// Resolve the constructed type, but don't check the constraints.
1441 public bool ResolveConstructedType (IResolveContext ec)
1445 // If we already know the fully resolved generic type.
1447 return DoResolveType (ec);
1453 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1457 num_args = TypeManager.GetNumberOfTypeArguments (t);
1458 if (num_args == 0) {
1459 Report.Error (308, loc,
1460 "The non-generic type `{0}' cannot " +
1461 "be used with type arguments.",
1462 TypeManager.CSharpName (t));
1466 gt = t.GetGenericTypeDefinition ();
1467 return DoResolveType (ec);
1470 bool DoResolveType (IResolveContext ec)
1473 // Resolve the arguments.
1475 if (args.Resolve (ec) == false)
1478 gen_params = gt.GetGenericArguments ();
1479 atypes = args.Arguments;
1481 if (atypes.Length != gen_params.Length) {
1482 Report.Error (305, loc,
1483 "Using the generic type `{0}' " +
1484 "requires {1} type arguments",
1485 TypeManager.CSharpName (gt),
1486 gen_params.Length.ToString ());
1491 // Now bind the parameters.
1493 type = gt.MakeGenericType (atypes);
1497 public Expression GetSimpleName (EmitContext ec)
1502 public override bool CheckAccessLevel (DeclSpace ds)
1504 return ds.CheckAccessLevel (gt);
1507 public override bool AsAccessible (DeclSpace ds, int flags)
1509 foreach (Type t in atypes) {
1510 if (!ds.AsAccessible (t, flags))
1514 return ds.AsAccessible (gt, flags);
1517 public override bool IsClass {
1518 get { return gt.IsClass; }
1521 public override bool IsValueType {
1522 get { return gt.IsValueType; }
1525 public override bool IsInterface {
1526 get { return gt.IsInterface; }
1529 public override bool IsSealed {
1530 get { return gt.IsSealed; }
1533 public override bool Equals (object obj)
1535 ConstructedType cobj = obj as ConstructedType;
1539 if ((type == null) || (cobj.type == null))
1542 return type == cobj.type;
1545 public override int GetHashCode ()
1547 return base.GetHashCode ();
1550 public override string Name {
1556 public override string FullName {
1563 public abstract class ConstraintChecker
1565 protected readonly Type[] gen_params;
1566 protected readonly Type[] atypes;
1567 protected readonly Location loc;
1569 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1571 this.gen_params = gen_params;
1572 this.atypes = atypes;
1577 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1578 /// after fully resolving the constructed type.
1580 public bool CheckConstraints (IResolveContext ec)
1582 for (int i = 0; i < gen_params.Length; i++) {
1583 if (!CheckConstraints (ec, i))
1590 protected bool CheckConstraints (IResolveContext ec, int index)
1592 Type atype = atypes [index];
1593 Type ptype = gen_params [index];
1598 Expression aexpr = new EmptyExpression (atype);
1600 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1604 bool is_class, is_struct;
1605 if (atype.IsGenericParameter) {
1606 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1608 if (agc is Constraints)
1609 ((Constraints) agc).Resolve (ec);
1610 is_class = agc.IsReferenceType;
1611 is_struct = agc.IsValueType;
1613 is_class = is_struct = false;
1618 if (!atype.IsGenericType)
1620 is_class = atype.IsClass || atype.IsInterface;
1621 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1625 // First, check the `class' and `struct' constraints.
1627 if (gc.HasReferenceTypeConstraint && !is_class) {
1628 Report.Error (452, loc, "The type `{0}' must be " +
1629 "a reference type in order to use it " +
1630 "as type parameter `{1}' in the " +
1631 "generic type or method `{2}'.",
1632 TypeManager.CSharpName (atype),
1633 TypeManager.CSharpName (ptype),
1634 GetSignatureForError ());
1636 } else if (gc.HasValueTypeConstraint && !is_struct) {
1637 Report.Error (453, loc, "The type `{0}' must be a " +
1638 "non-nullable value type in order to use it " +
1639 "as type parameter `{1}' in the " +
1640 "generic type or method `{2}'.",
1641 TypeManager.CSharpName (atype),
1642 TypeManager.CSharpName (ptype),
1643 GetSignatureForError ());
1648 // The class constraint comes next.
1650 if (gc.HasClassConstraint) {
1651 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1656 // Now, check the interface constraints.
1658 if (gc.InterfaceConstraints != null) {
1659 foreach (Type it in gc.InterfaceConstraints) {
1660 if (!CheckConstraint (ec, ptype, aexpr, it))
1666 // Finally, check the constructor constraint.
1669 if (!gc.HasConstructorConstraint)
1672 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1675 if (HasDefaultConstructor (atype))
1678 Report_SymbolRelatedToPreviousError ();
1679 Report.SymbolRelatedToPreviousError (atype);
1680 Report.Error (310, loc, "The type `{0}' must have a public " +
1681 "parameterless constructor in order to use it " +
1682 "as parameter `{1}' in the generic type or " +
1684 TypeManager.CSharpName (atype),
1685 TypeManager.CSharpName (ptype),
1686 GetSignatureForError ());
1690 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1693 if (TypeManager.HasGenericArguments (ctype)) {
1694 Type[] types = TypeManager.GetTypeArguments (ctype);
1696 TypeArguments new_args = new TypeArguments (loc);
1698 for (int i = 0; i < types.Length; i++) {
1701 if (t.IsGenericParameter) {
1702 int pos = t.GenericParameterPosition;
1705 new_args.Add (new TypeExpression (t, loc));
1708 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1709 if (ct.ResolveAsTypeStep (ec, false) == null)
1712 } else if (ctype.IsGenericParameter) {
1713 int pos = ctype.GenericParameterPosition;
1714 ctype = atypes [pos];
1717 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1720 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1724 bool HasDefaultConstructor (Type atype)
1726 if (atype.IsAbstract)
1730 atype = TypeManager.DropGenericTypeArguments (atype);
1731 if (atype is TypeBuilder) {
1732 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1733 if (tc.InstanceConstructors == null) {
1734 atype = atype.BaseType;
1738 foreach (Constructor c in tc.InstanceConstructors) {
1739 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1741 if ((c.Parameters.FixedParameters != null) &&
1742 (c.Parameters.FixedParameters.Length != 0))
1744 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1751 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1752 if (tparam != null) {
1753 if (tparam.GenericConstraints == null)
1756 return tparam.GenericConstraints.HasConstructorConstraint;
1759 MemberList list = TypeManager.FindMembers (
1760 atype, MemberTypes.Constructor,
1761 BindingFlags.Public | BindingFlags.Instance |
1762 BindingFlags.DeclaredOnly, null, null);
1764 if (atype.IsAbstract || (list == null))
1767 foreach (MethodBase mb in list) {
1768 ParameterData pd = TypeManager.GetParameterData (mb);
1769 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1776 protected abstract string GetSignatureForError ();
1777 protected abstract void Report_SymbolRelatedToPreviousError ();
1779 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1781 Report_SymbolRelatedToPreviousError ();
1782 Report.SymbolRelatedToPreviousError (atype);
1783 Report.Error (309, loc,
1784 "The type `{0}' must be convertible to `{1}' in order to " +
1785 "use it as parameter `{2}' in the generic type or method `{3}'",
1786 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1787 TypeManager.CSharpName (ptype), GetSignatureForError ());
1790 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1791 MethodBase instantiated, Location loc)
1793 MethodConstraintChecker checker = new MethodConstraintChecker (
1794 definition, definition.GetGenericArguments (),
1795 instantiated.GetGenericArguments (), loc);
1797 return checker.CheckConstraints (ec);
1800 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1801 Type[] atypes, Location loc)
1803 TypeConstraintChecker checker = new TypeConstraintChecker (
1804 gt, gen_params, atypes, loc);
1806 return checker.CheckConstraints (ec);
1809 protected class MethodConstraintChecker : ConstraintChecker
1811 MethodBase definition;
1813 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1814 Type[] atypes, Location loc)
1815 : base (gen_params, atypes, loc)
1817 this.definition = definition;
1820 protected override string GetSignatureForError ()
1822 return TypeManager.CSharpSignature (definition);
1825 protected override void Report_SymbolRelatedToPreviousError ()
1827 Report.SymbolRelatedToPreviousError (definition);
1831 protected class TypeConstraintChecker : ConstraintChecker
1835 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1837 : base (gen_params, atypes, loc)
1842 protected override string GetSignatureForError ()
1844 return TypeManager.CSharpName (gt);
1847 protected override void Report_SymbolRelatedToPreviousError ()
1849 Report.SymbolRelatedToPreviousError (gt);
1855 /// A generic method definition.
1857 public class GenericMethod : DeclSpace
1859 Expression return_type;
1860 Parameters parameters;
1862 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1863 Expression return_type, Parameters parameters)
1864 : base (ns, parent, name, null)
1866 this.return_type = return_type;
1867 this.parameters = parameters;
1870 public override TypeBuilder DefineType ()
1872 throw new Exception ();
1875 public override bool Define ()
1877 for (int i = 0; i < TypeParameters.Length; i++)
1878 if (!TypeParameters [i].Resolve (this))
1885 /// Define and resolve the type parameters.
1886 /// We're called from Method.Define().
1888 public bool Define (MethodBuilder mb, ToplevelBlock block)
1890 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1891 string[] snames = new string [names.Length];
1892 for (int i = 0; i < names.Length; i++) {
1893 string type_argument_name = names[i].Name;
1894 Parameter p = parameters.GetParameterByName (type_argument_name);
1896 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1900 snames[i] = type_argument_name;
1903 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1904 for (int i = 0; i < TypeParameters.Length; i++)
1905 TypeParameters [i].Define (gen_params [i]);
1910 for (int i = 0; i < TypeParameters.Length; i++) {
1911 if (!TypeParameters [i].ResolveType (this))
1918 internal static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1920 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1921 name, collisionWith);
1925 /// We're called from MethodData.Define() after creating the MethodBuilder.
1927 public bool DefineType (EmitContext ec, MethodBuilder mb,
1928 MethodInfo implementing, bool is_override)
1930 for (int i = 0; i < TypeParameters.Length; i++)
1931 if (!TypeParameters [i].DefineType (
1932 ec, mb, implementing, is_override))
1936 foreach (Parameter p in parameters.FixedParameters){
1937 if (!p.Resolve (ec))
1940 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1946 public void EmitAttributes ()
1948 for (int i = 0; i < TypeParameters.Length; i++)
1949 TypeParameters [i].Emit ();
1951 if (OptAttributes != null)
1952 OptAttributes.Emit ();
1955 public override bool DefineMembers ()
1960 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1961 MemberFilter filter, object criteria)
1963 throw new Exception ();
1966 public override MemberCache MemberCache {
1972 public override AttributeTargets AttributeTargets {
1974 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1978 public override string DocCommentHeader {
1979 get { return "M:"; }
1982 public new void VerifyClsCompliance ()
1984 foreach (TypeParameter tp in TypeParameters) {
1985 if (tp.Constraints == null)
1988 tp.Constraints.VerifyClsCompliance ();
1993 public class NullableType : TypeExpr
1995 Expression underlying;
1997 public NullableType (Expression underlying, Location l)
1999 this.underlying = underlying;
2002 eclass = ExprClass.Type;
2005 public NullableType (Type type, Location loc)
2006 : this (new TypeExpression (type, loc), loc)
2009 public override string Name {
2010 get { return underlying.ToString () + "?"; }
2013 public override string FullName {
2014 get { return underlying.ToString () + "?"; }
2017 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2019 TypeArguments args = new TypeArguments (loc);
2020 args.Add (underlying);
2022 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2023 return ctype.ResolveAsTypeTerminal (ec, false);
2027 public partial class TypeManager
2030 // A list of core types that the compiler requires or uses
2032 static public Type activator_type;
2033 static public Type generic_ilist_type;
2034 static public Type generic_icollection_type;
2035 static public Type generic_ienumerator_type;
2036 static public Type generic_ienumerable_type;
2037 static public Type generic_nullable_type;
2040 // These methods are called by code generated by the compiler
2042 static public MethodInfo activator_create_instance;
2044 static void InitGenericCoreTypes ()
2046 activator_type = CoreLookupType ("System", "Activator");
2048 generic_ilist_type = CoreLookupType (
2049 "System.Collections.Generic", "IList", 1);
2050 generic_icollection_type = CoreLookupType (
2051 "System.Collections.Generic", "ICollection", 1);
2052 generic_ienumerator_type = CoreLookupType (
2053 "System.Collections.Generic", "IEnumerator", 1);
2054 generic_ienumerable_type = CoreLookupType (
2055 "System.Collections.Generic", "IEnumerable", 1);
2056 generic_nullable_type = CoreLookupType (
2057 "System", "Nullable", 1);
2060 static void InitGenericCodeHelpers ()
2063 activator_create_instance = GetMethod (
2064 activator_type, "CreateInstance", Type.EmptyTypes);
2067 static Type CoreLookupType (string ns, string name, int arity)
2069 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2072 public static TypeContainer LookupGenericTypeContainer (Type t)
2074 t = DropGenericTypeArguments (t);
2075 return LookupTypeContainer (t);
2079 /// Check whether `a' and `b' may become equal generic types.
2080 /// The algorithm to do that is a little bit complicated.
2082 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2083 Type[] method_inferred)
2085 if (a.IsGenericParameter) {
2087 // If a is an array of a's type, they may never
2091 b = b.GetElementType ();
2097 // If b is a generic parameter or an actual type,
2098 // they may become equal:
2100 // class X<T,U> : I<T>, I<U>
2101 // class X<T> : I<T>, I<float>
2103 if (b.IsGenericParameter || !b.IsGenericType) {
2104 int pos = a.GenericParameterPosition;
2105 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2106 if (args [pos] == null) {
2111 return args [pos] == a;
2115 // We're now comparing a type parameter with a
2116 // generic instance. They may become equal unless
2117 // the type parameter appears anywhere in the
2118 // generic instance:
2120 // class X<T,U> : I<T>, I<X<U>>
2121 // -> error because you could instanciate it as
2124 // class X<T> : I<T>, I<X<T>> -> ok
2127 Type[] bargs = GetTypeArguments (b);
2128 for (int i = 0; i < bargs.Length; i++) {
2129 if (a.Equals (bargs [i]))
2136 if (b.IsGenericParameter)
2137 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2140 // At this point, neither a nor b are a type parameter.
2142 // If one of them is a generic instance, let
2143 // MayBecomeEqualGenericInstances() compare them (if the
2144 // other one is not a generic instance, they can never
2148 if (a.IsGenericType || b.IsGenericType)
2149 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2152 // If both of them are arrays.
2155 if (a.IsArray && b.IsArray) {
2156 if (a.GetArrayRank () != b.GetArrayRank ())
2159 a = a.GetElementType ();
2160 b = b.GetElementType ();
2162 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2166 // Ok, two ordinary types.
2169 return a.Equals (b);
2173 // Checks whether two generic instances may become equal for some
2174 // particular instantiation (26.3.1).
2176 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2177 Type[] class_inferred,
2178 Type[] method_inferred)
2180 if (!a.IsGenericType || !b.IsGenericType)
2182 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2185 return MayBecomeEqualGenericInstances (
2186 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2189 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2190 Type[] class_inferred,
2191 Type[] method_inferred)
2193 if (aargs.Length != bargs.Length)
2196 for (int i = 0; i < aargs.Length; i++) {
2197 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2205 /// Type inference. Try to infer the type arguments from the params method
2206 /// `method', which is invoked with the arguments `arguments'. This is used
2207 /// when resolving an Invocation or a DelegateInvocation and the user
2208 /// did not explicitly specify type arguments.
2210 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2211 ref MethodBase method)
2213 if (!TypeManager.IsGenericMethod (method))
2216 // if there are no arguments, there's no way to infer the type-arguments
2217 if (arguments == null || arguments.Count == 0)
2220 ParameterData pd = TypeManager.GetParameterData (method);
2221 int pd_count = pd.Count;
2222 int arg_count = arguments.Count;
2227 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2230 if (pd_count - 1 > arg_count)
2233 Type[] method_args = method.GetGenericArguments ();
2234 Type[] inferred_types = new Type [method_args.Length];
2237 // If we have come this far, the case which
2238 // remains is when the number of parameters is
2239 // less than or equal to the argument count.
2241 for (int i = 0; i < pd_count - 1; ++i) {
2242 Argument a = (Argument) arguments [i];
2244 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2247 Type pt = pd.ParameterType (i);
2250 if (!TypeInferenceV2.UnifyType (pt, at, inferred_types))
2254 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2256 for (int i = pd_count - 1; i < arg_count; i++) {
2257 Argument a = (Argument) arguments [i];
2259 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2262 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2266 for (int i = 0; i < inferred_types.Length; i++)
2267 if (inferred_types [i] == null)
2270 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2275 /// Type inference. Try to infer the type arguments from `method',
2276 /// which is invoked with the arguments `arguments'. This is used
2277 /// when resolving an Invocation or a DelegateInvocation and the user
2278 /// did not explicitly specify type arguments.
2280 public static int InferTypeArguments (EmitContext ec,
2281 ArrayList arguments,
2282 ref MethodBase method)
2284 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2285 Type[] i_args = ti.InferMethodArguments (ec, method);
2287 return ti.InferenceScore;
2289 if (i_args.Length == 0)
2292 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2299 public static bool InferTypeArguments (ParameterData apd,
2300 ref MethodBase method)
2302 if (!TypeManager.IsGenericMethod (method))
2305 ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
2306 Type[] i_args = ti.InferDelegateArguments (method);
2310 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2315 abstract class ATypeInference
2317 protected readonly ArrayList arguments;
2318 protected readonly int arg_count;
2320 protected ATypeInference (ArrayList arguments)
2322 this.arguments = arguments;
2323 if (arguments != null)
2324 arg_count = arguments.Count;
2327 public static ATypeInference CreateInstance (ArrayList arguments)
2329 if (RootContext.Version == LanguageVersion.ISO_2)
2330 return new TypeInferenceV2 (arguments);
2332 return new TypeInferenceV3 (arguments);
2335 public virtual int InferenceScore {
2337 return int.MaxValue;
2341 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2342 public abstract Type[] InferDelegateArguments (MethodBase method);
2346 // Implements C# 2.0 type inference
2348 class TypeInferenceV2 : ATypeInference
2350 public TypeInferenceV2 (ArrayList arguments)
2355 public override Type[] InferDelegateArguments (MethodBase method)
2357 ParameterData pd = TypeManager.GetParameterData (method);
2358 if (arg_count != pd.Count)
2361 Type[] method_args = method.GetGenericArguments ();
2362 Type[] inferred_types = new Type[method_args.Length];
2364 Type[] param_types = new Type[pd.Count];
2365 Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
2367 for (int i = 0; i < arg_count; i++) {
2368 param_types[i] = pd.ParameterType (i);
2371 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2374 return inferred_types;
2377 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2379 ParameterData pd = TypeManager.GetParameterData (method);
2380 Type[] method_generic_args = method.GetGenericArguments ();
2381 Type [] inferred_types = new Type [method_generic_args.Length];
2382 Type[] arg_types = new Type [pd.Count];
2384 int a_count = arg_types.Length;
2388 for (int i = 0; i < a_count; i++) {
2389 Argument a = (Argument) arguments[i];
2390 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2393 if (!TypeInferenceV2.UnifyType (pd.ParameterType (i), a.Type, inferred_types))
2398 Type element_type = TypeManager.GetElementType (pd.ParameterType (a_count));
2399 for (int i = a_count; i < arg_count; i++) {
2400 Argument a = (Argument) arguments [i];
2401 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2404 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2409 for (int i = 0; i < inferred_types.Length; i++)
2410 if (inferred_types [i] == null)
2413 return inferred_types;
2416 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2417 Type[] inferred_types)
2419 for (int i = 0; i < arg_types.Length; i++) {
2420 if (arg_types[i] == null)
2423 if (!UnifyType (param_types[i], arg_types[i], inferred_types))
2427 for (int i = 0; i < inferred_types.Length; ++i)
2428 if (inferred_types[i] == null)
2434 public static bool UnifyType (Type pt, Type at, Type[] inferred)
2436 if (pt.IsGenericParameter) {
2437 if (pt.DeclaringMethod == null)
2440 int pos = pt.GenericParameterPosition;
2442 if (inferred [pos] == null)
2443 inferred [pos] = at;
2445 return inferred [pos] == at;
2448 if (!pt.ContainsGenericParameters) {
2449 if (at.ContainsGenericParameters)
2450 return UnifyType (at, pt, inferred);
2457 if (at.GetArrayRank () != pt.GetArrayRank ())
2460 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2463 if (!pt.IsGenericType)
2466 Type gt = pt.GetGenericTypeDefinition ();
2467 if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
2468 (gt != TypeManager.generic_ienumerable_type))
2471 Type[] args = TypeManager.GetTypeArguments (pt);
2472 return UnifyType (args[0], at.GetElementType (), inferred);
2477 (pt.GetArrayRank () != at.GetArrayRank ()))
2480 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2483 if (pt.IsByRef && at.IsByRef)
2484 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2485 ArrayList list = new ArrayList ();
2486 if (at.IsGenericType)
2488 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2491 list.AddRange (TypeManager.GetInterfaces (at));
2493 foreach (Type type in list) {
2494 if (!type.IsGenericType)
2497 if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
2500 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2507 static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
2509 for (int i = 0; i < ats.Length; i++) {
2510 if (!UnifyType (pts [i], ats [i], inferred))
2518 // Implements C# 3.0 type inference
2520 class TypeInferenceV3 : ATypeInference
2523 // Tracks successful rate of type inference
2525 int score = int.MaxValue;
2527 public TypeInferenceV3 (ArrayList arguments)
2532 public override int InferenceScore {
2538 public override Type[] InferDelegateArguments (MethodBase method)
2540 ParameterData pd = TypeManager.GetParameterData (method);
2541 if (arg_count != pd.Count)
2544 Type[] d_gargs = method.GetGenericArguments ();
2545 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2547 // A lower-bound inference is made from each argument type Uj of D
2548 // to the corresponding parameter type Tj of M
2549 for (int i = 0; i < arg_count; ++i) {
2550 Type t = pd.Types [i];
2551 if (!t.IsGenericParameter)
2554 context.LowerBoundInference ((Type)arguments[i], t);
2557 if (!context.FixAllTypes ())
2560 return context.InferredTypeArguments;
2563 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2565 Type[] method_generic_args = method.GetGenericArguments ();
2566 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2567 if (!context.UnfixedVariableExists)
2568 return Type.EmptyTypes;
2570 ParameterData pd = TypeManager.GetParameterData (method);
2571 if (!InferInPhases (ec, context, pd))
2574 return context.InferredTypeArguments;
2578 // Implements method type arguments inference
2580 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters)
2583 // The first inference phase
2585 for (int i = 0; i < arg_count; i++) {
2586 Type method_parameter = methodParameters.ParameterType (i);
2588 Argument a = (Argument) arguments[i];
2591 // When a lambda expression, an anonymous method
2592 // is used an explicit argument type inference takes a place
2594 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2596 if (am.ExplicitTypeInference (tic, method_parameter))
2601 if (a.Expr.Type == TypeManager.null_type)
2605 // Otherwise an output type inference is made
2607 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2611 // Part of the second phase but because it happens only once
2612 // we don't need to call it in cycle
2614 bool fixed_any = false;
2615 if (!tic.FixIndependentTypeArguments (methodParameters, ref fixed_any))
2618 return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
2621 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters, bool fixDependent)
2623 bool fixed_any = false;
2624 if (fixDependent && !tic.FixDependentTypes (methodParameters, ref fixed_any))
2627 // If no further unfixed type variables exist, type inference succeeds
2628 if (!tic.UnfixedVariableExists)
2631 if (!fixed_any && fixDependent)
2634 // For all arguments where the corresponding argument output types
2635 // contain unfixed type variables but the input types do not,
2636 // an output type inference is made
2637 for (int i = 0; i < arg_count; i++) {
2638 Type t_i = methodParameters.ParameterType (i);
2639 if (!TypeManager.IsDelegateType (t_i))
2642 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2643 Type rtype = mi.ReturnType;
2646 // Blablabla, because reflection does not work with dynamic types
2647 Type[] g_args = t_i.GetGenericArguments ();
2648 rtype = g_args[rtype.GenericParameterPosition];
2651 if (tic.IsReturnTypeNonDependent (mi, rtype))
2652 score -= tic.OutputTypeInference (ec, ((Argument) arguments [i]).Expr, t_i);
2656 return DoSecondPhase (ec, tic, methodParameters, true);
2660 public class TypeInferenceContext
2662 readonly Type[] unfixed_types;
2663 readonly Type[] fixed_types;
2664 readonly ArrayList[] bounds;
2666 public TypeInferenceContext (Type[] typeArguments)
2668 if (typeArguments.Length == 0)
2669 throw new ArgumentException ("Empty generic arguments");
2671 fixed_types = new Type [typeArguments.Length];
2672 for (int i = 0; i < typeArguments.Length; ++i) {
2673 if (typeArguments [i].IsGenericParameter) {
2674 if (bounds == null) {
2675 bounds = new ArrayList [typeArguments.Length];
2676 unfixed_types = new Type [typeArguments.Length];
2678 unfixed_types [i] = typeArguments [i];
2680 fixed_types [i] = typeArguments [i];
2685 public Type[] InferredTypeArguments {
2691 void AddToBounds (Type t, int index)
2693 ArrayList a = bounds[index];
2695 a = new ArrayList ();
2707 bool AllTypesAreFixed (Type[] types)
2709 foreach (Type t in types) {
2710 if (t.IsGenericParameter) {
2716 if (t.IsGenericType)
2717 return AllTypesAreFixed (t.GetGenericArguments ());
2724 // 26.3.3.8 Exact Inference
2726 public int ExactInference (Type u, Type v)
2728 // If V is an array type
2733 if (u.GetArrayRank () != v.GetArrayRank ())
2736 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2739 // If V is constructed type and U is constructed type
2740 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2741 if (!u.IsGenericType)
2744 Type [] ga_u = u.GetGenericArguments ();
2745 Type [] ga_v = v.GetGenericArguments ();
2746 if (ga_u.Length != ga_v.Length)
2750 for (int i = 0; i < ga_u.Length; ++i)
2751 score += ExactInference (ga_u [i], ga_v [i]);
2753 return score > 0 ? 1 : 0;
2756 // If V is one of the unfixed type arguments
2757 int pos = IsUnfixed (v);
2761 AddToBounds (u, pos);
2765 public bool FixAllTypes ()
2767 for (int i = 0; i < unfixed_types.Length; ++i) {
2775 // All unfixed type variables Xi are fixed for which all of the following hold:
2776 // a, There is at least one type variable Xj that depends on Xi
2777 // b, Xi has a non-empty set of bounds
2779 public bool FixDependentTypes (ParameterData methodParameters, ref bool fixed_any)
2781 for (int i = 0; i < unfixed_types.Length; ++i) {
2782 if (unfixed_types[i] == null)
2785 if (bounds[i] == null)
2798 // All unfixed type variables Xi which depend on no Xj are fixed
2800 public bool FixIndependentTypeArguments (ParameterData methodParameters, ref bool fixed_any)
2802 ArrayList types_to_fix = new ArrayList (unfixed_types);
2803 foreach (Type t in methodParameters.Types) {
2804 if (t.IsGenericParameter)
2807 if (!TypeManager.IsDelegateType (t))
2810 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2811 Type rtype = invoke.ReturnType;
2812 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2816 // Blablabla, because reflection does not work with dynamic types
2817 if (rtype.IsGenericParameter) {
2818 Type [] g_args = t.GetGenericArguments ();
2819 rtype = g_args [rtype.GenericParameterPosition];
2822 // Remove dependent types, they cannot be fixed yet
2823 RemoveDependentTypes (types_to_fix, rtype);
2826 foreach (Type t in types_to_fix) {
2830 int idx = IsUnfixed (t);
2831 if (idx >= 0 && !FixType (idx)) {
2836 fixed_any = types_to_fix.Count > 0;
2843 public bool FixType (int i)
2845 // It's already fixed
2846 if (unfixed_types[i] == null)
2847 throw new InternalErrorException ("Type argument has been already fixed");
2849 ArrayList candidates = (ArrayList)bounds [i];
2850 if (candidates == null)
2853 if (candidates.Count == 1) {
2854 unfixed_types[i] = null;
2855 fixed_types[i] = (Type)candidates[0];
2859 // TODO: Review, I think it is still wrong
2860 Type best_candidate = null;
2861 for (int ci = 0; ci < candidates.Count; ++ci) {
2862 TypeExpr candidate = new TypeExpression ((Type)candidates[ci], Location.Null);
2863 bool failed = false;
2864 for (int cii = 0; cii < candidates.Count; ++cii) {
2868 if (!Convert.ImplicitStandardConversionExists (candidate, (Type)candidates[cii])) {
2876 if (best_candidate != null)
2879 best_candidate = candidate.Type;
2882 if (best_candidate == null)
2885 unfixed_types[i] = null;
2886 fixed_types[i] = best_candidate;
2891 // Uses inferred types to inflate delegate type argument
2893 public Type InflateGenericArgument (Type parameter)
2895 if (parameter.IsGenericParameter)
2896 return fixed_types [parameter.GenericParameterPosition];
2898 if (parameter.IsGenericType) {
2899 Type [] parameter_targs = parameter.GetGenericArguments ();
2900 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2901 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2903 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2910 // Tests whether all delegate input arguments are fixed and generic output type
2911 // requires output type inference
2913 public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
2915 if (returnType.IsGenericParameter) {
2916 if (IsFixed (returnType))
2918 } else if (returnType.IsGenericType) {
2919 if (TypeManager.IsDelegateType (returnType)) {
2920 invoke = Delegate.GetInvokeMethod (returnType, returnType);
2921 return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
2924 Type[] g_args = returnType.GetGenericArguments ();
2926 // At least one unfixed return type has to exist
2927 if (AllTypesAreFixed (g_args))
2933 // All generic input arguments have to be fixed
2934 ParameterData d_parameters = TypeManager.GetParameterData (invoke);
2935 return AllTypesAreFixed (d_parameters.Types);
2938 bool IsFixed (Type type)
2940 return IsUnfixed (type) == -1;
2943 int IsUnfixed (Type type)
2945 if (!type.IsGenericParameter)
2948 //return unfixed_types[type.GenericParameterPosition] != null;
2949 for (int i = 0; i < unfixed_types.Length; ++i) {
2950 if (unfixed_types [i] == type)
2958 // 26.3.3.9 Lower-bound Inference
2960 public int LowerBoundInference (Type u, Type v)
2962 // Remove ref, out modifiers
2964 v = v.GetElementType ();
2966 // If U is an array type
2968 int u_dim = u.GetArrayRank ();
2970 Type u_e = TypeManager.GetElementType (u);
2973 if (u_dim != v.GetArrayRank ())
2976 v_e = TypeManager.GetElementType (v);
2979 return LowerBoundInference (u_e, v_e);
2982 return ExactInference (u_e, v_e);
2988 if (v.IsGenericType) {
2989 Type g_v = v.GetGenericTypeDefinition ();
2990 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2991 (g_v != TypeManager.generic_ienumerable_type))
2994 v_e = TypeManager.GetTypeArguments (v)[0];
2997 return LowerBoundInference (u_e, v_e);
3000 return ExactInference (u_e, v_e);
3002 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
3004 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
3005 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
3006 // inference is made from each Ui for the corresponding Vi
3008 ArrayList u_candidates = new ArrayList ();
3009 if (u.IsGenericType)
3010 u_candidates.Add (u);
3012 for (Type t = u.BaseType; t != null; t = t.BaseType) {
3013 if (t.IsGenericType && !t.IsGenericTypeDefinition)
3014 u_candidates.Add (t);
3017 // TODO: Implement GetGenericInterfaces only and remove
3018 // the if from foreach
3019 u_candidates.AddRange (TypeManager.GetInterfaces (u));
3021 Type open_v = v.GetGenericTypeDefinition ();
3022 foreach (Type u_candidate in u_candidates) {
3023 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
3026 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
3029 Type [] ga_u = u_candidate.GetGenericArguments ();
3030 Type [] ga_v = v.GetGenericArguments ();
3032 for (int i = 0; i < ga_u.Length; ++i)
3033 score += ExactInference (ga_u [i], ga_v [i]);
3035 return score > 0 ? 1 : 0;
3040 // If V is one of the unfixed type arguments
3041 int pos = IsUnfixed (v);
3045 AddToBounds (u, pos);
3050 // 26.3.3.6 Output Type Inference
3052 public int OutputTypeInference (EmitContext ec, Expression e, Type t)
3054 // If e is a lambda or anonymous method with inferred return type
3055 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3057 Type rt = ame.InferReturnType (ec, this, t);
3058 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3061 ParameterData pd = TypeManager.GetParameterData (invoke);
3062 return ame.Parameters.Count == pd.Count ? 1 : 0;
3065 Type rtype = invoke.ReturnType;
3067 // Blablabla, because reflection does not work with dynamic types
3068 Type [] g_args = t.GetGenericArguments ();
3069 rtype = g_args [rtype.GenericParameterPosition];
3071 return LowerBoundInference (rt, rtype) + 1;
3074 if (e is MethodGroupExpr) {
3075 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3076 Type rtype = invoke.ReturnType;
3077 if (!TypeManager.IsGenericType (rtype))
3080 throw new NotImplementedException ();
3084 // if e is an expression with type U, then
3085 // a lower-bound inference is made from U for T
3087 return LowerBoundInference (e.Type, t) * 2;
3090 static void RemoveDependentTypes (ArrayList types, Type returnType)
3092 if (returnType.IsGenericParameter) {
3093 types [returnType.GenericParameterPosition] = null;
3097 if (returnType.IsGenericType) {
3098 foreach (Type t in returnType.GetGenericArguments ()) {
3099 RemoveDependentTypes (types, t);
3104 public bool UnfixedVariableExists {
3106 if (unfixed_types == null)
3109 foreach (Type ut in unfixed_types)
3117 public abstract class Nullable
3119 public sealed class NullableInfo
3121 public readonly Type Type;
3122 public readonly Type UnderlyingType;
3123 public readonly MethodInfo HasValue;
3124 public readonly MethodInfo Value;
3125 public readonly ConstructorInfo Constructor;
3127 public NullableInfo (Type type)
3130 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
3132 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
3133 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
3135 HasValue = has_value_pi.GetGetMethod (false);
3136 Value = value_pi.GetGetMethod (false);
3137 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
3141 public class HasValue : Expression
3146 private HasValue (Expression expr)
3151 public static Expression Create (Expression expr, EmitContext ec)
3153 return new HasValue (expr).Resolve (ec);
3156 public override void Emit (EmitContext ec)
3158 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
3159 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3162 public override Expression DoResolve (EmitContext ec)
3164 this.info = new NullableInfo (expr.Type);
3166 type = TypeManager.bool_type;
3167 eclass = expr.eclass;
3172 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
3177 LocalTemporary temp;
3180 protected Unwrap (Expression expr)
3183 this.loc = expr.Location;
3186 public static Unwrap Create (Expression expr, EmitContext ec)
3188 return new Unwrap (expr).Resolve (ec) as Unwrap;
3191 public override Expression DoResolve (EmitContext ec)
3193 expr = expr.Resolve (ec);
3197 temp = new LocalTemporary (expr.Type);
3199 info = new NullableInfo (expr.Type);
3200 type = info.UnderlyingType;
3201 eclass = expr.eclass;
3205 public override void Emit (EmitContext ec)
3207 AddressOf (ec, AddressOp.LoadStore);
3208 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
3211 public void EmitCheck (EmitContext ec)
3213 AddressOf (ec, AddressOp.LoadStore);
3214 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3217 public void Store (EmitContext ec)
3222 void create_temp (EmitContext ec)
3224 if ((temp != null) && !has_temp) {
3231 public void AddressOf (EmitContext ec, AddressOp mode)
3235 temp.AddressOf (ec, AddressOp.LoadStore);
3237 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
3240 public void Emit (EmitContext ec, bool leave_copy)
3253 public void EmitAssign (EmitContext ec, Expression source,
3254 bool leave_copy, bool prepare_for_load)
3256 InternalWrap wrap = new InternalWrap (source, info, loc);
3257 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
3260 protected class InternalWrap : Expression
3262 public Expression expr;
3263 public NullableInfo info;
3265 public InternalWrap (Expression expr, NullableInfo info, Location loc)
3272 eclass = ExprClass.Value;
3275 public override Expression DoResolve (EmitContext ec)
3280 public override void Emit (EmitContext ec)
3283 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3288 public class Wrap : Expression
3293 protected Wrap (Expression expr)
3296 this.loc = expr.Location;
3299 public static Wrap Create (Expression expr, EmitContext ec)
3301 return new Wrap (expr).Resolve (ec) as Wrap;
3304 public override Expression DoResolve (EmitContext ec)
3306 expr = expr.Resolve (ec);
3310 TypeExpr target_type = new NullableType (expr.Type, loc);
3311 target_type = target_type.ResolveAsTypeTerminal (ec, false);
3312 if (target_type == null)
3315 type = target_type.Type;
3316 info = new NullableInfo (type);
3317 eclass = ExprClass.Value;
3321 public override void Emit (EmitContext ec)
3324 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3328 public class NullableLiteral : NullLiteral, IMemoryLocation {
3329 public NullableLiteral (Type target_type, Location loc)
3332 this.type = target_type;
3334 eclass = ExprClass.Value;
3337 public override Expression DoResolve (EmitContext ec)
3342 public override void Emit (EmitContext ec)
3344 LocalTemporary value_target = new LocalTemporary (type);
3346 value_target.AddressOf (ec, AddressOp.Store);
3347 ec.ig.Emit (OpCodes.Initobj, type);
3348 value_target.Emit (ec);
3351 public void AddressOf (EmitContext ec, AddressOp Mode)
3353 LocalTemporary value_target = new LocalTemporary (type);
3355 value_target.AddressOf (ec, AddressOp.Store);
3356 ec.ig.Emit (OpCodes.Initobj, type);
3357 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
3361 public abstract class Lifted : Expression, IMemoryLocation
3363 Expression expr, underlying, wrap, null_value;
3366 protected Lifted (Expression expr, Location loc)
3372 public override Expression DoResolve (EmitContext ec)
3374 expr = expr.Resolve (ec);
3378 unwrap = Unwrap.Create (expr, ec);
3382 underlying = ResolveUnderlying (unwrap, ec);
3383 if (underlying == null)
3386 wrap = Wrap.Create (underlying, ec);
3390 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
3391 if (null_value == null)
3395 eclass = ExprClass.Value;
3399 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
3401 public override void Emit (EmitContext ec)
3403 ILGenerator ig = ec.ig;
3404 Label is_null_label = ig.DefineLabel ();
3405 Label end_label = ig.DefineLabel ();
3407 unwrap.EmitCheck (ec);
3408 ig.Emit (OpCodes.Brfalse, is_null_label);
3411 ig.Emit (OpCodes.Br, end_label);
3413 ig.MarkLabel (is_null_label);
3414 null_value.Emit (ec);
3416 ig.MarkLabel (end_label);
3419 public void AddressOf (EmitContext ec, AddressOp mode)
3421 unwrap.AddressOf (ec, mode);
3425 public class LiftedConversion : Lifted
3427 public readonly bool IsUser;
3428 public readonly bool IsExplicit;
3429 public readonly Type TargetType;
3431 public LiftedConversion (Expression expr, Type target_type, bool is_user,
3432 bool is_explicit, Location loc)
3435 this.IsUser = is_user;
3436 this.IsExplicit = is_explicit;
3437 this.TargetType = target_type;
3440 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3442 Type type = TypeManager.GetTypeArguments (TargetType) [0];
3445 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
3448 return Convert.ExplicitConversion (ec, unwrap, type, loc);
3450 return Convert.ImplicitConversion (ec, unwrap, type, loc);
3455 public class LiftedUnaryOperator : Lifted
3457 public readonly Unary.Operator Oper;
3459 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
3465 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3467 return new Unary (Oper, unwrap, loc);
3471 public class LiftedConditional : Lifted
3473 Expression true_expr, false_expr;
3475 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
3479 this.true_expr = true_expr;
3480 this.false_expr = false_expr;
3483 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3485 return new Conditional (unwrap, true_expr, false_expr);
3489 public class LiftedBinaryOperator : Binary
3491 Expression underlying, null_value, bool_wrap;
3492 Unwrap left_unwrap, right_unwrap;
3493 bool is_equality, is_comparision, is_boolean;
3495 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3497 : base (op, left, right)
3502 public override Expression DoResolve (EmitContext ec)
3504 if ((Oper == Binary.Operator.LogicalAnd) ||
3505 (Oper == Binary.Operator.LogicalOr)) {
3506 Error_OperatorCannotBeApplied ();
3510 if (TypeManager.IsNullableType (left.Type)) {
3511 left = left_unwrap = Unwrap.Create (left, ec);
3516 if (TypeManager.IsNullableType (right.Type)) {
3517 right = right_unwrap = Unwrap.Create (right, ec);
3522 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3523 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3524 Expression empty = new EmptyExpression (TypeManager.bool_type);
3525 bool_wrap = Wrap.Create (empty, ec);
3526 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3528 type = bool_wrap.Type;
3530 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3531 if (!(left is NullLiteral) && !(right is NullLiteral)) {
3532 underlying = new Binary (Oper, left, right).Resolve (ec);
3533 if (underlying == null)
3537 type = TypeManager.bool_type;
3539 } else if ((Oper == Binary.Operator.LessThan) ||
3540 (Oper == Binary.Operator.GreaterThan) ||
3541 (Oper == Binary.Operator.LessThanOrEqual) ||
3542 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3543 underlying = new Binary (Oper, left, right).Resolve (ec);
3544 if (underlying == null)
3547 type = TypeManager.bool_type;
3548 is_comparision = true;
3550 underlying = new Binary (Oper, left, right).Resolve (ec);
3551 if (underlying == null)
3554 underlying = Wrap.Create (underlying, ec);
3555 if (underlying == null)
3558 type = underlying.Type;
3559 null_value = new NullableLiteral (type, loc).Resolve (ec);
3562 eclass = ExprClass.Value;
3566 void EmitBoolean (EmitContext ec)
3568 ILGenerator ig = ec.ig;
3570 Label left_is_null_label = ig.DefineLabel ();
3571 Label right_is_null_label = ig.DefineLabel ();
3572 Label is_null_label = ig.DefineLabel ();
3573 Label wrap_label = ig.DefineLabel ();
3574 Label end_label = ig.DefineLabel ();
3576 if (left_unwrap != null) {
3577 left_unwrap.EmitCheck (ec);
3578 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3582 ig.Emit (OpCodes.Dup);
3583 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3584 ig.Emit (OpCodes.Brtrue, wrap_label);
3586 ig.Emit (OpCodes.Brfalse, wrap_label);
3588 if (right_unwrap != null) {
3589 right_unwrap.EmitCheck (ec);
3590 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3593 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3594 ig.Emit (OpCodes.Pop);
3597 if (Oper == Binary.Operator.BitwiseOr)
3598 ig.Emit (OpCodes.Or);
3599 else if (Oper == Binary.Operator.BitwiseAnd)
3600 ig.Emit (OpCodes.And);
3601 ig.Emit (OpCodes.Br, wrap_label);
3603 ig.MarkLabel (left_is_null_label);
3604 if (right_unwrap != null) {
3605 right_unwrap.EmitCheck (ec);
3606 ig.Emit (OpCodes.Brfalse, is_null_label);
3610 ig.Emit (OpCodes.Dup);
3611 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3612 ig.Emit (OpCodes.Brtrue, wrap_label);
3614 ig.Emit (OpCodes.Brfalse, wrap_label);
3616 ig.MarkLabel (right_is_null_label);
3617 ig.Emit (OpCodes.Pop);
3618 ig.MarkLabel (is_null_label);
3619 null_value.Emit (ec);
3620 ig.Emit (OpCodes.Br, end_label);
3622 ig.MarkLabel (wrap_label);
3623 ig.Emit (OpCodes.Nop);
3624 bool_wrap.Emit (ec);
3625 ig.Emit (OpCodes.Nop);
3627 ig.MarkLabel (end_label);
3630 void EmitEquality (EmitContext ec)
3632 ILGenerator ig = ec.ig;
3634 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
3635 if (left is NullLiteral) {
3636 if (right_unwrap == null)
3637 throw new InternalErrorException ();
3638 right_unwrap.EmitCheck (ec);
3639 if (Oper == Binary.Operator.Equality) {
3640 ig.Emit (OpCodes.Ldc_I4_0);
3641 ig.Emit (OpCodes.Ceq);
3646 if (right is NullLiteral) {
3647 if (left_unwrap == null)
3648 throw new InternalErrorException ();
3649 left_unwrap.EmitCheck (ec);
3650 if (Oper == Binary.Operator.Equality) {
3651 ig.Emit (OpCodes.Ldc_I4_0);
3652 ig.Emit (OpCodes.Ceq);
3657 Label both_have_value_label = ig.DefineLabel ();
3658 Label end_label = ig.DefineLabel ();
3660 if (left_unwrap != null && right_unwrap != null) {
3661 Label dissimilar_label = ig.DefineLabel ();
3663 left_unwrap.EmitCheck (ec);
3664 ig.Emit (OpCodes.Dup);
3665 right_unwrap.EmitCheck (ec);
3666 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3668 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3671 if (Oper == Binary.Operator.Equality)
3672 ig.Emit (OpCodes.Ldc_I4_1);
3674 ig.Emit (OpCodes.Ldc_I4_0);
3675 ig.Emit (OpCodes.Br, end_label);
3677 ig.MarkLabel (dissimilar_label);
3678 ig.Emit (OpCodes.Pop);
3679 } else if (left_unwrap != null) {
3680 left_unwrap.EmitCheck (ec);
3681 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3682 } else if (right_unwrap != null) {
3683 right_unwrap.EmitCheck (ec);
3684 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3686 throw new InternalErrorException ("shouldn't get here");
3689 // one is null while the other isn't
3690 if (Oper == Binary.Operator.Equality)
3691 ig.Emit (OpCodes.Ldc_I4_0);
3693 ig.Emit (OpCodes.Ldc_I4_1);
3694 ig.Emit (OpCodes.Br, end_label);
3696 ig.MarkLabel (both_have_value_label);
3697 underlying.Emit (ec);
3699 ig.MarkLabel (end_label);
3702 void EmitComparision (EmitContext ec)
3704 ILGenerator ig = ec.ig;
3706 Label is_null_label = ig.DefineLabel ();
3707 Label end_label = ig.DefineLabel ();
3709 if (left_unwrap != null) {
3710 left_unwrap.EmitCheck (ec);
3711 ig.Emit (OpCodes.Brfalse, is_null_label);
3714 if (right_unwrap != null) {
3715 right_unwrap.EmitCheck (ec);
3716 ig.Emit (OpCodes.Brfalse, is_null_label);
3719 underlying.Emit (ec);
3720 ig.Emit (OpCodes.Br, end_label);
3722 ig.MarkLabel (is_null_label);
3723 ig.Emit (OpCodes.Ldc_I4_0);
3725 ig.MarkLabel (end_label);
3728 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
3731 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
3734 public override void Emit (EmitContext ec)
3736 if (left_unwrap != null)
3737 left_unwrap.Store (ec);
3738 if (right_unwrap != null)
3739 right_unwrap.Store (ec);
3744 } else if (is_equality) {
3747 } else if (is_comparision) {
3748 EmitComparision (ec);
3752 ILGenerator ig = ec.ig;
3754 Label is_null_label = ig.DefineLabel ();
3755 Label end_label = ig.DefineLabel ();
3757 if (left_unwrap != null) {
3758 left_unwrap.EmitCheck (ec);
3759 ig.Emit (OpCodes.Brfalse, is_null_label);
3762 if (right_unwrap != null) {
3763 right_unwrap.EmitCheck (ec);
3764 ig.Emit (OpCodes.Brfalse, is_null_label);
3767 underlying.Emit (ec);
3768 ig.Emit (OpCodes.Br, end_label);
3770 ig.MarkLabel (is_null_label);
3771 null_value.Emit (ec);
3773 ig.MarkLabel (end_label);
3777 public class OperatorTrueOrFalse : Expression
3779 public readonly bool IsTrue;
3784 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3786 this.IsTrue = is_true;
3791 public override Expression DoResolve (EmitContext ec)
3793 unwrap = Unwrap.Create (expr, ec);
3797 if (unwrap.Type != TypeManager.bool_type)
3800 type = TypeManager.bool_type;
3801 eclass = ExprClass.Value;
3805 public override void Emit (EmitContext ec)
3807 ILGenerator ig = ec.ig;
3809 Label is_null_label = ig.DefineLabel ();
3810 Label end_label = ig.DefineLabel ();
3812 unwrap.EmitCheck (ec);
3813 ig.Emit (OpCodes.Brfalse, is_null_label);
3817 ig.Emit (OpCodes.Ldc_I4_0);
3818 ig.Emit (OpCodes.Ceq);
3820 ig.Emit (OpCodes.Br, end_label);
3822 ig.MarkLabel (is_null_label);
3823 ig.Emit (OpCodes.Ldc_I4_0);
3825 ig.MarkLabel (end_label);
3829 public class NullCoalescingOperator : Expression
3831 Expression left, right;
3835 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3841 eclass = ExprClass.Value;
3844 public override Expression DoResolve (EmitContext ec)
3849 left = left.Resolve (ec);
3853 right = right.Resolve (ec);
3857 Type ltype = left.Type, rtype = right.Type;
3859 if (TypeManager.IsNullableType (ltype)) {
3860 NullableInfo info = new NullableInfo (ltype);
3862 unwrap = Unwrap.Create (left, ec);
3866 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3873 if (left.IsNull || ltype.IsValueType) {
3874 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3879 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3885 Expression left_null = unwrap != null ? unwrap : left;
3886 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3894 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3898 public override void Emit (EmitContext ec)
3900 ILGenerator ig = ec.ig;
3902 Label is_null_label = ig.DefineLabel ();
3903 Label end_label = ig.DefineLabel ();
3905 if (unwrap != null) {
3906 unwrap.EmitCheck (ec);
3907 ig.Emit (OpCodes.Brfalse, is_null_label);
3910 ig.Emit (OpCodes.Br, end_label);
3912 ig.MarkLabel (is_null_label);
3915 ig.MarkLabel (end_label);
3918 ig.Emit (OpCodes.Dup);
3919 ig.Emit (OpCodes.Brtrue, end_label);
3921 ig.MarkLabel (is_null_label);
3923 ig.Emit (OpCodes.Pop);
3926 ig.MarkLabel (end_label);
3930 protected override void CloneTo (CloneContext clonectx, Expression t)
3932 NullCoalescingOperator target = (NullCoalescingOperator) t;
3934 target.left = left.Clone (clonectx);
3935 target.right = right.Clone (clonectx);
3939 public class LiftedUnaryMutator : ExpressionStatement
3941 public readonly UnaryMutator.Mode Mode;
3942 Expression expr, null_value;
3943 UnaryMutator underlying;
3946 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3952 eclass = ExprClass.Value;
3955 public override Expression DoResolve (EmitContext ec)
3957 expr = expr.Resolve (ec);
3961 unwrap = Unwrap.Create (expr, ec);
3965 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3966 if (underlying == null)
3969 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3970 if (null_value == null)
3977 void DoEmit (EmitContext ec, bool is_expr)
3979 ILGenerator ig = ec.ig;
3980 Label is_null_label = ig.DefineLabel ();
3981 Label end_label = ig.DefineLabel ();
3983 unwrap.EmitCheck (ec);
3984 ig.Emit (OpCodes.Brfalse, is_null_label);
3987 underlying.Emit (ec);
3989 underlying.EmitStatement (ec);
3990 ig.Emit (OpCodes.Br, end_label);
3992 ig.MarkLabel (is_null_label);
3994 null_value.Emit (ec);
3996 ig.MarkLabel (end_label);
3999 public override void Emit (EmitContext ec)
4004 public override void EmitStatement (EmitContext ec)