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 {
204 public bool Resolve (DeclSpace ds)
206 if (constraints != null)
207 return constraints.Resolve (ds);
212 public Type Define (TypeBuilder tb)
214 type = tb.DefineGenericParameter (name);
218 public Type DefineMethod (MethodBuilder mb)
220 type = mb.DefineGenericParameter (name);
224 public bool DefineType (EmitContext ec, TypeBuilder tb)
226 int index = type.GenericParameterPosition;
227 if (constraints == null)
228 tb.SetGenericParameterConstraints (index, new Type [0], false);
230 Type[] types = constraints.ResolveTypes (ec);
234 tb.SetGenericParameterConstraints (
235 index, types, constraints.HasConstructorConstraint);
241 public bool DefineType (EmitContext ec, MethodBuilder mb)
243 int index = type.GenericParameterPosition;
244 if (constraints == null)
245 mb.SetGenericParameterConstraints (index, new Type [0], false);
247 Type[] types = constraints.ResolveTypes (ec);
251 mb.SetGenericParameterConstraints (
252 index, types, constraints.HasConstructorConstraint);
258 public override string ToString ()
260 return "TypeParameter[" + name + "]";
265 // This type represents a generic type parameter reference.
267 // These expressions are born in a fully resolved state.
269 public class TypeParameterExpr : TypeExpr {
270 TypeParameter type_parameter;
272 public override string Name {
274 return type_parameter.Name;
278 public TypeParameter TypeParameter {
280 return type_parameter;
284 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
286 this.type_parameter = type_parameter;
290 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
292 type = type_parameter.Type;
297 public void Error_CannotUseAsUnmanagedType (Location loc)
299 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
303 public class TypeArguments {
304 public readonly Location Location;
310 public TypeArguments (Location loc)
312 args = new ArrayList ();
316 public void Add (Expression type)
319 throw new InvalidOperationException ();
324 public void Add (TypeArguments new_args)
327 throw new InvalidOperationException ();
329 args.AddRange (new_args.args);
332 public string[] GetDeclarations ()
334 string[] ret = new string [args.Count];
335 for (int i = 0; i < args.Count; i++) {
336 SimpleName sn = args [i] as SimpleName;
342 Report.Error (81, Location, "Type parameter declaration " +
343 "must be an identifier not a type");
349 public Type[] Arguments {
355 public bool HasTypeArguments {
357 return has_type_args;
367 public override string ToString ()
369 StringBuilder s = new StringBuilder ();
371 int count = args.Count;
372 for (int i = 0; i < count; i++){
374 // FIXME: Use TypeManager.CSharpname once we have the type
376 s.Append (args [i].ToString ());
380 return s.ToString ();
383 public bool Resolve (EmitContext ec)
385 DeclSpace ds = ec.DeclSpace;
386 int count = args.Count;
389 atypes = new Type [count];
391 for (int i = 0; i < count; i++){
392 TypeExpr te = ds.ResolveTypeExpr (
393 (Expression) args [i], false, Location);
398 if (te is TypeParameterExpr)
399 has_type_args = true;
400 atypes [i] = te.ResolveType (ec);
402 if (atypes [i] == null) {
403 Report.Error (246, Location, "Cannot find type `{0}'",
412 public class ConstructedType : TypeExpr {
413 string name, full_name;
415 Type[] gen_params, atypes;
418 public ConstructedType (string name, TypeArguments args, Location l)
424 eclass = ExprClass.Type;
425 full_name = name + "<" + args.ToString () + ">";
428 public ConstructedType (string name, TypeParameter[] type_params, Location l)
429 : this (type_params, l)
434 full_name = name + "<" + args.ToString () + ">";
437 protected ConstructedType (TypeArguments args, Location l)
442 eclass = ExprClass.Type;
445 protected ConstructedType (TypeParameter[] type_params, Location l)
449 args = new TypeArguments (l);
450 foreach (TypeParameter type_param in type_params)
451 args.Add (new TypeParameterExpr (type_param, l));
453 eclass = ExprClass.Type;
456 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
457 : this (type_params, l)
459 gt = t.GetGenericTypeDefinition ();
461 this.name = gt.FullName;
462 full_name = gt.FullName + "<" + args.ToString () + ">";
465 public ConstructedType (Type t, TypeArguments args, Location l)
468 gt = t.GetGenericTypeDefinition ();
470 this.name = gt.FullName;
471 full_name = gt.FullName + "<" + args.ToString () + ">";
474 public TypeArguments TypeArguments {
478 protected bool CheckConstraints (int index)
480 Type atype = atypes [index];
481 Type ptype = gen_params [index];
487 // First, check parent class.
489 if ((ptype.BaseType != atype.BaseType) &&
490 !atype.BaseType.IsSubclassOf (ptype.BaseType)) {
491 Report.Error (-219, loc, "Cannot create constructed type `{0}': " +
492 "type argument `{1}' must derive from `{2}'.",
493 full_name, atype, ptype.BaseType);
498 // Now, check the interfaces.
500 foreach (Type itype in ptype.GetInterfaces ()) {
501 if (TypeManager.ImplementsInterface (atype, itype))
504 Report.Error (-219, loc, "Cannot create constructed type `{0}: " +
505 "type argument `{1}' must implement interface `{2}'.",
506 full_name, atype, itype);
513 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
519 // First, resolve the generic type.
522 Type nested = ec.DeclSpace.FindNestedType (loc, name, out ds);
523 if (nested != null) {
524 gt = nested.GetGenericTypeDefinition ();
526 TypeArguments new_args = new TypeArguments (loc);
527 foreach (TypeParameter param in ds.TypeParameters)
528 new_args.Add (new TypeParameterExpr (param, loc));
535 SimpleName sn = new SimpleName (name, args.Count, loc);
536 TypeExpr resolved = sn.ResolveAsTypeTerminal (ec);
537 if (resolved == null) {
538 sn = new SimpleName (name, -1, loc);
539 resolved = sn.ResolveAsTypeTerminal (ec);
540 if ((resolved == null) || (resolved.Type == null)) {
541 Report.Error (246, loc,
542 "The type or namespace name `{0}<...>' "+
543 "could not be found", name);
547 Type t = resolved.Type;
548 int num_args = TypeManager.GetNumberOfTypeArguments (t);
551 Report.Error (308, loc,
552 "The non-generic type `{0}' cannot " +
553 "be used with type arguments.",
554 TypeManager.CSharpName (t));
558 Report.Error (305, loc,
559 "Using the generic type `{0}' " +
560 "requires {1} type arguments",
561 TypeManager.GetFullName (t), num_args);
565 if (resolved.Type == null)
566 throw new InternalErrorException (
567 "Failed to resolve constructed type `{0}'",
570 gt = resolved.Type.GetGenericTypeDefinition ();
574 public override Type ResolveType (EmitContext ec)
578 if (DoResolveAsTypeStep (ec) == null)
582 // Resolve the arguments.
584 if (args.Resolve (ec) == false)
587 gen_params = gt.GetGenericArguments ();
588 atypes = args.Arguments;
590 if (atypes.Length != gen_params.Length) {
591 Report.Error (-217, loc, "Generic type `{0}' takes {1} " +
592 "type parameters, but specified {2}.", gt.Name,
593 gen_params.Length, atypes.Length);
597 for (int i = 0; i < gen_params.Length; i++) {
598 if (!CheckConstraints (i))
603 // Now bind the parameters.
605 type = gt.BindGenericParameters (atypes);
609 public Expression GetMemberAccess (EmitContext ec)
612 if (ec.TypeContainer.CurrentType != null)
613 current = ec.TypeContainer.CurrentType;
615 current = new TypeExpression (ec.ContainerType, loc);
617 return new GenericMemberAccess (current, name, args, loc);
620 public override bool CheckAccessLevel (DeclSpace ds)
622 return ds.CheckAccessLevel (gt);
625 public override bool AsAccessible (DeclSpace ds, int flags)
627 return ds.AsAccessible (gt, flags);
630 public override bool IsClass {
631 get { return gt.IsClass; }
634 public override bool IsValueType {
635 get { return gt.IsValueType; }
638 public override bool IsInterface {
639 get { return gt.IsInterface; }
642 public override bool IsSealed {
643 get { return gt.IsSealed; }
646 public override bool IsAttribute {
647 get { return false; }
650 public override TypeExpr[] GetInterfaces ()
652 TypeExpr[] ifaces = TypeManager.GetInterfaces (gt);
656 public override bool Equals (object obj)
658 ConstructedType cobj = obj as ConstructedType;
662 if ((type == null) || (cobj.type == null))
665 return type == cobj.type;
668 public override string Name {
675 public class GenericMethod : DeclSpace
677 public GenericMethod (NamespaceEntry ns, TypeContainer parent, string name,
678 Attributes attrs, Location l)
679 : base (ns, parent, name, attrs, l)
682 public override TypeBuilder DefineType ()
684 throw new Exception ();
687 public override bool Define (TypeContainer parent)
689 for (int i = 0; i < TypeParameters.Length; i++)
690 if (!TypeParameters [i].Resolve (parent))
696 public bool Define (TypeContainer parent, MethodBuilder mb)
698 if (!Define (parent))
701 Type[] gen_params = new Type [TypeParameters.Length];
702 for (int i = 0; i < TypeParameters.Length; i++)
703 gen_params [i] = TypeParameters [i].DefineMethod (mb);
708 public bool DefineType (EmitContext ec, MethodBuilder mb)
710 for (int i = 0; i < TypeParameters.Length; i++)
711 if (!TypeParameters [i].DefineType (ec, mb))
717 public override bool DefineMembers (TypeContainer parent)
722 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
723 MemberFilter filter, object criteria)
725 throw new Exception ();
728 public override MemberCache MemberCache {
730 throw new Exception ();
735 public class GenericMemberAccess : MemberAccess
739 public GenericMemberAccess (Expression expr, string id, TypeArguments args, Location loc)
740 : base (expr, id, args.Count, loc)
745 private bool DoResolveBase (EmitContext ec)
747 ConstructedType cexpr = expr as ConstructedType;
749 TypeArguments new_args = new TypeArguments (loc);
750 new_args.Add (cexpr.TypeArguments);
759 public override Expression DoResolve (EmitContext ec, Expression right_side,
762 if (!DoResolveBase (ec))
765 Expression expr = base.DoResolve (ec, right_side, flags);
769 TypeExpr texpr = expr as TypeExpr;
771 Type t = texpr.ResolveType (ec);
775 ConstructedType ctype = new ConstructedType (t, args, loc);
776 return ctype.DoResolve (ec);
779 MethodGroupExpr mg = expr as MethodGroupExpr;
782 Report.Error (-220, loc, "Member `{0}' has type arguments, but did " +
783 "not resolve as a method group.", Identifier);
787 if (args.Resolve (ec) == false)
790 Type[] atypes = args.Arguments;
792 ArrayList list = new ArrayList ();
794 foreach (MethodBase method in mg.Methods) {
795 MethodInfo mi = method as MethodInfo;
799 Type[] gen_params = mi.GetGenericParameters ();
801 if (atypes.Length != gen_params.Length) {
802 Report.Error (-217, loc, "Generic method `{0}' takes {1} " +
803 "type parameters, but specified {2}.", mi.Name,
804 gen_params.Length, atypes.Length);
808 list.Add (mi.BindGenericParameters (args.Arguments));
811 MethodInfo[] methods = new MethodInfo [list.Count];
812 list.CopyTo (methods, 0);
814 MethodGroupExpr new_mg = new MethodGroupExpr (methods, mg.Location);
815 new_mg.InstanceExpression = mg.InstanceExpression;
816 new_mg.HasTypeArguments = true;
820 public override Expression ResolveAsTypeStep (EmitContext ec)
822 if (!DoResolveBase (ec))
825 expr = base.ResolveAsTypeStep (ec);
829 Type t = ((TypeExpr) expr).ResolveType (ec);
833 ConstructedType ctype = new ConstructedType (t, args, loc);
834 return ctype.ResolveAsTypeStep (ec);
838 public class DefaultValueExpression : Expression
841 LocalTemporary temp_storage;
843 public DefaultValueExpression (Expression expr, Location loc)
849 public override Expression DoResolve (EmitContext ec)
851 type = ec.DeclSpace.ResolveType (expr, false, loc);
855 if (type.IsGenericParameter || TypeManager.IsValueType (type))
856 temp_storage = new LocalTemporary (ec, type);
858 eclass = ExprClass.Variable;
862 public override void Emit (EmitContext ec)
864 if (temp_storage != null) {
865 temp_storage.AddressOf (ec, AddressOp.LoadStore);
866 ec.ig.Emit (OpCodes.Initobj, type);
867 temp_storage.Emit (ec);
869 ec.ig.Emit (OpCodes.Ldnull);