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 ||
1757 tparam.GenericConstraints.HasValueTypeConstraint;
1760 MemberList list = TypeManager.FindMembers (
1761 atype, MemberTypes.Constructor,
1762 BindingFlags.Public | BindingFlags.Instance |
1763 BindingFlags.DeclaredOnly, null, null);
1765 if (atype.IsAbstract || (list == null))
1768 foreach (MethodBase mb in list) {
1769 ParameterData pd = TypeManager.GetParameterData (mb);
1770 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1777 protected abstract string GetSignatureForError ();
1778 protected abstract void Report_SymbolRelatedToPreviousError ();
1780 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1782 Report_SymbolRelatedToPreviousError ();
1783 Report.SymbolRelatedToPreviousError (atype);
1784 Report.Error (309, loc,
1785 "The type `{0}' must be convertible to `{1}' in order to " +
1786 "use it as parameter `{2}' in the generic type or method `{3}'",
1787 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1788 TypeManager.CSharpName (ptype), GetSignatureForError ());
1791 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1792 MethodBase instantiated, Location loc)
1794 MethodConstraintChecker checker = new MethodConstraintChecker (
1795 definition, definition.GetGenericArguments (),
1796 instantiated.GetGenericArguments (), loc);
1798 return checker.CheckConstraints (ec);
1801 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1802 Type[] atypes, Location loc)
1804 TypeConstraintChecker checker = new TypeConstraintChecker (
1805 gt, gen_params, atypes, loc);
1807 return checker.CheckConstraints (ec);
1810 protected class MethodConstraintChecker : ConstraintChecker
1812 MethodBase definition;
1814 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1815 Type[] atypes, Location loc)
1816 : base (gen_params, atypes, loc)
1818 this.definition = definition;
1821 protected override string GetSignatureForError ()
1823 return TypeManager.CSharpSignature (definition);
1826 protected override void Report_SymbolRelatedToPreviousError ()
1828 Report.SymbolRelatedToPreviousError (definition);
1832 protected class TypeConstraintChecker : ConstraintChecker
1836 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1838 : base (gen_params, atypes, loc)
1843 protected override string GetSignatureForError ()
1845 return TypeManager.CSharpName (gt);
1848 protected override void Report_SymbolRelatedToPreviousError ()
1850 Report.SymbolRelatedToPreviousError (gt);
1856 /// A generic method definition.
1858 public class GenericMethod : DeclSpace
1860 Expression return_type;
1861 Parameters parameters;
1863 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1864 Expression return_type, Parameters parameters)
1865 : base (ns, parent, name, null)
1867 this.return_type = return_type;
1868 this.parameters = parameters;
1871 public override TypeBuilder DefineType ()
1873 throw new Exception ();
1876 public override bool Define ()
1878 for (int i = 0; i < TypeParameters.Length; i++)
1879 if (!TypeParameters [i].Resolve (this))
1886 /// Define and resolve the type parameters.
1887 /// We're called from Method.Define().
1889 public bool Define (MethodBuilder mb, ToplevelBlock block)
1891 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1892 string[] snames = new string [names.Length];
1893 for (int i = 0; i < names.Length; i++) {
1894 string type_argument_name = names[i].Name;
1895 Parameter p = parameters.GetParameterByName (type_argument_name);
1897 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1901 snames[i] = type_argument_name;
1904 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1905 for (int i = 0; i < TypeParameters.Length; i++)
1906 TypeParameters [i].Define (gen_params [i]);
1911 for (int i = 0; i < TypeParameters.Length; i++) {
1912 if (!TypeParameters [i].ResolveType (this))
1919 internal static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1921 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1922 name, collisionWith);
1926 /// We're called from MethodData.Define() after creating the MethodBuilder.
1928 public bool DefineType (EmitContext ec, MethodBuilder mb,
1929 MethodInfo implementing, bool is_override)
1931 for (int i = 0; i < TypeParameters.Length; i++)
1932 if (!TypeParameters [i].DefineType (
1933 ec, mb, implementing, is_override))
1937 foreach (Parameter p in parameters.FixedParameters){
1938 if (!p.Resolve (ec))
1941 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1947 public void EmitAttributes ()
1949 for (int i = 0; i < TypeParameters.Length; i++)
1950 TypeParameters [i].Emit ();
1952 if (OptAttributes != null)
1953 OptAttributes.Emit ();
1956 public override bool DefineMembers ()
1961 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1962 MemberFilter filter, object criteria)
1964 throw new Exception ();
1967 public override MemberCache MemberCache {
1973 public override AttributeTargets AttributeTargets {
1975 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1979 public override string DocCommentHeader {
1980 get { return "M:"; }
1983 public new void VerifyClsCompliance ()
1985 foreach (TypeParameter tp in TypeParameters) {
1986 if (tp.Constraints == null)
1989 tp.Constraints.VerifyClsCompliance ();
1994 public class NullableType : TypeExpr
1996 Expression underlying;
1998 public NullableType (Expression underlying, Location l)
2000 this.underlying = underlying;
2003 eclass = ExprClass.Type;
2006 public NullableType (Type type, Location loc)
2007 : this (new TypeExpression (type, loc), loc)
2010 public override string Name {
2011 get { return underlying.ToString () + "?"; }
2014 public override string FullName {
2015 get { return underlying.ToString () + "?"; }
2018 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2020 TypeArguments args = new TypeArguments (loc);
2021 args.Add (underlying);
2023 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2024 return ctype.ResolveAsTypeTerminal (ec, false);
2028 public partial class TypeManager
2031 // A list of core types that the compiler requires or uses
2033 static public Type activator_type;
2034 static public Type generic_ilist_type;
2035 static public Type generic_icollection_type;
2036 static public Type generic_ienumerator_type;
2037 static public Type generic_ienumerable_type;
2038 static public Type generic_nullable_type;
2041 // These methods are called by code generated by the compiler
2043 static public MethodInfo activator_create_instance;
2045 static void InitGenericCoreTypes ()
2047 activator_type = CoreLookupType ("System", "Activator");
2049 generic_ilist_type = CoreLookupType (
2050 "System.Collections.Generic", "IList", 1);
2051 generic_icollection_type = CoreLookupType (
2052 "System.Collections.Generic", "ICollection", 1);
2053 generic_ienumerator_type = CoreLookupType (
2054 "System.Collections.Generic", "IEnumerator", 1);
2055 generic_ienumerable_type = CoreLookupType (
2056 "System.Collections.Generic", "IEnumerable", 1);
2057 generic_nullable_type = CoreLookupType (
2058 "System", "Nullable", 1);
2061 static void InitGenericCodeHelpers ()
2064 activator_create_instance = GetMethod (
2065 activator_type, "CreateInstance", Type.EmptyTypes);
2068 static Type CoreLookupType (string ns, string name, int arity)
2070 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2073 public static TypeContainer LookupGenericTypeContainer (Type t)
2075 t = DropGenericTypeArguments (t);
2076 return LookupTypeContainer (t);
2080 /// Check whether `a' and `b' may become equal generic types.
2081 /// The algorithm to do that is a little bit complicated.
2083 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2084 Type[] method_inferred)
2086 if (a.IsGenericParameter) {
2088 // If a is an array of a's type, they may never
2092 b = b.GetElementType ();
2098 // If b is a generic parameter or an actual type,
2099 // they may become equal:
2101 // class X<T,U> : I<T>, I<U>
2102 // class X<T> : I<T>, I<float>
2104 if (b.IsGenericParameter || !b.IsGenericType) {
2105 int pos = a.GenericParameterPosition;
2106 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2107 if (args [pos] == null) {
2112 return args [pos] == a;
2116 // We're now comparing a type parameter with a
2117 // generic instance. They may become equal unless
2118 // the type parameter appears anywhere in the
2119 // generic instance:
2121 // class X<T,U> : I<T>, I<X<U>>
2122 // -> error because you could instanciate it as
2125 // class X<T> : I<T>, I<X<T>> -> ok
2128 Type[] bargs = GetTypeArguments (b);
2129 for (int i = 0; i < bargs.Length; i++) {
2130 if (a.Equals (bargs [i]))
2137 if (b.IsGenericParameter)
2138 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2141 // At this point, neither a nor b are a type parameter.
2143 // If one of them is a generic instance, let
2144 // MayBecomeEqualGenericInstances() compare them (if the
2145 // other one is not a generic instance, they can never
2149 if (a.IsGenericType || b.IsGenericType)
2150 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2153 // If both of them are arrays.
2156 if (a.IsArray && b.IsArray) {
2157 if (a.GetArrayRank () != b.GetArrayRank ())
2160 a = a.GetElementType ();
2161 b = b.GetElementType ();
2163 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2167 // Ok, two ordinary types.
2170 return a.Equals (b);
2174 // Checks whether two generic instances may become equal for some
2175 // particular instantiation (26.3.1).
2177 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2178 Type[] class_inferred,
2179 Type[] method_inferred)
2181 if (!a.IsGenericType || !b.IsGenericType)
2183 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2186 return MayBecomeEqualGenericInstances (
2187 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2190 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2191 Type[] class_inferred,
2192 Type[] method_inferred)
2194 if (aargs.Length != bargs.Length)
2197 for (int i = 0; i < aargs.Length; i++) {
2198 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2206 /// Type inference. Try to infer the type arguments from `method',
2207 /// which is invoked with the arguments `arguments'. This is used
2208 /// when resolving an Invocation or a DelegateInvocation and the user
2209 /// did not explicitly specify type arguments.
2211 public static int InferTypeArguments (EmitContext ec,
2212 ArrayList arguments,
2213 ref MethodBase method)
2215 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2216 Type[] i_args = ti.InferMethodArguments (ec, method);
2218 return ti.InferenceScore;
2220 if (i_args.Length == 0)
2223 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2230 public static bool InferTypeArguments (ParameterData apd,
2231 ref MethodBase method)
2233 if (!TypeManager.IsGenericMethod (method))
2236 ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
2237 Type[] i_args = ti.InferDelegateArguments (method);
2241 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2246 abstract class ATypeInference
2248 protected readonly ArrayList arguments;
2249 protected readonly int arg_count;
2251 protected ATypeInference (ArrayList arguments)
2253 this.arguments = arguments;
2254 if (arguments != null)
2255 arg_count = arguments.Count;
2258 public static ATypeInference CreateInstance (ArrayList arguments)
2260 if (RootContext.Version == LanguageVersion.ISO_2)
2261 return new TypeInferenceV2 (arguments);
2263 return new TypeInferenceV3 (arguments);
2266 public virtual int InferenceScore {
2268 return int.MaxValue;
2272 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2273 public abstract Type[] InferDelegateArguments (MethodBase method);
2277 // Implements C# 2.0 type inference
2279 class TypeInferenceV2 : ATypeInference
2281 public TypeInferenceV2 (ArrayList arguments)
2286 public override Type[] InferDelegateArguments (MethodBase method)
2288 ParameterData pd = TypeManager.GetParameterData (method);
2289 if (arg_count != pd.Count)
2292 Type[] method_args = method.GetGenericArguments ();
2293 Type[] inferred_types = new Type[method_args.Length];
2295 Type[] param_types = new Type[pd.Count];
2296 Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
2298 for (int i = 0; i < arg_count; i++) {
2299 param_types[i] = pd.ParameterType (i);
2302 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2305 return inferred_types;
2308 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2310 ParameterData pd = TypeManager.GetParameterData (method);
2311 Type[] method_generic_args = method.GetGenericArguments ();
2312 Type [] inferred_types = new Type [method_generic_args.Length];
2313 Type[] arg_types = new Type [pd.Count];
2315 int a_count = arg_types.Length;
2319 for (int i = 0; i < a_count; i++) {
2320 Argument a = (Argument) arguments[i];
2321 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2324 if (!TypeInferenceV2.UnifyType (pd.ParameterType (i), a.Type, inferred_types))
2329 Type element_type = TypeManager.GetElementType (pd.ParameterType (a_count));
2330 for (int i = a_count; i < arg_count; i++) {
2331 Argument a = (Argument) arguments [i];
2332 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2335 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2340 for (int i = 0; i < inferred_types.Length; i++)
2341 if (inferred_types [i] == null)
2344 return inferred_types;
2347 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2348 Type[] inferred_types)
2350 for (int i = 0; i < arg_types.Length; i++) {
2351 if (arg_types[i] == null)
2354 if (!UnifyType (param_types[i], arg_types[i], inferred_types))
2358 for (int i = 0; i < inferred_types.Length; ++i)
2359 if (inferred_types[i] == null)
2365 public static bool UnifyType (Type pt, Type at, Type[] inferred)
2367 if (pt.IsGenericParameter) {
2368 if (pt.DeclaringMethod == null)
2371 int pos = pt.GenericParameterPosition;
2373 if (inferred [pos] == null)
2374 inferred [pos] = at;
2376 return inferred [pos] == at;
2379 if (!pt.ContainsGenericParameters) {
2380 if (at.ContainsGenericParameters)
2381 return UnifyType (at, pt, inferred);
2388 if (at.GetArrayRank () != pt.GetArrayRank ())
2391 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2394 if (!pt.IsGenericType)
2397 Type gt = pt.GetGenericTypeDefinition ();
2398 if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
2399 (gt != TypeManager.generic_ienumerable_type))
2402 Type[] args = TypeManager.GetTypeArguments (pt);
2403 return UnifyType (args[0], at.GetElementType (), inferred);
2408 (pt.GetArrayRank () != at.GetArrayRank ()))
2411 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2414 if (pt.IsByRef && at.IsByRef)
2415 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2416 ArrayList list = new ArrayList ();
2417 if (at.IsGenericType)
2419 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2422 list.AddRange (TypeManager.GetInterfaces (at));
2424 foreach (Type type in list) {
2425 if (!type.IsGenericType)
2428 if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
2431 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2438 static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
2440 for (int i = 0; i < ats.Length; i++) {
2441 if (!UnifyType (pts [i], ats [i], inferred))
2449 // Implements C# 3.0 type inference
2451 class TypeInferenceV3 : ATypeInference
2454 // Tracks successful rate of type inference
2456 int score = int.MaxValue;
2458 public TypeInferenceV3 (ArrayList arguments)
2463 public override int InferenceScore {
2469 public override Type[] InferDelegateArguments (MethodBase method)
2471 ParameterData pd = TypeManager.GetParameterData (method);
2472 if (arg_count != pd.Count)
2475 Type[] d_gargs = method.GetGenericArguments ();
2476 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2478 // A lower-bound inference is made from each argument type Uj of D
2479 // to the corresponding parameter type Tj of M
2480 for (int i = 0; i < arg_count; ++i) {
2481 Type t = pd.Types [i];
2482 if (!t.IsGenericParameter)
2485 context.LowerBoundInference ((Type)arguments[i], t);
2488 if (!context.FixAllTypes ())
2491 return context.InferredTypeArguments;
2494 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2496 Type[] method_generic_args = method.GetGenericArguments ();
2497 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2498 if (!context.UnfixedVariableExists)
2499 return Type.EmptyTypes;
2501 ParameterData pd = TypeManager.GetParameterData (method);
2502 if (!InferInPhases (ec, context, pd))
2505 return context.InferredTypeArguments;
2509 // Implements method type arguments inference
2511 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters)
2513 int params_arguments_start;
2514 if (methodParameters.HasParams) {
2515 params_arguments_start = methodParameters.Count - 1;
2517 params_arguments_start = arg_count;
2521 // The first inference phase
2523 Type method_parameter = null;
2524 for (int i = 0; i < arg_count; i++) {
2525 if (i < params_arguments_start) {
2526 method_parameter = methodParameters.Types [i];
2527 } else if (i == params_arguments_start) {
2528 method_parameter = TypeManager.GetElementType (methodParameters.Types [params_arguments_start]);
2531 Argument a = (Argument) arguments[i];
2534 // When a lambda expression, an anonymous method
2535 // is used an explicit argument type inference takes a place
2537 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2539 if (am.ExplicitTypeInference (tic, method_parameter))
2544 if (a.Expr.Type == TypeManager.null_type)
2548 // Otherwise an output type inference is made
2550 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2554 // Part of the second phase but because it happens only once
2555 // we don't need to call it in cycle
2557 bool fixed_any = false;
2558 if (!tic.FixIndependentTypeArguments (methodParameters, ref fixed_any))
2561 return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
2564 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters, bool fixDependent)
2566 bool fixed_any = false;
2567 if (fixDependent && !tic.FixDependentTypes (methodParameters, ref fixed_any))
2570 // If no further unfixed type variables exist, type inference succeeds
2571 if (!tic.UnfixedVariableExists)
2574 if (!fixed_any && fixDependent)
2577 // For all arguments where the corresponding argument output types
2578 // contain unfixed type variables but the input types do not,
2579 // an output type inference is made
2580 for (int i = 0; i < arg_count; i++) {
2581 Type t_i = methodParameters.ParameterType (i);
2582 if (!TypeManager.IsDelegateType (t_i))
2585 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2586 Type rtype = mi.ReturnType;
2589 // Blablabla, because reflection does not work with dynamic types
2590 Type[] g_args = t_i.GetGenericArguments ();
2591 rtype = g_args[rtype.GenericParameterPosition];
2594 if (tic.IsReturnTypeNonDependent (mi, rtype))
2595 score -= tic.OutputTypeInference (ec, ((Argument) arguments [i]).Expr, t_i);
2599 return DoSecondPhase (ec, tic, methodParameters, true);
2603 public class TypeInferenceContext
2605 readonly Type[] unfixed_types;
2606 readonly Type[] fixed_types;
2607 readonly ArrayList[] bounds;
2609 public TypeInferenceContext (Type[] typeArguments)
2611 if (typeArguments.Length == 0)
2612 throw new ArgumentException ("Empty generic arguments");
2614 fixed_types = new Type [typeArguments.Length];
2615 for (int i = 0; i < typeArguments.Length; ++i) {
2616 if (typeArguments [i].IsGenericParameter) {
2617 if (bounds == null) {
2618 bounds = new ArrayList [typeArguments.Length];
2619 unfixed_types = new Type [typeArguments.Length];
2621 unfixed_types [i] = typeArguments [i];
2623 fixed_types [i] = typeArguments [i];
2628 public Type[] InferredTypeArguments {
2634 void AddToBounds (Type t, int index)
2636 ArrayList a = bounds[index];
2638 a = new ArrayList ();
2650 bool AllTypesAreFixed (Type[] types)
2652 foreach (Type t in types) {
2653 if (t.IsGenericParameter) {
2659 if (t.IsGenericType)
2660 return AllTypesAreFixed (t.GetGenericArguments ());
2667 // 26.3.3.8 Exact Inference
2669 public int ExactInference (Type u, Type v)
2671 // If V is an array type
2676 if (u.GetArrayRank () != v.GetArrayRank ())
2679 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2682 // If V is constructed type and U is constructed type
2683 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2684 if (!u.IsGenericType)
2687 Type [] ga_u = u.GetGenericArguments ();
2688 Type [] ga_v = v.GetGenericArguments ();
2689 if (ga_u.Length != ga_v.Length)
2693 for (int i = 0; i < ga_u.Length; ++i)
2694 score += ExactInference (ga_u [i], ga_v [i]);
2696 return score > 0 ? 1 : 0;
2699 // If V is one of the unfixed type arguments
2700 int pos = IsUnfixed (v);
2704 AddToBounds (u, pos);
2708 public bool FixAllTypes ()
2710 for (int i = 0; i < unfixed_types.Length; ++i) {
2718 // All unfixed type variables Xi are fixed for which all of the following hold:
2719 // a, There is at least one type variable Xj that depends on Xi
2720 // b, Xi has a non-empty set of bounds
2722 public bool FixDependentTypes (ParameterData methodParameters, ref bool fixed_any)
2724 for (int i = 0; i < unfixed_types.Length; ++i) {
2725 if (unfixed_types[i] == null)
2728 if (bounds[i] == null)
2741 // All unfixed type variables Xi which depend on no Xj are fixed
2743 public bool FixIndependentTypeArguments (ParameterData methodParameters, ref bool fixed_any)
2745 ArrayList types_to_fix = new ArrayList (unfixed_types);
2746 foreach (Type t in methodParameters.Types) {
2747 if (t.IsGenericParameter)
2750 if (!TypeManager.IsDelegateType (t))
2753 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2754 Type rtype = invoke.ReturnType;
2755 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2759 // Blablabla, because reflection does not work with dynamic types
2760 if (rtype.IsGenericParameter) {
2761 Type [] g_args = t.GetGenericArguments ();
2762 rtype = g_args [rtype.GenericParameterPosition];
2765 // Remove dependent types, they cannot be fixed yet
2766 RemoveDependentTypes (types_to_fix, rtype);
2769 foreach (Type t in types_to_fix) {
2773 int idx = IsUnfixed (t);
2774 if (idx >= 0 && !FixType (idx)) {
2779 fixed_any = types_to_fix.Count > 0;
2786 public bool FixType (int i)
2788 // It's already fixed
2789 if (unfixed_types[i] == null)
2790 throw new InternalErrorException ("Type argument has been already fixed");
2792 ArrayList candidates = (ArrayList)bounds [i];
2793 if (candidates == null)
2796 if (candidates.Count == 1) {
2797 unfixed_types[i] = null;
2798 fixed_types[i] = (Type)candidates[0];
2802 // TODO: Review, I think it is still wrong
2803 Type best_candidate = null;
2804 for (int ci = 0; ci < candidates.Count; ++ci) {
2805 TypeExpr candidate = new TypeExpression ((Type)candidates[ci], Location.Null);
2806 bool failed = false;
2807 for (int cii = 0; cii < candidates.Count; ++cii) {
2811 if (!Convert.ImplicitStandardConversionExists (candidate, (Type)candidates[cii])) {
2819 if (best_candidate != null)
2822 best_candidate = candidate.Type;
2825 if (best_candidate == null)
2828 unfixed_types[i] = null;
2829 fixed_types[i] = best_candidate;
2834 // Uses inferred types to inflate delegate type argument
2836 public Type InflateGenericArgument (Type parameter)
2838 if (parameter.IsGenericParameter)
2839 return fixed_types [parameter.GenericParameterPosition];
2841 if (parameter.IsGenericType) {
2842 Type [] parameter_targs = parameter.GetGenericArguments ();
2843 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2844 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2846 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2853 // Tests whether all delegate input arguments are fixed and generic output type
2854 // requires output type inference
2856 public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
2858 if (returnType.IsGenericParameter) {
2859 if (IsFixed (returnType))
2861 } else if (returnType.IsGenericType) {
2862 if (TypeManager.IsDelegateType (returnType)) {
2863 invoke = Delegate.GetInvokeMethod (returnType, returnType);
2864 return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
2867 Type[] g_args = returnType.GetGenericArguments ();
2869 // At least one unfixed return type has to exist
2870 if (AllTypesAreFixed (g_args))
2876 // All generic input arguments have to be fixed
2877 ParameterData d_parameters = TypeManager.GetParameterData (invoke);
2878 return AllTypesAreFixed (d_parameters.Types);
2881 bool IsFixed (Type type)
2883 return IsUnfixed (type) == -1;
2886 int IsUnfixed (Type type)
2888 if (!type.IsGenericParameter)
2891 //return unfixed_types[type.GenericParameterPosition] != null;
2892 for (int i = 0; i < unfixed_types.Length; ++i) {
2893 if (unfixed_types [i] == type)
2901 // 26.3.3.9 Lower-bound Inference
2903 public int LowerBoundInference (Type u, Type v)
2905 // Remove ref, out modifiers
2907 v = v.GetElementType ();
2909 // If U is an array type
2911 int u_dim = u.GetArrayRank ();
2913 Type u_e = TypeManager.GetElementType (u);
2916 if (u_dim != v.GetArrayRank ())
2919 v_e = TypeManager.GetElementType (v);
2922 return LowerBoundInference (u_e, v_e);
2925 return ExactInference (u_e, v_e);
2931 if (v.IsGenericType) {
2932 Type g_v = v.GetGenericTypeDefinition ();
2933 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2934 (g_v != TypeManager.generic_ienumerable_type))
2937 v_e = TypeManager.GetTypeArguments (v)[0];
2940 return LowerBoundInference (u_e, v_e);
2943 return ExactInference (u_e, v_e);
2945 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2947 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
2948 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
2949 // inference is made from each Ui for the corresponding Vi
2951 ArrayList u_candidates = new ArrayList ();
2952 if (u.IsGenericType)
2953 u_candidates.Add (u);
2955 for (Type t = u.BaseType; t != null; t = t.BaseType) {
2956 if (t.IsGenericType && !t.IsGenericTypeDefinition)
2957 u_candidates.Add (t);
2960 // TODO: Implement GetGenericInterfaces only and remove
2961 // the if from foreach
2962 u_candidates.AddRange (TypeManager.GetInterfaces (u));
2964 Type open_v = v.GetGenericTypeDefinition ();
2966 foreach (Type u_candidate in u_candidates) {
2967 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
2970 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
2973 Type [] ga_u = u_candidate.GetGenericArguments ();
2974 Type [] ga_v = v.GetGenericArguments ();
2975 bool all_exact = true;
2976 for (int i = 0; i < ga_u.Length; ++i)
2977 if (ExactInference (ga_u [i], ga_v [i]) == 0)
2980 if (all_exact && score == 0)
2986 // If V is one of the unfixed type arguments
2987 int pos = IsUnfixed (v);
2991 AddToBounds (u, pos);
2996 // 26.3.3.6 Output Type Inference
2998 public int OutputTypeInference (EmitContext ec, Expression e, Type t)
3000 // If e is a lambda or anonymous method with inferred return type
3001 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3003 Type rt = ame.InferReturnType (ec, this, t);
3004 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3007 ParameterData pd = TypeManager.GetParameterData (invoke);
3008 return ame.Parameters.Count == pd.Count ? 1 : 0;
3011 Type rtype = invoke.ReturnType;
3013 // Blablabla, because reflection does not work with dynamic types
3014 Type [] g_args = t.GetGenericArguments ();
3015 rtype = g_args [rtype.GenericParameterPosition];
3017 return LowerBoundInference (rt, rtype) + 1;
3020 if (e is MethodGroupExpr) {
3021 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3022 Type rtype = invoke.ReturnType;
3023 if (!TypeManager.IsGenericType (rtype))
3026 throw new NotImplementedException ();
3030 // if e is an expression with type U, then
3031 // a lower-bound inference is made from U for T
3033 return LowerBoundInference (e.Type, t) * 2;
3036 static void RemoveDependentTypes (ArrayList types, Type returnType)
3038 if (returnType.IsGenericParameter) {
3039 types [returnType.GenericParameterPosition] = null;
3043 if (returnType.IsGenericType) {
3044 foreach (Type t in returnType.GetGenericArguments ()) {
3045 RemoveDependentTypes (types, t);
3050 public bool UnfixedVariableExists {
3052 if (unfixed_types == null)
3055 foreach (Type ut in unfixed_types)
3063 public abstract class Nullable
3065 public sealed class NullableInfo
3067 public readonly Type Type;
3068 public readonly Type UnderlyingType;
3069 public readonly MethodInfo HasValue;
3070 public readonly MethodInfo Value;
3071 public readonly ConstructorInfo Constructor;
3073 public NullableInfo (Type type)
3076 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
3078 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
3079 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
3081 HasValue = has_value_pi.GetGetMethod (false);
3082 Value = value_pi.GetGetMethod (false);
3083 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
3087 public class HasValue : Expression
3092 private HasValue (Expression expr)
3097 public static Expression Create (Expression expr, EmitContext ec)
3099 return new HasValue (expr).Resolve (ec);
3102 public override void Emit (EmitContext ec)
3104 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
3105 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3108 public override Expression DoResolve (EmitContext ec)
3110 this.info = new NullableInfo (expr.Type);
3112 type = TypeManager.bool_type;
3113 eclass = expr.eclass;
3118 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
3123 LocalTemporary temp;
3126 protected Unwrap (Expression expr)
3129 this.loc = expr.Location;
3132 public static Unwrap Create (Expression expr, EmitContext ec)
3134 return new Unwrap (expr).Resolve (ec) as Unwrap;
3137 public override Expression DoResolve (EmitContext ec)
3139 expr = expr.Resolve (ec);
3143 temp = new LocalTemporary (expr.Type);
3145 info = new NullableInfo (expr.Type);
3146 type = info.UnderlyingType;
3147 eclass = expr.eclass;
3151 public override void Emit (EmitContext ec)
3153 AddressOf (ec, AddressOp.LoadStore);
3154 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
3157 public void EmitCheck (EmitContext ec)
3159 AddressOf (ec, AddressOp.LoadStore);
3160 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3163 public void Store (EmitContext ec)
3168 void create_temp (EmitContext ec)
3170 if ((temp != null) && !has_temp) {
3177 public void AddressOf (EmitContext ec, AddressOp mode)
3181 temp.AddressOf (ec, AddressOp.LoadStore);
3183 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
3186 public void Emit (EmitContext ec, bool leave_copy)
3199 public void EmitAssign (EmitContext ec, Expression source,
3200 bool leave_copy, bool prepare_for_load)
3202 InternalWrap wrap = new InternalWrap (source, info, loc);
3203 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
3206 protected class InternalWrap : Expression
3208 public Expression expr;
3209 public NullableInfo info;
3211 public InternalWrap (Expression expr, NullableInfo info, Location loc)
3218 eclass = ExprClass.Value;
3221 public override Expression DoResolve (EmitContext ec)
3226 public override void Emit (EmitContext ec)
3229 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3234 public class Wrap : Expression
3239 protected Wrap (Expression expr)
3242 this.loc = expr.Location;
3245 public static Wrap Create (Expression expr, EmitContext ec)
3247 return new Wrap (expr).Resolve (ec) as Wrap;
3250 public override Expression DoResolve (EmitContext ec)
3252 expr = expr.Resolve (ec);
3256 TypeExpr target_type = new NullableType (expr.Type, loc);
3257 target_type = target_type.ResolveAsTypeTerminal (ec, false);
3258 if (target_type == null)
3261 type = target_type.Type;
3262 info = new NullableInfo (type);
3263 eclass = ExprClass.Value;
3267 public override void Emit (EmitContext ec)
3270 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3274 public class NullableLiteral : NullLiteral, IMemoryLocation {
3275 public NullableLiteral (Type target_type, Location loc)
3278 this.type = target_type;
3280 eclass = ExprClass.Value;
3283 public override Expression DoResolve (EmitContext ec)
3288 public override void Emit (EmitContext ec)
3290 LocalTemporary value_target = new LocalTemporary (type);
3292 value_target.AddressOf (ec, AddressOp.Store);
3293 ec.ig.Emit (OpCodes.Initobj, type);
3294 value_target.Emit (ec);
3297 public void AddressOf (EmitContext ec, AddressOp Mode)
3299 LocalTemporary value_target = new LocalTemporary (type);
3301 value_target.AddressOf (ec, AddressOp.Store);
3302 ec.ig.Emit (OpCodes.Initobj, type);
3303 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
3307 public abstract class Lifted : Expression, IMemoryLocation
3309 Expression expr, underlying, wrap, null_value;
3312 protected Lifted (Expression expr, Location loc)
3318 public override Expression DoResolve (EmitContext ec)
3320 expr = expr.Resolve (ec);
3324 unwrap = Unwrap.Create (expr, ec);
3328 underlying = ResolveUnderlying (unwrap, ec);
3329 if (underlying == null)
3332 wrap = Wrap.Create (underlying, ec);
3336 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
3337 if (null_value == null)
3341 eclass = ExprClass.Value;
3345 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
3347 public override void Emit (EmitContext ec)
3349 ILGenerator ig = ec.ig;
3350 Label is_null_label = ig.DefineLabel ();
3351 Label end_label = ig.DefineLabel ();
3353 unwrap.EmitCheck (ec);
3354 ig.Emit (OpCodes.Brfalse, is_null_label);
3357 ig.Emit (OpCodes.Br, end_label);
3359 ig.MarkLabel (is_null_label);
3360 null_value.Emit (ec);
3362 ig.MarkLabel (end_label);
3365 public void AddressOf (EmitContext ec, AddressOp mode)
3367 unwrap.AddressOf (ec, mode);
3371 public class LiftedConversion : Lifted
3373 public readonly bool IsUser;
3374 public readonly bool IsExplicit;
3375 public readonly Type TargetType;
3377 public LiftedConversion (Expression expr, Type target_type, bool is_user,
3378 bool is_explicit, Location loc)
3381 this.IsUser = is_user;
3382 this.IsExplicit = is_explicit;
3383 this.TargetType = target_type;
3386 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3388 Type type = TypeManager.GetTypeArguments (TargetType) [0];
3391 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
3394 return Convert.ExplicitConversion (ec, unwrap, type, loc);
3396 return Convert.ImplicitConversion (ec, unwrap, type, loc);
3401 public class LiftedUnaryOperator : Lifted
3403 public readonly Unary.Operator Oper;
3405 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
3411 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3413 return new Unary (Oper, unwrap, loc);
3417 public class LiftedConditional : Lifted
3419 Expression true_expr, false_expr;
3421 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
3425 this.true_expr = true_expr;
3426 this.false_expr = false_expr;
3429 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3431 return new Conditional (unwrap, true_expr, false_expr);
3435 public class LiftedBinaryOperator : Binary
3437 Expression underlying, null_value, bool_wrap;
3438 Unwrap left_unwrap, right_unwrap;
3439 bool is_equality, is_comparision, is_boolean;
3441 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3443 : base (op, left, right)
3448 public override Expression DoResolve (EmitContext ec)
3450 if ((Oper == Binary.Operator.LogicalAnd) ||
3451 (Oper == Binary.Operator.LogicalOr)) {
3452 Error_OperatorCannotBeApplied ();
3456 if (TypeManager.IsNullableType (left.Type)) {
3457 left = left_unwrap = Unwrap.Create (left, ec);
3462 if (TypeManager.IsNullableType (right.Type)) {
3463 right = right_unwrap = Unwrap.Create (right, ec);
3468 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3469 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3470 Expression empty = new EmptyExpression (TypeManager.bool_type);
3471 bool_wrap = Wrap.Create (empty, ec);
3472 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3474 type = bool_wrap.Type;
3476 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3477 if (!(left is NullLiteral) && !(right is NullLiteral)) {
3478 underlying = new Binary (Oper, left, right).Resolve (ec);
3479 if (underlying == null)
3483 type = TypeManager.bool_type;
3485 } else if ((Oper == Binary.Operator.LessThan) ||
3486 (Oper == Binary.Operator.GreaterThan) ||
3487 (Oper == Binary.Operator.LessThanOrEqual) ||
3488 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3489 underlying = new Binary (Oper, left, right).Resolve (ec);
3490 if (underlying == null)
3493 type = TypeManager.bool_type;
3494 is_comparision = true;
3496 underlying = new Binary (Oper, left, right).Resolve (ec);
3497 if (underlying == null)
3500 underlying = Wrap.Create (underlying, ec);
3501 if (underlying == null)
3504 type = underlying.Type;
3505 null_value = new NullableLiteral (type, loc).Resolve (ec);
3508 eclass = ExprClass.Value;
3512 void EmitBoolean (EmitContext ec)
3514 ILGenerator ig = ec.ig;
3516 Label left_is_null_label = ig.DefineLabel ();
3517 Label right_is_null_label = ig.DefineLabel ();
3518 Label is_null_label = ig.DefineLabel ();
3519 Label wrap_label = ig.DefineLabel ();
3520 Label end_label = ig.DefineLabel ();
3522 if (left_unwrap != null) {
3523 left_unwrap.EmitCheck (ec);
3524 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3528 ig.Emit (OpCodes.Dup);
3529 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3530 ig.Emit (OpCodes.Brtrue, wrap_label);
3532 ig.Emit (OpCodes.Brfalse, wrap_label);
3534 if (right_unwrap != null) {
3535 right_unwrap.EmitCheck (ec);
3536 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3539 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3540 ig.Emit (OpCodes.Pop);
3543 if (Oper == Binary.Operator.BitwiseOr)
3544 ig.Emit (OpCodes.Or);
3545 else if (Oper == Binary.Operator.BitwiseAnd)
3546 ig.Emit (OpCodes.And);
3547 ig.Emit (OpCodes.Br, wrap_label);
3549 ig.MarkLabel (left_is_null_label);
3550 if (right_unwrap != null) {
3551 right_unwrap.EmitCheck (ec);
3552 ig.Emit (OpCodes.Brfalse, is_null_label);
3556 ig.Emit (OpCodes.Dup);
3557 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3558 ig.Emit (OpCodes.Brtrue, wrap_label);
3560 ig.Emit (OpCodes.Brfalse, wrap_label);
3562 ig.MarkLabel (right_is_null_label);
3563 ig.Emit (OpCodes.Pop);
3564 ig.MarkLabel (is_null_label);
3565 null_value.Emit (ec);
3566 ig.Emit (OpCodes.Br, end_label);
3568 ig.MarkLabel (wrap_label);
3569 ig.Emit (OpCodes.Nop);
3570 bool_wrap.Emit (ec);
3571 ig.Emit (OpCodes.Nop);
3573 ig.MarkLabel (end_label);
3576 void EmitEquality (EmitContext ec)
3578 ILGenerator ig = ec.ig;
3580 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
3581 if (left is NullLiteral) {
3582 if (right_unwrap == null)
3583 throw new InternalErrorException ();
3584 right_unwrap.EmitCheck (ec);
3585 if (Oper == Binary.Operator.Equality) {
3586 ig.Emit (OpCodes.Ldc_I4_0);
3587 ig.Emit (OpCodes.Ceq);
3592 if (right is NullLiteral) {
3593 if (left_unwrap == null)
3594 throw new InternalErrorException ();
3595 left_unwrap.EmitCheck (ec);
3596 if (Oper == Binary.Operator.Equality) {
3597 ig.Emit (OpCodes.Ldc_I4_0);
3598 ig.Emit (OpCodes.Ceq);
3603 Label both_have_value_label = ig.DefineLabel ();
3604 Label end_label = ig.DefineLabel ();
3606 if (left_unwrap != null && right_unwrap != null) {
3607 Label dissimilar_label = ig.DefineLabel ();
3609 left_unwrap.EmitCheck (ec);
3610 ig.Emit (OpCodes.Dup);
3611 right_unwrap.EmitCheck (ec);
3612 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3614 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3617 if (Oper == Binary.Operator.Equality)
3618 ig.Emit (OpCodes.Ldc_I4_1);
3620 ig.Emit (OpCodes.Ldc_I4_0);
3621 ig.Emit (OpCodes.Br, end_label);
3623 ig.MarkLabel (dissimilar_label);
3624 ig.Emit (OpCodes.Pop);
3625 } else if (left_unwrap != null) {
3626 left_unwrap.EmitCheck (ec);
3627 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3628 } else if (right_unwrap != null) {
3629 right_unwrap.EmitCheck (ec);
3630 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3632 throw new InternalErrorException ("shouldn't get here");
3635 // one is null while the other isn't
3636 if (Oper == Binary.Operator.Equality)
3637 ig.Emit (OpCodes.Ldc_I4_0);
3639 ig.Emit (OpCodes.Ldc_I4_1);
3640 ig.Emit (OpCodes.Br, end_label);
3642 ig.MarkLabel (both_have_value_label);
3643 underlying.Emit (ec);
3645 ig.MarkLabel (end_label);
3648 void EmitComparision (EmitContext ec)
3650 ILGenerator ig = ec.ig;
3652 Label is_null_label = ig.DefineLabel ();
3653 Label end_label = ig.DefineLabel ();
3655 if (left_unwrap != null) {
3656 left_unwrap.EmitCheck (ec);
3657 ig.Emit (OpCodes.Brfalse, is_null_label);
3660 if (right_unwrap != null) {
3661 right_unwrap.EmitCheck (ec);
3662 ig.Emit (OpCodes.Brfalse, is_null_label);
3665 underlying.Emit (ec);
3666 ig.Emit (OpCodes.Br, end_label);
3668 ig.MarkLabel (is_null_label);
3669 ig.Emit (OpCodes.Ldc_I4_0);
3671 ig.MarkLabel (end_label);
3674 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
3677 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
3680 public override void Emit (EmitContext ec)
3682 if (left_unwrap != null)
3683 left_unwrap.Store (ec);
3684 if (right_unwrap != null)
3685 right_unwrap.Store (ec);
3690 } else if (is_equality) {
3693 } else if (is_comparision) {
3694 EmitComparision (ec);
3698 ILGenerator ig = ec.ig;
3700 Label is_null_label = ig.DefineLabel ();
3701 Label end_label = ig.DefineLabel ();
3703 if (left_unwrap != null) {
3704 left_unwrap.EmitCheck (ec);
3705 ig.Emit (OpCodes.Brfalse, is_null_label);
3708 if (right_unwrap != null) {
3709 right_unwrap.EmitCheck (ec);
3710 ig.Emit (OpCodes.Brfalse, is_null_label);
3713 underlying.Emit (ec);
3714 ig.Emit (OpCodes.Br, end_label);
3716 ig.MarkLabel (is_null_label);
3717 null_value.Emit (ec);
3719 ig.MarkLabel (end_label);
3723 public class OperatorTrueOrFalse : Expression
3725 public readonly bool IsTrue;
3730 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3732 this.IsTrue = is_true;
3737 public override Expression DoResolve (EmitContext ec)
3739 unwrap = Unwrap.Create (expr, ec);
3743 if (unwrap.Type != TypeManager.bool_type)
3746 type = TypeManager.bool_type;
3747 eclass = ExprClass.Value;
3751 public override void Emit (EmitContext ec)
3753 ILGenerator ig = ec.ig;
3755 Label is_null_label = ig.DefineLabel ();
3756 Label end_label = ig.DefineLabel ();
3758 unwrap.EmitCheck (ec);
3759 ig.Emit (OpCodes.Brfalse, is_null_label);
3763 ig.Emit (OpCodes.Ldc_I4_0);
3764 ig.Emit (OpCodes.Ceq);
3766 ig.Emit (OpCodes.Br, end_label);
3768 ig.MarkLabel (is_null_label);
3769 ig.Emit (OpCodes.Ldc_I4_0);
3771 ig.MarkLabel (end_label);
3775 public class NullCoalescingOperator : Expression
3777 Expression left, right;
3781 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3787 eclass = ExprClass.Value;
3790 public override Expression DoResolve (EmitContext ec)
3795 left = left.Resolve (ec);
3799 right = right.Resolve (ec);
3803 Type ltype = left.Type, rtype = right.Type;
3805 if (TypeManager.IsNullableType (ltype)) {
3806 NullableInfo info = new NullableInfo (ltype);
3808 unwrap = Unwrap.Create (left, ec);
3812 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3818 } else if (!TypeManager.IsReferenceType (ltype)) {
3819 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3823 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3829 Expression left_null = unwrap != null ? unwrap : left;
3830 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3838 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3842 public override void Emit (EmitContext ec)
3844 ILGenerator ig = ec.ig;
3846 Label is_null_label = ig.DefineLabel ();
3847 Label end_label = ig.DefineLabel ();
3849 if (unwrap != null) {
3850 unwrap.EmitCheck (ec);
3851 ig.Emit (OpCodes.Brfalse, is_null_label);
3854 ig.Emit (OpCodes.Br, end_label);
3856 ig.MarkLabel (is_null_label);
3859 ig.MarkLabel (end_label);
3862 ig.Emit (OpCodes.Dup);
3863 ig.Emit (OpCodes.Brtrue, end_label);
3865 ig.MarkLabel (is_null_label);
3867 ig.Emit (OpCodes.Pop);
3870 ig.MarkLabel (end_label);
3874 protected override void CloneTo (CloneContext clonectx, Expression t)
3876 NullCoalescingOperator target = (NullCoalescingOperator) t;
3878 target.left = left.Clone (clonectx);
3879 target.right = right.Clone (clonectx);
3883 public class LiftedUnaryMutator : ExpressionStatement
3885 public readonly UnaryMutator.Mode Mode;
3886 Expression expr, null_value;
3887 UnaryMutator underlying;
3890 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3896 eclass = ExprClass.Value;
3899 public override Expression DoResolve (EmitContext ec)
3901 expr = expr.Resolve (ec);
3905 unwrap = Unwrap.Create (expr, ec);
3909 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3910 if (underlying == null)
3913 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3914 if (null_value == null)
3921 void DoEmit (EmitContext ec, bool is_expr)
3923 ILGenerator ig = ec.ig;
3924 Label is_null_label = ig.DefineLabel ();
3925 Label end_label = ig.DefineLabel ();
3927 unwrap.EmitCheck (ec);
3928 ig.Emit (OpCodes.Brfalse, is_null_label);
3931 underlying.Emit (ec);
3933 underlying.EmitStatement (ec);
3934 ig.Emit (OpCodes.Br, end_label);
3936 ig.MarkLabel (is_null_label);
3938 null_value.Emit (ec);
3940 ig.MarkLabel (end_label);
3943 public override void Emit (EmitContext ec)
3948 public override void EmitStatement (EmitContext ec)