2 // generic.cs: Generics support
4 // Authors: Martin Baulig (martin@ximian.com)
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Licensed under the terms of the GNU GPL
10 // (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // (C) 2004 Novell, Inc
14 using System.Reflection;
15 using System.Reflection.Emit;
16 using System.Globalization;
17 using System.Collections;
19 using System.Text.RegularExpressions;
21 namespace Mono.CSharp {
24 /// Abstract base class for type parameter constraints.
25 /// The type parameter can come from a generic type definition or from reflection.
27 public abstract class GenericConstraints {
28 public abstract string TypeParameter {
32 public abstract GenericParameterAttributes Attributes {
36 public bool HasConstructorConstraint {
37 get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
40 public bool HasReferenceTypeConstraint {
41 get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
44 public bool HasValueTypeConstraint {
45 get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
48 public virtual bool HasClassConstraint {
49 get { return ClassConstraint != null; }
52 public abstract Type ClassConstraint {
56 public abstract Type[] InterfaceConstraints {
60 public abstract Type EffectiveBaseClass {
65 // Returns whether the type parameter is "known to be a reference type".
67 public virtual bool IsReferenceType {
69 if (HasReferenceTypeConstraint)
71 if (HasValueTypeConstraint)
74 if (ClassConstraint != null) {
75 if (ClassConstraint.IsValueType)
78 if (ClassConstraint != TypeManager.object_type)
82 foreach (Type t in InterfaceConstraints) {
83 if (!t.IsGenericParameter)
86 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
87 if ((gc != null) && gc.IsReferenceType)
96 // Returns whether the type parameter is "known to be a value type".
98 public virtual bool IsValueType {
100 if (HasValueTypeConstraint)
102 if (HasReferenceTypeConstraint)
105 if (ClassConstraint != null) {
106 if (!ClassConstraint.IsValueType)
109 if (ClassConstraint != TypeManager.value_type)
113 foreach (Type t in InterfaceConstraints) {
114 if (!t.IsGenericParameter)
117 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
118 if ((gc != null) && gc.IsValueType)
127 public enum SpecialConstraint
135 /// Tracks the constraints for a type parameter from a generic type definition.
137 public class Constraints : GenericConstraints {
139 ArrayList constraints;
143 // name is the identifier, constraints is an arraylist of
144 // Expressions (with types) or `true' for the constructor constraint.
146 public Constraints (string name, ArrayList constraints,
150 this.constraints = constraints;
154 public override string TypeParameter {
160 public Constraints Clone ()
162 return new Constraints (name, constraints, loc);
165 GenericParameterAttributes attrs;
166 TypeExpr class_constraint;
167 ArrayList iface_constraints;
168 ArrayList type_param_constraints;
170 Type class_constraint_type;
171 Type[] iface_constraint_types;
172 Type effective_base_type;
177 /// Resolve the constraints - but only resolve things into Expression's, not
178 /// into actual types.
180 public bool Resolve (IResolveContext ec)
185 iface_constraints = new ArrayList ();
186 type_param_constraints = new ArrayList ();
188 foreach (object obj in constraints) {
189 if (HasConstructorConstraint) {
190 Report.Error (401, loc,
191 "The new() constraint must be the last constraint specified");
195 if (obj is SpecialConstraint) {
196 SpecialConstraint sc = (SpecialConstraint) obj;
198 if (sc == SpecialConstraint.Constructor) {
199 if (!HasValueTypeConstraint) {
200 attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
204 Report.Error (451, loc, "The `new()' constraint " +
205 "cannot be used with the `struct' constraint");
209 if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
210 Report.Error (449, loc, "The `class' or `struct' " +
211 "constraint must be the first constraint specified");
215 if (sc == SpecialConstraint.ReferenceType)
216 attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
218 attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
222 int errors = Report.Errors;
223 FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
226 if (errors != Report.Errors)
229 NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
234 ConstructedType cexpr = fn as ConstructedType;
236 if (!cexpr.ResolveConstructedType (ec))
241 expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
243 if ((expr == null) || (expr.Type == null))
246 // TODO: It's aleady done in ResolveAsBaseTerminal
247 if (!ec.GenericDeclContainer.AsAccessible (fn.Type, ec.GenericDeclContainer.ModFlags)) {
248 Report.SymbolRelatedToPreviousError (fn.Type);
249 Report.Error (703, loc,
250 "Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
251 fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
255 TypeParameterExpr texpr = expr as TypeParameterExpr;
257 type_param_constraints.Add (expr);
258 else if (expr.IsInterface)
259 iface_constraints.Add (expr);
260 else if (class_constraint != null) {
261 Report.Error (406, loc,
262 "`{0}': the class constraint for `{1}' " +
263 "must come before any other constraints.",
266 } else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
267 Report.Error (450, loc, "`{0}': cannot specify both " +
268 "a constraint class and the `class' " +
269 "or `struct' constraint", expr.GetSignatureForError ());
272 class_constraint = expr;
277 ArrayList list = new ArrayList ();
278 foreach (TypeExpr iface_constraint in iface_constraints) {
279 foreach (Type type in list) {
280 if (!type.Equals (iface_constraint.Type))
283 Report.Error (405, loc,
284 "Duplicate constraint `{0}' for type " +
285 "parameter `{1}'.", iface_constraint.GetSignatureForError (),
290 list.Add (iface_constraint.Type);
293 foreach (TypeParameterExpr expr in type_param_constraints) {
294 foreach (Type type in list) {
295 if (!type.Equals (expr.Type))
298 Report.Error (405, loc,
299 "Duplicate constraint `{0}' for type " +
300 "parameter `{1}'.", expr.GetSignatureForError (), name);
304 list.Add (expr.Type);
307 iface_constraint_types = new Type [list.Count];
308 list.CopyTo (iface_constraint_types, 0);
310 if (class_constraint != null) {
311 class_constraint_type = class_constraint.Type;
312 if (class_constraint_type == null)
315 if (class_constraint_type.IsSealed) {
316 if (class_constraint_type.IsAbstract)
318 Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
319 TypeManager.CSharpName (class_constraint_type));
323 Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
324 "a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
329 if ((class_constraint_type == TypeManager.array_type) ||
330 (class_constraint_type == TypeManager.delegate_type) ||
331 (class_constraint_type == TypeManager.enum_type) ||
332 (class_constraint_type == TypeManager.value_type) ||
333 (class_constraint_type == TypeManager.object_type)) {
334 Report.Error (702, loc,
335 "Bound cannot be special class `{0}'",
336 TypeManager.CSharpName (class_constraint_type));
341 if (class_constraint_type != null)
342 effective_base_type = class_constraint_type;
343 else if (HasValueTypeConstraint)
344 effective_base_type = TypeManager.value_type;
346 effective_base_type = TypeManager.object_type;
352 bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
354 seen.Add (tparam, true);
356 Constraints constraints = tparam.Constraints;
357 if (constraints == null)
360 if (constraints.HasValueTypeConstraint) {
361 Report.Error (456, loc, "Type parameter `{0}' has " +
362 "the `struct' constraint, so it cannot " +
363 "be used as a constraint for `{1}'",
368 if (constraints.type_param_constraints == null)
371 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
372 if (seen.Contains (expr.TypeParameter)) {
373 Report.Error (454, loc, "Circular constraint " +
374 "dependency involving `{0}' and `{1}'",
375 tparam.Name, expr.Name);
379 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
387 /// Resolve the constraints into actual types.
389 public bool ResolveTypes (IResolveContext ec)
394 resolved_types = true;
396 foreach (object obj in constraints) {
397 ConstructedType cexpr = obj as ConstructedType;
401 if (!cexpr.CheckConstraints (ec))
405 foreach (TypeParameterExpr expr in type_param_constraints) {
406 Hashtable seen = new Hashtable ();
407 if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
411 for (int i = 0; i < iface_constraints.Count; ++i) {
412 TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
413 iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
414 if (iface_constraint == null)
416 iface_constraints [i] = iface_constraint;
419 if (class_constraint != null) {
420 class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
421 if (class_constraint == null)
429 /// Check whether there are no conflicts in our type parameter constraints.
431 /// This is an example:
435 /// where U : T, struct
437 public bool CheckDependencies ()
439 foreach (TypeParameterExpr expr in type_param_constraints) {
440 if (!CheckDependencies (expr.TypeParameter))
447 bool CheckDependencies (TypeParameter tparam)
449 Constraints constraints = tparam.Constraints;
450 if (constraints == null)
453 if (HasValueTypeConstraint && constraints.HasClassConstraint) {
454 Report.Error (455, loc, "Type parameter `{0}' inherits " +
455 "conflicting constraints `{1}' and `{2}'",
456 name, TypeManager.CSharpName (constraints.ClassConstraint),
461 if (HasClassConstraint && constraints.HasClassConstraint) {
462 Type t1 = ClassConstraint;
463 TypeExpr e1 = class_constraint;
464 Type t2 = constraints.ClassConstraint;
465 TypeExpr e2 = constraints.class_constraint;
467 if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
468 !Convert.ImplicitReferenceConversionExists (e2, t1)) {
469 Report.Error (455, loc,
470 "Type parameter `{0}' inherits " +
471 "conflicting constraints `{1}' and `{2}'",
472 name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
477 if (constraints.type_param_constraints == null)
480 foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
481 if (!CheckDependencies (expr.TypeParameter))
488 public override GenericParameterAttributes Attributes {
489 get { return attrs; }
492 public override bool HasClassConstraint {
493 get { return class_constraint != null; }
496 public override Type ClassConstraint {
497 get { return class_constraint_type; }
500 public override Type[] InterfaceConstraints {
501 get { return iface_constraint_types; }
504 public override Type EffectiveBaseClass {
505 get { return effective_base_type; }
508 public bool IsSubclassOf (Type t)
510 if ((class_constraint_type != null) &&
511 class_constraint_type.IsSubclassOf (t))
514 if (iface_constraint_types == null)
517 foreach (Type iface in iface_constraint_types) {
518 if (TypeManager.IsSubclassOf (iface, t))
525 public Location Location {
532 /// This is used when we're implementing a generic interface method.
533 /// Each method type parameter in implementing method must have the same
534 /// constraints than the corresponding type parameter in the interface
535 /// method. To do that, we're called on each of the implementing method's
538 public bool CheckInterfaceMethod (GenericConstraints gc)
540 if (gc.Attributes != attrs)
543 if (HasClassConstraint != gc.HasClassConstraint)
545 if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
548 int gc_icount = gc.InterfaceConstraints != null ?
549 gc.InterfaceConstraints.Length : 0;
550 int icount = InterfaceConstraints != null ?
551 InterfaceConstraints.Length : 0;
553 if (gc_icount != icount)
556 foreach (Type iface in gc.InterfaceConstraints) {
558 foreach (Type check in InterfaceConstraints) {
559 if (TypeManager.IsEqual (iface, check)) {
572 public void VerifyClsCompliance ()
574 if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
575 Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
577 if (iface_constraint_types != null) {
578 for (int i = 0; i < iface_constraint_types.Length; ++i) {
579 if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
580 Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
581 ((TypeExpr)iface_constraints [i]).Location);
586 void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
588 Report.SymbolRelatedToPreviousError (t);
589 Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
590 TypeManager.CSharpName (t));
595 /// A type parameter from a generic type definition.
597 public class TypeParameter : MemberCore, IMemberContainer {
600 GenericConstraints gc;
601 Constraints constraints;
603 GenericTypeParameterBuilder type;
604 MemberCache member_cache;
606 public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
607 Constraints constraints, Attributes attrs, Location loc)
608 : base (parent, new MemberName (name, loc), attrs)
612 this.constraints = constraints;
616 public GenericConstraints GenericConstraints {
617 get { return gc != null ? gc : constraints; }
620 public Constraints Constraints {
621 get { return constraints; }
624 public DeclSpace DeclSpace {
633 /// This is the first method which is called during the resolving
634 /// process; we're called immediately after creating the type parameters
635 /// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
638 /// We're either called from TypeContainer.DefineType() or from
639 /// GenericMethod.Define() (called from Method.Define()).
641 public void Define (GenericTypeParameterBuilder type)
643 if (this.type != null)
644 throw new InvalidOperationException ();
647 TypeManager.AddTypeParameter (type, this);
651 /// This is the second method which is called during the resolving
652 /// process - in case of class type parameters, we're called from
653 /// TypeContainer.ResolveType() - after it resolved the class'es
654 /// base class and interfaces. For method type parameters, we're
655 /// called immediately after Define().
657 /// We're just resolving the constraints into expressions here, we
658 /// don't resolve them into actual types.
660 /// Note that in the special case of partial generic classes, we may be
661 /// called _before_ Define() and we may also be called multiple types.
663 public bool Resolve (DeclSpace ds)
665 if (constraints != null) {
666 if (!constraints.Resolve (ds)) {
676 /// This is the third method which is called during the resolving
677 /// process. We're called immediately after calling DefineConstraints()
678 /// on all of the current class'es type parameters.
680 /// Our job is to resolve the constraints to actual types.
682 /// Note that we may have circular dependencies on type parameters - this
683 /// is why Resolve() and ResolveType() are separate.
685 public bool ResolveType (IResolveContext ec)
687 if (constraints != null) {
688 if (!constraints.ResolveTypes (ec)) {
698 /// This is the fourth and last method which is called during the resolving
699 /// process. We're called after everything is fully resolved and actually
700 /// register the constraints with SRE and the TypeManager.
702 public bool DefineType (IResolveContext ec)
704 return DefineType (ec, null, null, false);
708 /// This is the fith and last method which is called during the resolving
709 /// process. We're called after everything is fully resolved and actually
710 /// register the constraints with SRE and the TypeManager.
712 /// The `builder', `implementing' and `is_override' arguments are only
713 /// applicable to method type parameters.
715 public bool DefineType (IResolveContext ec, MethodBuilder builder,
716 MethodInfo implementing, bool is_override)
718 if (!ResolveType (ec))
721 if (implementing != null) {
722 if (is_override && (constraints != null)) {
723 Report.Error (460, loc,
724 "`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
725 TypeManager.CSharpSignature (builder));
729 MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
731 int pos = type.GenericParameterPosition;
732 Type mparam = mb.GetGenericArguments () [pos];
733 GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
736 gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
737 else if (constraints != null)
738 gc = new InflatedConstraints (constraints, implementing.DeclaringType);
741 if (constraints != null) {
744 else if (!constraints.CheckInterfaceMethod (gc))
747 if (!is_override && (temp_gc != null))
752 Report.SymbolRelatedToPreviousError (implementing);
755 425, loc, "The constraints for type " +
756 "parameter `{0}' of method `{1}' must match " +
757 "the constraints for type parameter `{2}' " +
758 "of interface method `{3}'. Consider using " +
759 "an explicit interface implementation instead",
760 Name, TypeManager.CSharpSignature (builder),
761 TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
764 } else if (DeclSpace is CompilerGeneratedClass) {
765 TypeParameter[] tparams = DeclSpace.TypeParameters;
766 Type[] types = new Type [tparams.Length];
767 for (int i = 0; i < tparams.Length; i++)
768 types [i] = tparams [i].Type;
770 if (constraints != null)
771 gc = new InflatedConstraints (constraints, types);
773 gc = (GenericConstraints) constraints;
779 if (gc.HasClassConstraint)
780 type.SetBaseTypeConstraint (gc.ClassConstraint);
782 type.SetInterfaceConstraints (gc.InterfaceConstraints);
783 type.SetGenericParameterAttributes (gc.Attributes);
784 TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
790 /// Check whether there are no conflicts in our type parameter constraints.
792 /// This is an example:
796 /// where U : T, struct
798 public bool CheckDependencies ()
800 if (constraints != null)
801 return constraints.CheckDependencies ();
807 /// This is called for each part of a partial generic type definition.
809 /// If `new_constraints' is not null and we don't already have constraints,
810 /// they become our constraints. If we already have constraints, we must
811 /// check that they're the same.
814 public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
817 throw new InvalidOperationException ();
819 if (new_constraints == null)
822 if (!new_constraints.Resolve (ec))
824 if (!new_constraints.ResolveTypes (ec))
827 if (constraints != null)
828 return constraints.CheckInterfaceMethod (new_constraints);
830 constraints = new_constraints;
834 public void EmitAttributes ()
836 if (OptAttributes != null)
837 OptAttributes.Emit ();
840 public override string DocCommentHeader {
842 throw new InvalidOperationException (
843 "Unexpected attempt to get doc comment from " + this.GetType () + ".");
851 public override bool Define ()
856 public override void ApplyAttributeBuilder (Attribute a,
857 CustomAttributeBuilder cb)
859 type.SetCustomAttribute (cb);
862 public override AttributeTargets AttributeTargets {
864 return (AttributeTargets) AttributeTargets.GenericParameter;
868 public override string[] ValidAttributeTargets {
870 return new string [] { "type parameter" };
878 string IMemberContainer.Name {
882 MemberCache IMemberContainer.BaseCache {
887 if (gc.EffectiveBaseClass.BaseType == null)
890 return TypeManager.LookupMemberCache (gc.EffectiveBaseClass.BaseType);
894 bool IMemberContainer.IsInterface {
895 get { return false; }
898 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
900 return FindMembers (mt, bf, null, null);
903 public MemberCache MemberCache {
905 if (member_cache != null)
911 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
912 member_cache = new MemberCache (this, gc.EffectiveBaseClass, ifaces);
918 public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
919 MemberFilter filter, object criteria)
922 return MemberList.Empty;
924 ArrayList members = new ArrayList ();
926 if (gc.HasClassConstraint) {
927 MemberList list = TypeManager.FindMembers (
928 gc.ClassConstraint, mt, bf, filter, criteria);
930 members.AddRange (list);
933 Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
934 foreach (Type t in ifaces) {
935 MemberList list = TypeManager.FindMembers (
936 t, mt, bf, filter, criteria);
938 members.AddRange (list);
941 return new MemberList (members);
944 public bool IsSubclassOf (Type t)
949 if (constraints != null)
950 return constraints.IsSubclassOf (t);
955 public override string ToString ()
957 return "TypeParameter[" + name + "]";
960 public static string GetSignatureForError (TypeParameter[] tp)
962 if (tp == null || tp.Length == 0)
965 StringBuilder sb = new StringBuilder ("<");
966 for (int i = 0; i < tp.Length; ++i) {
969 sb.Append (tp[i].GetSignatureForError ());
972 return sb.ToString ();
975 public void InflateConstraints (Type declaring)
977 if (constraints != null)
978 gc = new InflatedConstraints (constraints, declaring);
981 protected class InflatedConstraints : GenericConstraints
983 GenericConstraints gc;
985 Type class_constraint;
986 Type[] iface_constraints;
989 public InflatedConstraints (GenericConstraints gc, Type declaring)
990 : this (gc, TypeManager.GetTypeArguments (declaring))
993 public InflatedConstraints (GenericConstraints gc, Type[] dargs)
998 ArrayList list = new ArrayList ();
999 if (gc.HasClassConstraint)
1000 list.Add (inflate (gc.ClassConstraint));
1001 foreach (Type iface in gc.InterfaceConstraints)
1002 list.Add (inflate (iface));
1004 bool has_class_constr = false;
1005 if (list.Count > 0) {
1006 Type first = (Type) list [0];
1007 has_class_constr = !first.IsGenericParameter && !first.IsInterface;
1010 if ((list.Count > 0) && has_class_constr) {
1011 class_constraint = (Type) list [0];
1012 iface_constraints = new Type [list.Count - 1];
1013 list.CopyTo (1, iface_constraints, 0, list.Count - 1);
1015 iface_constraints = new Type [list.Count];
1016 list.CopyTo (iface_constraints, 0);
1019 if (HasValueTypeConstraint)
1020 base_type = TypeManager.value_type;
1021 else if (class_constraint != null)
1022 base_type = class_constraint;
1024 base_type = TypeManager.object_type;
1027 Type inflate (Type t)
1031 if (t.IsGenericParameter)
1032 return dargs [t.GenericParameterPosition];
1033 if (t.IsGenericType) {
1034 Type[] args = t.GetGenericArguments ();
1035 Type[] inflated = new Type [args.Length];
1037 for (int i = 0; i < args.Length; i++)
1038 inflated [i] = inflate (args [i]);
1040 t = t.GetGenericTypeDefinition ();
1041 t = t.MakeGenericType (inflated);
1047 public override string TypeParameter {
1048 get { return gc.TypeParameter; }
1051 public override GenericParameterAttributes Attributes {
1052 get { return gc.Attributes; }
1055 public override Type ClassConstraint {
1056 get { return class_constraint; }
1059 public override Type EffectiveBaseClass {
1060 get { return base_type; }
1063 public override Type[] InterfaceConstraints {
1064 get { return iface_constraints; }
1070 /// A TypeExpr which already resolved to a type parameter.
1072 public class TypeParameterExpr : TypeExpr {
1073 TypeParameter type_parameter;
1075 public override string Name {
1077 return type_parameter.Name;
1081 public override string FullName {
1083 return type_parameter.Name;
1087 public TypeParameter TypeParameter {
1089 return type_parameter;
1093 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
1095 this.type_parameter = type_parameter;
1099 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1101 type = type_parameter.Type;
1106 public override bool IsInterface {
1107 get { return false; }
1110 public override bool CheckAccessLevel (DeclSpace ds)
1115 public void Error_CannotUseAsUnmanagedType (Location loc)
1117 Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
1122 /// Tracks the type arguments when instantiating a generic type. We're used in
1123 /// ConstructedType.
1125 public class TypeArguments {
1126 public readonly Location Location;
1133 public TypeArguments (Location loc)
1135 args = new ArrayList ();
1136 this.Location = loc;
1139 public TypeArguments (Location loc, params Expression[] types)
1141 this.Location = loc;
1142 this.args = new ArrayList (types);
1145 public TypeArguments (int dimension, Location loc)
1147 this.dimension = dimension;
1148 this.Location = loc;
1151 public void Add (Expression type)
1154 throw new InvalidOperationException ();
1159 public void Add (TypeArguments new_args)
1162 throw new InvalidOperationException ();
1164 args.AddRange (new_args.args);
1168 /// We're used during the parsing process: the parser can't distinguish
1169 /// between type parameters and type arguments. Because of that, the
1170 /// parser creates a `MemberName' with `TypeArguments' for both cases and
1171 /// in case of a generic type definition, we call GetDeclarations().
1173 public TypeParameterName[] GetDeclarations ()
1175 TypeParameterName[] ret = new TypeParameterName [args.Count];
1176 for (int i = 0; i < args.Count; i++) {
1177 TypeParameterName name = args [i] as TypeParameterName;
1182 SimpleName sn = args [i] as SimpleName;
1184 ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
1188 Report.Error (81, Location, "Type parameter declaration " +
1189 "must be an identifier not a type");
1196 /// We may only be used after Resolve() is called and return the fully
1199 public Type[] Arguments {
1205 public bool HasTypeArguments {
1207 return has_type_args;
1220 public bool IsUnbound {
1222 return dimension > 0;
1226 public override string ToString ()
1228 StringBuilder s = new StringBuilder ();
1231 for (int i = 0; i < count; i++){
1233 // FIXME: Use TypeManager.CSharpname once we have the type
1236 s.Append (args [i].ToString ());
1240 return s.ToString ();
1243 public string GetSignatureForError()
1245 StringBuilder sb = new StringBuilder();
1246 for (int i = 0; i < Count; ++i)
1248 Expression expr = (Expression)args [i];
1249 sb.Append(expr.GetSignatureForError());
1253 return sb.ToString();
1257 /// Resolve the type arguments.
1259 public bool Resolve (IResolveContext ec)
1261 int count = args.Count;
1264 atypes = new Type [count];
1266 for (int i = 0; i < count; i++){
1267 TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
1273 atypes[i] = te.Type;
1274 if (te.Type.IsGenericParameter) {
1275 if (te is TypeParameterExpr)
1276 has_type_args = true;
1280 if (te.Type.IsSealed && te.Type.IsAbstract) {
1281 Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
1282 te.GetSignatureForError ());
1286 if (te.Type.IsPointer) {
1287 Report.Error (306, Location, "The type `{0}' may not be used " +
1288 "as a type argument", TypeManager.CSharpName (te.Type));
1292 if (te.Type == TypeManager.void_type) {
1293 Expression.Error_VoidInvalidInTheContext (Location);
1300 public TypeArguments Clone ()
1302 TypeArguments copy = new TypeArguments (Location);
1303 foreach (Expression ta in args)
1310 public class TypeParameterName : SimpleName
1312 Attributes attributes;
1314 public TypeParameterName (string name, Attributes attrs, Location loc)
1320 public Attributes OptAttributes {
1328 /// An instantiation of a generic type.
1330 public class ConstructedType : TypeExpr {
1332 FullNamedExpression name;
1334 Type[] gen_params, atypes;
1338 /// Instantiate the generic type `fname' with the type arguments `args'.
1340 public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
1346 eclass = ExprClass.Type;
1347 full_name = name + "<" + args.ToString () + ">";
1350 protected ConstructedType (TypeArguments args, Location l)
1355 eclass = ExprClass.Type;
1358 protected ConstructedType (TypeParameter[] type_params, Location l)
1362 args = new TypeArguments (l);
1363 foreach (TypeParameter type_param in type_params)
1364 args.Add (new TypeParameterExpr (type_param, l));
1366 eclass = ExprClass.Type;
1370 /// This is used to construct the `this' type inside a generic type definition.
1372 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
1373 : this (type_params, l)
1375 gt = t.GetGenericTypeDefinition ();
1377 this.name = new TypeExpression (gt, l);
1378 full_name = gt.FullName + "<" + args.ToString () + ">";
1382 /// Instantiate the generic type `t' with the type arguments `args'.
1383 /// Use this constructor if you already know the fully resolved
1386 public ConstructedType (Type t, TypeArguments args, Location l)
1389 gt = t.GetGenericTypeDefinition ();
1391 this.name = new TypeExpression (gt, l);
1392 full_name = gt.FullName + "<" + args.ToString () + ">";
1395 public TypeArguments TypeArguments {
1396 get { return args; }
1399 public override string GetSignatureForError ()
1401 return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
1404 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
1406 if (!ResolveConstructedType (ec))
1413 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1414 /// after fully resolving the constructed type.
1416 public bool CheckConstraints (IResolveContext ec)
1418 return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
1422 /// Resolve the constructed type, but don't check the constraints.
1424 public bool ResolveConstructedType (IResolveContext ec)
1428 // If we already know the fully resolved generic type.
1430 return DoResolveType (ec);
1436 Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
1440 num_args = TypeManager.GetNumberOfTypeArguments (t);
1441 if (num_args == 0) {
1442 Report.Error (308, loc,
1443 "The non-generic type `{0}' cannot " +
1444 "be used with type arguments.",
1445 TypeManager.CSharpName (t));
1449 gt = t.GetGenericTypeDefinition ();
1450 return DoResolveType (ec);
1453 bool DoResolveType (IResolveContext ec)
1456 // Resolve the arguments.
1458 if (args.Resolve (ec) == false)
1461 gen_params = gt.GetGenericArguments ();
1462 atypes = args.Arguments;
1464 if (atypes.Length != gen_params.Length) {
1465 Report.Error (305, loc,
1466 "Using the generic type `{0}' " +
1467 "requires {1} type arguments",
1468 TypeManager.CSharpName (gt),
1469 gen_params.Length.ToString ());
1474 // Now bind the parameters.
1476 type = gt.MakeGenericType (atypes);
1480 public Expression GetSimpleName (EmitContext ec)
1485 public override bool CheckAccessLevel (DeclSpace ds)
1487 return ds.CheckAccessLevel (gt);
1490 public override bool AsAccessible (DeclSpace ds, int flags)
1492 foreach (Type t in atypes) {
1493 if (!ds.AsAccessible (t, flags))
1497 return ds.AsAccessible (gt, flags);
1500 public override bool IsClass {
1501 get { return gt.IsClass; }
1504 public override bool IsValueType {
1505 get { return gt.IsValueType; }
1508 public override bool IsInterface {
1509 get { return gt.IsInterface; }
1512 public override bool IsSealed {
1513 get { return gt.IsSealed; }
1516 public override bool Equals (object obj)
1518 ConstructedType cobj = obj as ConstructedType;
1522 if ((type == null) || (cobj.type == null))
1525 return type == cobj.type;
1528 public override int GetHashCode ()
1530 return base.GetHashCode ();
1533 public override string Name {
1539 public override string FullName {
1546 public abstract class ConstraintChecker
1548 protected readonly Type[] gen_params;
1549 protected readonly Type[] atypes;
1550 protected readonly Location loc;
1552 protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
1554 this.gen_params = gen_params;
1555 this.atypes = atypes;
1560 /// Check the constraints; we're called from ResolveAsTypeTerminal()
1561 /// after fully resolving the constructed type.
1563 public bool CheckConstraints (IResolveContext ec)
1565 for (int i = 0; i < gen_params.Length; i++) {
1566 if (!CheckConstraints (ec, i))
1573 protected bool CheckConstraints (IResolveContext ec, int index)
1575 Type atype = atypes [index];
1576 Type ptype = gen_params [index];
1581 Expression aexpr = new EmptyExpression (atype);
1583 GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
1587 bool is_class, is_struct;
1588 if (atype.IsGenericParameter) {
1589 GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
1591 if (agc is Constraints)
1592 ((Constraints) agc).Resolve (ec);
1593 is_class = agc.IsReferenceType;
1594 is_struct = agc.IsValueType;
1596 is_class = is_struct = false;
1601 if (!atype.IsGenericType)
1603 is_class = atype.IsClass || atype.IsInterface;
1604 is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
1608 // First, check the `class' and `struct' constraints.
1610 if (gc.HasReferenceTypeConstraint && !is_class) {
1611 Report.Error (452, loc, "The type `{0}' must be " +
1612 "a reference type in order to use it " +
1613 "as type parameter `{1}' in the " +
1614 "generic type or method `{2}'.",
1615 TypeManager.CSharpName (atype),
1616 TypeManager.CSharpName (ptype),
1617 GetSignatureForError ());
1619 } else if (gc.HasValueTypeConstraint && !is_struct) {
1620 Report.Error (453, loc, "The type `{0}' must be a " +
1621 "non-nullable value type in order to use it " +
1622 "as type parameter `{1}' in the " +
1623 "generic type or method `{2}'.",
1624 TypeManager.CSharpName (atype),
1625 TypeManager.CSharpName (ptype),
1626 GetSignatureForError ());
1631 // The class constraint comes next.
1633 if (gc.HasClassConstraint) {
1634 if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
1639 // Now, check the interface constraints.
1641 if (gc.InterfaceConstraints != null) {
1642 foreach (Type it in gc.InterfaceConstraints) {
1643 if (!CheckConstraint (ec, ptype, aexpr, it))
1649 // Finally, check the constructor constraint.
1652 if (!gc.HasConstructorConstraint)
1655 if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
1658 if (HasDefaultConstructor (atype))
1661 Report_SymbolRelatedToPreviousError ();
1662 Report.SymbolRelatedToPreviousError (atype);
1663 Report.Error (310, loc, "The type `{0}' must have a public " +
1664 "parameterless constructor in order to use it " +
1665 "as parameter `{1}' in the generic type or " +
1667 TypeManager.CSharpName (atype),
1668 TypeManager.CSharpName (ptype),
1669 GetSignatureForError ());
1673 protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
1676 if (TypeManager.HasGenericArguments (ctype)) {
1677 Type[] types = TypeManager.GetTypeArguments (ctype);
1679 TypeArguments new_args = new TypeArguments (loc);
1681 for (int i = 0; i < types.Length; i++) {
1684 if (t.IsGenericParameter) {
1685 int pos = t.GenericParameterPosition;
1688 new_args.Add (new TypeExpression (t, loc));
1691 TypeExpr ct = new ConstructedType (ctype, new_args, loc);
1692 if (ct.ResolveAsTypeStep (ec, false) == null)
1695 } else if (ctype.IsGenericParameter) {
1696 int pos = ctype.GenericParameterPosition;
1697 ctype = atypes [pos];
1700 if (Convert.ImplicitStandardConversionExists (expr, ctype))
1703 Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
1707 bool HasDefaultConstructor (Type atype)
1709 if (atype.IsAbstract)
1713 atype = TypeManager.DropGenericTypeArguments (atype);
1714 if (atype is TypeBuilder) {
1715 TypeContainer tc = TypeManager.LookupTypeContainer (atype);
1716 if (tc.InstanceConstructors == null) {
1717 atype = atype.BaseType;
1721 foreach (Constructor c in tc.InstanceConstructors) {
1722 if ((c.ModFlags & Modifiers.PUBLIC) == 0)
1724 if ((c.Parameters.FixedParameters != null) &&
1725 (c.Parameters.FixedParameters.Length != 0))
1727 if (c.Parameters.HasArglist || c.Parameters.HasParams)
1734 TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
1735 if (tparam != null) {
1736 if (tparam.GenericConstraints == null)
1739 return tparam.GenericConstraints.HasConstructorConstraint;
1742 MemberList list = TypeManager.FindMembers (
1743 atype, MemberTypes.Constructor,
1744 BindingFlags.Public | BindingFlags.Instance |
1745 BindingFlags.DeclaredOnly, null, null);
1747 if (atype.IsAbstract || (list == null))
1750 foreach (MethodBase mb in list) {
1751 ParameterData pd = TypeManager.GetParameterData (mb);
1752 if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
1759 protected abstract string GetSignatureForError ();
1760 protected abstract void Report_SymbolRelatedToPreviousError ();
1762 void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
1764 Report_SymbolRelatedToPreviousError ();
1765 Report.SymbolRelatedToPreviousError (atype);
1766 Report.Error (309, loc,
1767 "The type `{0}' must be convertible to `{1}' in order to " +
1768 "use it as parameter `{2}' in the generic type or method `{3}'",
1769 TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
1770 TypeManager.CSharpName (ptype), GetSignatureForError ());
1773 public static bool CheckConstraints (EmitContext ec, MethodBase definition,
1774 MethodBase instantiated, Location loc)
1776 MethodConstraintChecker checker = new MethodConstraintChecker (
1777 definition, definition.GetGenericArguments (),
1778 instantiated.GetGenericArguments (), loc);
1780 return checker.CheckConstraints (ec);
1783 public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
1784 Type[] atypes, Location loc)
1786 TypeConstraintChecker checker = new TypeConstraintChecker (
1787 gt, gen_params, atypes, loc);
1789 return checker.CheckConstraints (ec);
1792 protected class MethodConstraintChecker : ConstraintChecker
1794 MethodBase definition;
1796 public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
1797 Type[] atypes, Location loc)
1798 : base (gen_params, atypes, loc)
1800 this.definition = definition;
1803 protected override string GetSignatureForError ()
1805 return TypeManager.CSharpSignature (definition);
1808 protected override void Report_SymbolRelatedToPreviousError ()
1810 Report.SymbolRelatedToPreviousError (definition);
1814 protected class TypeConstraintChecker : ConstraintChecker
1818 public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
1820 : base (gen_params, atypes, loc)
1825 protected override string GetSignatureForError ()
1827 return TypeManager.CSharpName (gt);
1830 protected override void Report_SymbolRelatedToPreviousError ()
1832 Report.SymbolRelatedToPreviousError (gt);
1838 /// A generic method definition.
1840 public class GenericMethod : DeclSpace
1842 Expression return_type;
1843 Parameters parameters;
1845 public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
1846 Expression return_type, Parameters parameters)
1847 : base (ns, parent, name, null)
1849 this.return_type = return_type;
1850 this.parameters = parameters;
1853 public override TypeBuilder DefineType ()
1855 throw new Exception ();
1858 public override bool Define ()
1860 for (int i = 0; i < TypeParameters.Length; i++)
1861 if (!TypeParameters [i].Resolve (this))
1868 /// Define and resolve the type parameters.
1869 /// We're called from Method.Define().
1871 public bool Define (MethodBuilder mb, ToplevelBlock block)
1873 TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1874 string[] snames = new string [names.Length];
1875 for (int i = 0; i < names.Length; i++) {
1876 string type_argument_name = names[i].Name;
1877 Parameter p = parameters.GetParameterByName (type_argument_name);
1879 Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
1883 // FIXME: This is wrong, since it only looks at the outermost set of variables
1884 if (block != null) {
1885 LocalInfo li = (LocalInfo)block.Variables [type_argument_name];
1887 Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
1891 snames[i] = type_argument_name;
1894 GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
1895 for (int i = 0; i < TypeParameters.Length; i++)
1896 TypeParameters [i].Define (gen_params [i]);
1901 for (int i = 0; i < TypeParameters.Length; i++) {
1902 if (!TypeParameters [i].ResolveType (this))
1909 static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
1911 Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
1912 name, collisionWith);
1916 /// We're called from MethodData.Define() after creating the MethodBuilder.
1918 public bool DefineType (EmitContext ec, MethodBuilder mb,
1919 MethodInfo implementing, bool is_override)
1921 for (int i = 0; i < TypeParameters.Length; i++)
1922 if (!TypeParameters [i].DefineType (
1923 ec, mb, implementing, is_override))
1927 foreach (Parameter p in parameters.FixedParameters){
1928 if (!p.Resolve (ec))
1931 if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
1937 public void EmitAttributes ()
1939 for (int i = 0; i < TypeParameters.Length; i++)
1940 TypeParameters [i].EmitAttributes ();
1942 if (OptAttributes != null)
1943 OptAttributes.Emit ();
1946 public override bool DefineMembers ()
1951 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1952 MemberFilter filter, object criteria)
1954 throw new Exception ();
1957 public override MemberCache MemberCache {
1963 public override AttributeTargets AttributeTargets {
1965 return AttributeTargets.Method | AttributeTargets.ReturnValue;
1969 public override string DocCommentHeader {
1970 get { return "M:"; }
1973 public new void VerifyClsCompliance ()
1975 foreach (TypeParameter tp in TypeParameters) {
1976 if (tp.Constraints == null)
1979 tp.Constraints.VerifyClsCompliance ();
1984 public class DefaultValueExpression : Expression
1988 public DefaultValueExpression (Expression expr, Location loc)
1994 public override Expression DoResolve (EmitContext ec)
1996 TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
2002 if (type == TypeManager.void_type) {
2003 Error_VoidInvalidInTheContext (loc);
2007 if (type.IsGenericParameter)
2009 GenericConstraints constraints = TypeManager.GetTypeParameterConstraints(type);
2010 if (constraints != null && constraints.IsReferenceType)
2011 return new NullDefault (new NullLiteral (Location), type);
2015 Constant c = New.Constantify(type);
2017 return new NullDefault (c, type);
2019 if (!TypeManager.IsValueType (type))
2020 return new NullDefault (new NullLiteral (Location), type);
2022 eclass = ExprClass.Variable;
2026 public override void Emit (EmitContext ec)
2028 LocalTemporary temp_storage = new LocalTemporary(type);
2030 temp_storage.AddressOf(ec, AddressOp.LoadStore);
2031 ec.ig.Emit(OpCodes.Initobj, type);
2032 temp_storage.Emit(ec);
2035 protected override void CloneTo (CloneContext clonectx, Expression t)
2037 DefaultValueExpression target = (DefaultValueExpression) t;
2039 target.expr = expr.Clone (clonectx);
2043 public class NullableType : TypeExpr
2045 Expression underlying;
2047 public NullableType (Expression underlying, Location l)
2049 this.underlying = underlying;
2052 eclass = ExprClass.Type;
2055 public NullableType (Type type, Location loc)
2056 : this (new TypeExpression (type, loc), loc)
2059 public override string Name {
2060 get { return underlying.ToString () + "?"; }
2063 public override string FullName {
2064 get { return underlying.ToString () + "?"; }
2067 protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
2069 TypeArguments args = new TypeArguments (loc);
2070 args.Add (underlying);
2072 ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
2073 return ctype.ResolveAsTypeTerminal (ec, false);
2077 public partial class TypeManager
2080 // A list of core types that the compiler requires or uses
2082 static public Type activator_type;
2083 static public Type generic_ilist_type;
2084 static public Type generic_icollection_type;
2085 static public Type generic_ienumerator_type;
2086 static public Type generic_ienumerable_type;
2087 static public Type generic_nullable_type;
2090 // These methods are called by code generated by the compiler
2092 static public MethodInfo activator_create_instance;
2094 static void InitGenericCoreTypes ()
2096 activator_type = CoreLookupType ("System", "Activator");
2098 generic_ilist_type = CoreLookupType (
2099 "System.Collections.Generic", "IList", 1);
2100 generic_icollection_type = CoreLookupType (
2101 "System.Collections.Generic", "ICollection", 1);
2102 generic_ienumerator_type = CoreLookupType (
2103 "System.Collections.Generic", "IEnumerator", 1);
2104 generic_ienumerable_type = CoreLookupType (
2105 "System.Collections.Generic", "IEnumerable", 1);
2106 generic_nullable_type = CoreLookupType (
2107 "System", "Nullable", 1);
2110 static void InitGenericCodeHelpers ()
2113 activator_create_instance = GetMethod (
2114 activator_type, "CreateInstance", Type.EmptyTypes);
2117 static Type CoreLookupType (string ns, string name, int arity)
2119 return CoreLookupType (ns, MemberName.MakeName (name, arity));
2122 public static TypeContainer LookupGenericTypeContainer (Type t)
2124 t = DropGenericTypeArguments (t);
2125 return LookupTypeContainer (t);
2128 public static GenericConstraints GetTypeParameterConstraints (Type t)
2130 if (!t.IsGenericParameter)
2131 throw new InvalidOperationException ();
2133 TypeParameter tparam = LookupTypeParameter (t);
2135 return tparam.GenericConstraints;
2137 return ReflectionConstraints.GetConstraints (t);
2141 /// Check whether `a' and `b' may become equal generic types.
2142 /// The algorithm to do that is a little bit complicated.
2144 public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_inferred,
2145 Type[] method_inferred)
2147 if (a.IsGenericParameter) {
2149 // If a is an array of a's type, they may never
2153 b = b.GetElementType ();
2159 // If b is a generic parameter or an actual type,
2160 // they may become equal:
2162 // class X<T,U> : I<T>, I<U>
2163 // class X<T> : I<T>, I<float>
2165 if (b.IsGenericParameter || !b.IsGenericType) {
2166 int pos = a.GenericParameterPosition;
2167 Type[] args = a.DeclaringMethod != null ? method_inferred : class_inferred;
2168 if (args [pos] == null) {
2173 return args [pos] == a;
2177 // We're now comparing a type parameter with a
2178 // generic instance. They may become equal unless
2179 // the type parameter appears anywhere in the
2180 // generic instance:
2182 // class X<T,U> : I<T>, I<X<U>>
2183 // -> error because you could instanciate it as
2186 // class X<T> : I<T>, I<X<T>> -> ok
2189 Type[] bargs = GetTypeArguments (b);
2190 for (int i = 0; i < bargs.Length; i++) {
2191 if (a.Equals (bargs [i]))
2198 if (b.IsGenericParameter)
2199 return MayBecomeEqualGenericTypes (b, a, class_inferred, method_inferred);
2202 // At this point, neither a nor b are a type parameter.
2204 // If one of them is a generic instance, let
2205 // MayBecomeEqualGenericInstances() compare them (if the
2206 // other one is not a generic instance, they can never
2210 if (a.IsGenericType || b.IsGenericType)
2211 return MayBecomeEqualGenericInstances (a, b, class_inferred, method_inferred);
2214 // If both of them are arrays.
2217 if (a.IsArray && b.IsArray) {
2218 if (a.GetArrayRank () != b.GetArrayRank ())
2221 a = a.GetElementType ();
2222 b = b.GetElementType ();
2224 return MayBecomeEqualGenericTypes (a, b, class_inferred, method_inferred);
2228 // Ok, two ordinary types.
2231 return a.Equals (b);
2235 // Checks whether two generic instances may become equal for some
2236 // particular instantiation (26.3.1).
2238 public static bool MayBecomeEqualGenericInstances (Type a, Type b,
2239 Type[] class_inferred,
2240 Type[] method_inferred)
2242 if (!a.IsGenericType || !b.IsGenericType)
2244 if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2247 return MayBecomeEqualGenericInstances (
2248 GetTypeArguments (a), GetTypeArguments (b), class_inferred, method_inferred);
2251 public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
2252 Type[] class_inferred,
2253 Type[] method_inferred)
2255 if (aargs.Length != bargs.Length)
2258 for (int i = 0; i < aargs.Length; i++) {
2259 if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_inferred, method_inferred))
2267 /// Type inference. Try to infer the type arguments from the params method
2268 /// `method', which is invoked with the arguments `arguments'. This is used
2269 /// when resolving an Invocation or a DelegateInvocation and the user
2270 /// did not explicitly specify type arguments.
2272 public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
2273 ref MethodBase method)
2275 if (!TypeManager.IsGenericMethod (method))
2278 // if there are no arguments, there's no way to infer the type-arguments
2279 if (arguments == null || arguments.Count == 0)
2282 ParameterData pd = TypeManager.GetParameterData (method);
2283 int pd_count = pd.Count;
2284 int arg_count = arguments.Count;
2289 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
2292 if (pd_count - 1 > arg_count)
2295 Type[] method_args = method.GetGenericArguments ();
2296 Type[] inferred_types = new Type [method_args.Length];
2299 // If we have come this far, the case which
2300 // remains is when the number of parameters is
2301 // less than or equal to the argument count.
2303 for (int i = 0; i < pd_count - 1; ++i) {
2304 Argument a = (Argument) arguments [i];
2306 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2309 Type pt = pd.ParameterType (i);
2312 if (!TypeInferenceV2.UnifyType (pt, at, inferred_types))
2316 Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
2318 for (int i = pd_count - 1; i < arg_count; i++) {
2319 Argument a = (Argument) arguments [i];
2321 if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
2324 if (!TypeInferenceV2.UnifyType (element_type, a.Type, inferred_types))
2328 for (int i = 0; i < inferred_types.Length; i++)
2329 if (inferred_types [i] == null)
2332 method = ((MethodInfo)method).MakeGenericMethod (inferred_types);
2337 /// Type inference. Try to infer the type arguments from `method',
2338 /// which is invoked with the arguments `arguments'. This is used
2339 /// when resolving an Invocation or a DelegateInvocation and the user
2340 /// did not explicitly specify type arguments.
2342 public static bool InferTypeArguments (EmitContext ec,
2343 ArrayList arguments,
2344 ref MethodBase method)
2346 if (!TypeManager.IsGenericMethod (method))
2349 ATypeInference ti = ATypeInference.CreateInstance (arguments);
2350 Type[] i_args = ti.InferMethodArguments (ec, method);
2354 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2361 public static bool InferTypeArguments (ParameterData apd,
2362 ref MethodBase method)
2364 if (!TypeManager.IsGenericMethod (method))
2367 ATypeInference ti = ATypeInference.CreateInstance (ArrayList.Adapter (apd.Types));
2368 Type[] i_args = ti.InferDelegateArguments (method);
2372 method = ((MethodInfo) method).MakeGenericMethod (i_args);
2377 abstract class ATypeInference
2379 protected readonly ArrayList arguments;
2380 protected readonly int arg_count;
2382 protected ATypeInference (ArrayList arguments)
2384 this.arguments = arguments;
2385 if (arguments != null)
2386 arg_count = arguments.Count;
2389 public static ATypeInference CreateInstance (ArrayList arguments)
2391 if (RootContext.Version == LanguageVersion.LINQ)
2392 return new TypeInferenceV3 (arguments);
2394 return new TypeInferenceV2 (arguments);
2397 public abstract Type[] InferMethodArguments (EmitContext ec, MethodBase method);
2398 public abstract Type[] InferDelegateArguments (MethodBase method);
2402 // Implements C# 2.0 type inference
2404 class TypeInferenceV2 : ATypeInference
2406 public TypeInferenceV2 (ArrayList arguments)
2411 public override Type[] InferDelegateArguments (MethodBase method)
2413 ParameterData pd = TypeManager.GetParameterData (method);
2414 if (arg_count != pd.Count)
2417 Type[] method_args = method.GetGenericArguments ();
2418 Type[] inferred_types = new Type[method_args.Length];
2420 Type[] param_types = new Type[pd.Count];
2421 Type[] arg_types = (Type[])arguments.ToArray (typeof (Type));
2423 for (int i = 0; i < arg_count; i++) {
2424 param_types[i] = pd.ParameterType (i);
2427 if (!InferTypeArguments (param_types, arg_types, inferred_types))
2430 return inferred_types;
2433 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2435 ParameterData pd = TypeManager.GetParameterData (method);
2436 if (arg_count != pd.Count)
2439 Type[] method_generic_args = method.GetGenericArguments ();
2440 Type[] arg_types = new Type[pd.Count];
2441 for (int i = 0; i < arg_count; i++) {
2442 Argument a = (Argument) arguments[i];
2443 if (a.Expr is NullLiteral || a.Expr is MethodGroupExpr || a.Expr is AnonymousMethodExpression)
2446 arg_types[i] = a.Type;
2449 Type[] inferred_types = new Type [method_generic_args.Length];
2450 if (!InferTypeArguments (pd.Types, arg_types, inferred_types))
2453 return inferred_types;
2456 static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
2457 Type[] inferred_types)
2459 for (int i = 0; i < arg_types.Length; i++) {
2460 if (arg_types[i] == null)
2463 if (!UnifyType (param_types[i], arg_types[i], inferred_types))
2467 for (int i = 0; i < inferred_types.Length; ++i)
2468 if (inferred_types[i] == null)
2474 public static bool UnifyType (Type pt, Type at, Type[] inferred)
2476 if (pt.IsGenericParameter) {
2477 if (pt.DeclaringMethod == null)
2480 int pos = pt.GenericParameterPosition;
2482 if (inferred [pos] == null)
2483 inferred [pos] = at;
2485 return inferred [pos] == at;
2488 if (!pt.ContainsGenericParameters) {
2489 if (at.ContainsGenericParameters)
2490 return UnifyType (at, pt, inferred);
2497 if (at.GetArrayRank () != pt.GetArrayRank ())
2500 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2503 if (!pt.IsGenericType)
2506 Type gt = pt.GetGenericTypeDefinition ();
2507 if ((gt != TypeManager.generic_ilist_type) && (gt != TypeManager.generic_icollection_type) &&
2508 (gt != TypeManager.generic_ienumerable_type))
2511 Type[] args = TypeManager.GetTypeArguments (pt);
2512 return UnifyType (args[0], at.GetElementType (), inferred);
2517 (pt.GetArrayRank () != at.GetArrayRank ()))
2520 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2523 if (pt.IsByRef && at.IsByRef)
2524 return UnifyType (pt.GetElementType (), at.GetElementType (), inferred);
2525 ArrayList list = new ArrayList ();
2526 if (at.IsGenericType)
2528 for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
2531 list.AddRange (TypeManager.GetInterfaces (at));
2533 foreach (Type type in list) {
2534 if (!type.IsGenericType)
2537 if (TypeManager.DropGenericTypeArguments (pt) != TypeManager.DropGenericTypeArguments (type))
2540 if (!UnifyTypes (pt.GetGenericArguments (), type.GetGenericArguments (), inferred))
2547 static bool UnifyTypes (Type[] pts, Type[] ats, Type[] inferred)
2549 for (int i = 0; i < ats.Length; i++) {
2550 if (!UnifyType (pts [i], ats [i], inferred))
2558 // Implements C# 3.0 type inference
2560 class TypeInferenceV3 : ATypeInference
2562 public TypeInferenceV3 (ArrayList arguments)
2567 public override Type[] InferDelegateArguments (MethodBase method)
2569 ParameterData pd = TypeManager.GetParameterData (method);
2570 if (arg_count != pd.Count)
2573 Type[] d_gargs = method.GetGenericArguments ();
2574 TypeInferenceContext context = new TypeInferenceContext (d_gargs);
2576 // A lower-bound inference is made from each argument type Uj of D
2577 // to the corresponding parameter type Tj of M
2578 for (int i = 0; i < arg_count; ++i) {
2579 Type t = pd.Types [i];
2580 if (!t.IsGenericParameter)
2583 context.LowerBoundInference ((Type)arguments[i], t);
2586 if (!context.FixAllTypes ())
2589 return context.InferredTypeArguments;
2592 public override Type[] InferMethodArguments (EmitContext ec, MethodBase method)
2594 ParameterData pd = TypeManager.GetParameterData (method);
2595 if (arg_count != pd.Count)
2598 Type[] method_generic_args = method.GetGenericArguments ();
2599 TypeInferenceContext context = new TypeInferenceContext (method_generic_args);
2600 if (!InferInPhases (ec, context, pd))
2603 return context.InferredTypeArguments;
2607 // Implements method type arguments inference
2609 bool InferInPhases (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters)
2612 // The first inference phase
2614 for (int i = 0; i < arg_count; i++) {
2615 Type method_parameter = methodParameters.ParameterType (i);
2617 Argument a = (Argument) arguments[i];
2620 // When a lambda expression, an anonymous method
2621 // is used an explicit argument type inference takes a place
2623 AnonymousMethodExpression am = a.Expr as AnonymousMethodExpression;
2625 am.ExplicitTypeInference (tic, method_parameter);
2629 if (a.Expr.Type == TypeManager.null_type)
2633 // Otherwise an output type inference is made
2635 tic.OutputTypeInference (ec, a.Expr, method_parameter);
2639 // Part of the second phase but because it happens only once
2640 // we don't need to call it in cycle
2642 bool fixed_any = false;
2643 if (!tic.FixIndependentTypeArguments (methodParameters, ref fixed_any))
2646 return DoSecondPhase (ec, tic, methodParameters, !fixed_any);
2649 bool DoSecondPhase (EmitContext ec, TypeInferenceContext tic, ParameterData methodParameters, bool fixDependent)
2651 bool fixed_any = false;
2652 if (fixDependent && !tic.FixDependentTypes (methodParameters, ref fixed_any))
2655 // If no further unfixed type variables exist, type inference succeeds
2656 if (!tic.UnfixedVariableExists)
2659 if (!fixed_any && fixDependent)
2662 // For all arguments where the corresponding argument output types
2663 // contain unfixed type variables but the input types do not,
2664 // an output type inference is made
2665 for (int i = 0; i < arg_count; i++) {
2666 Type t_i = methodParameters.ParameterType (i);
2667 if (!TypeManager.IsDelegateType (t_i))
2670 MethodInfo mi = Delegate.GetInvokeMethod (t_i, t_i);
2671 Type rtype = mi.ReturnType;
2674 // Blablabla, because reflection does not work with dynamic types
2675 Type[] g_args = t_i.GetGenericArguments ();
2676 rtype = g_args[rtype.GenericParameterPosition];
2679 if (!rtype.IsGenericParameter)
2682 if (tic.IsUnfixed (rtype) < 0)
2685 ParameterData d_parameters = TypeManager.GetParameterData (mi);
2686 bool all_params_fixed = true;
2687 foreach (Type t in d_parameters.Types) {
2688 if (!t.IsGenericParameter)
2691 if (tic.IsUnfixed (t) >= 0) {
2692 all_params_fixed = false;
2697 if (all_params_fixed)
2698 tic.OutputTypeInference (ec, ((Argument) arguments[i]).Expr, t_i);
2702 return DoSecondPhase (ec, tic, methodParameters, true);
2706 public class TypeInferenceContext
2708 readonly Type[] unfixed_types;
2709 readonly Type[] fixed_types;
2710 readonly ArrayList[] bounds;
2712 public TypeInferenceContext (Type[] typeArguments)
2714 if (typeArguments.Length == 0)
2715 throw new ArgumentException ("Empty generic arguments");
2717 unfixed_types = new Type[typeArguments.Length];
2718 Array.Copy (typeArguments, unfixed_types, unfixed_types.Length);
2719 bounds = new ArrayList[typeArguments.Length];
2720 fixed_types = new Type[typeArguments.Length];
2723 public Type[] InferredTypeArguments {
2729 void AddToBounds (Type t, int index)
2731 ArrayList a = bounds[index];
2733 a = new ArrayList ();
2746 // 26.3.3.8 Exact Inference
2748 public void ExactInference (Type u, Type v)
2750 // If V is an array type
2755 if (u.GetArrayRank () != v.GetArrayRank ())
2758 ExactInference (TypeManager.GetElementType (u), TypeManager.GetElementType (v));
2762 // If V is constructed type and U is constructed type
2763 if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2764 if (!u.IsGenericType)
2767 Type [] ga_u = u.GetGenericArguments ();
2768 Type [] ga_v = v.GetGenericArguments ();
2769 if (ga_u.Length != ga_v.Length)
2772 for (int i = 0; i < ga_u.Length; ++i)
2773 ExactInference (ga_u [i], ga_v [i]);
2778 // If V is one of the unfixed type arguments
2779 int pos = IsUnfixed (v);
2783 AddToBounds (u, pos);
2786 public bool FixAllTypes ()
2788 for (int i = 0; i < unfixed_types.Length; ++i) {
2796 // All unfixed type variables Xi are fixed for which all of the following hold:
2797 // a, There is at least one type variable Xj that depends on Xi
2798 // b, Xi has a non-empty set of bounds
2800 public bool FixDependentTypes (ParameterData methodParameters, ref bool fixed_any)
2802 for (int i = 0; i < unfixed_types.Length; ++i) {
2803 if (unfixed_types[i] == null)
2806 if (bounds[i] == null)
2817 // All unfixed type variables Xi which depend on no Xj are fixed
2819 public bool FixIndependentTypeArguments (ParameterData methodParameters, ref bool fixed_any)
2821 ArrayList types_to_fix = new ArrayList (unfixed_types);
2822 foreach (Type t in methodParameters.Types) {
2823 if (t.IsGenericParameter)
2826 if (!TypeManager.IsDelegateType (t))
2829 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
2830 Type rtype = invoke.ReturnType;
2831 if (!rtype.IsGenericParameter)
2835 // Blablabla, because reflection does not work with dynamic types
2836 Type [] g_args = t.GetGenericArguments ();
2837 if (!rtype.IsGenericParameter)
2840 rtype = g_args [rtype.GenericParameterPosition];
2842 if (rtype.IsGenericParameter)
2843 types_to_fix [rtype.GenericParameterPosition] = null;
2846 foreach (Type t in types_to_fix) {
2850 if (!FixType (IsUnfixed (t)))
2854 fixed_any = types_to_fix.Count > 0;
2861 public bool FixType (int i)
2863 // It's already fixed
2864 if (unfixed_types[i] == null)
2865 throw new InternalErrorException ("Type argument has been already fixed");
2867 ArrayList candidates = (ArrayList)bounds [i];
2868 if (candidates == null)
2871 if (candidates.Count == 1) {
2872 unfixed_types[i] = null;
2873 fixed_types[i] = (Type)candidates[0];
2877 // TODO: Review, I think it is still wrong
2878 Type best_candidate = null;
2879 for (int ci = 0; ci < candidates.Count; ++ci) {
2880 TypeExpr candidate = new TypeExpression ((Type)candidates[ci], Location.Null);
2881 bool failed = false;
2882 for (int cii = 0; cii < candidates.Count; ++cii) {
2886 if (!Convert.ImplicitStandardConversionExists (candidate, (Type)candidates[cii])) {
2894 if (best_candidate != null)
2897 best_candidate = candidate.Type;
2900 if (best_candidate == null)
2903 unfixed_types[i] = null;
2904 fixed_types[i] = best_candidate;
2908 public int IsUnfixed (Type type)
2910 if (!type.IsGenericParameter)
2913 //return unfixed_types[type.GenericParameterPosition] != null;
2914 for (int i = 0; i < unfixed_types.Length; ++i) {
2915 if (unfixed_types [i] == type)
2923 // 26.3.3.9 Lower-bound Inference
2925 public void LowerBoundInference (Type u, Type v)
2927 // If U is an array type
2929 int u_dim = u.GetArrayRank ();
2931 Type u_e = TypeManager.GetElementType (u);
2934 if (u_dim != v.GetArrayRank ())
2937 v_e = TypeManager.GetElementType (v);
2940 LowerBoundInference (u_e, v_e);
2943 ExactInference (u_e, v_e);
2950 if (v.IsGenericType) {
2951 Type g_v = v.GetGenericTypeDefinition ();
2952 if ((g_v != TypeManager.generic_ilist_type) && (g_v != TypeManager.generic_icollection_type) &&
2953 (g_v != TypeManager.generic_ienumerable_type))
2956 v_e = TypeManager.GetTypeArguments (v)[0];
2959 LowerBoundInference (u_e, v_e);
2962 ExactInference (u_e, v_e);
2965 // If V is a constructed type C<V1..Vk>
2966 } else if (v.IsGenericType && !v.IsGenericTypeDefinition) {
2967 Type[] ga_u = u.GetGenericArguments ();
2968 Type[] ga_v = v.GetGenericArguments ();
2969 if (ga_u.Length != ga_v.Length)
2972 v = v.GetGenericTypeDefinition ().MakeGenericType (ga_u);
2974 // And standard implicit conversion exists from U to C<U1..Uk>
2975 if (!Convert.ImplicitStandardConversionExists (new TypeExpression (u, Location.Null), v))
2978 for (int i = 0; i < ga_u.Length; ++i)
2979 ExactInference (ga_u[i], ga_v[i]);
2984 // Remove ref, out modifiers
2985 if (v.HasElementType)
2986 v = v.GetElementType ();
2988 // If V is one of the unfixed type arguments
2989 int pos = IsUnfixed (v);
2993 AddToBounds (u, pos);
2997 // 26.3.3.6 Output Type Inference
2999 public void OutputTypeInference (EmitContext ec, Expression e, Type t)
3001 // If e is a lambda or anonymous method with inferred return type
3002 AnonymousMethodExpression ame = e as AnonymousMethodExpression;
3004 Type rt = ame.InferReturnType (ec, this, t);
3006 MethodInfo invoke = Delegate.GetInvokeMethod (t, t);
3007 Type rtype = invoke.ReturnType;
3009 // Blablabla, because reflection does not work with dynamic types
3010 Type [] g_args = t.GetGenericArguments ();
3011 rtype = g_args [rtype.GenericParameterPosition];
3013 LowerBoundInference (rt, rtype);
3018 if (e is MethodGroupExpr) {
3019 throw new NotImplementedException ();
3023 // if e is an expression with type U, then
3024 // a lower-bound inference is made from U for T
3026 LowerBoundInference (e.Type, t);
3029 public bool UnfixedVariableExists {
3031 foreach (Type ut in unfixed_types)
3039 public abstract class Nullable
3041 public sealed class NullableInfo
3043 public readonly Type Type;
3044 public readonly Type UnderlyingType;
3045 public readonly MethodInfo HasValue;
3046 public readonly MethodInfo Value;
3047 public readonly ConstructorInfo Constructor;
3049 public NullableInfo (Type type)
3052 UnderlyingType = TypeManager.GetTypeArguments (type) [0];
3054 PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
3055 PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
3057 HasValue = has_value_pi.GetGetMethod (false);
3058 Value = value_pi.GetGetMethod (false);
3059 Constructor = type.GetConstructor (new Type[] { UnderlyingType });
3063 public class Unwrap : Expression, IMemoryLocation, IAssignMethod
3068 LocalTemporary temp;
3071 protected Unwrap (Expression expr)
3074 this.loc = expr.Location;
3077 public static Unwrap Create (Expression expr, EmitContext ec)
3079 return new Unwrap (expr).Resolve (ec) as Unwrap;
3082 public override Expression DoResolve (EmitContext ec)
3084 expr = expr.Resolve (ec);
3088 temp = new LocalTemporary (expr.Type);
3090 info = new NullableInfo (expr.Type);
3091 type = info.UnderlyingType;
3092 eclass = expr.eclass;
3096 public override void Emit (EmitContext ec)
3098 AddressOf (ec, AddressOp.LoadStore);
3099 ec.ig.EmitCall (OpCodes.Call, info.Value, null);
3102 public void EmitCheck (EmitContext ec)
3104 AddressOf (ec, AddressOp.LoadStore);
3105 ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
3108 public void Store (EmitContext ec)
3113 void create_temp (EmitContext ec)
3115 if ((temp != null) && !has_temp) {
3122 public void AddressOf (EmitContext ec, AddressOp mode)
3126 temp.AddressOf (ec, AddressOp.LoadStore);
3128 ((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
3131 public void Emit (EmitContext ec, bool leave_copy)
3144 public void EmitAssign (EmitContext ec, Expression source,
3145 bool leave_copy, bool prepare_for_load)
3147 InternalWrap wrap = new InternalWrap (source, info, loc);
3148 ((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
3151 protected class InternalWrap : Expression
3153 public Expression expr;
3154 public NullableInfo info;
3156 public InternalWrap (Expression expr, NullableInfo info, Location loc)
3163 eclass = ExprClass.Value;
3166 public override Expression DoResolve (EmitContext ec)
3171 public override void Emit (EmitContext ec)
3174 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3179 public class Wrap : Expression
3184 protected Wrap (Expression expr)
3187 this.loc = expr.Location;
3190 public static Wrap Create (Expression expr, EmitContext ec)
3192 return new Wrap (expr).Resolve (ec) as Wrap;
3195 public override Expression DoResolve (EmitContext ec)
3197 expr = expr.Resolve (ec);
3201 TypeExpr target_type = new NullableType (expr.Type, loc);
3202 target_type = target_type.ResolveAsTypeTerminal (ec, false);
3203 if (target_type == null)
3206 type = target_type.Type;
3207 info = new NullableInfo (type);
3208 eclass = ExprClass.Value;
3212 public override void Emit (EmitContext ec)
3215 ec.ig.Emit (OpCodes.Newobj, info.Constructor);
3219 public class NullableLiteral : NullLiteral, IMemoryLocation {
3220 public NullableLiteral (Type target_type, Location loc)
3223 this.type = target_type;
3225 eclass = ExprClass.Value;
3228 public override Expression DoResolve (EmitContext ec)
3233 public override void Emit (EmitContext ec)
3235 LocalTemporary value_target = new LocalTemporary (type);
3237 value_target.AddressOf (ec, AddressOp.Store);
3238 ec.ig.Emit (OpCodes.Initobj, type);
3239 value_target.Emit (ec);
3242 public void AddressOf (EmitContext ec, AddressOp Mode)
3244 LocalTemporary value_target = new LocalTemporary (type);
3246 value_target.AddressOf (ec, AddressOp.Store);
3247 ec.ig.Emit (OpCodes.Initobj, type);
3248 ((IMemoryLocation) value_target).AddressOf (ec, Mode);
3252 public abstract class Lifted : Expression, IMemoryLocation
3254 Expression expr, underlying, wrap, null_value;
3257 protected Lifted (Expression expr, Location loc)
3263 public override Expression DoResolve (EmitContext ec)
3265 expr = expr.Resolve (ec);
3269 unwrap = Unwrap.Create (expr, ec);
3273 underlying = ResolveUnderlying (unwrap, ec);
3274 if (underlying == null)
3277 wrap = Wrap.Create (underlying, ec);
3281 null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
3282 if (null_value == null)
3286 eclass = ExprClass.Value;
3290 protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
3292 public override void Emit (EmitContext ec)
3294 ILGenerator ig = ec.ig;
3295 Label is_null_label = ig.DefineLabel ();
3296 Label end_label = ig.DefineLabel ();
3298 unwrap.EmitCheck (ec);
3299 ig.Emit (OpCodes.Brfalse, is_null_label);
3302 ig.Emit (OpCodes.Br, end_label);
3304 ig.MarkLabel (is_null_label);
3305 null_value.Emit (ec);
3307 ig.MarkLabel (end_label);
3310 public void AddressOf (EmitContext ec, AddressOp mode)
3312 unwrap.AddressOf (ec, mode);
3316 public class LiftedConversion : Lifted
3318 public readonly bool IsUser;
3319 public readonly bool IsExplicit;
3320 public readonly Type TargetType;
3322 public LiftedConversion (Expression expr, Type target_type, bool is_user,
3323 bool is_explicit, Location loc)
3326 this.IsUser = is_user;
3327 this.IsExplicit = is_explicit;
3328 this.TargetType = target_type;
3331 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3333 Type type = TypeManager.GetTypeArguments (TargetType) [0];
3336 return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
3339 return Convert.ExplicitConversion (ec, unwrap, type, loc);
3341 return Convert.ImplicitConversion (ec, unwrap, type, loc);
3346 public class LiftedUnaryOperator : Lifted
3348 public readonly Unary.Operator Oper;
3350 public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
3356 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3358 return new Unary (Oper, unwrap, loc);
3362 public class LiftedConditional : Lifted
3364 Expression true_expr, false_expr;
3366 public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
3370 this.true_expr = true_expr;
3371 this.false_expr = false_expr;
3374 protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
3376 return new Conditional (unwrap, true_expr, false_expr);
3380 public class LiftedBinaryOperator : Expression
3382 public readonly Binary.Operator Oper;
3384 Expression left, right, original_left, original_right;
3385 Expression underlying, null_value, bool_wrap;
3386 Unwrap left_unwrap, right_unwrap;
3387 bool is_equality, is_comparision, is_boolean;
3389 public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
3393 this.left = original_left = left;
3394 this.right = original_right = right;
3398 public override Expression DoResolve (EmitContext ec)
3400 if (TypeManager.IsNullableType (left.Type)) {
3401 left = left_unwrap = Unwrap.Create (left, ec);
3406 if (TypeManager.IsNullableType (right.Type)) {
3407 right = right_unwrap = Unwrap.Create (right, ec);
3412 if ((Oper == Binary.Operator.LogicalAnd) ||
3413 (Oper == Binary.Operator.LogicalOr)) {
3414 Binary.Error_OperatorCannotBeApplied (
3415 loc, Binary.OperName (Oper),
3416 original_left.GetSignatureForError (),
3417 original_right.GetSignatureForError ());
3421 if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
3422 ((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
3423 Expression empty = new EmptyExpression (TypeManager.bool_type);
3424 bool_wrap = Wrap.Create (empty, ec);
3425 null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
3427 type = bool_wrap.Type;
3429 } else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
3430 if (!(left is NullLiteral) && !(right is NullLiteral)) {
3431 underlying = new Binary (Oper, left, right).Resolve (ec);
3432 if (underlying == null)
3436 type = TypeManager.bool_type;
3438 } else if ((Oper == Binary.Operator.LessThan) ||
3439 (Oper == Binary.Operator.GreaterThan) ||
3440 (Oper == Binary.Operator.LessThanOrEqual) ||
3441 (Oper == Binary.Operator.GreaterThanOrEqual)) {
3442 underlying = new Binary (Oper, left, right).Resolve (ec);
3443 if (underlying == null)
3446 type = TypeManager.bool_type;
3447 is_comparision = true;
3449 underlying = new Binary (Oper, left, right).Resolve (ec);
3450 if (underlying == null)
3453 underlying = Wrap.Create (underlying, ec);
3454 if (underlying == null)
3457 type = underlying.Type;
3458 null_value = new NullableLiteral (type, loc).Resolve (ec);
3461 eclass = ExprClass.Value;
3465 void EmitBoolean (EmitContext ec)
3467 ILGenerator ig = ec.ig;
3469 Label left_is_null_label = ig.DefineLabel ();
3470 Label right_is_null_label = ig.DefineLabel ();
3471 Label is_null_label = ig.DefineLabel ();
3472 Label wrap_label = ig.DefineLabel ();
3473 Label end_label = ig.DefineLabel ();
3475 if (left_unwrap != null) {
3476 left_unwrap.EmitCheck (ec);
3477 ig.Emit (OpCodes.Brfalse, left_is_null_label);
3481 ig.Emit (OpCodes.Dup);
3482 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3483 ig.Emit (OpCodes.Brtrue, wrap_label);
3485 ig.Emit (OpCodes.Brfalse, wrap_label);
3487 if (right_unwrap != null) {
3488 right_unwrap.EmitCheck (ec);
3489 ig.Emit (OpCodes.Brfalse, right_is_null_label);
3492 if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
3493 ig.Emit (OpCodes.Pop);
3496 if (Oper == Binary.Operator.BitwiseOr)
3497 ig.Emit (OpCodes.Or);
3498 else if (Oper == Binary.Operator.BitwiseAnd)
3499 ig.Emit (OpCodes.And);
3500 ig.Emit (OpCodes.Br, wrap_label);
3502 ig.MarkLabel (left_is_null_label);
3503 if (right_unwrap != null) {
3504 right_unwrap.EmitCheck (ec);
3505 ig.Emit (OpCodes.Brfalse, is_null_label);
3509 ig.Emit (OpCodes.Dup);
3510 if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
3511 ig.Emit (OpCodes.Brtrue, wrap_label);
3513 ig.Emit (OpCodes.Brfalse, wrap_label);
3515 ig.MarkLabel (right_is_null_label);
3516 ig.Emit (OpCodes.Pop);
3517 ig.MarkLabel (is_null_label);
3518 null_value.Emit (ec);
3519 ig.Emit (OpCodes.Br, end_label);
3521 ig.MarkLabel (wrap_label);
3522 ig.Emit (OpCodes.Nop);
3523 bool_wrap.Emit (ec);
3524 ig.Emit (OpCodes.Nop);
3526 ig.MarkLabel (end_label);
3529 void EmitEquality (EmitContext ec)
3531 ILGenerator ig = ec.ig;
3533 // Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
3534 if (left is NullLiteral) {
3535 if (right_unwrap == null)
3536 throw new InternalErrorException ();
3537 right_unwrap.EmitCheck (ec);
3538 if (Oper == Binary.Operator.Equality) {
3539 ig.Emit (OpCodes.Ldc_I4_0);
3540 ig.Emit (OpCodes.Ceq);
3545 if (right is NullLiteral) {
3546 if (left_unwrap == null)
3547 throw new InternalErrorException ();
3548 left_unwrap.EmitCheck (ec);
3549 if (Oper == Binary.Operator.Equality) {
3550 ig.Emit (OpCodes.Ldc_I4_0);
3551 ig.Emit (OpCodes.Ceq);
3556 Label both_have_value_label = ig.DefineLabel ();
3557 Label end_label = ig.DefineLabel ();
3559 if (left_unwrap != null && right_unwrap != null) {
3560 Label dissimilar_label = ig.DefineLabel ();
3562 left_unwrap.EmitCheck (ec);
3563 ig.Emit (OpCodes.Dup);
3564 right_unwrap.EmitCheck (ec);
3565 ig.Emit (OpCodes.Bne_Un, dissimilar_label);
3567 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3570 if (Oper == Binary.Operator.Equality)
3571 ig.Emit (OpCodes.Ldc_I4_1);
3573 ig.Emit (OpCodes.Ldc_I4_0);
3574 ig.Emit (OpCodes.Br, end_label);
3576 ig.MarkLabel (dissimilar_label);
3577 ig.Emit (OpCodes.Pop);
3578 } else if (left_unwrap != null) {
3579 left_unwrap.EmitCheck (ec);
3580 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3581 } else if (right_unwrap != null) {
3582 right_unwrap.EmitCheck (ec);
3583 ig.Emit (OpCodes.Brtrue, both_have_value_label);
3585 throw new InternalErrorException ("shouldn't get here");
3588 // one is null while the other isn't
3589 if (Oper == Binary.Operator.Equality)
3590 ig.Emit (OpCodes.Ldc_I4_0);
3592 ig.Emit (OpCodes.Ldc_I4_1);
3593 ig.Emit (OpCodes.Br, end_label);
3595 ig.MarkLabel (both_have_value_label);
3596 underlying.Emit (ec);
3598 ig.MarkLabel (end_label);
3601 void EmitComparision (EmitContext ec)
3603 ILGenerator ig = ec.ig;
3605 Label is_null_label = ig.DefineLabel ();
3606 Label end_label = ig.DefineLabel ();
3608 if (left_unwrap != null) {
3609 left_unwrap.EmitCheck (ec);
3610 ig.Emit (OpCodes.Brfalse, is_null_label);
3613 if (right_unwrap != null) {
3614 right_unwrap.EmitCheck (ec);
3615 ig.Emit (OpCodes.Brfalse, is_null_label);
3618 underlying.Emit (ec);
3619 ig.Emit (OpCodes.Br, end_label);
3621 ig.MarkLabel (is_null_label);
3622 ig.Emit (OpCodes.Ldc_I4_0);
3624 ig.MarkLabel (end_label);
3627 public override void Emit (EmitContext ec)
3629 if (left_unwrap != null)
3630 left_unwrap.Store (ec);
3631 if (right_unwrap != null)
3632 right_unwrap.Store (ec);
3637 } else if (is_equality) {
3640 } else if (is_comparision) {
3641 EmitComparision (ec);
3645 ILGenerator ig = ec.ig;
3647 Label is_null_label = ig.DefineLabel ();
3648 Label end_label = ig.DefineLabel ();
3650 if (left_unwrap != null) {
3651 left_unwrap.EmitCheck (ec);
3652 ig.Emit (OpCodes.Brfalse, is_null_label);
3655 if (right_unwrap != null) {
3656 right_unwrap.EmitCheck (ec);
3657 ig.Emit (OpCodes.Brfalse, is_null_label);
3660 underlying.Emit (ec);
3661 ig.Emit (OpCodes.Br, end_label);
3663 ig.MarkLabel (is_null_label);
3664 null_value.Emit (ec);
3666 ig.MarkLabel (end_label);
3670 public class OperatorTrueOrFalse : Expression
3672 public readonly bool IsTrue;
3677 public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
3679 this.IsTrue = is_true;
3684 public override Expression DoResolve (EmitContext ec)
3686 unwrap = Unwrap.Create (expr, ec);
3690 if (unwrap.Type != TypeManager.bool_type)
3693 type = TypeManager.bool_type;
3694 eclass = ExprClass.Value;
3698 public override void Emit (EmitContext ec)
3700 ILGenerator ig = ec.ig;
3702 Label is_null_label = ig.DefineLabel ();
3703 Label end_label = ig.DefineLabel ();
3705 unwrap.EmitCheck (ec);
3706 ig.Emit (OpCodes.Brfalse, is_null_label);
3710 ig.Emit (OpCodes.Ldc_I4_0);
3711 ig.Emit (OpCodes.Ceq);
3713 ig.Emit (OpCodes.Br, end_label);
3715 ig.MarkLabel (is_null_label);
3716 ig.Emit (OpCodes.Ldc_I4_0);
3718 ig.MarkLabel (end_label);
3722 public class NullCoalescingOperator : Expression
3724 Expression left, right;
3728 public NullCoalescingOperator (Expression left, Expression right, Location loc)
3734 eclass = ExprClass.Value;
3737 public override Expression DoResolve (EmitContext ec)
3742 left = left.Resolve (ec);
3746 right = right.Resolve (ec);
3750 Type ltype = left.Type, rtype = right.Type;
3752 if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
3753 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3757 if (TypeManager.IsNullableType (ltype)) {
3758 NullableInfo info = new NullableInfo (ltype);
3760 unwrap = Unwrap.Create (left, ec);
3764 expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
3772 expr = Convert.ImplicitConversion (ec, right, ltype, loc);
3778 Expression left_null = unwrap != null ? unwrap : left;
3779 expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
3787 Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
3791 public override void Emit (EmitContext ec)
3793 ILGenerator ig = ec.ig;
3795 Label is_null_label = ig.DefineLabel ();
3796 Label end_label = ig.DefineLabel ();
3798 if (unwrap != null) {
3799 unwrap.EmitCheck (ec);
3800 ig.Emit (OpCodes.Brfalse, is_null_label);
3803 ig.Emit (OpCodes.Br, end_label);
3805 ig.MarkLabel (is_null_label);
3808 ig.MarkLabel (end_label);
3811 ig.Emit (OpCodes.Dup);
3812 ig.Emit (OpCodes.Brtrue, end_label);
3814 ig.MarkLabel (is_null_label);
3816 ig.Emit (OpCodes.Pop);
3819 ig.MarkLabel (end_label);
3824 public class LiftedUnaryMutator : ExpressionStatement
3826 public readonly UnaryMutator.Mode Mode;
3827 Expression expr, null_value;
3828 UnaryMutator underlying;
3831 public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
3837 eclass = ExprClass.Value;
3840 public override Expression DoResolve (EmitContext ec)
3842 expr = expr.Resolve (ec);
3846 unwrap = Unwrap.Create (expr, ec);
3850 underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
3851 if (underlying == null)
3854 null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
3855 if (null_value == null)
3862 void DoEmit (EmitContext ec, bool is_expr)
3864 ILGenerator ig = ec.ig;
3865 Label is_null_label = ig.DefineLabel ();
3866 Label end_label = ig.DefineLabel ();
3868 unwrap.EmitCheck (ec);
3869 ig.Emit (OpCodes.Brfalse, is_null_label);
3872 underlying.Emit (ec);
3874 underlying.EmitStatement (ec);
3875 ig.Emit (OpCodes.Br, end_label);
3877 ig.MarkLabel (is_null_label);
3879 null_value.Emit (ec);
3881 ig.MarkLabel (end_label);
3884 public override void Emit (EmitContext ec)
3889 public override void EmitStatement (EmitContext ec)