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 the params method
2207 /// `method', 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 bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2212 ref MethodBase method)
2214 if (!TypeManager.IsGenericMethod (method))
2217 // if there are no arguments, there's no way to infer the type-arguments
2218 if (arguments == null || arguments.Count == 0)
2221 ParameterData pd = TypeManager.GetParameterData (method);
2222 int pd_count = pd.Count;
2223 int arg_count = arguments.Count;
2228 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2231 if (pd_count - 1 > arg_count)
2234 Type[] method_args = method.GetGenericArguments ();
2235 Type[] inferred_types = new Type [method_args.Length];
2238 // If we have come this far, the case which
2239 // remains is when the number of parameters is
2240 // less than or equal to the argument count.
2242 for (int i = 0; i < pd_count - 1; ++i) {
2243 Argument a = (Argument) arguments [i];
2245 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2248 Type pt = pd.ParameterType (i);
2251 if (!TypeInferenceV2.UnifyType (pt, at, inferred_types))
2255 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2257 for (int i = pd_count - 1; i < arg_count; i++) {
2258 Argument a = (Argument) arguments [i];
2260 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2263 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2267 for (int i = 0; i < inferred_types.Length; i++)
2268 if (inferred_types [i] == null)
2271 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2276 /// Type inference. Try to infer the type arguments from `method',
2277 /// which is invoked with the arguments `arguments'. This is used
2278 /// when resolving an Invocation or a DelegateInvocation and the user
2279 /// did not explicitly specify type arguments.
2281 public static int InferTypeArguments (EmitContext ec,
2282 ArrayList arguments,
2283 ref MethodBase method)
2285 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2286 Type[] i_args = ti.InferMethodArguments (ec, method);
2288 return ti.InferenceScore;
2290 if (i_args.Length == 0)
2293 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2300 public static bool InferTypeArguments (ParameterData apd,
2301 ref MethodBase method)
2303 if (!TypeManager.IsGenericMethod (method))
2306 ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
2307 Type[] i_args = ti.InferDelegateArguments (method);
2311 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2316 abstract class ATypeInference
2318 protected readonly ArrayList arguments;
2319 protected readonly int arg_count;
2321 protected ATypeInference (ArrayList arguments)
2323 this.arguments = arguments;
2324 if (arguments != null)
2325 arg_count = arguments.Count;
2328 public static ATypeInference CreateInstance (ArrayList arguments)
2330 if (RootContext.Version == LanguageVersion.ISO_2)
2331 return new TypeInferenceV2 (arguments);
2333 return new TypeInferenceV3 (arguments);
2336 public virtual int InferenceScore {
2338 return int.MaxValue;
2342 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2343 public abstract Type[] InferDelegateArguments (MethodBase method);
2347 // Implements C# 2.0 type inference
2349 class TypeInferenceV2 : ATypeInference
2351 public TypeInferenceV2 (ArrayList arguments)
2356 public override Type[] InferDelegateArguments (MethodBase method)
2358 ParameterData pd = TypeManager.GetParameterData (method);
2359 if (arg_count != pd.Count)
2362 Type[] method_args = method.GetGenericArguments ();
2363 Type[] inferred_types = new Type[method_args.Length];
2365 Type[] param_types = new Type[pd.Count];
2366 Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
2368 for (int i = 0; i < arg_count; i++) {
2369 param_types[i] = pd.ParameterType (i);
2372 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2375 return inferred_types;
2378 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2380 ParameterData pd = TypeManager.GetParameterData (method);
2381 Type[] method_generic_args = method.GetGenericArguments ();
2382 Type [] inferred_types = new Type [method_generic_args.Length];
2383 Type[] arg_types = new Type [pd.Count];
2385 int a_count = arg_types.Length;
2389 for (int i = 0; i < a_count; i++) {
2390 Argument a = (Argument) arguments[i];
2391 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2394 if (!TypeInferenceV2.UnifyType (pd.ParameterType (i), a.Type, inferred_types))
2399 Type element_type = TypeManager.GetElementType (pd.ParameterType (a_count));
2400 for (int i = a_count; i < arg_count; i++) {
2401 Argument a = (Argument) arguments [i];
2402 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2405 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2410 for (int i = 0; i < inferred_types.Length; i++)
2411 if (inferred_types [i] == null)
2414 return inferred_types;
2417 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2418 Type[] inferred_types)
2420 for (int i = 0; i < arg_types.Length; i++) {
2421 if (arg_types[i] == null)
2424 if (!UnifyType (param_types[i], arg_types[i], inferred_types))
2428 for (int i = 0; i < inferred_types.Length; ++i)
2429 if (inferred_types[i] == null)
2435 public static bool UnifyType (Type pt, Type at, Type[] inferred)
2437 if (pt.IsGenericParameter) {
2438 if (pt.DeclaringMethod == null)
2441 int pos = pt.GenericParameterPosition;
2443 if (inferred [pos] == null)
2444 inferred [pos] = at;
2446 return inferred [pos] == at;
2449 if (!pt.ContainsGenericParameters) {
2450 if (at.ContainsGenericParameters)
2451 return UnifyType (at, pt, inferred);
2458 if (at.GetArrayRank () != pt.GetArrayRank ())
2461 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2464 if (!pt.IsGenericType)
2467 Type gt = pt.GetGenericTypeDefinition ();
2468 if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
2469 (gt != TypeManager.generic_ienumerable_type))
2472 Type[] args = TypeManager.GetTypeArguments (pt);
2473 return UnifyType (args[0], at.GetElementType (), inferred);
2478 (pt.GetArrayRank () != at.GetArrayRank ()))
2481 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2484 if (pt.IsByRef && at.IsByRef)
2485 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2486 ArrayList list = new ArrayList ();
2487 if (at.IsGenericType)
2489 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2492 list.AddRange (TypeManager.GetInterfaces (at));
2494 foreach (Type type in list) {
2495 if (!type.IsGenericType)
2498 if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
2501 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2508 static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
2510 for (int i = 0; i < ats.Length; i++) {
2511 if (!UnifyType (pts [i], ats [i], inferred))
2519 // Implements C# 3.0 type inference
2521 class TypeInferenceV3 : ATypeInference
2524 // Tracks successful rate of type inference
2526 int score = int.MaxValue;
2528 public TypeInferenceV3 (ArrayList arguments)
2533 public override int InferenceScore {
2539 public override Type[] InferDelegateArguments (MethodBase method)
2541 ParameterData pd = TypeManager.GetParameterData (method);
2542 if (arg_count != pd.Count)
2545 Type[] d_gargs = method.GetGenericArguments ();
2546 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2548 // A lower-bound inference is made from each argument type Uj of D
2549 // to the corresponding parameter type Tj of M
2550 for (int i = 0; i < arg_count; ++i) {
2551 Type t = pd.Types [i];
2552 if (!t.IsGenericParameter)
2555 context.LowerBoundInference ((Type)arguments[i], t);
2558 if (!context.FixAllTypes ())
2561 return context.InferredTypeArguments;
2564 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2566 Type[] method_generic_args = method.GetGenericArguments ();
2567 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2568 if (!context.UnfixedVariableExists)
2569 return Type.EmptyTypes;
2571 ParameterData pd = TypeManager.GetParameterData (method);
2572 if (!InferInPhases (ec, context, pd))
2575 return context.InferredTypeArguments;
2579 // Implements method type arguments inference
2581 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters)
2584 // The first inference phase
2586 for (int i = 0; i < arg_count; i++) {
2587 Type method_parameter = methodParameters.ParameterType (i);
2589 Argument a = (Argument) arguments[i];
2592 // When a lambda expression, an anonymous method
2593 // is used an explicit argument type inference takes a place
2595 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2597 if (am.ExplicitTypeInference (tic, method_parameter))
2602 if (a.Expr.Type == TypeManager.null_type)
2606 // Otherwise an output type inference is made
2608 score -= tic.OutputTypeInference (ec, a.Expr, method_parameter);
2612 // Part of the second phase but because it happens only once
2613 // we don't need to call it in cycle
2615 bool fixed_any = false;
2616 if (!tic.FixIndependentTypeArguments (methodParameters, ref fixed_any))
2619 return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
2622 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters, bool fixDependent)
2624 bool fixed_any = false;
2625 if (fixDependent && !tic.FixDependentTypes (methodParameters, ref fixed_any))
2628 // If no further unfixed type variables exist, type inference succeeds
2629 if (!tic.UnfixedVariableExists)
2632 if (!fixed_any && fixDependent)
2635 // For all arguments where the corresponding argument output types
2636 // contain unfixed type variables but the input types do not,
2637 // an output type inference is made
2638 for (int i = 0; i < arg_count; i++) {
2639 Type t_i = methodParameters.ParameterType (i);
2640 if (!TypeManager.IsDelegateType (t_i))
2643 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2644 Type rtype = mi.ReturnType;
2647 // Blablabla, because reflection does not work with dynamic types
2648 Type[] g_args = t_i.GetGenericArguments ();
2649 rtype = g_args[rtype.GenericParameterPosition];
2652 if (tic.IsReturnTypeNonDependent (mi, rtype))
2653 score -= tic.OutputTypeInference (ec, ((Argument) arguments [i]).Expr, t_i);
2657 return DoSecondPhase (ec, tic, methodParameters, true);
2661 public class TypeInferenceContext
2663 readonly Type[] unfixed_types;
2664 readonly Type[] fixed_types;
2665 readonly ArrayList[] bounds;
2667 public TypeInferenceContext (Type[] typeArguments)
2669 if (typeArguments.Length == 0)
2670 throw new ArgumentException ("Empty generic arguments");
2672 fixed_types = new Type [typeArguments.Length];
2673 for (int i = 0; i < typeArguments.Length; ++i) {
2674 if (typeArguments [i].IsGenericParameter) {
2675 if (bounds == null) {
2676 bounds = new ArrayList [typeArguments.Length];
2677 unfixed_types = new Type [typeArguments.Length];
2679 unfixed_types [i] = typeArguments [i];
2681 fixed_types [i] = typeArguments [i];
2686 public Type[] InferredTypeArguments {
2692 void AddToBounds (Type t, int index)
2694 ArrayList a = bounds[index];
2696 a = new ArrayList ();
2708 bool AllTypesAreFixed (Type[] types)
2710 foreach (Type t in types) {
2711 if (t.IsGenericParameter) {
2717 if (t.IsGenericType)
2718 return AllTypesAreFixed (t.GetGenericArguments ());
2725 // 26.3.3.8 Exact Inference
2727 public int ExactInference (Type u, Type v)
2729 // If V is an array type
2734 if (u.GetArrayRank () != v.GetArrayRank ())
2737 return ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2740 // If V is constructed type and U is constructed type
2741 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2742 if (!u.IsGenericType)
2745 Type [] ga_u = u.GetGenericArguments ();
2746 Type [] ga_v = v.GetGenericArguments ();
2747 if (ga_u.Length != ga_v.Length)
2751 for (int i = 0; i < ga_u.Length; ++i)
2752 score += ExactInference (ga_u [i], ga_v [i]);
2754 return score > 0 ? 1 : 0;
2757 // If V is one of the unfixed type arguments
2758 int pos = IsUnfixed (v);
2762 AddToBounds (u, pos);
2766 public bool FixAllTypes ()
2768 for (int i = 0; i < unfixed_types.Length; ++i) {
2776 // All unfixed type variables Xi are fixed for which all of the following hold:
2777 // a, There is at least one type variable Xj that depends on Xi
2778 // b, Xi has a non-empty set of bounds
2780 public bool FixDependentTypes (ParameterData methodParameters, ref bool fixed_any)
2782 for (int i = 0; i < unfixed_types.Length; ++i) {
2783 if (unfixed_types[i] == null)
2786 if (bounds[i] == null)
2799 // All unfixed type variables Xi which depend on no Xj are fixed
2801 public bool FixIndependentTypeArguments (ParameterData methodParameters, ref bool fixed_any)
2803 ArrayList types_to_fix = new ArrayList (unfixed_types);
2804 foreach (Type t in methodParameters.Types) {
2805 if (t.IsGenericParameter)
2808 if (!TypeManager.IsDelegateType (t))
2811 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2812 Type rtype = invoke.ReturnType;
2813 if (!rtype.IsGenericParameter && !rtype.IsGenericType)
2817 // Blablabla, because reflection does not work with dynamic types
2818 if (rtype.IsGenericParameter) {
2819 Type [] g_args = t.GetGenericArguments ();
2820 rtype = g_args [rtype.GenericParameterPosition];
2823 // Remove dependent types, they cannot be fixed yet
2824 RemoveDependentTypes (types_to_fix, rtype);
2827 foreach (Type t in types_to_fix) {
2831 int idx = IsUnfixed (t);
2832 if (idx >= 0 && !FixType (idx)) {
2837 fixed_any = types_to_fix.Count > 0;
2844 public bool FixType (int i)
2846 // It's already fixed
2847 if (unfixed_types[i] == null)
2848 throw new InternalErrorException ("Type argument has been already fixed");
2850 ArrayList candidates = (ArrayList)bounds [i];
2851 if (candidates == null)
2854 if (candidates.Count == 1) {
2855 unfixed_types[i] = null;
2856 fixed_types[i] = (Type)candidates[0];
2860 // TODO: Review, I think it is still wrong
2861 Type best_candidate = null;
2862 for (int ci = 0; ci < candidates.Count; ++ci) {
2863 TypeExpr candidate = new TypeExpression ((Type)candidates[ci], Location.Null);
2864 bool failed = false;
2865 for (int cii = 0; cii < candidates.Count; ++cii) {
2869 if (!Convert.ImplicitStandardConversionExists (candidate, (Type)candidates[cii])) {
2877 if (best_candidate != null)
2880 best_candidate = candidate.Type;
2883 if (best_candidate == null)
2886 unfixed_types[i] = null;
2887 fixed_types[i] = best_candidate;
2892 // Uses inferred types to inflate delegate type argument
2894 public Type InflateGenericArgument (Type parameter)
2896 if (parameter.IsGenericParameter)
2897 return fixed_types [parameter.GenericParameterPosition];
2899 if (parameter.IsGenericType) {
2900 Type [] parameter_targs = parameter.GetGenericArguments ();
2901 for (int ii = 0; ii < parameter_targs.Length; ++ii) {
2902 parameter_targs [ii] = InflateGenericArgument (parameter_targs [ii]);
2904 return parameter.GetGenericTypeDefinition ().MakeGenericType (parameter_targs);
2911 // Tests whether all delegate input arguments are fixed and generic output type
2912 // requires output type inference
2914 public bool IsReturnTypeNonDependent (MethodInfo invoke, Type returnType)
2916 if (returnType.IsGenericParameter) {
2917 if (IsFixed (returnType))
2919 } else if (returnType.IsGenericType) {
2920 if (TypeManager.IsDelegateType (returnType)) {
2921 invoke = Delegate.GetInvokeMethod (returnType, returnType);
2922 return IsReturnTypeNonDependent (invoke, invoke.ReturnType);
2925 Type[] g_args = returnType.GetGenericArguments ();
2927 // At least one unfixed return type has to exist
2928 if (AllTypesAreFixed (g_args))
2934 // All generic input arguments have to be fixed
2935 ParameterData d_parameters = TypeManager.GetParameterData (invoke);
2936 return AllTypesAreFixed (d_parameters.Types);
2939 bool IsFixed (Type type)
2941 return IsUnfixed (type) == -1;
2944 int IsUnfixed (Type type)
2946 if (!type.IsGenericParameter)
2949 //return unfixed_types[type.GenericParameterPosition] != null;
2950 for (int i = 0; i < unfixed_types.Length; ++i) {
2951 if (unfixed_types [i] == type)
2959 // 26.3.3.9 Lower-bound Inference
2961 public int LowerBoundInference (Type u, Type v)
2963 // Remove ref, out modifiers
2965 v = v.GetElementType ();
2967 // If U is an array type
2969 int u_dim = u.GetArrayRank ();
2971 Type u_e = TypeManager.GetElementType (u);
2974 if (u_dim != v.GetArrayRank ())
2977 v_e = TypeManager.GetElementType (v);
2980 return LowerBoundInference (u_e, v_e);
2983 return ExactInference (u_e, v_e);
2989 if (v.IsGenericType) {
2990 Type g_v = v.GetGenericTypeDefinition ();
2991 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2992 (g_v != TypeManager.generic_ienumerable_type))
2995 v_e = TypeManager.GetTypeArguments (v)[0];
2998 return LowerBoundInference (u_e, v_e);
3001 return ExactInference (u_e, v_e);
3003 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
3005 // if V is a constructed type C<V1..Vk> and there is a unique set of types U1..Uk
3006 // such that a standard implicit conversion exists from U to C<U1..Uk> then an exact
3007 // inference is made from each Ui for the corresponding Vi
3009 ArrayList u_candidates = new ArrayList ();
3010 if (u.IsGenericType)
3011 u_candidates.Add (u);
3013 for (Type t = u.BaseType; t != null; t = t.BaseType) {
3014 if (t.IsGenericType && !t.IsGenericTypeDefinition)
3015 u_candidates.Add (t);
3018 // TODO: Implement GetGenericInterfaces only and remove
3019 // the if from foreach
3020 u_candidates.AddRange (TypeManager.GetInterfaces (u));
3022 Type open_v = v.GetGenericTypeDefinition ();
3023 foreach (Type u_candidate in u_candidates) {
3024 if (!u_candidate.IsGenericType || u_candidate.IsGenericTypeDefinition)
3027 if (TypeManager.DropGenericTypeArguments (u_candidate) != open_v)
3030 Type [] ga_u = u_candidate.GetGenericArguments ();
3031 Type [] ga_v = v.GetGenericArguments ();
3033 for (int i = 0; i < ga_u.Length; ++i)
3034 score += ExactInference (ga_u [i], ga_v [i]);
3036 return score > 0 ? 1 : 0;
3041 // If V is one of the unfixed type arguments
3042 int pos = IsUnfixed (v);
3046 AddToBounds (u, pos);
3051 // 26.3.3.6 Output Type Inference
3053 public int OutputTypeInference (EmitContext ec, Expression e, Type t)
3055 // If e is a lambda or anonymous method with inferred return type
3056 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3058 Type rt = ame.InferReturnType (ec, this, t);
3059 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3062 ParameterData pd = TypeManager.GetParameterData (invoke);
3063 return ame.Parameters.Count == pd.Count ? 1 : 0;
3066 Type rtype = invoke.ReturnType;
3068 // Blablabla, because reflection does not work with dynamic types
3069 Type [] g_args = t.GetGenericArguments ();
3070 rtype = g_args [rtype.GenericParameterPosition];
3072 return LowerBoundInference (rt, rtype) + 1;
3075 if (e is MethodGroupExpr) {
3076 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3077 Type rtype = invoke.ReturnType;
3078 if (!TypeManager.IsGenericType (rtype))
3081 throw new NotImplementedException ();
3085 // if e is an expression with type U, then
3086 // a lower-bound inference is made from U for T
3088 return LowerBoundInference (e.Type, t) * 2;
3091 static void RemoveDependentTypes (ArrayList types, Type returnType)
3093 if (returnType.IsGenericParameter) {
3094 types [returnType.GenericParameterPosition] = null;
3098 if (returnType.IsGenericType) {
3099 foreach (Type t in returnType.GetGenericArguments ()) {
3100 RemoveDependentTypes (types, t);
3105 public bool UnfixedVariableExists {
3107 if (unfixed_types == null)
3110 foreach (Type ut in unfixed_types)
3118 public abstract class Nullable
3120 public sealed class NullableInfo
3122 public readonly Type Type;
3123 public readonly Type UnderlyingType;
3124 public readonly MethodInfo HasValue;
3125 public readonly MethodInfo Value;
3126 public readonly ConstructorInfo Constructor;
3128 public NullableInfo (Type type)
3131 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
3133 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
3134 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
3136 HasValue = has_value_pi.GetGetMethod (false);
3137 Value = value_pi.GetGetMethod (false);
3138 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
3142 public class HasValue : Expression
3147 private HasValue (Expression expr)
3152 public static Expression Create (Expression expr, EmitContext ec)
3154 return new HasValue (expr).Resolve (ec);
3157 public override void Emit (EmitContext ec)
3159 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
3160 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3163 public override Expression DoResolve (EmitContext ec)
3165 this.info = new NullableInfo (expr.Type);
3167 type = TypeManager.bool_type;
3168 eclass = expr.eclass;
3173 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
3178 LocalTemporary temp;
3181 protected Unwrap (Expression expr)
3184 this.loc = expr.Location;
3187 public static Unwrap Create (Expression expr, EmitContext ec)
3189 return new Unwrap (expr).Resolve (ec) as Unwrap;
3192 public override Expression DoResolve (EmitContext ec)
3194 expr = expr.Resolve (ec);
3198 temp = new LocalTemporary (expr.Type);
3200 info = new NullableInfo (expr.Type);
3201 type = info.UnderlyingType;
3202 eclass = expr.eclass;
3206 public override void Emit (EmitContext ec)
3208 AddressOf (ec, AddressOp.LoadStore);
3209 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
3212 public void EmitCheck (EmitContext ec)
3214 AddressOf (ec, AddressOp.LoadStore);
3215 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3218 public void Store (EmitContext ec)
3223 void create_temp (EmitContext ec)
3225 if ((temp != null) && !has_temp) {
3232 public void AddressOf (EmitContext ec, AddressOp mode)
3236 temp.AddressOf (ec, AddressOp.LoadStore);
3238 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
3241 public void Emit (EmitContext ec, bool leave_copy)
3254 public void EmitAssign (EmitContext ec, Expression source,
3255 bool leave_copy, bool prepare_for_load)
3257 InternalWrap wrap = new InternalWrap (source, info, loc);
3258 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
3261 protected class InternalWrap : Expression
3263 public Expression expr;
3264 public NullableInfo info;
3266 public InternalWrap (Expression expr, NullableInfo info, Location loc)
3273 eclass = ExprClass.Value;
3276 public override Expression DoResolve (EmitContext ec)
3281 public override void Emit (EmitContext ec)
3284 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3289 public class Wrap : Expression
3294 protected Wrap (Expression expr)
3297 this.loc = expr.Location;
3300 public static Wrap Create (Expression expr, EmitContext ec)
3302 return new Wrap (expr).Resolve (ec) as Wrap;
3305 public override Expression DoResolve (EmitContext ec)
3307 expr = expr.Resolve (ec);
3311 TypeExpr target_type = new NullableType (expr.Type, loc);
3312 target_type = target_type.ResolveAsTypeTerminal (ec, false);
3313 if (target_type == null)
3316 type = target_type.Type;
3317 info = new NullableInfo (type);
3318 eclass = ExprClass.Value;
3322 public override void Emit (EmitContext ec)
3325 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3329 public class NullableLiteral : NullLiteral, IMemoryLocation {
3330 public NullableLiteral (Type target_type, Location loc)
3333 this.type = target_type;
3335 eclass = ExprClass.Value;
3338 public override Expression DoResolve (EmitContext ec)
3343 public override void Emit (EmitContext ec)
3345 LocalTemporary value_target = new LocalTemporary (type);
3347 value_target.AddressOf (ec, AddressOp.Store);
3348 ec.ig.Emit (OpCodes.Initobj, type);
3349 value_target.Emit (ec);
3352 public void AddressOf (EmitContext ec, AddressOp Mode)
3354 LocalTemporary value_target = new LocalTemporary (type);
3356 value_target.AddressOf (ec, AddressOp.Store);
3357 ec.ig.Emit (OpCodes.Initobj, type);
3358 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
3362 public abstract class Lifted : Expression, IMemoryLocation
3364 Expression expr, underlying, wrap, null_value;
3367 protected Lifted (Expression expr, Location loc)
3373 public override Expression DoResolve (EmitContext ec)
3375 expr = expr.Resolve (ec);
3379 unwrap = Unwrap.Create (expr, ec);
3383 underlying = ResolveUnderlying (unwrap, ec);
3384 if (underlying == null)
3387 wrap = Wrap.Create (underlying, ec);
3391 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
3392 if (null_value == null)
3396 eclass = ExprClass.Value;
3400 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
3402 public override void Emit (EmitContext ec)
3404 ILGenerator ig = ec.ig;
3405 Label is_null_label = ig.DefineLabel ();
3406 Label end_label = ig.DefineLabel ();
3408 unwrap.EmitCheck (ec);
3409 ig.Emit (OpCodes.Brfalse, is_null_label);
3412 ig.Emit (OpCodes.Br, end_label);
3414 ig.MarkLabel (is_null_label);
3415 null_value.Emit (ec);
3417 ig.MarkLabel (end_label);
3420 public void AddressOf (EmitContext ec, AddressOp mode)
3422 unwrap.AddressOf (ec, mode);
3426 public class LiftedConversion : Lifted
3428 public readonly bool IsUser;
3429 public readonly bool IsExplicit;
3430 public readonly Type TargetType;
3432 public LiftedConversion (Expression expr, Type target_type, bool is_user,
3433 bool is_explicit, Location loc)
3436 this.IsUser = is_user;
3437 this.IsExplicit = is_explicit;
3438 this.TargetType = target_type;
3441 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3443 Type type = TypeManager.GetTypeArguments (TargetType) [0];
3446 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
3449 return Convert.ExplicitConversion (ec, unwrap, type, loc);
3451 return Convert.ImplicitConversion (ec, unwrap, type, loc);
3456 public class LiftedUnaryOperator : Lifted
3458 public readonly Unary.Operator Oper;
3460 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
3466 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3468 return new Unary (Oper, unwrap, loc);
3472 public class LiftedConditional : Lifted
3474 Expression true_expr, false_expr;
3476 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
3480 this.true_expr = true_expr;
3481 this.false_expr = false_expr;
3484 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3486 return new Conditional (unwrap, true_expr, false_expr);
3490 public class LiftedBinaryOperator : Binary
3492 Expression underlying, null_value, bool_wrap;
3493 Unwrap left_unwrap, right_unwrap;
3494 bool is_equality, is_comparision, is_boolean;
3496 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3498 : base (op, left, right)
3503 public override Expression DoResolve (EmitContext ec)
3505 if ((Oper == Binary.Operator.LogicalAnd) ||
3506 (Oper == Binary.Operator.LogicalOr)) {
3507 Error_OperatorCannotBeApplied ();
3511 if (TypeManager.IsNullableType (left.Type)) {
3512 left = left_unwrap = Unwrap.Create (left, ec);
3517 if (TypeManager.IsNullableType (right.Type)) {
3518 right = right_unwrap = Unwrap.Create (right, ec);
3523 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3524 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3525 Expression empty = new EmptyExpression (TypeManager.bool_type);
3526 bool_wrap = Wrap.Create (empty, ec);
3527 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3529 type = bool_wrap.Type;
3531 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3532 if (!(left is NullLiteral) && !(right is NullLiteral)) {
3533 underlying = new Binary (Oper, left, right).Resolve (ec);
3534 if (underlying == null)
3538 type = TypeManager.bool_type;
3540 } else if ((Oper == Binary.Operator.LessThan) ||
3541 (Oper == Binary.Operator.GreaterThan) ||
3542 (Oper == Binary.Operator.LessThanOrEqual) ||
3543 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3544 underlying = new Binary (Oper, left, right).Resolve (ec);
3545 if (underlying == null)
3548 type = TypeManager.bool_type;
3549 is_comparision = true;
3551 underlying = new Binary (Oper, left, right).Resolve (ec);
3552 if (underlying == null)
3555 underlying = Wrap.Create (underlying, ec);
3556 if (underlying == null)
3559 type = underlying.Type;
3560 null_value = new NullableLiteral (type, loc).Resolve (ec);
3563 eclass = ExprClass.Value;
3567 void EmitBoolean (EmitContext ec)
3569 ILGenerator ig = ec.ig;
3571 Label left_is_null_label = ig.DefineLabel ();
3572 Label right_is_null_label = ig.DefineLabel ();
3573 Label is_null_label = ig.DefineLabel ();
3574 Label wrap_label = ig.DefineLabel ();
3575 Label end_label = ig.DefineLabel ();
3577 if (left_unwrap != null) {
3578 left_unwrap.EmitCheck (ec);
3579 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3583 ig.Emit (OpCodes.Dup);
3584 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3585 ig.Emit (OpCodes.Brtrue, wrap_label);
3587 ig.Emit (OpCodes.Brfalse, wrap_label);
3589 if (right_unwrap != null) {
3590 right_unwrap.EmitCheck (ec);
3591 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3594 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3595 ig.Emit (OpCodes.Pop);
3598 if (Oper == Binary.Operator.BitwiseOr)
3599 ig.Emit (OpCodes.Or);
3600 else if (Oper == Binary.Operator.BitwiseAnd)
3601 ig.Emit (OpCodes.And);
3602 ig.Emit (OpCodes.Br, wrap_label);
3604 ig.MarkLabel (left_is_null_label);
3605 if (right_unwrap != null) {
3606 right_unwrap.EmitCheck (ec);
3607 ig.Emit (OpCodes.Brfalse, is_null_label);
3611 ig.Emit (OpCodes.Dup);
3612 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3613 ig.Emit (OpCodes.Brtrue, wrap_label);
3615 ig.Emit (OpCodes.Brfalse, wrap_label);
3617 ig.MarkLabel (right_is_null_label);
3618 ig.Emit (OpCodes.Pop);
3619 ig.MarkLabel (is_null_label);
3620 null_value.Emit (ec);
3621 ig.Emit (OpCodes.Br, end_label);
3623 ig.MarkLabel (wrap_label);
3624 ig.Emit (OpCodes.Nop);
3625 bool_wrap.Emit (ec);
3626 ig.Emit (OpCodes.Nop);
3628 ig.MarkLabel (end_label);
3631 void EmitEquality (EmitContext ec)
3633 ILGenerator ig = ec.ig;
3635 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
3636 if (left is NullLiteral) {
3637 if (right_unwrap == null)
3638 throw new InternalErrorException ();
3639 right_unwrap.EmitCheck (ec);
3640 if (Oper == Binary.Operator.Equality) {
3641 ig.Emit (OpCodes.Ldc_I4_0);
3642 ig.Emit (OpCodes.Ceq);
3647 if (right is NullLiteral) {
3648 if (left_unwrap == null)
3649 throw new InternalErrorException ();
3650 left_unwrap.EmitCheck (ec);
3651 if (Oper == Binary.Operator.Equality) {
3652 ig.Emit (OpCodes.Ldc_I4_0);
3653 ig.Emit (OpCodes.Ceq);
3658 Label both_have_value_label = ig.DefineLabel ();
3659 Label end_label = ig.DefineLabel ();
3661 if (left_unwrap != null && right_unwrap != null) {
3662 Label dissimilar_label = ig.DefineLabel ();
3664 left_unwrap.EmitCheck (ec);
3665 ig.Emit (OpCodes.Dup);
3666 right_unwrap.EmitCheck (ec);
3667 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3669 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3672 if (Oper == Binary.Operator.Equality)
3673 ig.Emit (OpCodes.Ldc_I4_1);
3675 ig.Emit (OpCodes.Ldc_I4_0);
3676 ig.Emit (OpCodes.Br, end_label);
3678 ig.MarkLabel (dissimilar_label);
3679 ig.Emit (OpCodes.Pop);
3680 } else if (left_unwrap != null) {
3681 left_unwrap.EmitCheck (ec);
3682 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3683 } else if (right_unwrap != null) {
3684 right_unwrap.EmitCheck (ec);
3685 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3687 throw new InternalErrorException ("shouldn't get here");
3690 // one is null while the other isn't
3691 if (Oper == Binary.Operator.Equality)
3692 ig.Emit (OpCodes.Ldc_I4_0);
3694 ig.Emit (OpCodes.Ldc_I4_1);
3695 ig.Emit (OpCodes.Br, end_label);
3697 ig.MarkLabel (both_have_value_label);
3698 underlying.Emit (ec);
3700 ig.MarkLabel (end_label);
3703 void EmitComparision (EmitContext ec)
3705 ILGenerator ig = ec.ig;
3707 Label is_null_label = ig.DefineLabel ();
3708 Label end_label = ig.DefineLabel ();
3710 if (left_unwrap != null) {
3711 left_unwrap.EmitCheck (ec);
3712 ig.Emit (OpCodes.Brfalse, is_null_label);
3715 if (right_unwrap != null) {
3716 right_unwrap.EmitCheck (ec);
3717 ig.Emit (OpCodes.Brfalse, is_null_label);
3720 underlying.Emit (ec);
3721 ig.Emit (OpCodes.Br, end_label);
3723 ig.MarkLabel (is_null_label);
3724 ig.Emit (OpCodes.Ldc_I4_0);
3726 ig.MarkLabel (end_label);
3729 public override void EmitBranchable (EmitContext ec, Label target, bool onTrue)
3732 ec.ig.Emit (onTrue ? OpCodes.Brtrue : OpCodes.Brfalse, target);
3735 public override void Emit (EmitContext ec)
3737 if (left_unwrap != null)
3738 left_unwrap.Store (ec);
3739 if (right_unwrap != null)
3740 right_unwrap.Store (ec);
3745 } else if (is_equality) {
3748 } else if (is_comparision) {
3749 EmitComparision (ec);
3753 ILGenerator ig = ec.ig;
3755 Label is_null_label = ig.DefineLabel ();
3756 Label end_label = ig.DefineLabel ();
3758 if (left_unwrap != null) {
3759 left_unwrap.EmitCheck (ec);
3760 ig.Emit (OpCodes.Brfalse, is_null_label);
3763 if (right_unwrap != null) {
3764 right_unwrap.EmitCheck (ec);
3765 ig.Emit (OpCodes.Brfalse, is_null_label);
3768 underlying.Emit (ec);
3769 ig.Emit (OpCodes.Br, end_label);
3771 ig.MarkLabel (is_null_label);
3772 null_value.Emit (ec);
3774 ig.MarkLabel (end_label);
3778 public class OperatorTrueOrFalse : Expression
3780 public readonly bool IsTrue;
3785 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3787 this.IsTrue = is_true;
3792 public override Expression DoResolve (EmitContext ec)
3794 unwrap = Unwrap.Create (expr, ec);
3798 if (unwrap.Type != TypeManager.bool_type)
3801 type = TypeManager.bool_type;
3802 eclass = ExprClass.Value;
3806 public override void Emit (EmitContext ec)
3808 ILGenerator ig = ec.ig;
3810 Label is_null_label = ig.DefineLabel ();
3811 Label end_label = ig.DefineLabel ();
3813 unwrap.EmitCheck (ec);
3814 ig.Emit (OpCodes.Brfalse, is_null_label);
3818 ig.Emit (OpCodes.Ldc_I4_0);
3819 ig.Emit (OpCodes.Ceq);
3821 ig.Emit (OpCodes.Br, end_label);
3823 ig.MarkLabel (is_null_label);
3824 ig.Emit (OpCodes.Ldc_I4_0);
3826 ig.MarkLabel (end_label);
3830 public class NullCoalescingOperator : Expression
3832 Expression left, right;
3836 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3842 eclass = ExprClass.Value;
3845 public override Expression DoResolve (EmitContext ec)
3850 left = left.Resolve (ec);
3854 right = right.Resolve (ec);
3858 Type ltype = left.Type, rtype = right.Type;
3860 if (TypeManager.IsNullableType (ltype)) {
3861 NullableInfo info = new NullableInfo (ltype);
3863 unwrap = Unwrap.Create (left, ec);
3867 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3873 } else if (!TypeManager.IsReferenceType (ltype)) {
3874 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3878 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3884 Expression left_null = unwrap != null ? unwrap : left;
3885 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3893 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3897 public override void Emit (EmitContext ec)
3899 ILGenerator ig = ec.ig;
3901 Label is_null_label = ig.DefineLabel ();
3902 Label end_label = ig.DefineLabel ();
3904 if (unwrap != null) {
3905 unwrap.EmitCheck (ec);
3906 ig.Emit (OpCodes.Brfalse, is_null_label);
3909 ig.Emit (OpCodes.Br, end_label);
3911 ig.MarkLabel (is_null_label);
3914 ig.MarkLabel (end_label);
3917 ig.Emit (OpCodes.Dup);
3918 ig.Emit (OpCodes.Brtrue, end_label);
3920 ig.MarkLabel (is_null_label);
3922 ig.Emit (OpCodes.Pop);
3925 ig.MarkLabel (end_label);
3929 protected override void CloneTo (CloneContext clonectx, Expression t)
3931 NullCoalescingOperator target = (NullCoalescingOperator) t;
3933 target.left = left.Clone (clonectx);
3934 target.right = right.Clone (clonectx);
3938 public class LiftedUnaryMutator : ExpressionStatement
3940 public readonly UnaryMutator.Mode Mode;
3941 Expression expr, null_value;
3942 UnaryMutator underlying;
3945 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3951 eclass = ExprClass.Value;
3954 public override Expression DoResolve (EmitContext ec)
3956 expr = expr.Resolve (ec);
3960 unwrap = Unwrap.Create (expr, ec);
3964 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3965 if (underlying == null)
3968 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3969 if (null_value == null)
3976 void DoEmit (EmitContext ec, bool is_expr)
3978 ILGenerator ig = ec.ig;
3979 Label is_null_label = ig.DefineLabel ();
3980 Label end_label = ig.DefineLabel ();
3982 unwrap.EmitCheck (ec);
3983 ig.Emit (OpCodes.Brfalse, is_null_label);
3986 underlying.Emit (ec);
3988 underlying.EmitStatement (ec);
3989 ig.Emit (OpCodes.Br, end_label);
3991 ig.MarkLabel (is_null_label);
3993 null_value.Emit (ec);
3995 ig.MarkLabel (end_label);
3998 public override void Emit (EmitContext ec)
4003 public override void EmitStatement (EmitContext ec)