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 {
22 string type_parameter;
23 ArrayList constraints;
27 // type_parameter is the identifier, constraints is an arraylist of
28 // Expressions (with types) or `true' for the constructor constraint.
30 public Constraints (string type_parameter, ArrayList constraints,
33 this.type_parameter = type_parameter;
34 this.constraints = constraints;
38 public string TypeParameter {
40 return type_parameter;
44 protected void Error (string message)
46 Report.Error (-218, "Invalid constraints clause for type " +
47 "parameter `{0}': {1}", type_parameter, message);
50 bool has_ctor_constraint;
51 TypeExpr class_constraint;
52 ArrayList iface_constraints;
53 TypeExpr[] constraint_types;
56 public bool HasConstructorConstraint {
57 get { return has_ctor_constraint; }
60 public bool Resolve (DeclSpace ds)
62 iface_constraints = new ArrayList ();
64 foreach (object obj in constraints) {
65 if (has_ctor_constraint) {
66 Error ("can only use one constructor constraint and " +
67 "it must be the last constraint in the list.");
72 has_ctor_constraint = true;
76 TypeExpr expr = ds.ResolveTypeExpr ((Expression) obj, false, loc);
81 iface_constraints.Add (expr);
82 else if (class_constraint != null) {
83 Error ("can have at most one class constraint.");
86 class_constraint = expr;
91 constraint_types = new TypeExpr [num_constraints];
93 if (class_constraint != null)
94 constraint_types [pos++] = class_constraint;
95 iface_constraints.CopyTo (constraint_types, pos);
100 public Type[] ResolveTypes (EmitContext ec)
102 Type [] types = new Type [constraint_types.Length];
104 for (int i = 0; i < constraint_types.Length; i++)
105 types [i] = constraint_types [i].ResolveType (ec);
112 // This type represents a generic type parameter
114 public class TypeParameter {
116 Constraints constraints;
120 public TypeParameter (string name, Constraints constraints, Location loc)
123 this.constraints = constraints;
133 public Location Location {
139 public Constraints Constraints {
151 public bool Resolve (DeclSpace ds)
153 if (constraints != null)
154 return constraints.Resolve (ds);
159 public Type Define (TypeBuilder tb)
161 type = tb.DefineGenericParameter (name);
165 public Type DefineMethod (MethodBuilder mb)
167 type = mb.DefineGenericParameter (name);
171 public void DefineType (EmitContext ec, TypeBuilder tb)
173 int index = type.GenericParameterPosition;
174 if (constraints == null)
175 tb.SetGenericParameterConstraints (index, new Type [0]);
177 tb.SetGenericParameterConstraints (index, constraints.ResolveTypes (ec));
180 public void DefineType (EmitContext ec, MethodBuilder mb)
182 int index = type.GenericParameterPosition;
183 if (constraints == null)
184 mb.SetGenericParameterConstraints (index, new Type [0]);
186 mb.SetGenericParameterConstraints (index, constraints.ResolveTypes (ec));
189 public override string ToString ()
191 return "TypeParameter[" + name + "]";
196 // This type represents a generic type parameter reference.
198 // These expressions are born in a fully resolved state.
200 public class TypeParameterExpr : TypeExpr {
201 TypeParameter type_parameter;
203 public override string Name {
205 return type_parameter.Name;
209 public TypeParameter TypeParameter {
211 return type_parameter;
215 public TypeParameterExpr (TypeParameter type_parameter, Location loc)
217 this.type_parameter = type_parameter;
220 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
222 type = type_parameter.Type;
227 public void Error_CannotUseAsUnmanagedType (Location loc)
229 Report.Error (-203, loc, "Can not use type parameter as unamanged type");
233 public class TypeArguments {
238 public TypeArguments ()
240 args = new ArrayList ();
243 public void Add (Expression type)
248 public void Add (TypeArguments new_args)
250 args.AddRange (new_args.args);
253 public Type[] Arguments {
259 public bool HasTypeArguments {
261 return has_type_args;
265 public override string ToString ()
267 StringBuilder s = new StringBuilder ();
269 int count = args.Count;
270 for (int i = 0; i < count; i++){
272 // FIXME: Use TypeManager.CSharpname once we have the type
274 s.Append (args [i].ToString ());
278 return s.ToString ();
281 public bool Resolve (EmitContext ec)
283 int count = args.Count;
286 atypes = new Type [count];
288 for (int i = 0; i < count; i++){
289 TypeExpr e = ((Expression)args [i]).ResolveAsTypeTerminal (ec);
294 if (e is TypeParameterExpr)
295 has_type_args = true;
297 atypes [i] = e.ResolveType (ec);
299 if (atypes [i] == null)
306 public class ConstructedType : TypeExpr {
307 string name, full_name;
309 Type[] gen_params, atypes;
312 public ConstructedType (string name, TypeArguments args, Location l)
318 eclass = ExprClass.Type;
319 full_name = name + "<" + args.ToString () + ">";
322 public ConstructedType (string name, TypeParameter[] type_params, Location l)
327 args = new TypeArguments ();
328 foreach (TypeParameter type_param in type_params)
329 args.Add (new TypeParameterExpr (type_param, l));
331 eclass = ExprClass.Type;
332 full_name = name + "<" + args.ToString () + ">";
335 public ConstructedType (Type t, TypeParameter[] type_params, Location l)
336 : this (t.Name, type_params, l)
338 gt = t.GetGenericTypeDefinition ();
341 public ConstructedType (Type t, TypeArguments args, Location l)
342 : this (t.Name, args, l)
344 gt = t.GetGenericTypeDefinition ();
347 public TypeArguments TypeArguments {
351 protected bool CheckConstraints (int index)
353 Type atype = atypes [index];
354 Type ptype = gen_params [index];
360 // First, check parent class.
362 if ((ptype.BaseType != atype.BaseType) &&
363 !atype.BaseType.IsSubclassOf (ptype.BaseType)) {
364 Report.Error (-219, loc, "Cannot create constructed type `{0}': " +
365 "type argument `{1}' must derive from `{2}'.",
366 full_name, atype, ptype.BaseType);
371 // Now, check the interfaces.
373 foreach (Type itype in ptype.GetInterfaces ()) {
374 if (TypeManager.ImplementsInterface (atype, itype))
377 Report.Error (-219, loc, "Cannot create constructed type `{0}: " +
378 "type argument `{1}' must implement interface `{2}'.",
379 full_name, atype, itype);
386 public override TypeExpr DoResolveAsTypeStep (EmitContext ec)
392 // First, resolve the generic type.
394 SimpleName sn = new SimpleName (name, loc);
395 TypeExpr resolved = sn.ResolveAsTypeTerminal (ec);
396 if (resolved == null)
399 if (resolved.Type == null) {
400 Report.Error (-220, loc, "Failed to resolve constructed type `{0}'",
405 gt = resolved.Type.GetGenericTypeDefinition ();
409 public override Type ResolveType (EmitContext ec)
413 if (DoResolveAsTypeStep (ec) == null)
417 // Resolve the arguments.
419 if (args.Resolve (ec) == false) {
420 Report.Error (-220, loc, "Failed to resolve constructed type `{0}'",
425 gen_params = gt.GetGenericArguments ();
427 DeclSpace decl = ec.DeclSpace, parent = null;
428 while (decl != null) {
429 if (TypeManager.IsNestedChildOf (gt, decl.TypeBuilder)) {
436 if (parent != null) {
437 TypeParameter[] pparams = parent.TypeParameters;
439 atypes = new Type [args.Arguments.Length + pparams.Length];
440 for (int i = 0; i < pparams.Length; i++) {
441 TypeParameter pparam = pparams [i];
442 if (pparam.Type == null)
443 throw new Exception ();
444 atypes [i] = pparam.Type;
446 args.Arguments.CopyTo (atypes, pparams.Length);
448 atypes = args.Arguments;
450 if (atypes.Length != gen_params.Length) {
451 Report.Error (-217, loc, "Generic type `{0}' takes {1} " +
452 "type parameters, but specified {2}.", gt.Name,
453 gen_params.Length, atypes.Length);
457 for (int i = 0; i < gen_params.Length; i++) {
458 if (!CheckConstraints (i))
463 // Now bind the parameters.
465 type = gt.BindGenericParameters (atypes);
469 public Expression GetMemberAccess (TypeExpr current_type)
471 return new GenericMemberAccess (current_type, name, args, loc);
474 public override bool CheckAccessLevel (DeclSpace ds)
476 return ds.CheckAccessLevel (gt);
479 public override bool AsAccessible (DeclSpace ds, int flags)
481 return ds.AsAccessible (gt, flags);
484 public override bool IsClass {
485 get { return gt.IsClass; }
488 public override bool IsValueType {
489 get { return gt.IsValueType; }
492 public override bool IsInterface {
493 get { return gt.IsInterface; }
496 public override bool IsSealed {
497 get { return gt.IsSealed; }
500 public override TypeExpr[] GetInterfaces ()
502 TypeExpr[] ifaces = TypeManager.GetInterfaces (gt);
506 public override string Name {
513 public class GenericMethod : DeclSpace
515 public GenericMethod (NamespaceEntry ns, TypeContainer parent, string name,
516 Attributes attrs, Location l)
517 : base (ns, parent, name, attrs, l)
520 public override TypeBuilder DefineType ()
522 throw new Exception ();
525 public override bool Define (TypeContainer parent)
530 public bool Define (MethodBuilder mb)
532 Type[] gen_params = new Type [TypeParameters.Length];
533 for (int i = 0; i < TypeParameters.Length; i++)
534 gen_params [i] = TypeParameters [i].DefineMethod (mb);
539 public bool DefineType (EmitContext ec, MethodBuilder mb)
541 for (int i = 0; i < TypeParameters.Length; i++)
542 TypeParameters [i].DefineType (ec, mb);
547 public override bool DefineMembers (TypeContainer parent)
552 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
553 MemberFilter filter, object criteria)
555 throw new Exception ();
558 public override MemberCache MemberCache {
560 throw new Exception ();
565 public class GenericMemberAccess : MemberAccess
569 public GenericMemberAccess (Expression expr, string id, TypeArguments args, Location loc)
570 : base (expr, id, loc)
575 public override Expression DoResolve (EmitContext ec, Expression right_side,
578 Expression expr = base.DoResolve (ec, right_side, flags);
582 MethodGroupExpr mg = expr as MethodGroupExpr;
584 Report.Error (-220, loc, "Member `{0}' has type arguments, but did " +
585 "not resolve as a method group.", Identifier);
589 if (args.Resolve (ec) == false)
592 Type[] atypes = args.Arguments;
594 ArrayList list = new ArrayList ();
596 foreach (MethodBase method in mg.Methods) {
597 MethodInfo mi = method as MethodInfo;
601 Type[] gen_params = mi.GetGenericArguments ();
603 if (atypes.Length != gen_params.Length) {
604 Report.Error (-217, loc, "Generic method `{0}' takes {1} " +
605 "type parameters, but specified {2}.", mi.Name,
606 gen_params.Length, atypes.Length);
610 list.Add (mi.BindGenericParameters (args.Arguments));
613 MethodInfo[] methods = new MethodInfo [list.Count];
614 list.CopyTo (methods, 0);
616 MethodGroupExpr new_mg = new MethodGroupExpr (methods, mg.Location);
617 new_mg.InstanceExpression = mg.InstanceExpression;
621 public override Expression ResolveAsTypeStep (EmitContext ec)
623 ConstructedType cexpr = expr as ConstructedType;
625 throw new Exception ();
627 expr = base.ResolveAsTypeStep (ec);
631 Type t = ((TypeExpr) expr).ResolveType (ec);
635 TypeArguments new_args = new TypeArguments ();
636 new_args.Add (cexpr.TypeArguments);
639 ConstructedType ctype = new ConstructedType (t, new_args, loc);
640 return ctype.ResolveAsTypeStep (ec);
644 public class DefaultValueExpression : Expression
647 LocalTemporary temp_storage;
649 public DefaultValueExpression (Expression expr, Location loc)
655 public override Expression DoResolve (EmitContext ec)
657 type = ec.DeclSpace.ResolveType (expr, false, loc);
661 if (type.IsGenericParameter || TypeManager.IsValueType (type))
662 temp_storage = new LocalTemporary (ec, type);
664 eclass = ExprClass.Variable;
668 public override void Emit (EmitContext ec)
670 if (temp_storage != null) {
671 temp_storage.AddressOf (ec, AddressOp.LoadStore);
672 ec.ig.Emit (OpCodes.Initobj, type);
673 temp_storage.Emit (ec);
675 ec.ig.Emit (OpCodes.Ldnull);