2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
13 using System.Reflection;
14 using System.Reflection.Emit;
15 using System.Globalization;
16 using System.Collections;
18 using System.Text.RegularExpressions;
20 namespace Mono.CSharp {
23 /// Abstract base class for type parameter constraints.
24 /// The type parameter can come from a generic type definition or from reflection.
26 public abstract class GenericConstraints {
27 public abstract string TypeParameter {
31 public abstract GenericParameterAttributes Attributes {
35 public bool HasConstructorConstraint {
36 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
39 public bool HasReferenceTypeConstraint {
40 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
43 public bool HasValueTypeConstraint {
44 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
47 public virtual bool HasClassConstraint {
48 get { return ClassConstraint != null; }
51 public abstract Type ClassConstraint {
55 public abstract Type[] InterfaceConstraints {
59 public abstract Type EffectiveBaseClass {
64 // Returns whether the type parameter is "known to be a reference type".
66 public virtual bool IsReferenceType {
68 if (HasReferenceTypeConstraint)
70 if (HasValueTypeConstraint)
73 if (ClassConstraint != null) {
74 if (ClassConstraint.IsValueType)
77 if (ClassConstraint != TypeManager.object_type)
81 foreach (Type t in InterfaceConstraints) {
82 if (!t.IsGenericParameter)
85 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
86 if ((gc != null) && gc.IsReferenceType)
95 // Returns whether the type parameter is "known to be a value type".
97 public virtual bool IsValueType {
99 if (HasValueTypeConstraint)
101 if (HasReferenceTypeConstraint)
104 if (ClassConstraint != null) {
105 if (!ClassConstraint.IsValueType)
108 if (ClassConstraint != TypeManager.value_type)
112 foreach (Type t in InterfaceConstraints) {
113 if (!t.IsGenericParameter)
116 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
117 if ((gc != null) && gc.IsValueType)
126 public enum SpecialConstraint
134 /// Tracks the constraints for a type parameter from a generic type definition.
136 public class Constraints : GenericConstraints {
138 ArrayList constraints;
142 // name is the identifier, constraints is an arraylist of
143 // Expressions (with types) or `true' for the constructor constraint.
145 public Constraints (string name, ArrayList constraints,
149 this.constraints = constraints;
153 public override string TypeParameter {
159 public Constraints Clone ()
161 return new Constraints (name, constraints, loc);
164 GenericParameterAttributes attrs;
165 TypeExpr class_constraint;
166 ArrayList iface_constraints;
167 ArrayList type_param_constraints;
169 Type class_constraint_type;
170 Type[] iface_constraint_types;
171 Type effective_base_type;
176 /// Resolve the constraints - but only resolve things into Expression's, not
177 /// into actual types.
179 public bool Resolve (IResolveContext ec)
184 iface_constraints = new ArrayList ();
185 type_param_constraints = new ArrayList ();
187 foreach (object obj in constraints) {
188 if (HasConstructorConstraint) {
189 Report.Error (401, loc,
190 "The new() constraint must be the last constraint specified");
194 if (obj is SpecialConstraint) {
195 SpecialConstraint sc = (SpecialConstraint) obj;
197 if (sc == SpecialConstraint.Constructor) {
198 if (!HasValueTypeConstraint) {
199 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
203 Report.Error (451, loc, "The `new()' constraint " +
204 "cannot be used with the `struct' constraint");
208 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
209 Report.Error (449, loc, "The `class' or `struct' " +
210 "constraint must be the first constraint specified");
214 if (sc == SpecialConstraint.ReferenceType)
215 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
217 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
221 int errors = Report.Errors;
222 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
225 if (errors != Report.Errors)
228 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
233 ConstructedType cexpr = fn as ConstructedType;
235 if (!cexpr.ResolveConstructedType (ec))
240 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
242 if ((expr == null) || (expr.Type == null))
245 // TODO: It's aleady done in ResolveAsBaseTerminal
246 if (!ec.GenericDeclContainer.AsAccessible (fn.Type, ec.GenericDeclContainer.ModFlags)) {
247 Report.SymbolRelatedToPreviousError (fn.Type);
248 Report.Error (703, loc,
249 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
250 fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
254 TypeParameterExpr texpr = expr as TypeParameterExpr;
256 type_param_constraints.Add (expr);
257 else if (expr.IsInterface)
258 iface_constraints.Add (expr);
259 else if (class_constraint != null) {
260 Report.Error (406, loc,
261 "`{0}': the class constraint for `{1}' " +
262 "must come before any other constraints.",
265 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
266 Report.Error (450, loc, "`{0}': cannot specify both " +
267 "a constraint class and the `class' " +
268 "or `struct' constraint", expr.GetSignatureForError ());
271 class_constraint = expr;
276 ArrayList list = new ArrayList ();
277 foreach (TypeExpr iface_constraint in iface_constraints) {
278 foreach (Type type in list) {
279 if (!type.Equals (iface_constraint.Type))
282 Report.Error (405, loc,
283 "Duplicate constraint `{0}' for type " +
284 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
289 list.Add (iface_constraint.Type);
292 foreach (TypeParameterExpr expr in type_param_constraints) {
293 foreach (Type type in list) {
294 if (!type.Equals (expr.Type))
297 Report.Error (405, loc,
298 "Duplicate constraint `{0}' for type " +
299 "parameter `{1}'.", expr.GetSignatureForError (), name);
303 list.Add (expr.Type);
306 iface_constraint_types = new Type [list.Count];
307 list.CopyTo (iface_constraint_types, 0);
309 if (class_constraint != null) {
310 class_constraint_type = class_constraint.Type;
311 if (class_constraint_type == null)
314 if (class_constraint_type.IsSealed) {
315 if (class_constraint_type.IsAbstract)
317 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
318 TypeManager.CSharpName (class_constraint_type));
322 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
323 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
328 if ((class_constraint_type == TypeManager.array_type) ||
329 (class_constraint_type == TypeManager.delegate_type) ||
330 (class_constraint_type == TypeManager.enum_type) ||
331 (class_constraint_type == TypeManager.value_type) ||
332 (class_constraint_type == TypeManager.object_type)) {
333 Report.Error (702, loc,
334 "Bound cannot be special class `{0}'",
335 TypeManager.CSharpName (class_constraint_type));
340 if (class_constraint_type != null)
341 effective_base_type = class_constraint_type;
342 else if (HasValueTypeConstraint)
343 effective_base_type = TypeManager.value_type;
345 effective_base_type = TypeManager.object_type;
351 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
353 seen.Add (tparam, true);
355 Constraints constraints = tparam.Constraints;
356 if (constraints == null)
359 if (constraints.HasValueTypeConstraint) {
360 Report.Error (456, loc, "Type parameter `{0}' has " +
361 "the `struct' constraint, so it cannot " +
362 "be used as a constraint for `{1}'",
367 if (constraints.type_param_constraints == null)
370 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
371 if (seen.Contains (expr.TypeParameter)) {
372 Report.Error (454, loc, "Circular constraint " +
373 "dependency involving `{0}' and `{1}'",
374 tparam.Name, expr.Name);
378 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
386 /// Resolve the constraints into actual types.
388 public bool ResolveTypes (IResolveContext ec)
393 resolved_types = true;
395 foreach (object obj in constraints) {
396 ConstructedType cexpr = obj as ConstructedType;
400 if (!cexpr.CheckConstraints (ec))
404 foreach (TypeParameterExpr expr in type_param_constraints) {
405 Hashtable seen = new Hashtable ();
406 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
410 for (int i = 0; i < iface_constraints.Count; ++i) {
411 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
412 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
413 if (iface_constraint == null)
415 iface_constraints [i] = iface_constraint;
418 if (class_constraint != null) {
419 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
420 if (class_constraint == null)
428 /// Check whether there are no conflicts in our type parameter constraints.
430 /// This is an example:
434 /// where U : T, struct
436 public bool CheckDependencies ()
438 foreach (TypeParameterExpr expr in type_param_constraints) {
439 if (!CheckDependencies (expr.TypeParameter))
446 bool CheckDependencies (TypeParameter tparam)
448 Constraints constraints = tparam.Constraints;
449 if (constraints == null)
452 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
453 Report.Error (455, loc, "Type parameter `{0}' inherits " +
454 "conflicting constraints `{1}' and `{2}'",
455 name, TypeManager.CSharpName (constraints.ClassConstraint),
460 if (HasClassConstraint && constraints.HasClassConstraint) {
461 Type t1 = ClassConstraint;
462 TypeExpr e1 = class_constraint;
463 Type t2 = constraints.ClassConstraint;
464 TypeExpr e2 = constraints.class_constraint;
466 if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
467 !Convert.ImplicitReferenceConversionExists (e2, t1)) {
468 Report.Error (455, loc,
469 "Type parameter `{0}' inherits " +
470 "conflicting constraints `{1}' and `{2}'",
471 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
476 if (constraints.type_param_constraints == null)
479 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
480 if (!CheckDependencies (expr.TypeParameter))
487 public override GenericParameterAttributes Attributes {
488 get { return attrs; }
491 public override bool HasClassConstraint {
492 get { return class_constraint != null; }
495 public override Type ClassConstraint {
496 get { return class_constraint_type; }
499 public override Type[] InterfaceConstraints {
500 get { return iface_constraint_types; }
503 public override Type EffectiveBaseClass {
504 get { return effective_base_type; }
507 public bool IsSubclassOf (Type t)
509 if ((class_constraint_type != null) &&
510 class_constraint_type.IsSubclassOf (t))
513 if (iface_constraint_types == null)
516 foreach (Type iface in iface_constraint_types) {
517 if (TypeManager.IsSubclassOf (iface, t))
524 public Location Location {
531 /// This is used when we're implementing a generic interface method.
532 /// Each method type parameter in implementing method must have the same
533 /// constraints than the corresponding type parameter in the interface
534 /// method. To do that, we're called on each of the implementing method's
537 public bool CheckInterfaceMethod (GenericConstraints gc)
539 if (gc.Attributes != attrs)
542 if (HasClassConstraint != gc.HasClassConstraint)
544 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
547 int gc_icount = gc.InterfaceConstraints != null ?
548 gc.InterfaceConstraints.Length : 0;
549 int icount = InterfaceConstraints != null ?
550 InterfaceConstraints.Length : 0;
552 if (gc_icount != icount)
555 foreach (Type iface in gc.InterfaceConstraints) {
557 foreach (Type check in InterfaceConstraints) {
558 if (TypeManager.IsEqual (iface, check)) {
571 public void VerifyClsCompliance ()
573 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
574 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
576 if (iface_constraint_types != null) {
577 for (int i = 0; i < iface_constraint_types.Length; ++i) {
578 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
579 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
580 ((TypeExpr)iface_constraints [i]).Location);
585 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
587 Report.SymbolRelatedToPreviousError (t);
588 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
589 TypeManager.CSharpName (t));
594 /// A type parameter from a generic type definition.
596 public class TypeParameter : MemberCore, IMemberContainer {
599 GenericConstraints gc;
600 Constraints constraints;
602 GenericTypeParameterBuilder type;
604 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
605 Constraints constraints, Attributes attrs, Location loc)
606 : base (parent, new MemberName (name, loc), attrs)
610 this.constraints = constraints;
614 public GenericConstraints GenericConstraints {
615 get { return gc != null ? gc : constraints; }
618 public Constraints Constraints {
619 get { return constraints; }
622 public bool HasConstructorConstraint {
623 get { return constraints != null && constraints.HasConstructorConstraint; }
626 public DeclSpace DeclSpace {
635 /// This is the first method which is called during the resolving
636 /// process; we're called immediately after creating the type parameters
637 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
640 /// We're either called from TypeContainer.DefineType() or from
641 /// GenericMethod.Define() (called from Method.Define()).
643 public void Define (GenericTypeParameterBuilder type)
645 if (this.type != null)
646 throw new InvalidOperationException ();
649 TypeManager.AddTypeParameter (type, this);
653 /// This is the second method which is called during the resolving
654 /// process - in case of class type parameters, we're called from
655 /// TypeContainer.ResolveType() - after it resolved the class'es
656 /// base class and interfaces. For method type parameters, we're
657 /// called immediately after Define().
659 /// We're just resolving the constraints into expressions here, we
660 /// don't resolve them into actual types.
662 /// Note that in the special case of partial generic classes, we may be
663 /// called _before_ Define() and we may also be called multiple types.
665 public bool Resolve (DeclSpace ds)
667 if (constraints != null) {
668 if (!constraints.Resolve (ds)) {
678 /// This is the third method which is called during the resolving
679 /// process. We're called immediately after calling DefineConstraints()
680 /// on all of the current class'es type parameters.
682 /// Our job is to resolve the constraints to actual types.
684 /// Note that we may have circular dependencies on type parameters - this
685 /// is why Resolve() and ResolveType() are separate.
687 public bool ResolveType (IResolveContext ec)
689 if (constraints != null) {
690 if (!constraints.ResolveTypes (ec)) {
700 /// This is the fourth and last method which is called during the resolving
701 /// process. We're called after everything is fully resolved and actually
702 /// register the constraints with SRE and the TypeManager.
704 public bool DefineType (IResolveContext ec)
706 return DefineType (ec, null, null, false);
710 /// This is the fith and last method which is called during the resolving
711 /// process. We're called after everything is fully resolved and actually
712 /// register the constraints with SRE and the TypeManager.
714 /// The `builder', `implementing' and `is_override' arguments are only
715 /// applicable to method type parameters.
717 public bool DefineType (IResolveContext ec, MethodBuilder builder,
718 MethodInfo implementing, bool is_override)
720 if (!ResolveType (ec))
723 if (implementing != null) {
724 if (is_override && (constraints != null)) {
725 Report.Error (460, loc,
726 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
727 TypeManager.CSharpSignature (builder));
731 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
733 int pos = type.GenericParameterPosition;
734 Type mparam = mb.GetGenericArguments () [pos];
735 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
738 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
739 else if (constraints != null)
740 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
743 if (constraints != null) {
746 else if (!constraints.CheckInterfaceMethod (gc))
749 if (!is_override && (temp_gc != null))
754 Report.SymbolRelatedToPreviousError (implementing);
757 425, loc, "The constraints for type " +
758 "parameter `{0}' of method `{1}' must match " +
759 "the constraints for type parameter `{2}' " +
760 "of interface method `{3}'. Consider using " +
761 "an explicit interface implementation instead",
762 Name, TypeManager.CSharpSignature (builder),
763 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
766 } else if (DeclSpace is CompilerGeneratedClass) {
767 TypeParameter[] tparams = DeclSpace.TypeParameters;
768 Type[] types = new Type [tparams.Length];
769 for (int i = 0; i < tparams.Length; i++)
770 types [i] = tparams [i].Type;
772 if (constraints != null)
773 gc = new InflatedConstraints (constraints, types);
775 gc = (GenericConstraints) constraints;
781 if (gc.HasClassConstraint)
782 type.SetBaseTypeConstraint (gc.ClassConstraint);
784 type.SetInterfaceConstraints (gc.InterfaceConstraints);
785 type.SetGenericParameterAttributes (gc.Attributes);
786 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
792 /// Check whether there are no conflicts in our type parameter constraints.
794 /// This is an example:
798 /// where U : T, struct
800 public bool CheckDependencies ()
802 if (constraints != null)
803 return constraints.CheckDependencies ();
809 /// This is called for each part of a partial generic type definition.
811 /// If `new_constraints' is not null and we don't already have constraints,
812 /// they become our constraints. If we already have constraints, we must
813 /// check that they're the same.
816 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
819 throw new InvalidOperationException ();
821 if (new_constraints == null)
824 if (!new_constraints.Resolve (ec))
826 if (!new_constraints.ResolveTypes (ec))
829 if (constraints != null)
830 return constraints.CheckInterfaceMethod (new_constraints);
832 constraints = new_constraints;
836 public void EmitAttributes ()
838 if (OptAttributes != null)
839 OptAttributes.Emit ();
842 public override string DocCommentHeader {
844 throw new InvalidOperationException (
845 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
853 public override bool Define ()
858 public override void ApplyAttributeBuilder (Attribute a,
859 CustomAttributeBuilder cb)
861 type.SetCustomAttribute (cb);
864 public override AttributeTargets AttributeTargets {
866 return (AttributeTargets) AttributeTargets.GenericParameter;
870 public override string[] ValidAttributeTargets {
872 return new string [] { "type parameter" };
880 string IMemberContainer.Name {
884 MemberCache IMemberContainer.BaseCache {
888 bool IMemberContainer.IsInterface {
892 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
894 return FindMembers (mt, bf, null, null);
897 MemberCache IMemberContainer.MemberCache {
901 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
902 MemberFilter filter, object criteria)
905 return MemberList.Empty;
907 ArrayList members = new ArrayList ();
909 if (gc.HasClassConstraint) {
910 MemberList list = TypeManager.FindMembers (
911 gc.ClassConstraint, mt, bf, filter, criteria);
913 members.AddRange (list);
916 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
917 foreach (Type t in ifaces) {
918 MemberList list = TypeManager.FindMembers (
919 t, mt, bf, filter, criteria);
921 members.AddRange (list);
924 return new MemberList (members);
927 public bool IsSubclassOf (Type t)
932 if (constraints != null)
933 return constraints.IsSubclassOf (t);
938 public override string ToString ()
940 return "TypeParameter[" + name + "]";
943 public static string GetSignatureForError (TypeParameter[] tp)
945 if (tp == null || tp.Length == 0)
948 StringBuilder sb = new StringBuilder ("<");
949 for (int i = 0; i < tp.Length; ++i) {
952 sb.Append (tp[i].GetSignatureForError ());
955 return sb.ToString ();
958 public void InflateConstraints (Type declaring)
960 if (constraints != null)
961 gc = new InflatedConstraints (constraints, declaring);
964 protected class InflatedConstraints : GenericConstraints
966 GenericConstraints gc;
968 Type class_constraint;
969 Type[] iface_constraints;
972 public InflatedConstraints (GenericConstraints gc, Type declaring)
973 : this (gc, TypeManager.GetTypeArguments (declaring))
976 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
981 ArrayList list = new ArrayList ();
982 if (gc.HasClassConstraint)
983 list.Add (inflate (gc.ClassConstraint));
984 foreach (Type iface in gc.InterfaceConstraints)
985 list.Add (inflate (iface));
987 bool has_class_constr = false;
988 if (list.Count > 0) {
989 Type first = (Type) list [0];
990 has_class_constr = !first.IsInterface && !first.IsGenericParameter;
993 if ((list.Count > 0) && has_class_constr) {
994 class_constraint = (Type) list [0];
995 iface_constraints = new Type [list.Count - 1];
996 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
998 iface_constraints = new Type [list.Count];
999 list.CopyTo (iface_constraints, 0);
1002 if (HasValueTypeConstraint)
1003 base_type = TypeManager.value_type;
1004 else if (class_constraint != null)
1005 base_type = class_constraint;
1007 base_type = TypeManager.object_type;
1010 Type inflate (Type t)
1014 if (t.IsGenericParameter)
1015 return dargs [t.GenericParameterPosition];
1016 if (t.IsGenericType) {
1017 Type[] args = t.GetGenericArguments ();
1018 Type[] inflated = new Type [args.Length];
1020 for (int i = 0; i < args.Length; i++)
1021 inflated [i] = inflate (args [i]);
1023 t = t.GetGenericTypeDefinition ();
1024 t = t.MakeGenericType (inflated);
1030 public override string TypeParameter {
1031 get { return gc.TypeParameter; }
1034 public override GenericParameterAttributes Attributes {
1035 get { return gc.Attributes; }
1038 public override Type ClassConstraint {
1039 get { return class_constraint; }
1042 public override Type EffectiveBaseClass {
1043 get { return base_type; }
1046 public override Type[] InterfaceConstraints {
1047 get { return iface_constraints; }
1053 /// A TypeExpr which already resolved to a type parameter.
1055 public class TypeParameterExpr : TypeExpr {
1056 TypeParameter type_parameter;
1058 public override string Name {
1060 return type_parameter.Name;
1064 public override string FullName {
1066 return type_parameter.Name;
1070 public TypeParameter TypeParameter {
1072 return type_parameter;
1076 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1078 this.type_parameter = type_parameter;
1082 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1084 type = type_parameter.Type;
1089 public override bool IsInterface {
1090 get { return false; }
1093 public override bool CheckAccessLevel (DeclSpace ds)
1098 public void Error_CannotUseAsUnmanagedType (Location loc)
1100 Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
1105 /// Tracks the type arguments when instantiating a generic type. We're used in
1106 /// ConstructedType.
1108 public class TypeArguments {
1109 public readonly Location Location;
1116 public TypeArguments (Location loc)
1118 args = new ArrayList ();
1119 this.Location = loc;
1122 public TypeArguments (int dimension, Location loc)
1124 this.dimension = dimension;
1125 this.Location = loc;
1128 public void Add (Expression type)
1131 throw new InvalidOperationException ();
1136 public void Add (TypeArguments new_args)
1139 throw new InvalidOperationException ();
1141 args.AddRange (new_args.args);
1145 /// We're used during the parsing process: the parser can't distinguish
1146 /// between type parameters and type arguments. Because of that, the
1147 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1148 /// in case of a generic type definition, we call GetDeclarations().
1150 public TypeParameterName[] GetDeclarations ()
1152 TypeParameterName[] ret = new TypeParameterName [args.Count];
1153 for (int i = 0; i < args.Count; i++) {
1154 TypeParameterName name = args [i] as TypeParameterName;
1159 SimpleName sn = args [i] as SimpleName;
1161 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1165 Report.Error (81, Location, "Type parameter declaration " +
1166 "must be an identifier not a type");
1173 /// We may only be used after Resolve() is called and return the fully
1176 public Type[] Arguments {
1182 public bool HasTypeArguments {
1184 return has_type_args;
1197 public bool IsUnbound {
1199 return dimension > 0;
1203 public override string ToString ()
1205 StringBuilder s = new StringBuilder ();
1208 for (int i = 0; i < count; i++){
1210 // FIXME: Use TypeManager.CSharpname once we have the type
1213 s.Append (args [i].ToString ());
1217 return s.ToString ();
1220 public string GetSignatureForError()
1222 StringBuilder sb = new StringBuilder();
1223 for (int i = 0; i < Count; ++i)
1225 Expression expr = (Expression)args [i];
1226 sb.Append(expr.GetSignatureForError());
1230 return sb.ToString();
1234 /// Resolve the type arguments.
1236 public bool Resolve (IResolveContext ec)
1238 int count = args.Count;
1241 atypes = new Type [count];
1243 for (int i = 0; i < count; i++){
1244 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1249 if (te is TypeParameterExpr)
1250 has_type_args = true;
1253 if (te.Type.IsSealed && te.Type.IsAbstract) {
1254 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1255 te.GetSignatureForError ());
1259 if (te.Type.IsPointer) {
1260 Report.Error (306, Location, "The type `{0}' may not be used " +
1261 "as a type argument", TypeManager.CSharpName (te.Type));
1265 if (te.Type == TypeManager.void_type) {
1266 Expression.Error_VoidInvalidInTheContext (Location);
1270 atypes [i] = te.Type;
1276 public class TypeParameterName : SimpleName
1278 Attributes attributes;
1280 public TypeParameterName (string name, Attributes attrs, Location loc)
1286 public Attributes OptAttributes {
1294 /// An instantiation of a generic type.
1296 public class ConstructedType : TypeExpr {
1298 FullNamedExpression name;
1300 Type[] gen_params, atypes;
1304 /// Instantiate the generic type `fname' with the type arguments `args'.
1306 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1312 eclass = ExprClass.Type;
1313 full_name = name + "<" + args.ToString () + ">";
1316 protected ConstructedType (TypeArguments args, Location l)
1321 eclass = ExprClass.Type;
1324 protected ConstructedType (TypeParameter[] type_params, Location l)
1328 args = new TypeArguments (l);
1329 foreach (TypeParameter type_param in type_params)
1330 args.Add (new TypeParameterExpr (type_param, l));
1332 eclass = ExprClass.Type;
1336 /// This is used to construct the `this' type inside a generic type definition.
1338 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1339 : this (type_params, l)
1341 gt = t.GetGenericTypeDefinition ();
1343 this.name = new TypeExpression (gt, l);
1344 full_name = gt.FullName + "<" + args.ToString () + ">";
1348 /// Instantiate the generic type `t' with the type arguments `args'.
1349 /// Use this constructor if you already know the fully resolved
1352 public ConstructedType (Type t, TypeArguments args, Location l)
1355 gt = t.GetGenericTypeDefinition ();
1357 this.name = new TypeExpression (gt, l);
1358 full_name = gt.FullName + "<" + args.ToString () + ">";
1361 public TypeArguments TypeArguments {
1362 get { return args; }
1365 public override string GetSignatureForError ()
1367 return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1370 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1372 if (!ResolveConstructedType (ec))
1379 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1380 /// after fully resolving the constructed type.
1382 public bool CheckConstraints (IResolveContext ec)
1384 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1388 /// Resolve the constructed type, but don't check the constraints.
1390 public bool ResolveConstructedType (IResolveContext ec)
1394 // If we already know the fully resolved generic type.
1396 return DoResolveType (ec);
1402 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1406 num_args = TypeManager.GetNumberOfTypeArguments (t);
1407 if (num_args == 0) {
1408 Report.Error (308, loc,
1409 "The non-generic type `{0}' cannot " +
1410 "be used with type arguments.",
1411 TypeManager.CSharpName (t));
1415 gt = t.GetGenericTypeDefinition ();
1416 return DoResolveType (ec);
1419 bool DoResolveType (IResolveContext ec)
1422 // Resolve the arguments.
1424 if (args.Resolve (ec) == false)
1427 gen_params = gt.GetGenericArguments ();
1428 atypes = args.Arguments;
1430 if (atypes.Length != gen_params.Length) {
1431 Report.Error (305, loc,
1432 "Using the generic type `{0}' " +
1433 "requires {1} type arguments",
1434 TypeManager.CSharpName (gt),
1435 gen_params.Length.ToString ());
1440 // Now bind the parameters.
1442 type = gt.MakeGenericType (atypes);
1446 public Expression GetSimpleName (EmitContext ec)
1451 public override bool CheckAccessLevel (DeclSpace ds)
1453 return ds.CheckAccessLevel (gt);
1456 public override bool AsAccessible (DeclSpace ds, int flags)
1458 foreach (Type t in atypes) {
1459 if (!ds.AsAccessible (t, flags))
1463 return ds.AsAccessible (gt, flags);
1466 public override bool IsClass {
1467 get { return gt.IsClass; }
1470 public override bool IsValueType {
1471 get { return gt.IsValueType; }
1474 public override bool IsInterface {
1475 get { return gt.IsInterface; }
1478 public override bool IsSealed {
1479 get { return gt.IsSealed; }
1482 public override bool Equals (object obj)
1484 ConstructedType cobj = obj as ConstructedType;
1488 if ((type == null) || (cobj.type == null))
1491 return type == cobj.type;
1494 public override int GetHashCode ()
1496 return base.GetHashCode ();
1499 public override string Name {
1505 public override string FullName {
1512 public abstract class ConstraintChecker
1514 protected readonly Type[] gen_params;
1515 protected readonly Type[] atypes;
1516 protected readonly Location loc;
1518 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1520 this.gen_params = gen_params;
1521 this.atypes = atypes;
1526 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1527 /// after fully resolving the constructed type.
1529 public bool CheckConstraints (IResolveContext ec)
1531 for (int i = 0; i < gen_params.Length; i++) {
1532 if (!CheckConstraints (ec, i))
1539 protected bool CheckConstraints (IResolveContext ec, int index)
1541 Type atype = atypes [index];
1542 Type ptype = gen_params [index];
1547 Expression aexpr = new EmptyExpression (atype);
1549 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1553 bool is_class, is_struct;
1554 if (atype.IsGenericParameter) {
1555 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1557 if (agc is Constraints)
1558 ((Constraints) agc).Resolve (ec);
1559 is_class = agc.IsReferenceType;
1560 is_struct = agc.IsValueType;
1562 is_class = is_struct = false;
1567 if (!atype.IsGenericType)
1569 is_class = atype.IsClass || atype.IsInterface;
1570 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1574 // First, check the `class' and `struct' constraints.
1576 if (gc.HasReferenceTypeConstraint && !is_class) {
1577 Report.Error (452, loc, "The type `{0}' must be " +
1578 "a reference type in order to use it " +
1579 "as type parameter `{1}' in the " +
1580 "generic type or method `{2}'.",
1581 TypeManager.CSharpName (atype),
1582 TypeManager.CSharpName (ptype),
1583 GetSignatureForError ());
1585 } else if (gc.HasValueTypeConstraint && !is_struct) {
1586 Report.Error (453, loc, "The type `{0}' must be a " +
1587 "non-nullable value type in order to use it " +
1588 "as type parameter `{1}' in the " +
1589 "generic type or method `{2}'.",
1590 TypeManager.CSharpName (atype),
1591 TypeManager.CSharpName (ptype),
1592 GetSignatureForError ());
1597 // The class constraint comes next.
1599 if (gc.HasClassConstraint) {
1600 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1605 // Now, check the interface constraints.
1607 if (gc.InterfaceConstraints != null) {
1608 foreach (Type it in gc.InterfaceConstraints) {
1609 if (!CheckConstraint (ec, ptype, aexpr, it))
1615 // Finally, check the constructor constraint.
1618 if (!gc.HasConstructorConstraint)
1621 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1624 if (HasDefaultConstructor (ec.DeclContainer.TypeBuilder, atype))
1627 Report_SymbolRelatedToPreviousError ();
1628 Report.SymbolRelatedToPreviousError (atype);
1629 Report.Error (310, loc, "The type `{0}' must have a public " +
1630 "parameterless constructor in order to use it " +
1631 "as parameter `{1}' in the generic type or " +
1633 TypeManager.CSharpName (atype),
1634 TypeManager.CSharpName (ptype),
1635 GetSignatureForError ());
1639 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1642 if (TypeManager.HasGenericArguments (ctype)) {
1643 Type[] types = TypeManager.GetTypeArguments (ctype);
1645 TypeArguments new_args = new TypeArguments (loc);
1647 for (int i = 0; i < types.Length; i++) {
1650 if (t.IsGenericParameter) {
1651 int pos = t.GenericParameterPosition;
1654 new_args.Add (new TypeExpression (t, loc));
1657 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1658 if (ct.ResolveAsTypeStep (ec, false) == null)
1661 } else if (ctype.IsGenericParameter) {
1662 int pos = ctype.GenericParameterPosition;
1663 ctype = atypes [pos];
1666 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1669 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1673 bool HasDefaultConstructor (Type containerType, Type atype)
1675 if (atype.IsAbstract)
1679 atype = TypeManager.DropGenericTypeArguments (atype);
1680 if (atype is TypeBuilder) {
1681 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1682 if (tc.InstanceConstructors == null) {
1683 atype = atype.BaseType;
1687 foreach (Constructor c in tc.InstanceConstructors) {
1688 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1690 if ((c.Parameters.FixedParameters != null) &&
1691 (c.Parameters.FixedParameters.Length != 0))
1693 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1700 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1702 return tparam.HasConstructorConstraint;
1704 MemberList list = TypeManager.FindMembers (
1705 atype, MemberTypes.Constructor,
1706 BindingFlags.Public | BindingFlags.Instance |
1707 BindingFlags.DeclaredOnly, null, null);
1709 if (atype.IsAbstract || (list == null))
1712 foreach (MethodBase mb in list) {
1713 ParameterData pd = TypeManager.GetParameterData (mb);
1714 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1721 protected abstract string GetSignatureForError ();
1722 protected abstract void Report_SymbolRelatedToPreviousError ();
1724 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1726 Report_SymbolRelatedToPreviousError ();
1727 Report.SymbolRelatedToPreviousError (atype);
1728 Report.Error (309, loc,
1729 "The type `{0}' must be convertible to `{1}' in order to " +
1730 "use it as parameter `{2}' in the generic type or method `{3}'",
1731 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1732 TypeManager.CSharpName (ptype), GetSignatureForError ());
1735 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1736 MethodBase instantiated, Location loc)
1738 MethodConstraintChecker checker = new MethodConstraintChecker (
1739 definition, definition.GetGenericArguments (),
1740 instantiated.GetGenericArguments (), loc);
1742 return checker.CheckConstraints (ec);
1745 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1746 Type[] atypes, Location loc)
1748 TypeConstraintChecker checker = new TypeConstraintChecker (
1749 gt, gen_params, atypes, loc);
1751 return checker.CheckConstraints (ec);
1754 protected class MethodConstraintChecker : ConstraintChecker
1756 MethodBase definition;
1758 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1759 Type[] atypes, Location loc)
1760 : base (gen_params, atypes, loc)
1762 this.definition = definition;
1765 protected override string GetSignatureForError ()
1767 return TypeManager.CSharpSignature (definition);
1770 protected override void Report_SymbolRelatedToPreviousError ()
1772 Report.SymbolRelatedToPreviousError (definition);
1776 protected class TypeConstraintChecker : ConstraintChecker
1780 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1782 : base (gen_params, atypes, loc)
1787 protected override string GetSignatureForError ()
1789 return TypeManager.CSharpName (gt);
1792 protected override void Report_SymbolRelatedToPreviousError ()
1794 Report.SymbolRelatedToPreviousError (gt);
1800 /// A generic method definition.
1802 public class GenericMethod : DeclSpace
1804 Expression return_type;
1805 Parameters parameters;
1807 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1808 Expression return_type, Parameters parameters)
1809 : base (ns, parent, name, null)
1811 this.return_type = return_type;
1812 this.parameters = parameters;
1815 public override TypeBuilder DefineType ()
1817 throw new Exception ();
1820 public override bool Define ()
1822 for (int i = 0; i < TypeParameters.Length; i++)
1823 if (!TypeParameters [i].Resolve (this))
1830 /// Define and resolve the type parameters.
1831 /// We're called from Method.Define().
1833 public bool Define (MethodBuilder mb, ToplevelBlock block)
1835 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1836 string[] snames = new string [names.Length];
1837 for (int i = 0; i < names.Length; i++) {
1838 string type_argument_name = names[i].Name;
1839 Parameter p = parameters.GetParameterByName (type_argument_name);
1841 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1844 if (block != null) {
1845 LocalInfo li = (LocalInfo)block.Variables[type_argument_name];
1847 Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
1851 snames[i] = type_argument_name;
1854 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1855 for (int i = 0; i < TypeParameters.Length; i++)
1856 TypeParameters [i].Define (gen_params [i]);
1861 for (int i = 0; i < TypeParameters.Length; i++) {
1862 if (!TypeParameters [i].ResolveType (this))
1869 static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1871 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1872 name, collisionWith);
1876 /// We're called from MethodData.Define() after creating the MethodBuilder.
1878 public bool DefineType (EmitContext ec, MethodBuilder mb,
1879 MethodInfo implementing, bool is_override)
1881 for (int i = 0; i < TypeParameters.Length; i++)
1882 if (!TypeParameters [i].DefineType (
1883 ec, mb, implementing, is_override))
1887 foreach (Parameter p in parameters.FixedParameters){
1888 if (!p.Resolve (ec))
1891 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1897 public void EmitAttributes ()
1899 for (int i = 0; i < TypeParameters.Length; i++)
1900 TypeParameters [i].EmitAttributes ();
1902 if (OptAttributes != null)
1903 OptAttributes.Emit ();
1906 public override bool DefineMembers ()
1911 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1912 MemberFilter filter, object criteria)
1914 throw new Exception ();
1917 public override MemberCache MemberCache {
1923 public override AttributeTargets AttributeTargets {
1925 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1929 public override string DocCommentHeader {
1930 get { return "M:"; }
1933 public new void VerifyClsCompliance ()
1935 foreach (TypeParameter tp in TypeParameters) {
1936 if (tp.Constraints == null)
1939 tp.Constraints.VerifyClsCompliance ();
1944 public class DefaultValueExpression : Expression
1948 public DefaultValueExpression (Expression expr, Location loc)
1954 public override Expression DoResolve (EmitContext ec)
1956 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1962 if (type == TypeManager.void_type) {
1963 Error_VoidInvalidInTheContext (loc);
1967 if (type.IsGenericParameter)
1969 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints(type);
1970 if (constraints != null && constraints.IsReferenceType)
1971 return new NullDefault (new NullLiteral (Location), type);
1975 Constant c = New.Constantify(type);
1977 return new NullDefault (c, type);
1979 if (!TypeManager.IsValueType (type))
1980 return new NullDefault (new NullLiteral (Location), type);
1982 eclass = ExprClass.Variable;
1986 public override void Emit (EmitContext ec)
1988 LocalTemporary temp_storage = new LocalTemporary(type);
1990 temp_storage.AddressOf(ec, AddressOp.LoadStore);
1991 ec.ig.Emit(OpCodes.Initobj, type);
1992 temp_storage.Emit(ec);
1996 public class NullableType : TypeExpr
1998 Expression underlying;
2000 public NullableType (Expression underlying, Location l)
2002 this.underlying = underlying;
2005 eclass = ExprClass.Type;
2008 public NullableType (Type type, Location loc)
2009 : this (new TypeExpression (type, loc), loc)
2012 public override string Name {
2013 get { return underlying.ToString () + "?"; }
2016 public override string FullName {
2017 get { return underlying.ToString () + "?"; }
2020 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2022 TypeArguments args = new TypeArguments (loc);
2023 args.Add (underlying);
2025 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2026 return ctype.ResolveAsTypeTerminal (ec, false);
2030 public partial class TypeManager
2033 // A list of core types that the compiler requires or uses
2035 static public Type activator_type;
2036 static public Type generic_ilist_type;
2037 static public Type generic_icollection_type;
2038 static public Type generic_ienumerator_type;
2039 static public Type generic_ienumerable_type;
2040 static public Type generic_nullable_type;
2043 // These methods are called by code generated by the compiler
2045 static public MethodInfo activator_create_instance;
2047 static void InitGenericCoreTypes ()
2049 activator_type = CoreLookupType ("System", "Activator");
2051 generic_ilist_type = CoreLookupType (
2052 "System.Collections.Generic", "IList", 1);
2053 generic_icollection_type = CoreLookupType (
2054 "System.Collections.Generic", "ICollection", 1);
2055 generic_ienumerator_type = CoreLookupType (
2056 "System.Collections.Generic", "IEnumerator", 1);
2057 generic_ienumerable_type = CoreLookupType (
2058 "System.Collections.Generic", "IEnumerable", 1);
2059 generic_nullable_type = CoreLookupType (
2060 "System", "Nullable", 1);
2063 static void InitGenericCodeHelpers ()
2066 Type [] type_arg = { type_type };
2067 activator_create_instance = GetMethod (
2068 activator_type, "CreateInstance", type_arg);
2071 static Type CoreLookupType (string ns, string name, int arity)
2073 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2076 public static TypeContainer LookupGenericTypeContainer (Type t)
2078 t = DropGenericTypeArguments (t);
2079 return LookupTypeContainer (t);
2082 public static GenericConstraints GetTypeParameterConstraints (Type t)
2084 if (!t.IsGenericParameter)
2085 throw new InvalidOperationException ();
2087 TypeParameter tparam = LookupTypeParameter (t);
2089 return tparam.GenericConstraints;
2091 return ReflectionConstraints.GetConstraints (t);
2095 /// Check whether `a' and `b' may become equal generic types.
2096 /// The algorithm to do that is a little bit complicated.
2098 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2099 Type[] method_inferred)
2101 if (a.IsGenericParameter) {
2103 // If a is an array of a's type, they may never
2107 b = b.GetElementType ();
2113 // If b is a generic parameter or an actual type,
2114 // they may become equal:
2116 // class X<T,U> : I<T>, I<U>
2117 // class X<T> : I<T>, I<float>
2119 if (b.IsGenericParameter || !b.IsGenericType) {
2120 int pos = a.GenericParameterPosition;
2121 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2122 if (args [pos] == null) {
2127 return args [pos] == a;
2131 // We're now comparing a type parameter with a
2132 // generic instance. They may become equal unless
2133 // the type parameter appears anywhere in the
2134 // generic instance:
2136 // class X<T,U> : I<T>, I<X<U>>
2137 // -> error because you could instanciate it as
2140 // class X<T> : I<T>, I<X<T>> -> ok
2143 Type[] bargs = GetTypeArguments (b);
2144 for (int i = 0; i < bargs.Length; i++) {
2145 if (a.Equals (bargs [i]))
2152 if (b.IsGenericParameter)
2153 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2156 // At this point, neither a nor b are a type parameter.
2158 // If one of them is a generic instance, let
2159 // MayBecomeEqualGenericInstances() compare them (if the
2160 // other one is not a generic instance, they can never
2164 if (a.IsGenericType || b.IsGenericType)
2165 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2168 // If both of them are arrays.
2171 if (a.IsArray && b.IsArray) {
2172 if (a.GetArrayRank () != b.GetArrayRank ())
2175 a = a.GetElementType ();
2176 b = b.GetElementType ();
2178 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2182 // Ok, two ordinary types.
2185 return a.Equals (b);
2189 // Checks whether two generic instances may become equal for some
2190 // particular instantiation (26.3.1).
2192 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2193 Type[] class_inferred,
2194 Type[] method_inferred)
2196 if (!a.IsGenericType || !b.IsGenericType)
2198 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2201 return MayBecomeEqualGenericInstances (
2202 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2205 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2206 Type[] class_inferred,
2207 Type[] method_inferred)
2209 if (aargs.Length != bargs.Length)
2212 for (int i = 0; i < aargs.Length; i++) {
2213 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2220 static bool UnifyType (Type pt, Type at, Type[] inferred)
2222 if (pt.IsGenericParameter) {
2223 if (pt.DeclaringMethod == null)
2226 int pos = pt.GenericParameterPosition;
2228 if (inferred [pos] == null)
2229 inferred [pos] = at;
2231 return inferred [pos] == at;
2234 if (!pt.ContainsGenericParameters) {
2235 if (at.ContainsGenericParameters)
2236 return UnifyType (at, pt, inferred);
2243 if (at.GetArrayRank () != pt.GetArrayRank ())
2246 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2249 if (!pt.IsGenericType)
2252 Type gt = pt.GetGenericTypeDefinition ();
2253 if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
2254 (gt != generic_ienumerable_type))
2257 Type[] args = GetTypeArguments (pt);
2258 return UnifyType (args [0], at.GetElementType (), inferred);
2263 (pt.GetArrayRank () != at.GetArrayRank ()))
2266 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2269 if (pt.IsByRef && at.IsByRef)
2270 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2271 ArrayList list = new ArrayList ();
2272 if (at.IsGenericType)
2274 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2277 list.AddRange (TypeManager.GetInterfaces (at));
2279 foreach (Type type in list) {
2280 if (!type.IsGenericType)
2283 if (DropGenericTypeArguments (pt) != DropGenericTypeArguments (type))
2286 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2293 static bool UnifyTypes (Type[] pts, Type [] ats, Type [] inferred)
2295 for (int i = 0; i < ats.Length; i++) {
2296 if (!UnifyType (pts [i], ats [i], inferred))
2303 /// Type inference. Try to infer the type arguments from the params method
2304 /// `method', which is invoked with the arguments `arguments'. This is used
2305 /// when resolving an Invocation or a DelegateInvocation and the user
2306 /// did not explicitly specify type arguments.
2308 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2309 ref MethodBase method)
2311 if (!TypeManager.IsGenericMethod (method))
2314 // if there are no arguments, there's no way to infer the type-arguments
2315 if (arguments == null || arguments.Count == 0)
2318 ParameterData pd = TypeManager.GetParameterData (method);
2319 int pd_count = pd.Count;
2320 int arg_count = arguments.Count;
2325 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2328 if (pd_count - 1 > arg_count)
2331 Type[] method_args = method.GetGenericArguments ();
2332 Type[] inferred_types = new Type [method_args.Length];
2335 // If we have come this far, the case which
2336 // remains is when the number of parameters is
2337 // less than or equal to the argument count.
2339 for (int i = 0; i < pd_count - 1; ++i) {
2340 Argument a = (Argument) arguments [i];
2342 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2345 Type pt = pd.ParameterType (i);
2348 if (!UnifyType (pt, at, inferred_types))
2352 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2354 for (int i = pd_count - 1; i < arg_count; i++) {
2355 Argument a = (Argument) arguments [i];
2357 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2360 if (!UnifyType (element_type, a.Type, inferred_types))
2364 for (int i = 0; i < inferred_types.Length; i++)
2365 if (inferred_types [i] == null)
2368 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2372 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2373 Type[] inferred_types)
2375 for (int i = 0; i < arg_types.Length; i++) {
2376 if (arg_types [i] == null)
2379 if (!UnifyType (param_types [i], arg_types [i], inferred_types))
2383 for (int i = 0; i < inferred_types.Length; i++)
2384 if (inferred_types [i] == null)
2391 /// Type inference. Try to infer the type arguments from `method',
2392 /// which is invoked with the arguments `arguments'. This is used
2393 /// when resolving an Invocation or a DelegateInvocation and the user
2394 /// did not explicitly specify type arguments.
2396 public static bool InferTypeArguments (ArrayList arguments,
2397 ref MethodBase method)
2399 if (!TypeManager.IsGenericMethod (method))
2403 if (arguments != null)
2404 arg_count = arguments.Count;
2408 ParameterData pd = TypeManager.GetParameterData (method);
2409 if (arg_count != pd.Count)
2412 Type[] method_args = method.GetGenericArguments ();
2414 bool is_open = false;
2415 for (int i = 0; i < method_args.Length; i++) {
2416 if (method_args [i].IsGenericParameter) {
2422 // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
2424 return !TypeManager.IsGenericMethodDefinition (method);
2426 Type[] inferred_types = new Type [method_args.Length];
2428 Type[] param_types = new Type [pd.Count];
2429 Type[] arg_types = new Type [pd.Count];
2431 for (int i = 0; i < arg_count; i++) {
2432 param_types [i] = pd.ParameterType (i);
2434 Argument a = (Argument) arguments [i];
2435 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2436 (a.Expr is AnonymousMethodExpression))
2439 arg_types [i] = a.Type;
2442 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2445 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2452 public static bool InferTypeArguments (ParameterData apd,
2453 ref MethodBase method)
2455 if (!TypeManager.IsGenericMethod (method))
2458 ParameterData pd = TypeManager.GetParameterData (method);
2459 if (apd.Count != pd.Count)
2462 Type[] method_args = method.GetGenericArguments ();
2463 Type[] inferred_types = new Type [method_args.Length];
2465 Type[] param_types = new Type [pd.Count];
2466 Type[] arg_types = new Type [pd.Count];
2468 for (int i = 0; i < apd.Count; i++) {
2469 param_types [i] = pd.ParameterType (i);
2470 arg_types [i] = apd.ParameterType (i);
2473 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2476 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2481 public abstract class Nullable
2483 public sealed class NullableInfo
2485 public readonly Type Type;
2486 public readonly Type UnderlyingType;
2487 public readonly MethodInfo HasValue;
2488 public readonly MethodInfo Value;
2489 public readonly ConstructorInfo Constructor;
2491 public NullableInfo (Type type)
2494 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2496 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2497 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2499 HasValue = has_value_pi.GetGetMethod (false);
2500 Value = value_pi.GetGetMethod (false);
2501 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2505 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
2510 LocalTemporary temp;
2513 protected Unwrap (Expression expr)
2516 this.loc = expr.Location;
2519 public static Unwrap Create (Expression expr, EmitContext ec)
2521 return new Unwrap (expr).Resolve (ec) as Unwrap;
2524 public override Expression DoResolve (EmitContext ec)
2526 expr = expr.Resolve (ec);
2530 temp = new LocalTemporary (expr.Type);
2532 info = new NullableInfo (expr.Type);
2533 type = info.UnderlyingType;
2534 eclass = expr.eclass;
2538 public override void Emit (EmitContext ec)
2540 AddressOf (ec, AddressOp.LoadStore);
2541 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2544 public void EmitCheck (EmitContext ec)
2546 AddressOf (ec, AddressOp.LoadStore);
2547 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2550 public void Store (EmitContext ec)
2555 void create_temp (EmitContext ec)
2557 if ((temp != null) && !has_temp) {
2564 public void AddressOf (EmitContext ec, AddressOp mode)
2568 temp.AddressOf (ec, AddressOp.LoadStore);
2570 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2573 public void Emit (EmitContext ec, bool leave_copy)
2586 public void EmitAssign (EmitContext ec, Expression source,
2587 bool leave_copy, bool prepare_for_load)
2589 InternalWrap wrap = new InternalWrap (source, info, loc);
2590 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
2593 protected class InternalWrap : Expression
2595 public Expression expr;
2596 public NullableInfo info;
2598 public InternalWrap (Expression expr, NullableInfo info, Location loc)
2605 eclass = ExprClass.Value;
2608 public override Expression DoResolve (EmitContext ec)
2613 public override void Emit (EmitContext ec)
2616 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2621 public class Wrap : Expression
2626 protected Wrap (Expression expr)
2629 this.loc = expr.Location;
2632 public static Wrap Create (Expression expr, EmitContext ec)
2634 return new Wrap (expr).Resolve (ec) as Wrap;
2637 public override Expression DoResolve (EmitContext ec)
2639 expr = expr.Resolve (ec);
2643 TypeExpr target_type = new NullableType (expr.Type, loc);
2644 target_type = target_type.ResolveAsTypeTerminal (ec, false);
2645 if (target_type == null)
2648 type = target_type.Type;
2649 info = new NullableInfo (type);
2650 eclass = ExprClass.Value;
2654 public override void Emit (EmitContext ec)
2657 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2661 public class NullableLiteral : NullLiteral, IMemoryLocation {
2662 public NullableLiteral (Type target_type, Location loc)
2665 this.type = target_type;
2667 eclass = ExprClass.Value;
2670 public override Expression DoResolve (EmitContext ec)
2675 public override void Emit (EmitContext ec)
2677 LocalTemporary value_target = new LocalTemporary (type);
2679 value_target.AddressOf (ec, AddressOp.Store);
2680 ec.ig.Emit (OpCodes.Initobj, type);
2681 value_target.Emit (ec);
2684 public void AddressOf (EmitContext ec, AddressOp Mode)
2686 LocalTemporary value_target = new LocalTemporary (type);
2688 value_target.AddressOf (ec, AddressOp.Store);
2689 ec.ig.Emit (OpCodes.Initobj, type);
2690 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2694 public abstract class Lifted : Expression, IMemoryLocation
2696 Expression expr, underlying, wrap, null_value;
2699 protected Lifted (Expression expr, Location loc)
2705 public override Expression DoResolve (EmitContext ec)
2707 expr = expr.Resolve (ec);
2711 unwrap = Unwrap.Create (expr, ec);
2715 underlying = ResolveUnderlying (unwrap, ec);
2716 if (underlying == null)
2719 wrap = Wrap.Create (underlying, ec);
2723 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2724 if (null_value == null)
2728 eclass = ExprClass.Value;
2732 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2734 public override void Emit (EmitContext ec)
2736 ILGenerator ig = ec.ig;
2737 Label is_null_label = ig.DefineLabel ();
2738 Label end_label = ig.DefineLabel ();
2740 unwrap.EmitCheck (ec);
2741 ig.Emit (OpCodes.Brfalse, is_null_label);
2744 ig.Emit (OpCodes.Br, end_label);
2746 ig.MarkLabel (is_null_label);
2747 null_value.Emit (ec);
2749 ig.MarkLabel (end_label);
2752 public void AddressOf (EmitContext ec, AddressOp mode)
2754 unwrap.AddressOf (ec, mode);
2758 public class LiftedConversion : Lifted
2760 public readonly bool IsUser;
2761 public readonly bool IsExplicit;
2762 public readonly Type TargetType;
2764 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2765 bool is_explicit, Location loc)
2768 this.IsUser = is_user;
2769 this.IsExplicit = is_explicit;
2770 this.TargetType = target_type;
2773 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2775 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2778 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2781 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2783 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2788 public class LiftedUnaryOperator : Lifted
2790 public readonly Unary.Operator Oper;
2792 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2798 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2800 return new Unary (Oper, unwrap, loc);
2804 public class LiftedConditional : Lifted
2806 Expression true_expr, false_expr;
2808 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2812 this.true_expr = true_expr;
2813 this.false_expr = false_expr;
2816 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2818 return new Conditional (unwrap, true_expr, false_expr);
2822 public class LiftedBinaryOperator : Expression
2824 public readonly Binary.Operator Oper;
2826 Expression left, right, original_left, original_right;
2827 Expression underlying, null_value, bool_wrap;
2828 Unwrap left_unwrap, right_unwrap;
2829 bool is_equality, is_comparision, is_boolean;
2831 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2835 this.left = original_left = left;
2836 this.right = original_right = right;
2840 public override Expression DoResolve (EmitContext ec)
2842 if (TypeManager.IsNullableType (left.Type)) {
2843 left = left_unwrap = Unwrap.Create (left, ec);
2848 if (TypeManager.IsNullableType (right.Type)) {
2849 right = right_unwrap = Unwrap.Create (right, ec);
2854 if ((Oper == Binary.Operator.LogicalAnd) ||
2855 (Oper == Binary.Operator.LogicalOr)) {
2856 Binary.Error_OperatorCannotBeApplied (
2857 loc, Binary.OperName (Oper),
2858 original_left.GetSignatureForError (),
2859 original_right.GetSignatureForError ());
2863 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
2864 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2865 Expression empty = new EmptyExpression (TypeManager.bool_type);
2866 bool_wrap = Wrap.Create (empty, ec);
2867 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2869 type = bool_wrap.Type;
2871 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2872 if (!(left is NullLiteral) && !(right is NullLiteral)) {
2873 underlying = new Binary (Oper, left, right).Resolve (ec);
2874 if (underlying == null)
2878 type = TypeManager.bool_type;
2880 } else if ((Oper == Binary.Operator.LessThan) ||
2881 (Oper == Binary.Operator.GreaterThan) ||
2882 (Oper == Binary.Operator.LessThanOrEqual) ||
2883 (Oper == Binary.Operator.GreaterThanOrEqual)) {
2884 underlying = new Binary (Oper, left, right).Resolve (ec);
2885 if (underlying == null)
2888 type = TypeManager.bool_type;
2889 is_comparision = true;
2891 underlying = new Binary (Oper, left, right).Resolve (ec);
2892 if (underlying == null)
2895 underlying = Wrap.Create (underlying, ec);
2896 if (underlying == null)
2899 type = underlying.Type;
2900 null_value = new NullableLiteral (type, loc).Resolve (ec);
2903 eclass = ExprClass.Value;
2907 void EmitBoolean (EmitContext ec)
2909 ILGenerator ig = ec.ig;
2911 Label left_is_null_label = ig.DefineLabel ();
2912 Label right_is_null_label = ig.DefineLabel ();
2913 Label is_null_label = ig.DefineLabel ();
2914 Label wrap_label = ig.DefineLabel ();
2915 Label end_label = ig.DefineLabel ();
2917 if (left_unwrap != null) {
2918 left_unwrap.EmitCheck (ec);
2919 ig.Emit (OpCodes.Brfalse, left_is_null_label);
2923 ig.Emit (OpCodes.Dup);
2924 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2925 ig.Emit (OpCodes.Brtrue, wrap_label);
2927 ig.Emit (OpCodes.Brfalse, wrap_label);
2929 if (right_unwrap != null) {
2930 right_unwrap.EmitCheck (ec);
2931 ig.Emit (OpCodes.Brfalse, right_is_null_label);
2934 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
2935 ig.Emit (OpCodes.Pop);
2938 if (Oper == Binary.Operator.BitwiseOr)
2939 ig.Emit (OpCodes.Or);
2940 else if (Oper == Binary.Operator.BitwiseAnd)
2941 ig.Emit (OpCodes.And);
2942 ig.Emit (OpCodes.Br, wrap_label);
2944 ig.MarkLabel (left_is_null_label);
2945 if (right_unwrap != null) {
2946 right_unwrap.EmitCheck (ec);
2947 ig.Emit (OpCodes.Brfalse, is_null_label);
2951 ig.Emit (OpCodes.Dup);
2952 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2953 ig.Emit (OpCodes.Brtrue, wrap_label);
2955 ig.Emit (OpCodes.Brfalse, wrap_label);
2957 ig.MarkLabel (right_is_null_label);
2958 ig.Emit (OpCodes.Pop);
2959 ig.MarkLabel (is_null_label);
2960 null_value.Emit (ec);
2961 ig.Emit (OpCodes.Br, end_label);
2963 ig.MarkLabel (wrap_label);
2964 ig.Emit (OpCodes.Nop);
2965 bool_wrap.Emit (ec);
2966 ig.Emit (OpCodes.Nop);
2968 ig.MarkLabel (end_label);
2971 void EmitEquality (EmitContext ec)
2973 ILGenerator ig = ec.ig;
2975 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
2976 if (left is NullLiteral) {
2977 if (right_unwrap == null)
2978 throw new InternalErrorException ();
2979 right_unwrap.EmitCheck (ec);
2980 if (Oper == Binary.Operator.Equality) {
2981 ig.Emit (OpCodes.Ldc_I4_0);
2982 ig.Emit (OpCodes.Ceq);
2987 if (right is NullLiteral) {
2988 if (left_unwrap == null)
2989 throw new InternalErrorException ();
2990 left_unwrap.EmitCheck (ec);
2991 if (Oper == Binary.Operator.Equality) {
2992 ig.Emit (OpCodes.Ldc_I4_0);
2993 ig.Emit (OpCodes.Ceq);
2998 Label both_have_value_label = ig.DefineLabel ();
2999 Label end_label = ig.DefineLabel ();
3001 if (left_unwrap != null && right_unwrap != null) {
3002 Label dissimilar_label = ig.DefineLabel ();
3004 left_unwrap.EmitCheck (ec);
3005 ig.Emit (OpCodes.Dup);
3006 right_unwrap.EmitCheck (ec);
3007 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3009 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3012 if (Oper == Binary.Operator.Equality)
3013 ig.Emit (OpCodes.Ldc_I4_1);
3015 ig.Emit (OpCodes.Ldc_I4_0);
3016 ig.Emit (OpCodes.Br, end_label);
3018 ig.MarkLabel (dissimilar_label);
3019 ig.Emit (OpCodes.Pop);
3020 } else if (left_unwrap != null) {
3021 left_unwrap.EmitCheck (ec);
3022 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3023 } else if (right_unwrap != null) {
3024 right_unwrap.EmitCheck (ec);
3025 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3027 throw new InternalErrorException ("shouldn't get here");
3030 // one is null while the other isn't
3031 if (Oper == Binary.Operator.Equality)
3032 ig.Emit (OpCodes.Ldc_I4_0);
3034 ig.Emit (OpCodes.Ldc_I4_1);
3035 ig.Emit (OpCodes.Br, end_label);
3037 ig.MarkLabel (both_have_value_label);
3038 underlying.Emit (ec);
3040 ig.MarkLabel (end_label);
3043 void EmitComparision (EmitContext ec)
3045 ILGenerator ig = ec.ig;
3047 Label is_null_label = ig.DefineLabel ();
3048 Label end_label = ig.DefineLabel ();
3050 if (left_unwrap != null) {
3051 left_unwrap.EmitCheck (ec);
3052 ig.Emit (OpCodes.Brfalse, is_null_label);
3055 if (right_unwrap != null) {
3056 right_unwrap.EmitCheck (ec);
3057 ig.Emit (OpCodes.Brfalse, is_null_label);
3060 underlying.Emit (ec);
3061 ig.Emit (OpCodes.Br, end_label);
3063 ig.MarkLabel (is_null_label);
3064 ig.Emit (OpCodes.Ldc_I4_0);
3066 ig.MarkLabel (end_label);
3069 public override void Emit (EmitContext ec)
3071 if (left_unwrap != null)
3072 left_unwrap.Store (ec);
3073 if (right_unwrap != null)
3074 right_unwrap.Store (ec);
3079 } else if (is_equality) {
3082 } else if (is_comparision) {
3083 EmitComparision (ec);
3087 ILGenerator ig = ec.ig;
3089 Label is_null_label = ig.DefineLabel ();
3090 Label end_label = ig.DefineLabel ();
3092 if (left_unwrap != null) {
3093 left_unwrap.EmitCheck (ec);
3094 ig.Emit (OpCodes.Brfalse, is_null_label);
3097 if (right_unwrap != null) {
3098 right_unwrap.EmitCheck (ec);
3099 ig.Emit (OpCodes.Brfalse, is_null_label);
3102 underlying.Emit (ec);
3103 ig.Emit (OpCodes.Br, end_label);
3105 ig.MarkLabel (is_null_label);
3106 null_value.Emit (ec);
3108 ig.MarkLabel (end_label);
3112 public class OperatorTrueOrFalse : Expression
3114 public readonly bool IsTrue;
3119 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3121 this.IsTrue = is_true;
3126 public override Expression DoResolve (EmitContext ec)
3128 unwrap = Unwrap.Create (expr, ec);
3132 if (unwrap.Type != TypeManager.bool_type)
3135 type = TypeManager.bool_type;
3136 eclass = ExprClass.Value;
3140 public override void Emit (EmitContext ec)
3142 ILGenerator ig = ec.ig;
3144 Label is_null_label = ig.DefineLabel ();
3145 Label end_label = ig.DefineLabel ();
3147 unwrap.EmitCheck (ec);
3148 ig.Emit (OpCodes.Brfalse, is_null_label);
3152 ig.Emit (OpCodes.Ldc_I4_0);
3153 ig.Emit (OpCodes.Ceq);
3155 ig.Emit (OpCodes.Br, end_label);
3157 ig.MarkLabel (is_null_label);
3158 ig.Emit (OpCodes.Ldc_I4_0);
3160 ig.MarkLabel (end_label);
3164 public class NullCoalescingOperator : Expression
3166 Expression left, right;
3170 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3176 eclass = ExprClass.Value;
3179 public override Expression DoResolve (EmitContext ec)
3184 left = left.Resolve (ec);
3188 right = right.Resolve (ec);
3192 Type ltype = left.Type, rtype = right.Type;
3194 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3195 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3199 if (TypeManager.IsNullableType (ltype)) {
3200 NullableInfo info = new NullableInfo (ltype);
3202 unwrap = Unwrap.Create (left, ec);
3206 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3214 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3220 Expression left_null = unwrap != null ? unwrap : left;
3221 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3229 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3233 public override void Emit (EmitContext ec)
3235 ILGenerator ig = ec.ig;
3237 Label is_null_label = ig.DefineLabel ();
3238 Label end_label = ig.DefineLabel ();
3240 if (unwrap != null) {
3241 unwrap.EmitCheck (ec);
3242 ig.Emit (OpCodes.Brfalse, is_null_label);
3245 ig.Emit (OpCodes.Br, end_label);
3247 ig.MarkLabel (is_null_label);
3250 ig.MarkLabel (end_label);
3253 ig.Emit (OpCodes.Dup);
3254 ig.Emit (OpCodes.Brtrue, end_label);
3256 ig.MarkLabel (is_null_label);
3258 ig.Emit (OpCodes.Pop);
3261 ig.MarkLabel (end_label);
3266 public class LiftedUnaryMutator : ExpressionStatement
3268 public readonly UnaryMutator.Mode Mode;
3269 Expression expr, null_value;
3270 UnaryMutator underlying;
3273 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3279 eclass = ExprClass.Value;
3282 public override Expression DoResolve (EmitContext ec)
3284 expr = expr.Resolve (ec);
3288 unwrap = Unwrap.Create (expr, ec);
3292 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3293 if (underlying == null)
3296 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3297 if (null_value == null)
3304 void DoEmit (EmitContext ec, bool is_expr)
3306 ILGenerator ig = ec.ig;
3307 Label is_null_label = ig.DefineLabel ();
3308 Label end_label = ig.DefineLabel ();
3310 unwrap.EmitCheck (ec);
3311 ig.Emit (OpCodes.Brfalse, is_null_label);
3314 underlying.Emit (ec);
3316 underlying.EmitStatement (ec);
3317 ig.Emit (OpCodes.Br, end_label);
3319 ig.MarkLabel (is_null_label);
3321 null_value.Emit (ec);
3323 ig.MarkLabel (end_label);
3326 public override void Emit (EmitContext ec)
3331 public override void EmitStatement (EmitContext ec)