2 // generic.cs: Support classes for generics
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2003 Ximian, Inc.
10 using System.Reflection;
11 using System.Reflection.Emit;
12 using System.Globalization;
13 using System.Collections;
16 namespace Mono.CSharp {
19 // Tracks the constraints for a type parameter
21 public class Constraints : GenericConstraints {
23 ArrayList constraints;
27 // name is the identifier, constraints is an arraylist of
28 // Expressions (with types) or `true' for the constructor constraint.
30 public Constraints (string name, ArrayList constraints,
34 this.constraints = constraints;
38 public string TypeParameter {
44 bool has_ctor_constraint;
45 TypeExpr class_constraint;
46 ArrayList iface_constraints;
47 TypeExpr[] constraint_types;
48 int num_constraints, first_constraint;
51 public bool HasConstructorConstraint {
52 get { return has_ctor_constraint; }
55 public bool Resolve (DeclSpace ds)
57 iface_constraints = new ArrayList ();
59 foreach (object obj in constraints) {
60 if (has_ctor_constraint) {
61 Report.Error (401, loc,
62 "The new() constraint must be last.");
67 has_ctor_constraint = true;
71 TypeExpr expr = ds.ResolveTypeExpr ((Expression) obj, false, loc);
75 if (expr is TypeParameterExpr) {
76 Report.Error (700, loc,
77 "`{0}': naked type parameters cannot " +
78 "be used as bounds", expr.Name);
83 iface_constraints.Add (expr);
84 else if (class_constraint != null) {
85 Report.Error (406, loc,
86 "`{0}': the class constraint for `{1}' " +
87 "must come before any other constraints.",
91 class_constraint = expr;
96 constraint_types = new TypeExpr [num_constraints];
97 if (class_constraint != null)
98 constraint_types [first_constraint++] = class_constraint;
99 iface_constraints.CopyTo (constraint_types, first_constraint);
104 public Type[] ResolveTypes (EmitContext ec)
106 types = new Type [constraint_types.Length];
108 for (int i = 0; i < constraint_types.Length; i++) {
109 types [i] = constraint_types [i].ResolveType (ec);
110 if (types [i] == null)
113 for (int j = first_constraint; j < i; j++) {
114 if (!types [j].Equals (types [i]))
117 Report.Error (405, loc,
118 "Duplicate constraint `{0}' for type " +
119 "parameter `{1}'.", types [i], name);
124 if (class_constraint != null) {
125 if (types [0].IsSealed) {
126 Report.Error (701, loc,
127 "`{0}' is not a valid bound. Bounds " +
128 "must be interfaces or non sealed " +
129 "classes", types [0]);
133 if ((types [0] == TypeManager.array_type) ||
134 (types [0] == TypeManager.delegate_type) ||
135 (types [0] == TypeManager.enum_type) ||
136 (types [0] == TypeManager.value_type) ||
137 (types [0] == TypeManager.object_type)) {
138 Report.Error (702, loc,
139 "Bound cannot be special class `{0}'",
148 bool GenericConstraints.HasConstructor {
150 return has_ctor_constraint;
154 Type[] GenericConstraints.Types {
157 throw new InvalidOperationException ();
165 // This type represents a generic type parameter
167 public class TypeParameter {
169 Constraints constraints;
173 public TypeParameter (string name, Constraints constraints, Location loc)
176 this.constraints = constraints;
186 public Location Location {
192 public Constraints Constraints {
198 public bool HasConstructorConstraint {
200 if (constraints != null)
201 return constraints.HasConstructorConstraint;
213 public bool Resolve (DeclSpace ds)
215 if (constraints != null)
216 return constraints.Resolve (ds);
221 public Type Define (TypeBuilder tb)
223 type = tb.DefineGenericParameter (name);
224 TypeManager.AddTypeParameter (type, this);
228 public Type DefineMethod (MethodBuilder mb)
230 type = mb.DefineGenericParameter (name);
231 TypeManager.AddTypeParameter (type, this);
235 public bool DefineType (EmitContext ec, TypeBuilder tb)
237 int index = type.GenericParameterPosition;
238 if (constraints == null)
239 tb.SetGenericParameterConstraints (index, new Type [0], false);
241 Type[] types = constraints.ResolveTypes (ec);
245 tb.SetGenericParameterConstraints (
246 index, types, constraints.HasConstructorConstraint);
252 public bool DefineType (EmitContext ec, MethodBuilder mb)
254 int index = type.GenericParameterPosition;
255 if (constraints == null)
256 mb.SetGenericParameterConstraints (index, new Type [0], false);
258 Type[] types = constraints.ResolveTypes (ec);
262 mb.SetGenericParameterConstraints (
263 index, types, constraints.HasConstructorConstraint);
269 public override string ToString ()
271 return "TypeParameter[" + name + "]";
276 // This type represents a generic type parameter reference.
278 // These expressions are born in a fully resolved state.
280 public class TypeParameterExpr : TypeExpr {
281 TypeParameter type_parameter;
283 public override string Name {
285 return type_parameter.Name;
289 public TypeParameter TypeParameter {
291 return type_parameter;
295 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
297 this.type_parameter = type_parameter;
301 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
303 type = type_parameter.Type;
308 public void Error_CannotUseAsUnmanagedType (Location loc)
310 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
314 public class TypeArguments {
315 public readonly Location Location;
321 public TypeArguments (Location loc)
323 args = new ArrayList ();
327 public void Add (Expression type)
330 throw new InvalidOperationException ();
335 public void Add (TypeArguments new_args)
338 throw new InvalidOperationException ();
340 args.AddRange (new_args.args);
343 public string[] GetDeclarations ()
345 string[] ret = new string [args.Count];
346 for (int i = 0; i < args.Count; i++) {
347 SimpleName sn = args [i] as SimpleName;
353 Report.Error (81, Location, "Type parameter declaration " +
354 "must be an identifier not a type");
360 public Type[] Arguments {
366 public bool HasTypeArguments {
368 return has_type_args;
378 public override string ToString ()
380 StringBuilder s = new StringBuilder ();
382 int count = args.Count;
383 for (int i = 0; i < count; i++){
385 // FIXME: Use TypeManager.CSharpname once we have the type
387 s.Append (args [i].ToString ());
391 return s.ToString ();
394 public bool Resolve (EmitContext ec)
396 DeclSpace ds = ec.DeclSpace;
397 int count = args.Count;
400 atypes = new Type [count];
402 for (int i = 0; i < count; i++){
403 TypeExpr te = ds.ResolveTypeExpr (
404 (Expression) args [i], false, Location);
409 if (te is TypeParameterExpr)
410 has_type_args = true;
411 atypes [i] = te.ResolveType (ec);
413 if (atypes [i] == null) {
414 Report.Error (246, Location, "Cannot find type `{0}'",
423 public class ConstructedType : TypeExpr {
424 string name, full_name;
426 Type[] gen_params, atypes;
429 public ConstructedType (string name, TypeArguments args, Location l)
435 eclass = ExprClass.Type;
436 full_name = name + "<" + args.ToString () + ">";
439 public ConstructedType (string name, TypeParameter[] type_params, Location l)
440 : this (type_params, l)
445 full_name = name + "<" + args.ToString () + ">";
448 protected ConstructedType (TypeArguments args, Location l)
453 eclass = ExprClass.Type;
456 protected ConstructedType (TypeParameter[] type_params, Location l)
460 args = new TypeArguments (l);
461 foreach (TypeParameter type_param in type_params)
462 args.Add (new TypeParameterExpr (type_param, l));
464 eclass = ExprClass.Type;
467 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
468 : this (type_params, l)
470 gt = t.GetGenericTypeDefinition ();
472 this.name = gt.FullName;
473 full_name = gt.FullName + "<" + args.ToString () + ">";
476 public ConstructedType (Type t, TypeArguments args, Location l)
479 gt = t.GetGenericTypeDefinition ();
481 this.name = gt.FullName;
482 full_name = gt.FullName + "<" + args.ToString () + ">";
485 public TypeArguments TypeArguments {
489 protected string DeclarationName {
491 StringBuilder sb = new StringBuilder ();
492 sb.Append (gt.FullName);
494 for (int i = 0; i < gen_params.Length; i++) {
497 sb.Append (gen_params [i]);
500 return sb.ToString ();
504 protected bool CheckConstraints (EmitContext ec, int index)
506 Type atype = atypes [index];
507 Type ptype = gen_params [index];
512 Expression aexpr = new EmptyExpression (atype);
515 // First, check the class constraint.
518 Type parent = ptype.BaseType;
519 if ((parent != null) && (parent != TypeManager.object_type)) {
520 if (!Convert.ImplicitStandardConversionExists (aexpr, parent)) {
521 Report.Error (309, loc, "The type `{0}' must be " +
522 "convertible to `{1}' in order to " +
523 "use it as parameter `{2}' in the " +
524 "generic type or method `{3}'",
525 atype, parent, ptype, DeclarationName);
531 // Now, check the interface constraints.
533 foreach (Type itype in ptype.GetInterfaces ()) {
534 if (!Convert.ImplicitStandardConversionExists (aexpr, itype)) {
535 Report.Error (309, loc, "The type `{0}' must be " +
536 "convertible to `{1}' in order to " +
537 "use it as parameter `{2}' in the " +
538 "generic type or method `{3}'",
539 atype, itype, ptype, DeclarationName);
545 // Finally, check the constructor constraint.
548 if (!TypeManager.HasConstructorConstraint (ptype))
551 MethodGroupExpr mg = Expression.MemberLookup (
552 ec, atype, ".ctor", MemberTypes.Constructor,
553 BindingFlags.Public | BindingFlags.Instance |
554 BindingFlags.DeclaredOnly, loc)
557 if (atype.IsAbstract || (mg == null) || !mg.IsInstance) {
558 Report.Error (310, loc, "The type `{0}' must have a public " +
559 "parameterless constructor in order to use it " +
560 "as parameter `{1}' in the generic type or " +
561 "method `{2}'", atype, ptype, DeclarationName);
568 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
574 // First, resolve the generic type.
577 Type nested = ec.DeclSpace.FindNestedType (loc, name, out ds);
578 if (nested != null) {
579 gt = nested.GetGenericTypeDefinition ();
581 TypeArguments new_args = new TypeArguments (loc);
582 foreach (TypeParameter param in ds.TypeParameters)
583 new_args.Add (new TypeParameterExpr (param, loc));
593 SimpleName sn = new SimpleName (name, args.Count, loc);
594 TypeExpr resolved = sn.ResolveAsTypeTerminal (ec);
595 if (resolved == null) {
596 sn = new SimpleName (name, -1, loc);
597 resolved = sn.ResolveAsTypeTerminal (ec);
598 if ((resolved == null) || (resolved.Type == null)) {
599 Report.Error (246, loc,
600 "The type or namespace name `{0}<...>' "+
601 "could not be found", name);
606 num_args = TypeManager.GetNumberOfTypeArguments (t);
609 Report.Error (308, loc,
610 "The non-generic type `{0}' cannot " +
611 "be used with type arguments.",
612 TypeManager.CSharpName (t));
616 Report.Error (305, loc,
617 "Using the generic type `{0}' " +
618 "requires {1} type arguments",
619 TypeManager.GetFullName (t), num_args);
625 Report.Error (246, loc, "Cannot find type `{0}'", full_name);
629 num_args = TypeManager.GetNumberOfTypeArguments (t);
631 Report.Error (308, loc,
632 "The non-generic type `{0}' cannot " +
633 "be used with type arguments.",
634 TypeManager.CSharpName (t));
638 gt = t.GetGenericTypeDefinition ();
642 public override Type ResolveType (EmitContext ec)
646 if (DoResolveAsTypeStep (ec) == null)
650 // Resolve the arguments.
652 if (args.Resolve (ec) == false)
655 gen_params = gt.GetGenericArguments ();
656 atypes = args.Arguments;
658 if (atypes.Length != gen_params.Length) {
659 Report.Error (305, loc,
660 "Using the generic type `{0}' " +
661 "requires {1} type arguments",
662 TypeManager.GetFullName (gt),
667 for (int i = 0; i < gen_params.Length; i++) {
668 if (!CheckConstraints (ec, i))
673 // Now bind the parameters.
675 type = gt.BindGenericParameters (atypes);
679 public Expression GetMemberAccess (EmitContext ec)
682 if (ec.TypeContainer.CurrentType != null)
683 current = ec.TypeContainer.CurrentType;
685 current = new TypeExpression (ec.ContainerType, loc);
687 return new GenericMemberAccess (current, name, args, loc);
690 public override bool CheckAccessLevel (DeclSpace ds)
692 return ds.CheckAccessLevel (gt);
695 public override bool AsAccessible (DeclSpace ds, int flags)
697 return ds.AsAccessible (gt, flags);
700 public override bool IsClass {
701 get { return gt.IsClass; }
704 public override bool IsValueType {
705 get { return gt.IsValueType; }
708 public override bool IsInterface {
709 get { return gt.IsInterface; }
712 public override bool IsSealed {
713 get { return gt.IsSealed; }
716 public override bool IsAttribute {
717 get { return false; }
720 public override TypeExpr[] GetInterfaces ()
722 TypeExpr[] ifaces = TypeManager.GetInterfaces (gt);
726 public override bool Equals (object obj)
728 ConstructedType cobj = obj as ConstructedType;
732 if ((type == null) || (cobj.type == null))
735 return type == cobj.type;
738 public override string Name {
745 public class GenericMethod : DeclSpace
747 public GenericMethod (NamespaceEntry ns, TypeContainer parent, string name,
748 Attributes attrs, Location l)
749 : base (ns, parent, name, attrs, l)
752 public override TypeBuilder DefineType ()
754 throw new Exception ();
757 public override bool Define (TypeContainer parent)
759 for (int i = 0; i < TypeParameters.Length; i++)
760 if (!TypeParameters [i].Resolve (parent))
766 public bool Define (TypeContainer parent, MethodBuilder mb)
768 if (!Define (parent))
771 Type[] gen_params = new Type [TypeParameters.Length];
772 for (int i = 0; i < TypeParameters.Length; i++)
773 gen_params [i] = TypeParameters [i].DefineMethod (mb);
778 public bool DefineType (EmitContext ec, MethodBuilder mb)
780 for (int i = 0; i < TypeParameters.Length; i++)
781 if (!TypeParameters [i].DefineType (ec, mb))
787 public override bool DefineMembers (TypeContainer parent)
792 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
793 MemberFilter filter, object criteria)
795 throw new Exception ();
798 public override MemberCache MemberCache {
800 throw new Exception ();
805 public class GenericMemberAccess : MemberAccess
809 public GenericMemberAccess (Expression expr, string id, TypeArguments args, Location loc)
810 : base (expr, id, args.Count, loc)
815 private bool DoResolveBase (EmitContext ec)
817 ConstructedType cexpr = expr as ConstructedType;
819 TypeArguments new_args = new TypeArguments (loc);
820 new_args.Add (cexpr.TypeArguments);
829 public override Expression DoResolve (EmitContext ec, Expression right_side,
832 if (!DoResolveBase (ec))
835 Expression expr = base.DoResolve (ec, right_side, flags);
839 TypeExpr texpr = expr as TypeExpr;
841 Type t = texpr.ResolveType (ec);
845 ConstructedType ctype = new ConstructedType (t, args, loc);
846 return ctype.DoResolve (ec);
849 MethodGroupExpr mg = expr as MethodGroupExpr;
852 Report.Error (-220, loc, "Member `{0}' has type arguments, but did " +
853 "not resolve as a method group.", Identifier);
857 if (args.Resolve (ec) == false)
860 Type[] atypes = args.Arguments;
862 ArrayList list = new ArrayList ();
864 foreach (MethodBase method in mg.Methods) {
865 MethodInfo mi = method as MethodInfo;
869 Type[] gen_params = mi.GetGenericParameters ();
871 if (atypes.Length != gen_params.Length) {
872 Report.Error (-217, loc, "Generic method `{0}' takes {1} " +
873 "type parameters, but specified {2}.", mi.Name,
874 gen_params.Length, atypes.Length);
878 list.Add (mi.BindGenericParameters (args.Arguments));
881 MethodInfo[] methods = new MethodInfo [list.Count];
882 list.CopyTo (methods, 0);
884 MethodGroupExpr new_mg = new MethodGroupExpr (methods, mg.Location);
885 new_mg.InstanceExpression = mg.InstanceExpression;
886 new_mg.HasTypeArguments = true;
890 public override Expression ResolveAsTypeStep (EmitContext ec)
892 if (!DoResolveBase (ec))
895 expr = base.ResolveAsTypeStep (ec);
899 Type t = ((TypeExpr) expr).ResolveType (ec);
903 ConstructedType ctype = new ConstructedType (t, args, loc);
904 return ctype.ResolveAsTypeStep (ec);
908 public class DefaultValueExpression : Expression
911 LocalTemporary temp_storage;
913 public DefaultValueExpression (Expression expr, Location loc)
919 public override Expression DoResolve (EmitContext ec)
921 type = ec.DeclSpace.ResolveType (expr, false, loc);
925 if (type.IsGenericParameter || TypeManager.IsValueType (type))
926 temp_storage = new LocalTemporary (ec, type);
928 eclass = ExprClass.Variable;
932 public override void Emit (EmitContext ec)
934 if (temp_storage != null) {
935 temp_storage.AddressOf (ec, AddressOp.LoadStore);
936 ec.ig.Emit (OpCodes.Initobj, type);
937 temp_storage.Emit (ec);
939 ec.ig.Emit (OpCodes.Ldnull);