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)
904 if (constraints == null)
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;
1252 if (te.Type.IsSealed && te.Type.IsAbstract) {
1253 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1254 te.GetSignatureForError ());
1257 if (te.Type.IsPointer) {
1258 Report.Error (306, Location, "The type `{0}' may not be used " +
1259 "as a type argument", TypeManager.CSharpName (te.Type));
1263 if (te.Type == TypeManager.void_type) {
1264 Expression.Error_VoidInvalidInTheContext (Location);
1268 atypes [i] = te.Type;
1274 public class TypeParameterName : SimpleName
1276 Attributes attributes;
1278 public TypeParameterName (string name, Attributes attrs, Location loc)
1284 public Attributes OptAttributes {
1292 /// An instantiation of a generic type.
1294 public class ConstructedType : TypeExpr {
1296 FullNamedExpression name;
1298 Type[] gen_params, atypes;
1302 /// Instantiate the generic type `fname' with the type arguments `args'.
1304 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1310 eclass = ExprClass.Type;
1311 full_name = name + "<" + args.ToString () + ">";
1314 protected ConstructedType (TypeArguments args, Location l)
1319 eclass = ExprClass.Type;
1322 protected ConstructedType (TypeParameter[] type_params, Location l)
1326 args = new TypeArguments (l);
1327 foreach (TypeParameter type_param in type_params)
1328 args.Add (new TypeParameterExpr (type_param, l));
1330 eclass = ExprClass.Type;
1334 /// This is used to construct the `this' type inside a generic type definition.
1336 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1337 : this (type_params, l)
1339 gt = t.GetGenericTypeDefinition ();
1341 this.name = new TypeExpression (gt, l);
1342 full_name = gt.FullName + "<" + args.ToString () + ">";
1346 /// Instantiate the generic type `t' with the type arguments `args'.
1347 /// Use this constructor if you already know the fully resolved
1350 public ConstructedType (Type t, TypeArguments args, Location l)
1353 gt = t.GetGenericTypeDefinition ();
1355 this.name = new TypeExpression (gt, l);
1356 full_name = gt.FullName + "<" + args.ToString () + ">";
1359 public TypeArguments TypeArguments {
1360 get { return args; }
1363 public override string GetSignatureForError ()
1365 return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1368 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1370 if (!ResolveConstructedType (ec))
1377 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1378 /// after fully resolving the constructed type.
1380 public bool CheckConstraints (IResolveContext ec)
1382 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1386 /// Resolve the constructed type, but don't check the constraints.
1388 public bool ResolveConstructedType (IResolveContext ec)
1392 // If we already know the fully resolved generic type.
1394 return DoResolveType (ec);
1400 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1404 num_args = TypeManager.GetNumberOfTypeArguments (t);
1405 if (num_args == 0) {
1406 Report.Error (308, loc,
1407 "The non-generic type `{0}' cannot " +
1408 "be used with type arguments.",
1409 TypeManager.CSharpName (t));
1413 gt = t.GetGenericTypeDefinition ();
1414 return DoResolveType (ec);
1417 bool DoResolveType (IResolveContext ec)
1420 // Resolve the arguments.
1422 if (args.Resolve (ec) == false)
1425 gen_params = gt.GetGenericArguments ();
1426 atypes = args.Arguments;
1428 if (atypes.Length != gen_params.Length) {
1429 Report.Error (305, loc,
1430 "Using the generic type `{0}' " +
1431 "requires {1} type arguments",
1432 TypeManager.CSharpName (gt),
1433 gen_params.Length.ToString ());
1438 // Now bind the parameters.
1440 type = gt.MakeGenericType (atypes);
1444 public Expression GetSimpleName (EmitContext ec)
1449 public override bool CheckAccessLevel (DeclSpace ds)
1451 return ds.CheckAccessLevel (gt);
1454 public override bool AsAccessible (DeclSpace ds, int flags)
1456 return ds.AsAccessible (gt, flags);
1459 public override bool IsClass {
1460 get { return gt.IsClass; }
1463 public override bool IsValueType {
1464 get { return gt.IsValueType; }
1467 public override bool IsInterface {
1468 get { return gt.IsInterface; }
1471 public override bool IsSealed {
1472 get { return gt.IsSealed; }
1475 public override bool Equals (object obj)
1477 ConstructedType cobj = obj as ConstructedType;
1481 if ((type == null) || (cobj.type == null))
1484 return type == cobj.type;
1487 public override int GetHashCode ()
1489 return base.GetHashCode ();
1492 public override string Name {
1498 public override string FullName {
1505 public abstract class ConstraintChecker
1507 protected readonly Type[] gen_params;
1508 protected readonly Type[] atypes;
1509 protected readonly Location loc;
1511 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1513 this.gen_params = gen_params;
1514 this.atypes = atypes;
1519 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1520 /// after fully resolving the constructed type.
1522 public bool CheckConstraints (IResolveContext ec)
1524 for (int i = 0; i < gen_params.Length; i++) {
1525 if (!CheckConstraints (ec, i))
1532 protected bool CheckConstraints (IResolveContext ec, int index)
1534 Type atype = atypes [index];
1535 Type ptype = gen_params [index];
1540 Expression aexpr = new EmptyExpression (atype);
1542 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1546 bool is_class, is_struct;
1547 if (atype.IsGenericParameter) {
1548 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1550 if (agc is Constraints)
1551 ((Constraints) agc).Resolve (ec);
1552 is_class = agc.HasReferenceTypeConstraint;
1553 is_struct = agc.HasValueTypeConstraint;
1555 is_class = is_struct = false;
1560 if (!atype.IsGenericType)
1562 is_class = atype.IsClass || atype.IsInterface;
1563 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1567 // First, check the `class' and `struct' constraints.
1569 if (gc.HasReferenceTypeConstraint && !is_class) {
1570 Report.Error (452, loc, "The type `{0}' must be " +
1571 "a reference type in order to use it " +
1572 "as type parameter `{1}' in the " +
1573 "generic type or method `{2}'.",
1574 TypeManager.CSharpName (atype),
1575 TypeManager.CSharpName (ptype),
1576 GetSignatureForError ());
1578 } else if (gc.HasValueTypeConstraint && !is_struct) {
1579 Report.Error (453, loc, "The type `{0}' must be a " +
1580 "non-nullable value type in order to use it " +
1581 "as type parameter `{1}' in the " +
1582 "generic type or method `{2}'.",
1583 TypeManager.CSharpName (atype),
1584 TypeManager.CSharpName (ptype),
1585 GetSignatureForError ());
1590 // The class constraint comes next.
1592 if (gc.HasClassConstraint) {
1593 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1598 // Now, check the interface constraints.
1600 if (gc.InterfaceConstraints != null) {
1601 foreach (Type it in gc.InterfaceConstraints) {
1602 if (!CheckConstraint (ec, ptype, aexpr, it))
1608 // Finally, check the constructor constraint.
1611 if (!gc.HasConstructorConstraint)
1614 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1617 if (HasDefaultConstructor (ec.DeclContainer.TypeBuilder, atype))
1620 Report_SymbolRelatedToPreviousError ();
1621 Report.SymbolRelatedToPreviousError (atype);
1622 Report.Error (310, loc, "The type `{0}' must have a public " +
1623 "parameterless constructor in order to use it " +
1624 "as parameter `{1}' in the generic type or " +
1626 TypeManager.CSharpName (atype),
1627 TypeManager.CSharpName (ptype),
1628 GetSignatureForError ());
1632 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1635 if (TypeManager.HasGenericArguments (ctype)) {
1636 Type[] types = TypeManager.GetTypeArguments (ctype);
1638 TypeArguments new_args = new TypeArguments (loc);
1640 for (int i = 0; i < types.Length; i++) {
1643 if (t.IsGenericParameter) {
1644 int pos = t.GenericParameterPosition;
1647 new_args.Add (new TypeExpression (t, loc));
1650 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1651 if (ct.ResolveAsTypeStep (ec, false) == null)
1654 } else if (ctype.IsGenericParameter) {
1655 int pos = ctype.GenericParameterPosition;
1656 ctype = atypes [pos];
1659 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1662 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1666 bool HasDefaultConstructor (Type containerType, Type atype)
1668 if (atype.IsAbstract)
1672 atype = TypeManager.DropGenericTypeArguments (atype);
1673 if (atype is TypeBuilder) {
1674 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1675 if (tc.InstanceConstructors == null) {
1676 atype = atype.BaseType;
1680 foreach (Constructor c in tc.InstanceConstructors) {
1681 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1683 if ((c.Parameters.FixedParameters != null) &&
1684 (c.Parameters.FixedParameters.Length != 0))
1686 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1693 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1695 return tparam.HasConstructorConstraint;
1697 MemberList list = TypeManager.FindMembers (
1698 atype, MemberTypes.Constructor,
1699 BindingFlags.Public | BindingFlags.Instance |
1700 BindingFlags.DeclaredOnly, null, null);
1702 if (atype.IsAbstract || (list == null))
1705 foreach (MethodBase mb in list) {
1706 ParameterData pd = TypeManager.GetParameterData (mb);
1707 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1714 protected abstract string GetSignatureForError ();
1715 protected abstract void Report_SymbolRelatedToPreviousError ();
1717 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1719 Report_SymbolRelatedToPreviousError ();
1720 Report.SymbolRelatedToPreviousError (atype);
1721 Report.Error (309, loc,
1722 "The type `{0}' must be convertible to `{1}' in order to " +
1723 "use it as parameter `{2}' in the generic type or method `{3}'",
1724 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1725 TypeManager.CSharpName (ptype), GetSignatureForError ());
1728 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1729 MethodBase instantiated, Location loc)
1731 MethodConstraintChecker checker = new MethodConstraintChecker (
1732 definition, definition.GetGenericArguments (),
1733 instantiated.GetGenericArguments (), loc);
1735 return checker.CheckConstraints (ec);
1738 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1739 Type[] atypes, Location loc)
1741 TypeConstraintChecker checker = new TypeConstraintChecker (
1742 gt, gen_params, atypes, loc);
1744 return checker.CheckConstraints (ec);
1747 protected class MethodConstraintChecker : ConstraintChecker
1749 MethodBase definition;
1751 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1752 Type[] atypes, Location loc)
1753 : base (gen_params, atypes, loc)
1755 this.definition = definition;
1758 protected override string GetSignatureForError ()
1760 return TypeManager.CSharpSignature (definition);
1763 protected override void Report_SymbolRelatedToPreviousError ()
1765 Report.SymbolRelatedToPreviousError (definition);
1769 protected class TypeConstraintChecker : ConstraintChecker
1773 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1775 : base (gen_params, atypes, loc)
1780 protected override string GetSignatureForError ()
1782 return TypeManager.CSharpName (gt);
1785 protected override void Report_SymbolRelatedToPreviousError ()
1787 Report.SymbolRelatedToPreviousError (gt);
1793 /// A generic method definition.
1795 public class GenericMethod : DeclSpace
1797 Expression return_type;
1798 Parameters parameters;
1800 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1801 Expression return_type, Parameters parameters)
1802 : base (ns, parent, name, null)
1804 this.return_type = return_type;
1805 this.parameters = parameters;
1808 public override TypeBuilder DefineType ()
1810 throw new Exception ();
1813 public override bool Define ()
1815 for (int i = 0; i < TypeParameters.Length; i++)
1816 if (!TypeParameters [i].Resolve (this))
1823 /// Define and resolve the type parameters.
1824 /// We're called from Method.Define().
1826 public bool Define (MethodBuilder mb, ToplevelBlock block)
1828 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1829 string[] snames = new string [names.Length];
1830 for (int i = 0; i < names.Length; i++) {
1831 string type_argument_name = names[i].Name;
1832 Parameter p = parameters.GetParameterByName (type_argument_name);
1834 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1837 if (block != null) {
1838 LocalInfo li = (LocalInfo)block.Variables[type_argument_name];
1840 Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
1844 snames[i] = type_argument_name;
1847 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1848 for (int i = 0; i < TypeParameters.Length; i++)
1849 TypeParameters [i].Define (gen_params [i]);
1854 for (int i = 0; i < TypeParameters.Length; i++) {
1855 if (!TypeParameters [i].ResolveType (this))
1862 static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1864 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1865 name, collisionWith);
1869 /// We're called from MethodData.Define() after creating the MethodBuilder.
1871 public bool DefineType (EmitContext ec, MethodBuilder mb,
1872 MethodInfo implementing, bool is_override)
1874 for (int i = 0; i < TypeParameters.Length; i++)
1875 if (!TypeParameters [i].DefineType (
1876 ec, mb, implementing, is_override))
1880 foreach (Parameter p in parameters.FixedParameters){
1881 if (!p.Resolve (ec))
1884 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1890 public void EmitAttributes ()
1892 for (int i = 0; i < TypeParameters.Length; i++)
1893 TypeParameters [i].EmitAttributes ();
1895 if (OptAttributes != null)
1896 OptAttributes.Emit ();
1899 public override bool DefineMembers ()
1904 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1905 MemberFilter filter, object criteria)
1907 throw new Exception ();
1910 public override MemberCache MemberCache {
1916 public override AttributeTargets AttributeTargets {
1918 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1922 public override string DocCommentHeader {
1923 get { return "M:"; }
1926 public new void VerifyClsCompliance ()
1928 foreach (TypeParameter tp in TypeParameters) {
1929 if (tp.Constraints == null)
1932 tp.Constraints.VerifyClsCompliance ();
1937 public class DefaultValueExpression : Expression
1941 public DefaultValueExpression (Expression expr, Location loc)
1947 public override Expression DoResolve (EmitContext ec)
1949 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
1955 if (type == TypeManager.void_type) {
1956 Error_VoidInvalidInTheContext (loc);
1960 if (type.IsGenericParameter)
1962 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints(type);
1963 if (constraints != null && constraints.IsReferenceType)
1964 return new NullDefault (new NullLiteral (Location), type);
1968 Constant c = New.Constantify(type);
1970 return new NullDefault (c, type);
1972 if (!TypeManager.IsValueType (type))
1973 return new NullDefault (new NullLiteral (Location), type);
1975 eclass = ExprClass.Variable;
1979 public override void Emit (EmitContext ec)
1981 LocalTemporary temp_storage = new LocalTemporary(type);
1983 temp_storage.AddressOf(ec, AddressOp.LoadStore);
1984 ec.ig.Emit(OpCodes.Initobj, type);
1985 temp_storage.Emit(ec);
1989 public class NullableType : TypeExpr
1991 Expression underlying;
1993 public NullableType (Expression underlying, Location l)
1995 this.underlying = underlying;
1998 eclass = ExprClass.Type;
2001 public NullableType (Type type, Location loc)
2002 : this (new TypeExpression (type, loc), loc)
2005 public override string Name {
2006 get { return underlying.ToString () + "?"; }
2009 public override string FullName {
2010 get { return underlying.ToString () + "?"; }
2013 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2015 TypeArguments args = new TypeArguments (loc);
2016 args.Add (underlying);
2018 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2019 return ctype.ResolveAsTypeTerminal (ec, false);
2023 public partial class TypeManager
2026 // A list of core types that the compiler requires or uses
2028 static public Type activator_type;
2029 static public Type generic_ilist_type;
2030 static public Type generic_icollection_type;
2031 static public Type generic_ienumerator_type;
2032 static public Type generic_ienumerable_type;
2033 static public Type generic_nullable_type;
2036 // These methods are called by code generated by the compiler
2038 static public MethodInfo activator_create_instance;
2040 static void InitGenericCoreTypes ()
2042 activator_type = CoreLookupType ("System", "Activator");
2044 generic_ilist_type = CoreLookupType (
2045 "System.Collections.Generic", "IList", 1);
2046 generic_icollection_type = CoreLookupType (
2047 "System.Collections.Generic", "ICollection", 1);
2048 generic_ienumerator_type = CoreLookupType (
2049 "System.Collections.Generic", "IEnumerator", 1);
2050 generic_ienumerable_type = CoreLookupType (
2051 "System.Collections.Generic", "IEnumerable", 1);
2052 generic_nullable_type = CoreLookupType (
2053 "System", "Nullable", 1);
2056 static void InitGenericCodeHelpers ()
2059 Type [] type_arg = { type_type };
2060 activator_create_instance = GetMethod (
2061 activator_type, "CreateInstance", type_arg);
2064 static Type CoreLookupType (string ns, string name, int arity)
2066 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2069 public static TypeContainer LookupGenericTypeContainer (Type t)
2071 t = DropGenericTypeArguments (t);
2072 return LookupTypeContainer (t);
2075 public static GenericConstraints GetTypeParameterConstraints (Type t)
2077 if (!t.IsGenericParameter)
2078 throw new InvalidOperationException ();
2080 TypeParameter tparam = LookupTypeParameter (t);
2082 return tparam.GenericConstraints;
2084 return ReflectionConstraints.GetConstraints (t);
2088 /// Check whether `a' and `b' may become equal generic types.
2089 /// The algorithm to do that is a little bit complicated.
2091 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
2092 Type[] method_infered)
2094 if (a.IsGenericParameter) {
2096 // If a is an array of a's type, they may never
2100 b = b.GetElementType ();
2106 // If b is a generic parameter or an actual type,
2107 // they may become equal:
2109 // class X<T,U> : I<T>, I<U>
2110 // class X<T> : I<T>, I<float>
2112 if (b.IsGenericParameter || !b.IsGenericType) {
2113 int pos = a.GenericParameterPosition;
2114 Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
2115 if (args [pos] == null) {
2120 return args [pos] == a;
2124 // We're now comparing a type parameter with a
2125 // generic instance. They may become equal unless
2126 // the type parameter appears anywhere in the
2127 // generic instance:
2129 // class X<T,U> : I<T>, I<X<U>>
2130 // -> error because you could instanciate it as
2133 // class X<T> : I<T>, I<X<T>> -> ok
2136 Type[] bargs = GetTypeArguments (b);
2137 for (int i = 0; i < bargs.Length; i++) {
2138 if (a.Equals (bargs [i]))
2145 if (b.IsGenericParameter)
2146 return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
2149 // At this point, neither a nor b are a type parameter.
2151 // If one of them is a generic instance, let
2152 // MayBecomeEqualGenericInstances() compare them (if the
2153 // other one is not a generic instance, they can never
2157 if (a.IsGenericType || b.IsGenericType)
2158 return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
2161 // If both of them are arrays.
2164 if (a.IsArray && b.IsArray) {
2165 if (a.GetArrayRank () != b.GetArrayRank ())
2168 a = a.GetElementType ();
2169 b = b.GetElementType ();
2171 return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
2175 // Ok, two ordinary types.
2178 return a.Equals (b);
2182 // Checks whether two generic instances may become equal for some
2183 // particular instantiation (26.3.1).
2185 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2186 Type[] class_infered,
2187 Type[] method_infered)
2189 if (!a.IsGenericType || !b.IsGenericType)
2191 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2194 return MayBecomeEqualGenericInstances (
2195 GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
2198 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2199 Type[] class_infered,
2200 Type[] method_infered)
2202 if (aargs.Length != bargs.Length)
2205 for (int i = 0; i < aargs.Length; i++) {
2206 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
2217 static bool InferType (Type pt, Type at, Type[] infered)
2219 if (pt.IsGenericParameter) {
2220 if (pt.DeclaringMethod == null)
2223 int pos = pt.GenericParameterPosition;
2225 if (infered [pos] == null) {
2230 if (infered [pos] != at)
2236 if (!pt.ContainsGenericParameters) {
2237 if (at.ContainsGenericParameters)
2238 return InferType (at, pt, infered);
2245 if (at.GetArrayRank () != pt.GetArrayRank ())
2248 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2251 if (!pt.IsGenericType)
2254 Type gt = pt.GetGenericTypeDefinition ();
2255 if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
2256 (gt != generic_ienumerable_type))
2259 Type[] args = GetTypeArguments (pt);
2260 return InferType (args [0], at.GetElementType (), infered);
2265 (pt.GetArrayRank () != at.GetArrayRank ()))
2268 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2271 if (pt.IsByRef && at.IsByRef)
2272 return InferType (pt.GetElementType (), at.GetElementType (), infered);
2273 ArrayList list = new ArrayList ();
2274 if (at.IsGenericType)
2276 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2279 list.AddRange (TypeManager.GetInterfaces (at));
2281 bool found_one = false;
2283 foreach (Type type in list) {
2284 if (!type.IsGenericType)
2287 Type[] infered_types = new Type [infered.Length];
2289 if (!InferGenericInstance (pt, type, infered_types))
2292 for (int i = 0; i < infered_types.Length; i++) {
2293 if (infered [i] == null) {
2294 infered [i] = infered_types [i];
2298 if (infered [i] != infered_types [i])
2308 static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
2310 Type[] at_args = at.GetGenericArguments ();
2311 Type[] pt_args = pt.GetGenericArguments ();
2313 if (at_args.Length != pt_args.Length)
2316 for (int i = 0; i < at_args.Length; i++) {
2317 if (!InferType (pt_args [i], at_args [i], infered_types))
2321 for (int i = 0; i < infered_types.Length; i++) {
2322 if (infered_types [i] == null)
2330 /// Type inference. Try to infer the type arguments from the params method
2331 /// `method', which is invoked with the arguments `arguments'. This is used
2332 /// when resolving an Invocation or a DelegateInvocation and the user
2333 /// did not explicitly specify type arguments.
2335 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2336 ref MethodBase method)
2338 if (!TypeManager.IsGenericMethod (method))
2341 // if there are no arguments, there's no way to infer the type-arguments
2342 if (arguments == null || arguments.Count == 0)
2345 ParameterData pd = TypeManager.GetParameterData (method);
2346 int pd_count = pd.Count;
2347 int arg_count = arguments.Count;
2352 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2355 if (pd_count - 1 > arg_count)
2358 Type[] method_args = method.GetGenericArguments ();
2359 Type[] infered_types = new Type [method_args.Length];
2362 // If we have come this far, the case which
2363 // remains is when the number of parameters is
2364 // less than or equal to the argument count.
2366 for (int i = 0; i < pd_count - 1; ++i) {
2367 Argument a = (Argument) arguments [i];
2369 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2372 Type pt = pd.ParameterType (i);
2375 if (!InferType (pt, at, infered_types))
2379 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2381 for (int i = pd_count - 1; i < arg_count; i++) {
2382 Argument a = (Argument) arguments [i];
2384 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2387 if (!InferType (element_type, a.Type, infered_types))
2391 for (int i = 0; i < infered_types.Length; i++)
2392 if (infered_types [i] == null)
2395 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2399 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2400 Type[] infered_types)
2402 if (infered_types == null)
2405 for (int i = 0; i < arg_types.Length; i++) {
2406 if (arg_types [i] == null)
2409 if (!InferType (param_types [i], arg_types [i], infered_types))
2413 for (int i = 0; i < infered_types.Length; i++)
2414 if (infered_types [i] == null)
2421 /// Type inference. Try to infer the type arguments from `method',
2422 /// which is invoked with the arguments `arguments'. This is used
2423 /// when resolving an Invocation or a DelegateInvocation and the user
2424 /// did not explicitly specify type arguments.
2426 public static bool InferTypeArguments (ArrayList arguments,
2427 ref MethodBase method)
2429 if (!TypeManager.IsGenericMethod (method))
2433 if (arguments != null)
2434 arg_count = arguments.Count;
2438 ParameterData pd = TypeManager.GetParameterData (method);
2439 if (arg_count != pd.Count)
2442 Type[] method_args = method.GetGenericArguments ();
2444 bool is_open = false;
2445 for (int i = 0; i < method_args.Length; i++) {
2446 if (method_args [i].IsGenericParameter) {
2452 // If none of the method parameters mention a generic parameter, we can't infer the generic parameters
2454 return !TypeManager.IsGenericMethodDefinition (method);
2456 Type[] infered_types = new Type [method_args.Length];
2458 Type[] param_types = new Type [pd.Count];
2459 Type[] arg_types = new Type [pd.Count];
2461 for (int i = 0; i < arg_count; i++) {
2462 param_types [i] = pd.ParameterType (i);
2464 Argument a = (Argument) arguments [i];
2465 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
2466 (a.Expr is AnonymousMethodExpression))
2469 arg_types [i] = a.Type;
2472 if (!InferTypeArguments (param_types, arg_types, infered_types))
2475 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2482 public static bool InferTypeArguments (ParameterData apd,
2483 ref MethodBase method)
2485 if (!TypeManager.IsGenericMethod (method))
2488 ParameterData pd = TypeManager.GetParameterData (method);
2489 if (apd.Count != pd.Count)
2492 Type[] method_args = method.GetGenericArguments ();
2493 Type[] infered_types = new Type [method_args.Length];
2495 Type[] param_types = new Type [pd.Count];
2496 Type[] arg_types = new Type [pd.Count];
2498 for (int i = 0; i < apd.Count; i++) {
2499 param_types [i] = pd.ParameterType (i);
2500 arg_types [i] = apd.ParameterType (i);
2503 if (!InferTypeArguments (param_types, arg_types, infered_types))
2506 method = ((MethodInfo)method).MakeGenericMethod (infered_types);
2511 public abstract class Nullable
2513 public sealed class NullableInfo
2515 public readonly Type Type;
2516 public readonly Type UnderlyingType;
2517 public readonly MethodInfo HasValue;
2518 public readonly MethodInfo Value;
2519 public readonly ConstructorInfo Constructor;
2521 public NullableInfo (Type type)
2524 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
2526 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
2527 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
2529 HasValue = has_value_pi.GetGetMethod (false);
2530 Value = value_pi.GetGetMethod (false);
2531 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
2535 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
2540 LocalTemporary temp;
2543 protected Unwrap (Expression expr)
2546 this.loc = expr.Location;
2549 public static Unwrap Create (Expression expr, EmitContext ec)
2551 return new Unwrap (expr).Resolve (ec) as Unwrap;
2554 public override Expression DoResolve (EmitContext ec)
2556 expr = expr.Resolve (ec);
2560 temp = new LocalTemporary (expr.Type);
2562 info = new NullableInfo (expr.Type);
2563 type = info.UnderlyingType;
2564 eclass = expr.eclass;
2568 public override void Emit (EmitContext ec)
2570 AddressOf (ec, AddressOp.LoadStore);
2571 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
2574 public void EmitCheck (EmitContext ec)
2576 AddressOf (ec, AddressOp.LoadStore);
2577 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
2580 public void Store (EmitContext ec)
2585 void create_temp (EmitContext ec)
2587 if ((temp != null) && !has_temp) {
2594 public void AddressOf (EmitContext ec, AddressOp mode)
2598 temp.AddressOf (ec, AddressOp.LoadStore);
2600 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
2603 public void Emit (EmitContext ec, bool leave_copy)
2616 public void EmitAssign (EmitContext ec, Expression source,
2617 bool leave_copy, bool prepare_for_load)
2619 InternalWrap wrap = new InternalWrap (source, info, loc);
2620 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
2623 protected class InternalWrap : Expression
2625 public Expression expr;
2626 public NullableInfo info;
2628 public InternalWrap (Expression expr, NullableInfo info, Location loc)
2635 eclass = ExprClass.Value;
2638 public override Expression DoResolve (EmitContext ec)
2643 public override void Emit (EmitContext ec)
2646 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2651 public class Wrap : Expression
2656 protected Wrap (Expression expr)
2659 this.loc = expr.Location;
2662 public static Wrap Create (Expression expr, EmitContext ec)
2664 return new Wrap (expr).Resolve (ec) as Wrap;
2667 public override Expression DoResolve (EmitContext ec)
2669 expr = expr.Resolve (ec);
2673 TypeExpr target_type = new NullableType (expr.Type, loc);
2674 target_type = target_type.ResolveAsTypeTerminal (ec, false);
2675 if (target_type == null)
2678 type = target_type.Type;
2679 info = new NullableInfo (type);
2680 eclass = ExprClass.Value;
2684 public override void Emit (EmitContext ec)
2687 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
2691 public class NullableLiteral : NullLiteral, IMemoryLocation {
2692 public NullableLiteral (Type target_type, Location loc)
2695 this.type = target_type;
2697 eclass = ExprClass.Value;
2700 public override Expression DoResolve (EmitContext ec)
2705 public override void Emit (EmitContext ec)
2707 LocalTemporary value_target = new LocalTemporary (type);
2709 value_target.AddressOf (ec, AddressOp.Store);
2710 ec.ig.Emit (OpCodes.Initobj, type);
2711 value_target.Emit (ec);
2714 public void AddressOf (EmitContext ec, AddressOp Mode)
2716 LocalTemporary value_target = new LocalTemporary (type);
2718 value_target.AddressOf (ec, AddressOp.Store);
2719 ec.ig.Emit (OpCodes.Initobj, type);
2720 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
2724 public abstract class Lifted : Expression, IMemoryLocation
2726 Expression expr, underlying, wrap, null_value;
2729 protected Lifted (Expression expr, Location loc)
2735 public override Expression DoResolve (EmitContext ec)
2737 expr = expr.Resolve (ec);
2741 unwrap = Unwrap.Create (expr, ec);
2745 underlying = ResolveUnderlying (unwrap, ec);
2746 if (underlying == null)
2749 wrap = Wrap.Create (underlying, ec);
2753 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
2754 if (null_value == null)
2758 eclass = ExprClass.Value;
2762 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
2764 public override void Emit (EmitContext ec)
2766 ILGenerator ig = ec.ig;
2767 Label is_null_label = ig.DefineLabel ();
2768 Label end_label = ig.DefineLabel ();
2770 unwrap.EmitCheck (ec);
2771 ig.Emit (OpCodes.Brfalse, is_null_label);
2774 ig.Emit (OpCodes.Br, end_label);
2776 ig.MarkLabel (is_null_label);
2777 null_value.Emit (ec);
2779 ig.MarkLabel (end_label);
2782 public void AddressOf (EmitContext ec, AddressOp mode)
2784 unwrap.AddressOf (ec, mode);
2788 public class LiftedConversion : Lifted
2790 public readonly bool IsUser;
2791 public readonly bool IsExplicit;
2792 public readonly Type TargetType;
2794 public LiftedConversion (Expression expr, Type target_type, bool is_user,
2795 bool is_explicit, Location loc)
2798 this.IsUser = is_user;
2799 this.IsExplicit = is_explicit;
2800 this.TargetType = target_type;
2803 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2805 Type type = TypeManager.GetTypeArguments (TargetType) [0];
2808 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
2811 return Convert.ExplicitConversion (ec, unwrap, type, loc);
2813 return Convert.ImplicitConversion (ec, unwrap, type, loc);
2818 public class LiftedUnaryOperator : Lifted
2820 public readonly Unary.Operator Oper;
2822 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
2828 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2830 return new Unary (Oper, unwrap, loc);
2834 public class LiftedConditional : Lifted
2836 Expression true_expr, false_expr;
2838 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
2842 this.true_expr = true_expr;
2843 this.false_expr = false_expr;
2846 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
2848 return new Conditional (unwrap, true_expr, false_expr);
2852 public class LiftedBinaryOperator : Expression
2854 public readonly Binary.Operator Oper;
2856 Expression left, right, original_left, original_right;
2857 Expression underlying, null_value, bool_wrap;
2858 Unwrap left_unwrap, right_unwrap;
2859 bool is_equality, is_comparision, is_boolean;
2861 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
2865 this.left = original_left = left;
2866 this.right = original_right = right;
2870 public override Expression DoResolve (EmitContext ec)
2872 if (TypeManager.IsNullableType (left.Type)) {
2873 left = left_unwrap = Unwrap.Create (left, ec);
2878 if (TypeManager.IsNullableType (right.Type)) {
2879 right = right_unwrap = Unwrap.Create (right, ec);
2884 if ((Oper == Binary.Operator.LogicalAnd) ||
2885 (Oper == Binary.Operator.LogicalOr)) {
2886 Binary.Error_OperatorCannotBeApplied (
2887 loc, Binary.OperName (Oper),
2888 original_left.GetSignatureForError (),
2889 original_right.GetSignatureForError ());
2893 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
2894 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
2895 Expression empty = new EmptyExpression (TypeManager.bool_type);
2896 bool_wrap = Wrap.Create (empty, ec);
2897 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
2899 type = bool_wrap.Type;
2901 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
2902 if (!(left is NullLiteral) && !(right is NullLiteral)) {
2903 underlying = new Binary (Oper, left, right).Resolve (ec);
2904 if (underlying == null)
2908 type = TypeManager.bool_type;
2910 } else if ((Oper == Binary.Operator.LessThan) ||
2911 (Oper == Binary.Operator.GreaterThan) ||
2912 (Oper == Binary.Operator.LessThanOrEqual) ||
2913 (Oper == Binary.Operator.GreaterThanOrEqual)) {
2914 underlying = new Binary (Oper, left, right).Resolve (ec);
2915 if (underlying == null)
2918 type = TypeManager.bool_type;
2919 is_comparision = true;
2921 underlying = new Binary (Oper, left, right).Resolve (ec);
2922 if (underlying == null)
2925 underlying = Wrap.Create (underlying, ec);
2926 if (underlying == null)
2929 type = underlying.Type;
2930 null_value = new NullableLiteral (type, loc).Resolve (ec);
2933 eclass = ExprClass.Value;
2937 void EmitBoolean (EmitContext ec)
2939 ILGenerator ig = ec.ig;
2941 Label left_is_null_label = ig.DefineLabel ();
2942 Label right_is_null_label = ig.DefineLabel ();
2943 Label is_null_label = ig.DefineLabel ();
2944 Label wrap_label = ig.DefineLabel ();
2945 Label end_label = ig.DefineLabel ();
2947 if (left_unwrap != null) {
2948 left_unwrap.EmitCheck (ec);
2949 ig.Emit (OpCodes.Brfalse, left_is_null_label);
2953 ig.Emit (OpCodes.Dup);
2954 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2955 ig.Emit (OpCodes.Brtrue, wrap_label);
2957 ig.Emit (OpCodes.Brfalse, wrap_label);
2959 if (right_unwrap != null) {
2960 right_unwrap.EmitCheck (ec);
2961 ig.Emit (OpCodes.Brfalse, right_is_null_label);
2964 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
2965 ig.Emit (OpCodes.Pop);
2968 if (Oper == Binary.Operator.BitwiseOr)
2969 ig.Emit (OpCodes.Or);
2970 else if (Oper == Binary.Operator.BitwiseAnd)
2971 ig.Emit (OpCodes.And);
2972 ig.Emit (OpCodes.Br, wrap_label);
2974 ig.MarkLabel (left_is_null_label);
2975 if (right_unwrap != null) {
2976 right_unwrap.EmitCheck (ec);
2977 ig.Emit (OpCodes.Brfalse, is_null_label);
2981 ig.Emit (OpCodes.Dup);
2982 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
2983 ig.Emit (OpCodes.Brtrue, wrap_label);
2985 ig.Emit (OpCodes.Brfalse, wrap_label);
2987 ig.MarkLabel (right_is_null_label);
2988 ig.Emit (OpCodes.Pop);
2989 ig.MarkLabel (is_null_label);
2990 null_value.Emit (ec);
2991 ig.Emit (OpCodes.Br, end_label);
2993 ig.MarkLabel (wrap_label);
2994 ig.Emit (OpCodes.Nop);
2995 bool_wrap.Emit (ec);
2996 ig.Emit (OpCodes.Nop);
2998 ig.MarkLabel (end_label);
3001 void EmitEquality (EmitContext ec)
3003 ILGenerator ig = ec.ig;
3005 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
3006 if (left is NullLiteral) {
3007 if (right_unwrap == null)
3008 throw new InternalErrorException ();
3009 right_unwrap.EmitCheck (ec);
3010 if (Oper == Binary.Operator.Equality) {
3011 ig.Emit (OpCodes.Ldc_I4_0);
3012 ig.Emit (OpCodes.Ceq);
3017 if (right is NullLiteral) {
3018 if (left_unwrap == null)
3019 throw new InternalErrorException ();
3020 left_unwrap.EmitCheck (ec);
3021 if (Oper == Binary.Operator.Equality) {
3022 ig.Emit (OpCodes.Ldc_I4_0);
3023 ig.Emit (OpCodes.Ceq);
3028 Label both_have_value_label = ig.DefineLabel ();
3029 Label end_label = ig.DefineLabel ();
3031 if (left_unwrap != null && right_unwrap != null) {
3032 Label dissimilar_label = ig.DefineLabel ();
3034 left_unwrap.EmitCheck (ec);
3035 ig.Emit (OpCodes.Dup);
3036 right_unwrap.EmitCheck (ec);
3037 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3039 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3042 if (Oper == Binary.Operator.Equality)
3043 ig.Emit (OpCodes.Ldc_I4_1);
3045 ig.Emit (OpCodes.Ldc_I4_0);
3046 ig.Emit (OpCodes.Br, end_label);
3048 ig.MarkLabel (dissimilar_label);
3049 ig.Emit (OpCodes.Pop);
3050 } else if (left_unwrap != null) {
3051 left_unwrap.EmitCheck (ec);
3052 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3053 } else if (right_unwrap != null) {
3054 right_unwrap.EmitCheck (ec);
3055 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3057 throw new InternalErrorException ("shouldn't get here");
3060 // one is null while the other isn't
3061 if (Oper == Binary.Operator.Equality)
3062 ig.Emit (OpCodes.Ldc_I4_0);
3064 ig.Emit (OpCodes.Ldc_I4_1);
3065 ig.Emit (OpCodes.Br, end_label);
3067 ig.MarkLabel (both_have_value_label);
3068 underlying.Emit (ec);
3070 ig.MarkLabel (end_label);
3073 void EmitComparision (EmitContext ec)
3075 ILGenerator ig = ec.ig;
3077 Label is_null_label = ig.DefineLabel ();
3078 Label end_label = ig.DefineLabel ();
3080 if (left_unwrap != null) {
3081 left_unwrap.EmitCheck (ec);
3082 ig.Emit (OpCodes.Brfalse, is_null_label);
3085 if (right_unwrap != null) {
3086 right_unwrap.EmitCheck (ec);
3087 ig.Emit (OpCodes.Brfalse, is_null_label);
3090 underlying.Emit (ec);
3091 ig.Emit (OpCodes.Br, end_label);
3093 ig.MarkLabel (is_null_label);
3094 ig.Emit (OpCodes.Ldc_I4_0);
3096 ig.MarkLabel (end_label);
3099 public override void Emit (EmitContext ec)
3101 if (left_unwrap != null)
3102 left_unwrap.Store (ec);
3103 if (right_unwrap != null)
3104 right_unwrap.Store (ec);
3109 } else if (is_equality) {
3112 } else if (is_comparision) {
3113 EmitComparision (ec);
3117 ILGenerator ig = ec.ig;
3119 Label is_null_label = ig.DefineLabel ();
3120 Label end_label = ig.DefineLabel ();
3122 if (left_unwrap != null) {
3123 left_unwrap.EmitCheck (ec);
3124 ig.Emit (OpCodes.Brfalse, is_null_label);
3127 if (right_unwrap != null) {
3128 right_unwrap.EmitCheck (ec);
3129 ig.Emit (OpCodes.Brfalse, is_null_label);
3132 underlying.Emit (ec);
3133 ig.Emit (OpCodes.Br, end_label);
3135 ig.MarkLabel (is_null_label);
3136 null_value.Emit (ec);
3138 ig.MarkLabel (end_label);
3142 public class OperatorTrueOrFalse : Expression
3144 public readonly bool IsTrue;
3149 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3151 this.IsTrue = is_true;
3156 public override Expression DoResolve (EmitContext ec)
3158 unwrap = Unwrap.Create (expr, ec);
3162 if (unwrap.Type != TypeManager.bool_type)
3165 type = TypeManager.bool_type;
3166 eclass = ExprClass.Value;
3170 public override void Emit (EmitContext ec)
3172 ILGenerator ig = ec.ig;
3174 Label is_null_label = ig.DefineLabel ();
3175 Label end_label = ig.DefineLabel ();
3177 unwrap.EmitCheck (ec);
3178 ig.Emit (OpCodes.Brfalse, is_null_label);
3182 ig.Emit (OpCodes.Ldc_I4_0);
3183 ig.Emit (OpCodes.Ceq);
3185 ig.Emit (OpCodes.Br, end_label);
3187 ig.MarkLabel (is_null_label);
3188 ig.Emit (OpCodes.Ldc_I4_0);
3190 ig.MarkLabel (end_label);
3194 public class NullCoalescingOperator : Expression
3196 Expression left, right;
3200 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3206 eclass = ExprClass.Value;
3209 public override Expression DoResolve (EmitContext ec)
3214 left = left.Resolve (ec);
3218 right = right.Resolve (ec);
3222 Type ltype = left.Type, rtype = right.Type;
3224 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3225 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3229 if (TypeManager.IsNullableType (ltype)) {
3230 NullableInfo info = new NullableInfo (ltype);
3232 unwrap = Unwrap.Create (left, ec);
3236 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3244 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3250 Expression left_null = unwrap != null ? unwrap : left;
3251 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3259 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3263 public override void Emit (EmitContext ec)
3265 ILGenerator ig = ec.ig;
3267 Label is_null_label = ig.DefineLabel ();
3268 Label end_label = ig.DefineLabel ();
3270 if (unwrap != null) {
3271 unwrap.EmitCheck (ec);
3272 ig.Emit (OpCodes.Brfalse, is_null_label);
3275 ig.Emit (OpCodes.Br, end_label);
3277 ig.MarkLabel (is_null_label);
3280 ig.MarkLabel (end_label);
3283 ig.Emit (OpCodes.Dup);
3284 ig.Emit (OpCodes.Brtrue, end_label);
3286 ig.MarkLabel (is_null_label);
3288 ig.Emit (OpCodes.Pop);
3291 ig.MarkLabel (end_label);
3296 public class LiftedUnaryMutator : ExpressionStatement
3298 public readonly UnaryMutator.Mode Mode;
3299 Expression expr, null_value;
3300 UnaryMutator underlying;
3303 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3309 eclass = ExprClass.Value;
3312 public override Expression DoResolve (EmitContext ec)
3314 expr = expr.Resolve (ec);
3318 unwrap = Unwrap.Create (expr, ec);
3322 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3323 if (underlying == null)
3326 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3327 if (null_value == null)
3334 void DoEmit (EmitContext ec, bool is_expr)
3336 ILGenerator ig = ec.ig;
3337 Label is_null_label = ig.DefineLabel ();
3338 Label end_label = ig.DefineLabel ();
3340 unwrap.EmitCheck (ec);
3341 ig.Emit (OpCodes.Brfalse, is_null_label);
3344 underlying.Emit (ec);
3346 underlying.EmitStatement (ec);
3347 ig.Emit (OpCodes.Br, end_label);
3349 ig.MarkLabel (is_null_label);
3351 null_value.Emit (ec);
3353 ig.MarkLabel (end_label);
3356 public override void Emit (EmitContext ec)
3361 public override void EmitStatement (EmitContext ec)