2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
11 // Maybe we should make Resolve be an instance method that just calls
12 // the virtual DoResolve function and checks conditions like the eclass
13 // and type being set if a non-null value is returned. For robustness
19 using System.Collections;
20 using System.Diagnostics;
21 using System.Reflection;
22 using System.Reflection.Emit;
26 // The ExprClass class contains the is used to pass the
27 // classification of an expression (value, variable, namespace,
28 // type, method group, property access, event access, indexer access,
31 public enum ExprClass {
35 Variable, // Every Variable should implement LValue
46 // Base class for expressions
48 public abstract class Expression {
49 protected ExprClass eclass;
62 public ExprClass ExprClass {
73 // Utility wrapper routine for Error, just to beautify the code
75 static protected void Error (int error, string s)
77 Report.Error (error, s);
80 static protected void Error (int error, Location loc, string s)
82 Report.Error (error, loc, s);
86 // Utility wrapper routine for Warning, just to beautify the code
88 static protected void Warning (int warning, string s)
90 Report.Warning (warning, s);
94 // Performs semantic analysis on the Expression
98 // The Resolve method is invoked to perform the semantic analysis
101 // The return value is an expression (it can be the
102 // same expression in some cases) or a new
103 // expression that better represents this node.
105 // For example, optimizations of Unary (LiteralInt)
106 // would return a new LiteralInt with a negated
109 // If there is an error during semantic analysis,
110 // then an error should be reported (using Report)
111 // and a null value should be returned.
113 // There are two side effects expected from calling
114 // Resolve(): the the field variable "eclass" should
115 // be set to any value of the enumeration
116 // `ExprClass' and the type variable should be set
117 // to a valid type (this is the type of the
121 public abstract Expression DoResolve (EmitContext ec);
125 // Currently Resolve wraps DoResolve to perform sanity
126 // checking and assertion checking on what we expect from Resolve
129 public Expression Resolve (EmitContext ec)
131 Expression e = DoResolve (ec);
137 if (e.ExprClass == ExprClass.Invalid)
138 throw new Exception ("Expression " + e +
139 " ExprClass is Invalid after resolve");
141 if (e.ExprClass != ExprClass.MethodGroup)
143 throw new Exception ("Expression " + e +
144 " did not set its type after Resolve");
147 e = ((LValue) e).LValueResolve (ec);
154 // Emits the code for the expression
159 // The Emit method is invoked to generate the code
160 // for the expression.
163 public abstract void Emit (EmitContext ec);
166 // Protected constructor. Only derivate types should
167 // be able to be created
170 protected Expression ()
172 eclass = ExprClass.Invalid;
177 // Returns a literalized version of a literal FieldInfo
179 static Expression Literalize (FieldInfo fi)
181 Type t = fi.FieldType;
182 object v = fi.GetValue (fi);
184 if (t == TypeManager.int32_type)
185 return new IntLiteral ((int) v);
186 else if (t == TypeManager.uint32_type)
187 return new UIntLiteral ((uint) v);
188 else if (t == TypeManager.int64_type)
189 return new LongLiteral ((long) v);
190 else if (t == TypeManager.uint64_type)
191 return new ULongLiteral ((ulong) v);
192 else if (t == TypeManager.float_type)
193 return new FloatLiteral ((float) v);
194 else if (t == TypeManager.double_type)
195 return new DoubleLiteral ((double) v);
196 else if (t == TypeManager.string_type)
197 return new StringLiteral ((string) v);
198 else if (t == TypeManager.short_type)
199 return new IntLiteral ((int) ((short)v));
200 else if (t == TypeManager.ushort_type)
201 return new IntLiteral ((int) ((ushort)v));
202 else if (t == TypeManager.sbyte_type)
203 return new IntLiteral ((int) ((sbyte)v));
204 else if (t == TypeManager.byte_type)
205 return new IntLiteral ((int) ((byte)v));
206 else if (t == TypeManager.char_type)
207 return new IntLiteral ((int) ((char)v));
209 throw new Exception ("Unknown type for literal (" + v.GetType () +
210 "), details: " + fi);
214 // Returns a fully formed expression after a MemberLookup
216 static Expression ExprClassFromMemberInfo (EmitContext ec, MemberInfo mi, Location loc)
218 if (mi is EventInfo){
219 return new EventExpr ((EventInfo) mi, loc);
220 } else if (mi is FieldInfo){
221 FieldInfo fi = (FieldInfo) mi;
224 Expression e = Literalize (fi);
229 return new FieldExpr (fi);
230 } else if (mi is PropertyInfo){
231 return new PropertyExpr ((PropertyInfo) mi, loc);
232 } else if (mi is Type)
233 return new TypeExpr ((Type) mi);
239 // FIXME: Probably implement a cache for (t,name,current_access_set)?
241 // FIXME: We need to cope with access permissions here, or this wont
244 // This code could use some optimizations, but we need to do some
245 // measurements. For example, we could use a delegate to `flag' when
246 // something can not any longer be a method-group (because it is something
250 // If the return value is an Array, then it is an array of
253 // If the return value is an MemberInfo, it is anything, but a Method
257 // FIXME: When calling MemberLookup inside an `Invocation', we should pass
258 // the arguments here and have MemberLookup return only the methods that
259 // match the argument count/type, unlike we are doing now (we delay this
262 // This is so we can catch correctly attempts to invoke instance methods
263 // from a static body (scan for error 120 in ResolveSimpleName).
265 public static Expression MemberLookup (EmitContext ec, Type t, string name,
266 bool same_type, MemberTypes mt,
267 BindingFlags bf, Location loc)
270 bf |= BindingFlags.NonPublic;
272 MemberInfo [] mi = ec.TypeContainer.RootContext.TypeManager.FindMembers (
273 t, mt, bf, Type.FilterName, name);
278 // FIXME : How does this wierd case arise ?
282 if (mi.Length == 1 && !(mi [0] is MethodBase))
283 return Expression.ExprClassFromMemberInfo (ec, mi [0], loc);
285 for (int i = 0; i < mi.Length; i++)
286 if (!(mi [i] is MethodBase)){
287 Error (-5, "Do not know how to reproduce this case: " +
288 "Methods and non-Method with the same name, " +
289 "report this please");
291 for (i = 0; i < mi.Length; i++){
292 Type tt = mi [i].GetType ();
294 Console.WriteLine (i + ": " + mi [i]);
295 while (tt != TypeManager.object_type){
296 Console.WriteLine (tt);
302 return new MethodGroupExpr (mi);
305 public const MemberTypes AllMemberTypes =
306 MemberTypes.Constructor |
310 MemberTypes.NestedType |
311 MemberTypes.Property;
313 public const BindingFlags AllBindingsFlags =
314 BindingFlags.Public |
315 BindingFlags.Static |
316 BindingFlags.Instance;
318 public static Expression MemberLookup (EmitContext ec, Type t, string name,
319 bool same_type, Location loc)
321 return MemberLookup (ec, t, name, same_type, AllMemberTypes, AllBindingsFlags, loc);
325 // I am in general unhappy with this implementation.
327 // I need to revise this.
330 // static public Expression ResolveMemberAccess (EmitContext ec, string name)
332 // Expression left_e = null;
333 // int dot_pos = name.LastIndexOf (".");
334 // string left = name.Substring (0, dot_pos);
335 // string right = name.Substring (dot_pos + 1);
338 // if ((t = ec.TypeContainer.LookupType (left, false)) != null){
341 // left_e = new TypeExpr (t);
342 // e = new MemberAccess (left_e, right);
343 // return e.Resolve (ec);
346 // // FIXME: IMplement:
349 // // T.P Static property access (P) on Type T.
350 // // e.P instance property access on instance e for P.
355 // if (left_e == null){
356 // Error (246, "Can not find type or namespace `"+left+"'");
360 // switch (left_e.ExprClass){
361 // case ExprClass.Type:
362 // return MemberLookup (ec,
363 // left_e.Type, right,
364 // left_e.Type == ec.TypeContainer.TypeBuilder);
366 // case ExprClass.Namespace:
367 // case ExprClass.PropertyAccess:
368 // case ExprClass.IndexerAccess:
369 // case ExprClass.Variable:
370 // case ExprClass.Value:
371 // case ExprClass.Nothing:
372 // case ExprClass.EventAccess:
373 // case ExprClass.MethodGroup:
374 // case ExprClass.Invalid:
375 // throw new Exception ("Should have got the " + left_e.ExprClass +
376 // " handled before");
382 static public Expression ImplicitReferenceConversion (Expression expr, Type target_type)
384 Type expr_type = expr.Type;
386 if (target_type == TypeManager.object_type) {
387 if (expr_type.IsClass)
388 return new EmptyCast (expr, target_type);
389 if (expr_type.IsValueType)
390 return new BoxedCast (expr);
391 } else if (expr_type.IsSubclassOf (target_type)) {
392 return new EmptyCast (expr, target_type);
394 // from any class-type S to any interface-type T.
395 if (expr_type.IsClass && target_type.IsInterface) {
396 Type [] interfaces = expr_type.FindInterfaces (Module.FilterTypeName,
397 target_type.FullName);
398 if (interfaces != null)
399 return new EmptyCast (expr, target_type);
402 // from any interface type S to interface-type T.
403 // FIXME : Is it right to use IsAssignableFrom ?
404 if (expr_type.IsInterface && target_type.IsInterface)
405 if (target_type.IsAssignableFrom (expr_type))
406 return new EmptyCast (expr, target_type);
409 // from an array-type S to an array-type of type T
410 if (expr_type.IsArray && target_type.IsArray) {
411 if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
413 Type expr_element_type = expr_type.GetElementType ();
414 Type target_element_type = target_type.GetElementType ();
416 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
417 if (StandardConversionExists (expr_element_type,
418 target_element_type))
419 return new EmptyCast (expr, target_type);
424 // from an array-type to System.Array
425 if (expr_type.IsArray && target_type.IsAssignableFrom (expr_type))
426 return new EmptyCast (expr, target_type);
428 // from any delegate type to System.Delegate
429 if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
430 target_type == TypeManager.delegate_type)
431 if (target_type.IsAssignableFrom (expr_type))
432 return new EmptyCast (expr, target_type);
434 // from any array-type or delegate type into System.ICloneable.
435 if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
436 if (target_type == TypeManager.icloneable_type)
437 return new EmptyCast (expr, target_type);
439 // from the null type to any reference-type.
440 if (expr is NullLiteral)
441 return new EmptyCast (expr, target_type);
451 // Handles expressions like this: decimal d; d = 1;
452 // and changes them into: decimal d; d = new System.Decimal (1);
454 static Expression InternalTypeConstructor (EmitContext ec, Expression expr, Type target)
456 ArrayList args = new ArrayList ();
458 args.Add (new Argument (expr, Argument.AType.Expression));
460 Expression ne = new New (target.FullName, args,
463 return ne.Resolve (ec);
467 // Implicit Numeric Conversions.
469 // expr is the expression to convert, returns a new expression of type
470 // target_type or null if an implicit conversion is not possible.
473 static public Expression ImplicitNumericConversion (EmitContext ec, Expression expr,
474 Type target_type, Location loc)
476 Type expr_type = expr.Type;
479 // Attempt to do the implicit constant expression conversions
481 if (expr is IntLiteral){
484 e = TryImplicitIntConversion (target_type, (IntLiteral) expr);
487 } else if (expr is LongLiteral){
489 // Try the implicit constant expression conversion
490 // from long to ulong, instead of a nice routine,
493 if (((LongLiteral) expr).Value > 0)
494 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
497 if (expr_type == TypeManager.sbyte_type){
499 // From sbyte to short, int, long, float, double.
501 if (target_type == TypeManager.int32_type)
502 return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
503 if (target_type == TypeManager.int64_type)
504 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
505 if (target_type == TypeManager.double_type)
506 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
507 if (target_type == TypeManager.float_type)
508 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
509 if (target_type == TypeManager.short_type)
510 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
511 if (target_type == TypeManager.decimal_type)
512 return InternalTypeConstructor (ec, expr, target_type);
513 } else if (expr_type == TypeManager.byte_type){
515 // From byte to short, ushort, int, uint, long, ulong, float, double
517 if ((target_type == TypeManager.short_type) ||
518 (target_type == TypeManager.ushort_type) ||
519 (target_type == TypeManager.int32_type) ||
520 (target_type == TypeManager.uint32_type))
521 return new EmptyCast (expr, target_type);
523 if (target_type == TypeManager.uint64_type)
524 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
525 if (target_type == TypeManager.int64_type)
526 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
528 if (target_type == TypeManager.float_type)
529 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
530 if (target_type == TypeManager.double_type)
531 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
532 if (target_type == TypeManager.decimal_type)
533 return InternalTypeConstructor (ec, expr, target_type);
534 } else if (expr_type == TypeManager.short_type){
536 // From short to int, long, float, double
538 if (target_type == TypeManager.int32_type)
539 return new EmptyCast (expr, target_type);
540 if (target_type == TypeManager.int64_type)
541 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
542 if (target_type == TypeManager.double_type)
543 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
544 if (target_type == TypeManager.float_type)
545 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
546 if (target_type == TypeManager.decimal_type)
547 return InternalTypeConstructor (ec, expr, target_type);
548 } else if (expr_type == TypeManager.ushort_type){
550 // From ushort to int, uint, long, ulong, float, double
552 if (target_type == TypeManager.uint32_type)
553 return new EmptyCast (expr, target_type);
555 if (target_type == TypeManager.uint64_type)
556 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
557 if (target_type == TypeManager.int32_type)
558 return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
559 if (target_type == TypeManager.int64_type)
560 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
561 if (target_type == TypeManager.double_type)
562 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
563 if (target_type == TypeManager.float_type)
564 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
565 if (target_type == TypeManager.decimal_type)
566 return InternalTypeConstructor (ec, expr, target_type);
567 } else if (expr_type == TypeManager.int32_type){
569 // From int to long, float, double
571 if (target_type == TypeManager.int64_type)
572 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
573 if (target_type == TypeManager.double_type)
574 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
575 if (target_type == TypeManager.float_type)
576 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
577 if (target_type == TypeManager.decimal_type)
578 return InternalTypeConstructor (ec, expr, target_type);
579 } else if (expr_type == TypeManager.uint32_type){
581 // From uint to long, ulong, float, double
583 if (target_type == TypeManager.int64_type)
584 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
585 if (target_type == TypeManager.uint64_type)
586 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
587 if (target_type == TypeManager.double_type)
588 return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
590 if (target_type == TypeManager.float_type)
591 return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
593 if (target_type == TypeManager.decimal_type)
594 return InternalTypeConstructor (ec, expr, target_type);
595 } else if ((expr_type == TypeManager.uint64_type) ||
596 (expr_type == TypeManager.int64_type)){
598 // From long/ulong to float, double
600 if (target_type == TypeManager.double_type)
601 return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
603 if (target_type == TypeManager.float_type)
604 return new OpcodeCast (expr, target_type, OpCodes.Conv_R_Un,
606 if (target_type == TypeManager.decimal_type)
607 return InternalTypeConstructor (ec, expr, target_type);
608 } else if (expr_type == TypeManager.char_type){
610 // From char to ushort, int, uint, long, ulong, float, double
612 if ((target_type == TypeManager.ushort_type) ||
613 (target_type == TypeManager.int32_type) ||
614 (target_type == TypeManager.uint32_type))
615 return new EmptyCast (expr, target_type);
616 if (target_type == TypeManager.uint64_type)
617 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
618 if (target_type == TypeManager.int64_type)
619 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
620 if (target_type == TypeManager.float_type)
621 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
622 if (target_type == TypeManager.double_type)
623 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
624 if (target_type == TypeManager.decimal_type)
625 return InternalTypeConstructor (ec, expr, target_type);
626 } else if (expr_type == TypeManager.float_type){
630 if (target_type == TypeManager.double_type)
631 return new OpcodeCast (expr, target_type, OpCodes.Conv_R8);
638 // Determines if a standard implicit conversion exists from
639 // expr_type to target_type
641 public static bool StandardConversionExists (Type expr_type, Type target_type)
643 if (expr_type == target_type)
646 // First numeric conversions
648 if (expr_type == TypeManager.sbyte_type){
650 // From sbyte to short, int, long, float, double.
652 if ((target_type == TypeManager.int32_type) ||
653 (target_type == TypeManager.int64_type) ||
654 (target_type == TypeManager.double_type) ||
655 (target_type == TypeManager.float_type) ||
656 (target_type == TypeManager.short_type) ||
657 (target_type == TypeManager.decimal_type))
660 } else if (expr_type == TypeManager.byte_type){
662 // From byte to short, ushort, int, uint, long, ulong, float, double
664 if ((target_type == TypeManager.short_type) ||
665 (target_type == TypeManager.ushort_type) ||
666 (target_type == TypeManager.int32_type) ||
667 (target_type == TypeManager.uint32_type) ||
668 (target_type == TypeManager.uint64_type) ||
669 (target_type == TypeManager.int64_type) ||
670 (target_type == TypeManager.float_type) ||
671 (target_type == TypeManager.double_type) ||
672 (target_type == TypeManager.decimal_type))
675 } else if (expr_type == TypeManager.short_type){
677 // From short to int, long, float, double
679 if ((target_type == TypeManager.int32_type) ||
680 (target_type == TypeManager.int64_type) ||
681 (target_type == TypeManager.double_type) ||
682 (target_type == TypeManager.float_type) ||
683 (target_type == TypeManager.decimal_type))
686 } else if (expr_type == TypeManager.ushort_type){
688 // From ushort to int, uint, long, ulong, float, double
690 if ((target_type == TypeManager.uint32_type) ||
691 (target_type == TypeManager.uint64_type) ||
692 (target_type == TypeManager.int32_type) ||
693 (target_type == TypeManager.int64_type) ||
694 (target_type == TypeManager.double_type) ||
695 (target_type == TypeManager.float_type) ||
696 (target_type == TypeManager.decimal_type))
699 } else if (expr_type == TypeManager.int32_type){
701 // From int to long, float, double
703 if ((target_type == TypeManager.int64_type) ||
704 (target_type == TypeManager.double_type) ||
705 (target_type == TypeManager.float_type) ||
706 (target_type == TypeManager.decimal_type))
709 } else if (expr_type == TypeManager.uint32_type){
711 // From uint to long, ulong, float, double
713 if ((target_type == TypeManager.int64_type) ||
714 (target_type == TypeManager.uint64_type) ||
715 (target_type == TypeManager.double_type) ||
716 (target_type == TypeManager.float_type) ||
717 (target_type == TypeManager.decimal_type))
720 } else if ((expr_type == TypeManager.uint64_type) ||
721 (expr_type == TypeManager.int64_type)) {
723 // From long/ulong to float, double
725 if ((target_type == TypeManager.double_type) ||
726 (target_type == TypeManager.float_type) ||
727 (target_type == TypeManager.decimal_type))
730 } else if (expr_type == TypeManager.char_type){
732 // From char to ushort, int, uint, long, ulong, float, double
734 if ((target_type == TypeManager.ushort_type) ||
735 (target_type == TypeManager.int32_type) ||
736 (target_type == TypeManager.uint32_type) ||
737 (target_type == TypeManager.uint64_type) ||
738 (target_type == TypeManager.int64_type) ||
739 (target_type == TypeManager.float_type) ||
740 (target_type == TypeManager.double_type) ||
741 (target_type == TypeManager.decimal_type))
744 } else if (expr_type == TypeManager.float_type){
748 if (target_type == TypeManager.double_type)
752 // Next reference conversions
754 if (target_type == TypeManager.object_type) {
755 if ((expr_type.IsClass) ||
756 (expr_type.IsValueType))
759 } else if (expr_type.IsSubclassOf (target_type)) {
763 // from any class-type S to any interface-type T.
764 if (expr_type.IsClass && target_type.IsInterface)
767 // from any interface type S to interface-type T.
768 // FIXME : Is it right to use IsAssignableFrom ?
769 if (expr_type.IsInterface && target_type.IsInterface)
770 if (target_type.IsAssignableFrom (expr_type))
773 // from an array-type S to an array-type of type T
774 if (expr_type.IsArray && target_type.IsArray) {
775 if (expr_type.GetArrayRank () == target_type.GetArrayRank ()) {
777 Type expr_element_type = expr_type.GetElementType ();
778 Type target_element_type = target_type.GetElementType ();
780 if (!expr_element_type.IsValueType && !target_element_type.IsValueType)
781 if (StandardConversionExists (expr_element_type,
782 target_element_type))
787 // from an array-type to System.Array
788 if (expr_type.IsArray && target_type.IsAssignableFrom (expr_type))
791 // from any delegate type to System.Delegate
792 if (expr_type.IsSubclassOf (TypeManager.delegate_type) &&
793 target_type == TypeManager.delegate_type)
794 if (target_type.IsAssignableFrom (expr_type))
797 // from any array-type or delegate type into System.ICloneable.
798 if (expr_type.IsArray || expr_type.IsSubclassOf (TypeManager.delegate_type))
799 if (target_type == TypeManager.icloneable_type)
802 // from the null type to any reference-type.
803 // FIXME : How do we do this ?
811 // Finds "most encompassed type" according to the spec (13.4.2)
812 // amongst the methods in the MethodGroupExpr which convert from a
813 // type encompassing source_type
815 static Type FindMostEncompassedType (MethodGroupExpr me, Type source_type)
819 for (int i = me.Methods.Length; i > 0; ) {
822 MethodBase mb = me.Methods [i];
823 ParameterData pd = Invocation.GetParameterData (mb);
824 Type param_type = pd.ParameterType (0);
826 if (StandardConversionExists (source_type, param_type)) {
830 if (StandardConversionExists (param_type, best))
839 // Finds "most encompassing type" according to the spec (13.4.2)
840 // amongst the methods in the MethodGroupExpr which convert to a
841 // type encompassed by target_type
843 static Type FindMostEncompassingType (MethodGroupExpr me, Type target)
847 for (int i = me.Methods.Length; i > 0; ) {
850 MethodInfo mi = (MethodInfo) me.Methods [i];
851 Type ret_type = mi.ReturnType;
853 if (StandardConversionExists (ret_type, target)) {
857 if (!StandardConversionExists (ret_type, best))
869 // User-defined Implicit conversions
871 static public Expression ImplicitUserConversion (EmitContext ec, Expression source,
872 Type target, Location loc)
874 return UserDefinedConversion (ec, source, target, loc, false);
878 // User-defined Explicit conversions
880 static public Expression ExplicitUserConversion (EmitContext ec, Expression source,
881 Type target, Location loc)
883 return UserDefinedConversion (ec, source, target, loc, true);
887 // User-defined conversions
889 static public Expression UserDefinedConversion (EmitContext ec, Expression source,
890 Type target, Location loc,
891 bool look_for_explicit)
893 Expression mg1 = null, mg2 = null, mg3 = null, mg4 = null;
894 Expression mg5 = null, mg6 = null, mg7 = null, mg8 = null;
896 MethodBase method = null;
897 Type source_type = source.Type;
901 // If we have a boolean type, we need to check for the True operator
903 // FIXME : How does the False operator come into the picture ?
904 // FIXME : This doesn't look complete and very correct !
905 if (target == TypeManager.bool_type)
908 op_name = "op_Implicit";
910 mg1 = MemberLookup (ec, source_type, op_name, false, loc);
912 if (source_type.BaseType != null)
913 mg2 = MemberLookup (ec, source_type.BaseType, op_name, false, loc);
915 mg3 = MemberLookup (ec, target, op_name, false, loc);
917 if (target.BaseType != null)
918 mg4 = MemberLookup (ec, target.BaseType, op_name, false, loc);
920 MethodGroupExpr union1 = Invocation.MakeUnionSet (mg1, mg2);
921 MethodGroupExpr union2 = Invocation.MakeUnionSet (mg3, mg4);
923 MethodGroupExpr union3 = Invocation.MakeUnionSet (union1, union2);
925 MethodGroupExpr union4 = null;
927 if (look_for_explicit) {
929 op_name = "op_Explicit";
931 mg5 = MemberLookup (ec, source_type, op_name, false, loc);
933 if (source_type.BaseType != null)
934 mg6 = MemberLookup (ec, source_type.BaseType, op_name, false, loc);
936 mg7 = MemberLookup (ec, target, op_name, false, loc);
938 if (target.BaseType != null)
939 mg8 = MemberLookup (ec, target.BaseType, op_name, false, loc);
941 MethodGroupExpr union5 = Invocation.MakeUnionSet (mg5, mg6);
942 MethodGroupExpr union6 = Invocation.MakeUnionSet (mg7, mg8);
944 union4 = Invocation.MakeUnionSet (union5, union6);
947 MethodGroupExpr union = Invocation.MakeUnionSet (union3, union4);
951 Type most_specific_source, most_specific_target;
953 most_specific_source = FindMostEncompassedType (union, source_type);
954 if (most_specific_source == null)
957 most_specific_target = FindMostEncompassingType (union, target);
958 if (most_specific_target == null)
963 for (int i = union.Methods.Length; i > 0;) {
966 MethodBase mb = union.Methods [i];
967 ParameterData pd = Invocation.GetParameterData (mb);
968 MethodInfo mi = (MethodInfo) union.Methods [i];
970 if (pd.ParameterType (0) == most_specific_source &&
971 mi.ReturnType == most_specific_target) {
977 if (method == null || count > 1) {
978 Report.Error (-11, loc, "Ambiguous user defined conversion");
983 // This will do the conversion to the best match that we
984 // found. Now we need to perform an implict standard conversion
985 // if the best match was not the type that we were requested
988 if (look_for_explicit)
989 source = ConvertExplicitStandard (ec, source, most_specific_source, loc);
991 source = ConvertImplicitStandard (ec, source,
992 most_specific_source, loc);
997 e = new UserCast ((MethodInfo) method, source);
999 if (e.Type != target){
1000 if (!look_for_explicit)
1001 e = ConvertImplicitStandard (ec, e, target, loc);
1003 e = ConvertExplicitStandard (ec, e, target, loc);
1014 // Converts implicitly the resolved expression `expr' into the
1015 // `target_type'. It returns a new expression that can be used
1016 // in a context that expects a `target_type'.
1018 static public Expression ConvertImplicit (EmitContext ec, Expression expr,
1019 Type target_type, Location loc)
1021 Type expr_type = expr.Type;
1024 if (expr_type == target_type)
1027 e = ImplicitNumericConversion (ec, expr, target_type, loc);
1031 e = ImplicitReferenceConversion (expr, target_type);
1035 e = ImplicitUserConversion (ec, expr, target_type, loc);
1039 if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
1040 IntLiteral i = (IntLiteral) expr;
1043 return new EmptyCast (expr, target_type);
1051 // Attempts to apply the `Standard Implicit
1052 // Conversion' rules to the expression `expr' into
1053 // the `target_type'. It returns a new expression
1054 // that can be used in a context that expects a
1057 // This is different from `ConvertImplicit' in that the
1058 // user defined implicit conversions are excluded.
1060 static public Expression ConvertImplicitStandard (EmitContext ec, Expression expr,
1061 Type target_type, Location loc)
1063 Type expr_type = expr.Type;
1066 if (expr_type == target_type)
1069 e = ImplicitNumericConversion (ec, expr, target_type, loc);
1073 e = ImplicitReferenceConversion (expr, target_type);
1077 if (target_type.IsSubclassOf (TypeManager.enum_type) && expr is IntLiteral){
1078 IntLiteral i = (IntLiteral) expr;
1081 return new EmptyCast (expr, target_type);
1086 // Attemps to perform an implict constant conversion of the IntLiteral
1087 // into a different data type using casts (See Implicit Constant
1088 // Expression Conversions)
1090 static protected Expression TryImplicitIntConversion (Type target_type, IntLiteral il)
1092 int value = il.Value;
1094 if (target_type == TypeManager.sbyte_type){
1095 if (value >= SByte.MinValue && value <= SByte.MaxValue)
1097 } else if (target_type == TypeManager.byte_type){
1098 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
1100 } else if (target_type == TypeManager.short_type){
1101 if (value >= Int16.MinValue && value <= Int16.MaxValue)
1103 } else if (target_type == TypeManager.ushort_type){
1104 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
1106 } else if (target_type == TypeManager.uint32_type){
1108 // we can optimize this case: a positive int32
1109 // always fits on a uint32
1113 } else if (target_type == TypeManager.uint64_type){
1115 // we can optimize this case: a positive int32
1116 // always fits on a uint64. But we need an opcode
1120 return new OpcodeCast (il, target_type, OpCodes.Conv_I8);
1127 // Attemptes to implicityly convert `target' into `type', using
1128 // ConvertImplicit. If there is no implicit conversion, then
1129 // an error is signaled
1131 static public Expression ConvertImplicitRequired (EmitContext ec, Expression target,
1132 Type type, Location loc)
1136 e = ConvertImplicit (ec, target, type, loc);
1140 string msg = "Can not convert implicitly from `"+
1141 TypeManager.CSharpName (target.Type) + "' to `" +
1142 TypeManager.CSharpName (type) + "'";
1144 Error (29, loc, msg);
1150 // Performs the explicit numeric conversions
1152 static Expression ConvertNumericExplicit (EmitContext ec, Expression expr,
1155 Type expr_type = expr.Type;
1157 if (expr_type == TypeManager.sbyte_type){
1159 // From sbyte to byte, ushort, uint, ulong, char
1161 if (target_type == TypeManager.byte_type)
1162 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1163 if (target_type == TypeManager.ushort_type)
1164 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1165 if (target_type == TypeManager.uint32_type)
1166 return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1167 if (target_type == TypeManager.uint64_type)
1168 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1169 if (target_type == TypeManager.char_type)
1170 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1171 } else if (expr_type == TypeManager.byte_type){
1173 // From byte to sbyte and char
1175 if (target_type == TypeManager.sbyte_type)
1176 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1177 if (target_type == TypeManager.char_type)
1178 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1179 } else if (expr_type == TypeManager.short_type){
1181 // From short to sbyte, byte, ushort, uint, ulong, char
1183 if (target_type == TypeManager.sbyte_type)
1184 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1185 if (target_type == TypeManager.byte_type)
1186 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1187 if (target_type == TypeManager.ushort_type)
1188 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1189 if (target_type == TypeManager.uint32_type)
1190 return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1191 if (target_type == TypeManager.uint64_type)
1192 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1193 if (target_type == TypeManager.char_type)
1194 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1195 } else if (expr_type == TypeManager.ushort_type){
1197 // From ushort to sbyte, byte, short, char
1199 if (target_type == TypeManager.sbyte_type)
1200 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1201 if (target_type == TypeManager.byte_type)
1202 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1203 if (target_type == TypeManager.short_type)
1204 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1205 if (target_type == TypeManager.char_type)
1206 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1207 } else if (expr_type == TypeManager.int32_type){
1209 // From int to sbyte, byte, short, ushort, uint, ulong, char
1211 if (target_type == TypeManager.sbyte_type)
1212 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1213 if (target_type == TypeManager.byte_type)
1214 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1215 if (target_type == TypeManager.short_type)
1216 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1217 if (target_type == TypeManager.ushort_type)
1218 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1219 if (target_type == TypeManager.uint32_type)
1220 return new EmptyCast (expr, target_type);
1221 if (target_type == TypeManager.uint64_type)
1222 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1223 if (target_type == TypeManager.char_type)
1224 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1225 } else if (expr_type == TypeManager.uint32_type){
1227 // From uint to sbyte, byte, short, ushort, int, char
1229 if (target_type == TypeManager.sbyte_type)
1230 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1231 if (target_type == TypeManager.byte_type)
1232 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1233 if (target_type == TypeManager.short_type)
1234 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1235 if (target_type == TypeManager.ushort_type)
1236 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1237 if (target_type == TypeManager.int32_type)
1238 return new EmptyCast (expr, target_type);
1239 if (target_type == TypeManager.char_type)
1240 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1241 } else if (expr_type == TypeManager.int64_type){
1243 // From long to sbyte, byte, short, ushort, int, uint, ulong, char
1245 if (target_type == TypeManager.sbyte_type)
1246 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1247 if (target_type == TypeManager.byte_type)
1248 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1249 if (target_type == TypeManager.short_type)
1250 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1251 if (target_type == TypeManager.ushort_type)
1252 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1253 if (target_type == TypeManager.int32_type)
1254 return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1255 if (target_type == TypeManager.uint32_type)
1256 return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1257 if (target_type == TypeManager.uint64_type)
1258 return new EmptyCast (expr, target_type);
1259 if (target_type == TypeManager.char_type)
1260 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1261 } else if (expr_type == TypeManager.uint64_type){
1263 // From ulong to sbyte, byte, short, ushort, int, uint, long, char
1265 if (target_type == TypeManager.sbyte_type)
1266 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1267 if (target_type == TypeManager.byte_type)
1268 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1269 if (target_type == TypeManager.short_type)
1270 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1271 if (target_type == TypeManager.ushort_type)
1272 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1273 if (target_type == TypeManager.int32_type)
1274 return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1275 if (target_type == TypeManager.uint32_type)
1276 return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1277 if (target_type == TypeManager.int64_type)
1278 return new EmptyCast (expr, target_type);
1279 if (target_type == TypeManager.char_type)
1280 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1281 } else if (expr_type == TypeManager.char_type){
1283 // From char to sbyte, byte, short
1285 if (target_type == TypeManager.sbyte_type)
1286 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1287 if (target_type == TypeManager.byte_type)
1288 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1289 if (target_type == TypeManager.short_type)
1290 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1291 } else if (expr_type == TypeManager.float_type){
1293 // From float to sbyte, byte, short,
1294 // ushort, int, uint, long, ulong, char
1297 if (target_type == TypeManager.sbyte_type)
1298 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1299 if (target_type == TypeManager.byte_type)
1300 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1301 if (target_type == TypeManager.short_type)
1302 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1303 if (target_type == TypeManager.ushort_type)
1304 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1305 if (target_type == TypeManager.int32_type)
1306 return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1307 if (target_type == TypeManager.uint32_type)
1308 return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1309 if (target_type == TypeManager.int64_type)
1310 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1311 if (target_type == TypeManager.uint64_type)
1312 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
1313 if (target_type == TypeManager.char_type)
1314 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1315 if (target_type == TypeManager.decimal_type)
1316 return InternalTypeConstructor (ec, expr, target_type);
1317 } else if (expr_type == TypeManager.double_type){
1319 // From double to byte, byte, short,
1320 // ushort, int, uint, long, ulong,
1321 // char, float or decimal
1323 if (target_type == TypeManager.sbyte_type)
1324 return new OpcodeCast (expr, target_type, OpCodes.Conv_I1);
1325 if (target_type == TypeManager.byte_type)
1326 return new OpcodeCast (expr, target_type, OpCodes.Conv_U1);
1327 if (target_type == TypeManager.short_type)
1328 return new OpcodeCast (expr, target_type, OpCodes.Conv_I2);
1329 if (target_type == TypeManager.ushort_type)
1330 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1331 if (target_type == TypeManager.int32_type)
1332 return new OpcodeCast (expr, target_type, OpCodes.Conv_I4);
1333 if (target_type == TypeManager.uint32_type)
1334 return new OpcodeCast (expr, target_type, OpCodes.Conv_U4);
1335 if (target_type == TypeManager.int64_type)
1336 return new OpcodeCast (expr, target_type, OpCodes.Conv_I8);
1337 if (target_type == TypeManager.uint64_type)
1338 return new OpcodeCast (expr, target_type, OpCodes.Conv_U8);
1339 if (target_type == TypeManager.char_type)
1340 return new OpcodeCast (expr, target_type, OpCodes.Conv_U2);
1341 if (target_type == TypeManager.float_type)
1342 return new OpcodeCast (expr, target_type, OpCodes.Conv_R4);
1343 if (target_type == TypeManager.decimal_type)
1344 return InternalTypeConstructor (ec, expr, target_type);
1347 // decimal is taken care of by the op_Explicit methods.
1353 // Returns whether an explicit reference conversion can be performed
1354 // from source_type to target_type
1356 static bool ExplicitReferenceConversionExists (Type source_type, Type target_type)
1358 bool target_is_value_type = target_type.IsValueType;
1360 if (source_type == target_type)
1364 // From object to any reference type
1366 if (source_type == TypeManager.object_type && !target_is_value_type)
1370 // From any class S to any class-type T, provided S is a base class of T
1372 if (target_type.IsSubclassOf (source_type))
1376 // From any interface type S to any interface T provided S is not derived from T
1378 if (source_type.IsInterface && target_type.IsInterface){
1379 if (!target_type.IsSubclassOf (source_type))
1384 // From any class type S to any interface T, provides S is not sealed
1385 // and provided S does not implement T.
1387 if (target_type.IsInterface && !source_type.IsSealed &&
1388 !target_type.IsAssignableFrom (source_type))
1392 // From any interface-type S to to any class type T, provided T is not
1393 // sealed, or provided T implements S.
1395 if (source_type.IsInterface &&
1396 (!target_type.IsSealed || source_type.IsAssignableFrom (target_type)))
1399 // From an array type S with an element type Se to an array type T with an
1400 // element type Te provided all the following are true:
1401 // * S and T differe only in element type, in other words, S and T
1402 // have the same number of dimensions.
1403 // * Both Se and Te are reference types
1404 // * An explicit referenc conversions exist from Se to Te
1406 if (source_type.IsArray && target_type.IsArray) {
1407 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1409 Type source_element_type = source_type.GetElementType ();
1410 Type target_element_type = target_type.GetElementType ();
1412 if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1413 if (ExplicitReferenceConversionExists (source_element_type,
1414 target_element_type))
1420 // From System.Array to any array-type
1421 if (source_type == TypeManager.array_type &&
1422 target_type.IsSubclassOf (TypeManager.array_type)){
1427 // From System delegate to any delegate-type
1429 if (source_type == TypeManager.delegate_type &&
1430 target_type.IsSubclassOf (TypeManager.delegate_type))
1434 // From ICloneable to Array or Delegate types
1436 if (source_type == TypeManager.icloneable_type &&
1437 (target_type == TypeManager.array_type ||
1438 target_type == TypeManager.delegate_type))
1445 // Implements Explicit Reference conversions
1447 static Expression ConvertReferenceExplicit (Expression source, Type target_type)
1449 Type source_type = source.Type;
1450 bool target_is_value_type = target_type.IsValueType;
1453 // From object to any reference type
1455 if (source_type == TypeManager.object_type && !target_is_value_type)
1456 return new ClassCast (source, target_type);
1460 // From any class S to any class-type T, provided S is a base class of T
1462 if (target_type.IsSubclassOf (source_type))
1463 return new ClassCast (source, target_type);
1466 // From any interface type S to any interface T provided S is not derived from T
1468 if (source_type.IsInterface && target_type.IsInterface){
1469 if (!target_type.IsSubclassOf (source_type))
1470 return new ClassCast (source, target_type);
1474 // From any class type S to any interface T, provides S is not sealed
1475 // and provided S does not implement T.
1477 if (target_type.IsInterface && !source_type.IsSealed &&
1478 !target_type.IsAssignableFrom (source_type))
1479 return new ClassCast (source, target_type);
1482 // From any interface-type S to to any class type T, provided T is not
1483 // sealed, or provided T implements S.
1485 if (source_type.IsInterface &&
1486 (!target_type.IsSealed || source_type.IsAssignableFrom (target_type)))
1487 return new ClassCast (source, target_type);
1489 // From an array type S with an element type Se to an array type T with an
1490 // element type Te provided all the following are true:
1491 // * S and T differe only in element type, in other words, S and T
1492 // have the same number of dimensions.
1493 // * Both Se and Te are reference types
1494 // * An explicit referenc conversions exist from Se to Te
1496 if (source_type.IsArray && target_type.IsArray) {
1497 if (source_type.GetArrayRank () == target_type.GetArrayRank ()) {
1499 Type source_element_type = source_type.GetElementType ();
1500 Type target_element_type = target_type.GetElementType ();
1502 if (!source_element_type.IsValueType && !target_element_type.IsValueType)
1503 if (ExplicitReferenceConversionExists (source_element_type,
1504 target_element_type))
1505 return new ClassCast (source, target_type);
1510 // From System.Array to any array-type
1511 if (source_type == TypeManager.array_type &&
1512 target_type.IsSubclassOf (TypeManager.array_type)){
1513 return new ClassCast (source, target_type);
1517 // From System delegate to any delegate-type
1519 if (source_type == TypeManager.delegate_type &&
1520 target_type.IsSubclassOf (TypeManager.delegate_type))
1521 return new ClassCast (source, target_type);
1524 // From ICloneable to Array or Delegate types
1526 if (source_type == TypeManager.icloneable_type &&
1527 (target_type == TypeManager.array_type ||
1528 target_type == TypeManager.delegate_type))
1529 return new ClassCast (source, target_type);
1535 // Performs an explicit conversion of the expression `expr' whose
1536 // type is expr.Type to `target_type'.
1538 static public Expression ConvertExplicit (EmitContext ec, Expression expr,
1539 Type target_type, Location loc)
1541 Expression ne = ConvertImplicitStandard (ec, expr, target_type, loc);
1546 ne = ConvertNumericExplicit (ec, expr, target_type);
1550 ne = ConvertReferenceExplicit (expr, target_type);
1554 ne = ExplicitUserConversion (ec, expr, target_type, loc);
1558 Report.Error (30, loc, "Cannot convert type '" + TypeManager.CSharpName (expr.Type) + "' to '"
1559 + TypeManager.CSharpName (target_type) + "'");
1564 // Same as ConverExplicit, only it doesn't include user defined conversions
1566 static public Expression ConvertExplicitStandard (EmitContext ec, Expression expr,
1567 Type target_type, Location l)
1569 Expression ne = ConvertImplicitStandard (ec, expr, target_type, l);
1574 ne = ConvertNumericExplicit (ec, expr, target_type);
1578 ne = ConvertReferenceExplicit (expr, target_type);
1582 Report.Error (30, l, "Cannot convert type '" +
1583 TypeManager.CSharpName (expr.Type) + "' to '" +
1584 TypeManager.CSharpName (target_type) + "'");
1588 static string ExprClassName (ExprClass c)
1591 case ExprClass.Invalid:
1593 case ExprClass.Value:
1595 case ExprClass.Variable:
1597 case ExprClass.Namespace:
1599 case ExprClass.Type:
1601 case ExprClass.MethodGroup:
1602 return "method group";
1603 case ExprClass.PropertyAccess:
1604 return "property access";
1605 case ExprClass.EventAccess:
1606 return "event access";
1607 case ExprClass.IndexerAccess:
1608 return "indexer access";
1609 case ExprClass.Nothing:
1612 throw new Exception ("Should not happen");
1616 // Reports that we were expecting `expr' to be of class `expected'
1618 protected void report118 (Location loc, Expression expr, string expected)
1620 string kind = "Unknown";
1623 kind = ExprClassName (expr.ExprClass);
1625 Error (118, loc, "Expression denotes a '" + kind +
1626 "' where an " + expected + " was expected");
1631 // This is just a base class for expressions that can
1632 // appear on statements (invocations, object creation,
1633 // assignments, post/pre increment and decrement). The idea
1634 // being that they would support an extra Emition interface that
1635 // does not leave a result on the stack.
1638 public abstract class ExpressionStatement : Expression {
1641 // Requests the expression to be emitted in a `statement'
1642 // context. This means that no new value is left on the
1643 // stack after invoking this method (constrasted with
1644 // Emit that will always leave a value on the stack).
1646 public abstract void EmitStatement (EmitContext ec);
1650 // This kind of cast is used to encapsulate the child
1651 // whose type is child.Type into an expression that is
1652 // reported to return "return_type". This is used to encapsulate
1653 // expressions which have compatible types, but need to be dealt
1654 // at higher levels with.
1656 // For example, a "byte" expression could be encapsulated in one
1657 // of these as an "unsigned int". The type for the expression
1658 // would be "unsigned int".
1662 public class EmptyCast : Expression {
1663 protected Expression child;
1665 public EmptyCast (Expression child, Type return_type)
1667 ExprClass = child.ExprClass;
1672 public override Expression DoResolve (EmitContext ec)
1674 // This should never be invoked, we are born in fully
1675 // initialized state.
1680 public override void Emit (EmitContext ec)
1687 // This kind of cast is used to encapsulate Value Types in objects.
1689 // The effect of it is to box the value type emitted by the previous
1692 public class BoxedCast : EmptyCast {
1694 public BoxedCast (Expression expr)
1695 : base (expr, TypeManager.object_type)
1699 public override Expression DoResolve (EmitContext ec)
1701 // This should never be invoked, we are born in fully
1702 // initialized state.
1707 public override void Emit (EmitContext ec)
1710 ec.ig.Emit (OpCodes.Box, child.Type);
1715 // This kind of cast is used to encapsulate a child expression
1716 // that can be trivially converted to a target type using one or
1717 // two opcodes. The opcodes are passed as arguments.
1719 public class OpcodeCast : EmptyCast {
1723 public OpcodeCast (Expression child, Type return_type, OpCode op)
1724 : base (child, return_type)
1728 second_valid = false;
1731 public OpcodeCast (Expression child, Type return_type, OpCode op, OpCode op2)
1732 : base (child, return_type)
1737 second_valid = true;
1740 public override Expression DoResolve (EmitContext ec)
1742 // This should never be invoked, we are born in fully
1743 // initialized state.
1748 public override void Emit (EmitContext ec)
1760 // This kind of cast is used to encapsulate a child and cast it
1761 // to the class requested
1763 public class ClassCast : EmptyCast {
1764 public ClassCast (Expression child, Type return_type)
1765 : base (child, return_type)
1770 public override Expression DoResolve (EmitContext ec)
1772 // This should never be invoked, we are born in fully
1773 // initialized state.
1778 public override void Emit (EmitContext ec)
1782 ec.ig.Emit (OpCodes.Castclass, type);
1788 // Unary expressions.
1792 // Unary implements unary expressions. It derives from
1793 // ExpressionStatement becuase the pre/post increment/decrement
1794 // operators can be used in a statement context.
1796 public class Unary : ExpressionStatement {
1797 public enum Operator {
1798 Addition, Subtraction, Negate, BitComplement,
1799 Indirection, AddressOf, PreIncrement,
1800 PreDecrement, PostIncrement, PostDecrement
1805 ArrayList Arguments;
1809 public Unary (Operator op, Expression expr, Location loc)
1816 public Expression Expr {
1826 public Operator Oper {
1837 // Returns a stringified representation of the Operator
1842 case Operator.Addition:
1844 case Operator.Subtraction:
1846 case Operator.Negate:
1848 case Operator.BitComplement:
1850 case Operator.AddressOf:
1852 case Operator.Indirection:
1854 case Operator.PreIncrement : case Operator.PostIncrement :
1856 case Operator.PreDecrement : case Operator.PostDecrement :
1860 return oper.ToString ();
1863 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1865 if (expr.Type == target_type)
1868 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1871 void error23 (Type t)
1874 23, loc, "Operator " + OperName () +
1875 " cannot be applied to operand of type `" +
1876 TypeManager.CSharpName (t) + "'");
1880 // Returns whether an object of type `t' can be incremented
1881 // or decremented with add/sub (ie, basically whether we can
1882 // use pre-post incr-decr operations on it, but it is not a
1883 // System.Decimal, which we test elsewhere)
1885 static bool IsIncrementableNumber (Type t)
1887 return (t == TypeManager.sbyte_type) ||
1888 (t == TypeManager.byte_type) ||
1889 (t == TypeManager.short_type) ||
1890 (t == TypeManager.ushort_type) ||
1891 (t == TypeManager.int32_type) ||
1892 (t == TypeManager.uint32_type) ||
1893 (t == TypeManager.int64_type) ||
1894 (t == TypeManager.uint64_type) ||
1895 (t == TypeManager.char_type) ||
1896 (t.IsSubclassOf (TypeManager.enum_type)) ||
1897 (t == TypeManager.float_type) ||
1898 (t == TypeManager.double_type);
1901 Expression ResolveOperator (EmitContext ec)
1903 Type expr_type = expr.Type;
1906 // Step 1: Perform Operator Overload location
1911 if (oper == Operator.PostIncrement || oper == Operator.PreIncrement)
1912 op_name = "op_Increment";
1913 else if (oper == Operator.PostDecrement || oper == Operator.PreDecrement)
1914 op_name = "op_Decrement";
1916 op_name = "op_" + oper;
1918 mg = MemberLookup (ec, expr_type, op_name, false, loc);
1920 if (mg == null && expr_type.BaseType != null)
1921 mg = MemberLookup (ec, expr_type.BaseType, op_name, false, loc);
1924 Arguments = new ArrayList ();
1925 Arguments.Add (new Argument (expr, Argument.AType.Expression));
1927 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg,
1929 if (method != null) {
1930 MethodInfo mi = (MethodInfo) method;
1931 type = mi.ReturnType;
1934 error23 (expr_type);
1941 // Step 2: Default operations on CLI native types.
1944 // Only perform numeric promotions on:
1947 if (expr_type == null)
1950 if (oper == Operator.Negate){
1951 if (expr_type != TypeManager.bool_type) {
1952 error23 (expr.Type);
1956 type = TypeManager.bool_type;
1960 if (oper == Operator.BitComplement) {
1961 if (!((expr_type == TypeManager.int32_type) ||
1962 (expr_type == TypeManager.uint32_type) ||
1963 (expr_type == TypeManager.int64_type) ||
1964 (expr_type == TypeManager.uint64_type) ||
1965 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
1966 error23 (expr.Type);
1973 if (oper == Operator.Addition) {
1975 // A plus in front of something is just a no-op, so return the child.
1981 // Deals with -literals
1982 // int operator- (int x)
1983 // long operator- (long x)
1984 // float operator- (float f)
1985 // double operator- (double d)
1986 // decimal operator- (decimal d)
1988 if (oper == Operator.Subtraction){
1990 // Fold a "- Constant" into a negative constant
1993 Expression e = null;
1996 // Is this a constant?
1998 if (expr is IntLiteral)
1999 e = new IntLiteral (-((IntLiteral) expr).Value);
2000 else if (expr is LongLiteral)
2001 e = new LongLiteral (-((LongLiteral) expr).Value);
2002 else if (expr is FloatLiteral)
2003 e = new FloatLiteral (-((FloatLiteral) expr).Value);
2004 else if (expr is DoubleLiteral)
2005 e = new DoubleLiteral (-((DoubleLiteral) expr).Value);
2006 else if (expr is DecimalLiteral)
2007 e = new DecimalLiteral (-((DecimalLiteral) expr).Value);
2015 // Not a constant we can optimize, perform numeric
2016 // promotions to int, long, double.
2019 // The following is inneficient, because we call
2020 // ConvertImplicit too many times.
2022 // It is also not clear if we should convert to Float
2023 // or Double initially.
2025 if (expr_type == TypeManager.uint32_type){
2027 // FIXME: handle exception to this rule that
2028 // permits the int value -2147483648 (-2^31) to
2029 // bt written as a decimal interger literal
2031 type = TypeManager.int64_type;
2032 expr = ConvertImplicit (ec, expr, type, loc);
2036 if (expr_type == TypeManager.uint64_type){
2038 // FIXME: Handle exception of `long value'
2039 // -92233720368547758087 (-2^63) to be written as
2040 // decimal integer literal.
2042 error23 (expr_type);
2046 e = ConvertImplicit (ec, expr, TypeManager.int32_type, loc);
2053 e = ConvertImplicit (ec, expr, TypeManager.int64_type, loc);
2060 e = ConvertImplicit (ec, expr, TypeManager.double_type, loc);
2067 error23 (expr_type);
2072 // The operand of the prefix/postfix increment decrement operators
2073 // should be an expression that is classified as a variable,
2074 // a property access or an indexer access
2076 if (oper == Operator.PreDecrement || oper == Operator.PreIncrement ||
2077 oper == Operator.PostDecrement || oper == Operator.PostIncrement){
2078 if (expr.ExprClass == ExprClass.Variable){
2079 if (IsIncrementableNumber (expr_type) ||
2080 expr_type == TypeManager.decimal_type){
2084 } else if (expr.ExprClass == ExprClass.IndexerAccess){
2086 // FIXME: Verify that we have both get and set methods
2088 throw new Exception ("Implement me");
2089 } else if (expr.ExprClass == ExprClass.PropertyAccess){
2091 // FIXME: Verify that we have both get and set methods
2093 throw new Exception ("Implement me");
2095 report118 (loc, expr, "variable, indexer or property access");
2099 if (oper == Operator.AddressOf){
2100 if (expr.ExprClass != ExprClass.Variable){
2101 Error (211, "Cannot take the address of non-variables");
2104 type = Type.GetType (expr.Type.ToString () + "*");
2107 Error (187, "No such operator '" + OperName () + "' defined for type '" +
2108 TypeManager.CSharpName (expr_type) + "'");
2113 public override Expression DoResolve (EmitContext ec)
2115 expr = expr.Resolve (ec);
2120 eclass = ExprClass.Value;
2121 return ResolveOperator (ec);
2124 public override void Emit (EmitContext ec)
2126 ILGenerator ig = ec.ig;
2127 Type expr_type = expr.Type;
2129 if (method != null) {
2131 // Note that operators are static anyway
2133 if (Arguments != null)
2134 Invocation.EmitArguments (ec, method, Arguments);
2137 // Post increment/decrement operations need a copy at this
2140 if (oper == Operator.PostDecrement || oper == Operator.PostIncrement)
2141 ig.Emit (OpCodes.Dup);
2144 ig.Emit (OpCodes.Call, (MethodInfo) method);
2147 // Pre Increment and Decrement operators
2149 if (oper == Operator.PreIncrement || oper == Operator.PreDecrement){
2150 ig.Emit (OpCodes.Dup);
2154 // Increment and Decrement should store the result
2156 if (oper == Operator.PreDecrement || oper == Operator.PreIncrement ||
2157 oper == Operator.PostDecrement || oper == Operator.PostIncrement){
2158 ((LValue) expr).Store (ec);
2164 case Operator.Addition:
2165 throw new Exception ("This should be caught by Resolve");
2167 case Operator.Subtraction:
2169 ig.Emit (OpCodes.Neg);
2172 case Operator.Negate:
2174 ig.Emit (OpCodes.Ldc_I4_0);
2175 ig.Emit (OpCodes.Ceq);
2178 case Operator.BitComplement:
2180 ig.Emit (OpCodes.Not);
2183 case Operator.AddressOf:
2184 ((MemoryLocation)expr).AddressOf (ec);
2187 case Operator.Indirection:
2188 throw new Exception ("Not implemented yet");
2190 case Operator.PreIncrement:
2191 case Operator.PreDecrement:
2192 if (expr.ExprClass == ExprClass.Variable){
2194 // Resolve already verified that it is an "incrementable"
2197 ig.Emit (OpCodes.Ldc_I4_1);
2199 if (oper == Operator.PreDecrement)
2200 ig.Emit (OpCodes.Sub);
2202 ig.Emit (OpCodes.Add);
2203 ig.Emit (OpCodes.Dup);
2204 ((LValue) expr).Store (ec);
2206 throw new Exception ("Handle Indexers and Properties here");
2210 case Operator.PostIncrement:
2211 case Operator.PostDecrement:
2212 if (expr.ExprClass == ExprClass.Variable){
2214 // Resolve already verified that it is an "incrementable"
2217 ig.Emit (OpCodes.Dup);
2218 ig.Emit (OpCodes.Ldc_I4_1);
2220 if (oper == Operator.PostDecrement)
2221 ig.Emit (OpCodes.Sub);
2223 ig.Emit (OpCodes.Add);
2224 ((LValue) expr).Store (ec);
2226 throw new Exception ("Handle Indexers and Properties here");
2231 throw new Exception ("This should not happen: Operator = "
2232 + oper.ToString ());
2237 public override void EmitStatement (EmitContext ec)
2240 // FIXME: we should rewrite this code to generate
2241 // better code for ++ and -- as we know we wont need
2242 // the values on the stack
2245 ec.ig.Emit (OpCodes.Pop);
2249 public class Probe : Expression {
2250 public readonly string ProbeType;
2251 public readonly Operator Oper;
2255 public enum Operator {
2259 public Probe (Operator oper, Expression expr, string probe_type)
2262 ProbeType = probe_type;
2266 public Expression Expr {
2272 public override Expression DoResolve (EmitContext ec)
2274 probe_type = ec.TypeContainer.LookupType (ProbeType, false);
2276 if (probe_type == null)
2279 expr = expr.Resolve (ec);
2281 type = TypeManager.bool_type;
2282 eclass = ExprClass.Value;
2287 public override void Emit (EmitContext ec)
2289 ILGenerator ig = ec.ig;
2293 if (Oper == Operator.Is){
2294 ig.Emit (OpCodes.Isinst, probe_type);
2295 ig.Emit (OpCodes.Ldnull);
2296 ig.Emit (OpCodes.Cgt_Un);
2298 ig.Emit (OpCodes.Isinst, probe_type);
2304 // This represents a typecast in the source language.
2306 // FIXME: Cast expressions have an unusual set of parsing
2307 // rules, we need to figure those out.
2309 public class Cast : Expression {
2314 public Cast (string cast_type, Expression expr, Location loc)
2316 this.target_type = cast_type;
2321 public string TargetType {
2327 public Expression Expr {
2336 public override Expression DoResolve (EmitContext ec)
2338 expr = expr.Resolve (ec);
2342 type = ec.TypeContainer.LookupType (target_type, false);
2343 eclass = ExprClass.Value;
2348 expr = ConvertExplicit (ec, expr, type, loc);
2353 public override void Emit (EmitContext ec)
2356 // This one will never happen
2358 throw new Exception ("Should not happen");
2362 public class Binary : Expression {
2363 public enum Operator {
2364 Multiply, Division, Modulus,
2365 Addition, Subtraction,
2366 LeftShift, RightShift,
2367 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
2368 Equality, Inequality,
2377 Expression left, right;
2379 ArrayList Arguments;
2383 public Binary (Operator oper, Expression left, Expression right, Location loc)
2391 public Operator Oper {
2400 public Expression Left {
2409 public Expression Right {
2420 // Returns a stringified representation of the Operator
2425 case Operator.Multiply:
2427 case Operator.Division:
2429 case Operator.Modulus:
2431 case Operator.Addition:
2433 case Operator.Subtraction:
2435 case Operator.LeftShift:
2437 case Operator.RightShift:
2439 case Operator.LessThan:
2441 case Operator.GreaterThan:
2443 case Operator.LessThanOrEqual:
2445 case Operator.GreaterThanOrEqual:
2447 case Operator.Equality:
2449 case Operator.Inequality:
2451 case Operator.BitwiseAnd:
2453 case Operator.BitwiseOr:
2455 case Operator.ExclusiveOr:
2457 case Operator.LogicalOr:
2459 case Operator.LogicalAnd:
2463 return oper.ToString ();
2466 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
2468 if (expr.Type == target_type)
2471 return ConvertImplicit (ec, expr, target_type, new Location (-1));
2475 // Note that handling the case l == Decimal || r == Decimal
2476 // is taken care of by the Step 1 Operator Overload resolution.
2478 void DoNumericPromotions (EmitContext ec, Type l, Type r)
2480 if (l == TypeManager.double_type || r == TypeManager.double_type){
2482 // If either operand is of type double, the other operand is
2483 // conveted to type double.
2485 if (r != TypeManager.double_type)
2486 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
2487 if (l != TypeManager.double_type)
2488 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
2490 type = TypeManager.double_type;
2491 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
2493 // if either operand is of type float, th eother operand is
2494 // converd to type float.
2496 if (r != TypeManager.double_type)
2497 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
2498 if (l != TypeManager.double_type)
2499 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
2500 type = TypeManager.float_type;
2501 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
2505 // If either operand is of type ulong, the other operand is
2506 // converted to type ulong. or an error ocurrs if the other
2507 // operand is of type sbyte, short, int or long
2510 if (l == TypeManager.uint64_type){
2511 if (r != TypeManager.uint64_type && right is IntLiteral){
2512 e = TryImplicitIntConversion (l, (IntLiteral) right);
2518 if (left is IntLiteral){
2519 e = TryImplicitIntConversion (r, (IntLiteral) left);
2526 if ((other == TypeManager.sbyte_type) ||
2527 (other == TypeManager.short_type) ||
2528 (other == TypeManager.int32_type) ||
2529 (other == TypeManager.int64_type)){
2530 string oper = OperName ();
2532 Error (34, loc, "Operator `" + OperName ()
2533 + "' is ambiguous on operands of type `"
2534 + TypeManager.CSharpName (l) + "' "
2535 + "and `" + TypeManager.CSharpName (r)
2538 type = TypeManager.uint64_type;
2539 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
2541 // If either operand is of type long, the other operand is converted
2544 if (l != TypeManager.int64_type)
2545 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
2546 if (r != TypeManager.int64_type)
2547 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
2549 type = TypeManager.int64_type;
2550 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
2552 // If either operand is of type uint, and the other
2553 // operand is of type sbyte, short or int, othe operands are
2554 // converted to type long.
2558 if (l == TypeManager.uint32_type)
2560 else if (r == TypeManager.uint32_type)
2563 if ((other == TypeManager.sbyte_type) ||
2564 (other == TypeManager.short_type) ||
2565 (other == TypeManager.int32_type)){
2566 left = ForceConversion (ec, left, TypeManager.int64_type);
2567 right = ForceConversion (ec, right, TypeManager.int64_type);
2568 type = TypeManager.int64_type;
2571 // if either operand is of type uint, the other
2572 // operand is converd to type uint
2574 left = ForceConversion (ec, left, TypeManager.uint32_type);
2575 right = ForceConversion (ec, right, TypeManager.uint32_type);
2576 type = TypeManager.uint32_type;
2578 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
2579 if (l != TypeManager.decimal_type)
2580 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
2581 if (r != TypeManager.decimal_type)
2582 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
2584 type = TypeManager.decimal_type;
2586 Expression l_tmp, r_tmp;
2588 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
2589 if (l_tmp == null) {
2595 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
2596 if (r_tmp == null) {
2602 type = TypeManager.int32_type;
2609 "Operator " + OperName () + " cannot be applied to operands of type `" +
2610 TypeManager.CSharpName (left.Type) + "' and `" +
2611 TypeManager.CSharpName (right.Type) + "'");
2615 Expression CheckShiftArguments (EmitContext ec)
2619 Type r = right.Type;
2621 e = ForceConversion (ec, right, TypeManager.int32_type);
2628 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
2629 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
2630 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
2631 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
2641 Expression ResolveOperator (EmitContext ec)
2644 Type r = right.Type;
2647 // Step 1: Perform Operator Overload location
2649 Expression left_expr, right_expr;
2651 string op = "op_" + oper;
2653 left_expr = MemberLookup (ec, l, op, false, loc);
2654 if (left_expr == null && l.BaseType != null)
2655 left_expr = MemberLookup (ec, l.BaseType, op, false, loc);
2657 right_expr = MemberLookup (ec, r, op, false, loc);
2658 if (right_expr == null && r.BaseType != null)
2659 right_expr = MemberLookup (ec, r.BaseType, op, false, loc);
2661 MethodGroupExpr union = Invocation.MakeUnionSet (left_expr, right_expr);
2663 if (union != null) {
2664 Arguments = new ArrayList ();
2665 Arguments.Add (new Argument (left, Argument.AType.Expression));
2666 Arguments.Add (new Argument (right, Argument.AType.Expression));
2668 method = Invocation.OverloadResolve (ec, union, Arguments, loc);
2669 if (method != null) {
2670 MethodInfo mi = (MethodInfo) method;
2671 type = mi.ReturnType;
2680 // Step 2: Default operations on CLI native types.
2683 // Only perform numeric promotions on:
2684 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
2686 if (oper == Operator.Addition){
2688 // If any of the arguments is a string, cast to string
2690 if (l == TypeManager.string_type){
2691 if (r == TypeManager.string_type){
2693 method = TypeManager.string_concat_string_string;
2696 method = TypeManager.string_concat_object_object;
2697 right = ConvertImplicit (ec, right,
2698 TypeManager.object_type, loc);
2700 type = TypeManager.string_type;
2702 Arguments = new ArrayList ();
2703 Arguments.Add (new Argument (left, Argument.AType.Expression));
2704 Arguments.Add (new Argument (right, Argument.AType.Expression));
2708 } else if (r == TypeManager.string_type){
2710 method = TypeManager.string_concat_object_object;
2711 Arguments = new ArrayList ();
2712 Arguments.Add (new Argument (left, Argument.AType.Expression));
2713 Arguments.Add (new Argument (right, Argument.AType.Expression));
2715 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
2716 type = TypeManager.string_type;
2722 // FIXME: is Delegate operator + (D x, D y) handled?
2726 if (oper == Operator.LeftShift || oper == Operator.RightShift)
2727 return CheckShiftArguments (ec);
2729 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
2730 if (l != TypeManager.bool_type || r != TypeManager.bool_type)
2733 type = TypeManager.bool_type;
2738 // We are dealing with numbers
2741 DoNumericPromotions (ec, l, r);
2743 if (left == null || right == null)
2747 if (oper == Operator.BitwiseAnd ||
2748 oper == Operator.BitwiseOr ||
2749 oper == Operator.ExclusiveOr){
2750 if (!((l == TypeManager.int32_type) ||
2751 (l == TypeManager.uint32_type) ||
2752 (l == TypeManager.int64_type) ||
2753 (l == TypeManager.uint64_type))){
2760 if (oper == Operator.Equality ||
2761 oper == Operator.Inequality ||
2762 oper == Operator.LessThanOrEqual ||
2763 oper == Operator.LessThan ||
2764 oper == Operator.GreaterThanOrEqual ||
2765 oper == Operator.GreaterThan){
2766 type = TypeManager.bool_type;
2772 public override Expression DoResolve (EmitContext ec)
2774 left = left.Resolve (ec);
2775 right = right.Resolve (ec);
2777 if (left == null || right == null)
2780 if (left.Type == null)
2781 throw new Exception (
2782 "Resolve returned non null, but did not set the type! (" +
2784 if (right.Type == null)
2785 throw new Exception (
2786 "Resolve returned non null, but did not set the type! (" +
2789 eclass = ExprClass.Value;
2791 return ResolveOperator (ec);
2794 public bool IsBranchable ()
2796 if (oper == Operator.Equality ||
2797 oper == Operator.Inequality ||
2798 oper == Operator.LessThan ||
2799 oper == Operator.GreaterThan ||
2800 oper == Operator.LessThanOrEqual ||
2801 oper == Operator.GreaterThanOrEqual){
2808 // This entry point is used by routines that might want
2809 // to emit a brfalse/brtrue after an expression, and instead
2810 // they could use a more compact notation.
2812 // Typically the code would generate l.emit/r.emit, followed
2813 // by the comparission and then a brtrue/brfalse. The comparissions
2814 // are sometimes inneficient (there are not as complete as the branches
2815 // look for the hacks in Emit using double ceqs).
2817 // So for those cases we provide EmitBranchable that can emit the
2818 // branch with the test
2820 public void EmitBranchable (EmitContext ec, int target)
2823 bool close_target = false;
2829 case Operator.Equality:
2831 opcode = OpCodes.Beq_S;
2833 opcode = OpCodes.Beq;
2836 case Operator.Inequality:
2838 opcode = OpCodes.Bne_Un_S;
2840 opcode = OpCodes.Bne_Un;
2843 case Operator.LessThan:
2845 opcode = OpCodes.Blt_S;
2847 opcode = OpCodes.Blt;
2850 case Operator.GreaterThan:
2852 opcode = OpCodes.Bgt_S;
2854 opcode = OpCodes.Bgt;
2857 case Operator.LessThanOrEqual:
2859 opcode = OpCodes.Ble_S;
2861 opcode = OpCodes.Ble;
2864 case Operator.GreaterThanOrEqual:
2866 opcode = OpCodes.Bge_S;
2868 opcode = OpCodes.Ble;
2872 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
2873 + oper.ToString ());
2876 ec.ig.Emit (opcode, target);
2879 public override void Emit (EmitContext ec)
2881 ILGenerator ig = ec.ig;
2883 Type r = right.Type;
2886 if (method != null) {
2888 // Note that operators are static anyway
2890 if (Arguments != null)
2891 Invocation.EmitArguments (ec, method, Arguments);
2893 if (method is MethodInfo)
2894 ig.Emit (OpCodes.Call, (MethodInfo) method);
2896 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2905 case Operator.Multiply:
2907 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2908 opcode = OpCodes.Mul_Ovf;
2909 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2910 opcode = OpCodes.Mul_Ovf_Un;
2912 opcode = OpCodes.Mul;
2914 opcode = OpCodes.Mul;
2918 case Operator.Division:
2919 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2920 opcode = OpCodes.Div_Un;
2922 opcode = OpCodes.Div;
2925 case Operator.Modulus:
2926 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2927 opcode = OpCodes.Rem_Un;
2929 opcode = OpCodes.Rem;
2932 case Operator.Addition:
2934 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2935 opcode = OpCodes.Add_Ovf;
2936 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2937 opcode = OpCodes.Add_Ovf_Un;
2939 opcode = OpCodes.Mul;
2941 opcode = OpCodes.Add;
2944 case Operator.Subtraction:
2946 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2947 opcode = OpCodes.Sub_Ovf;
2948 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2949 opcode = OpCodes.Sub_Ovf_Un;
2951 opcode = OpCodes.Sub;
2953 opcode = OpCodes.Sub;
2956 case Operator.RightShift:
2957 opcode = OpCodes.Shr;
2960 case Operator.LeftShift:
2961 opcode = OpCodes.Shl;
2964 case Operator.Equality:
2965 opcode = OpCodes.Ceq;
2968 case Operator.Inequality:
2969 ec.ig.Emit (OpCodes.Ceq);
2970 ec.ig.Emit (OpCodes.Ldc_I4_0);
2972 opcode = OpCodes.Ceq;
2975 case Operator.LessThan:
2976 opcode = OpCodes.Clt;
2979 case Operator.GreaterThan:
2980 opcode = OpCodes.Cgt;
2983 case Operator.LessThanOrEqual:
2984 ec.ig.Emit (OpCodes.Cgt);
2985 ec.ig.Emit (OpCodes.Ldc_I4_0);
2987 opcode = OpCodes.Ceq;
2990 case Operator.GreaterThanOrEqual:
2991 ec.ig.Emit (OpCodes.Clt);
2992 ec.ig.Emit (OpCodes.Ldc_I4_1);
2994 opcode = OpCodes.Sub;
2997 case Operator.LogicalOr:
2998 case Operator.BitwiseOr:
2999 opcode = OpCodes.Or;
3002 case Operator.LogicalAnd:
3003 case Operator.BitwiseAnd:
3004 opcode = OpCodes.And;
3007 case Operator.ExclusiveOr:
3008 opcode = OpCodes.Xor;
3012 throw new Exception ("This should not happen: Operator = "
3013 + oper.ToString ());
3020 public class Conditional : Expression {
3021 Expression expr, trueExpr, falseExpr;
3024 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
3027 this.trueExpr = trueExpr;
3028 this.falseExpr = falseExpr;
3032 public Expression Expr {
3038 public Expression TrueExpr {
3044 public Expression FalseExpr {
3050 public override Expression DoResolve (EmitContext ec)
3052 expr = expr.Resolve (ec);
3054 if (expr.Type != TypeManager.bool_type)
3055 expr = Expression.ConvertImplicitRequired (
3056 ec, expr, TypeManager.bool_type, loc);
3058 trueExpr = trueExpr.Resolve (ec);
3059 falseExpr = falseExpr.Resolve (ec);
3061 if (expr == null || trueExpr == null || falseExpr == null)
3064 if (trueExpr.Type == falseExpr.Type)
3065 type = trueExpr.Type;
3070 // First, if an implicit conversion exists from trueExpr
3071 // to falseExpr, then the result type is of type falseExpr.Type
3073 conv = ConvertImplicit (ec, trueExpr, falseExpr.Type, loc);
3075 type = falseExpr.Type;
3077 } else if ((conv = ConvertImplicit(ec, falseExpr,trueExpr.Type,loc))!= null){
3078 type = trueExpr.Type;
3081 Error (173, loc, "The type of the conditional expression can " +
3082 "not be computed because there is no implicit conversion" +
3083 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
3084 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
3089 eclass = ExprClass.Value;
3093 public override void Emit (EmitContext ec)
3095 ILGenerator ig = ec.ig;
3096 Label false_target = ig.DefineLabel ();
3097 Label end_target = ig.DefineLabel ();
3100 ig.Emit (OpCodes.Brfalse, false_target);
3102 ig.Emit (OpCodes.Br, end_target);
3103 ig.MarkLabel (false_target);
3104 falseExpr.Emit (ec);
3105 ig.MarkLabel (end_target);
3110 // SimpleName expressions are initially formed of a single
3111 // word and it only happens at the beginning of the expression.
3113 // The expression will try to be bound to a Field, a Method
3114 // group or a Property. If those fail we pass the name to our
3115 // caller and the SimpleName is compounded to perform a type
3116 // lookup. The idea behind this process is that we want to avoid
3117 // creating a namespace map from the assemblies, as that requires
3118 // the GetExportedTypes function to be called and a hashtable to
3119 // be constructed which reduces startup time. If later we find
3120 // that this is slower, we should create a `NamespaceExpr' expression
3121 // that fully participates in the resolution process.
3123 // For example `System.Console.WriteLine' is decomposed into
3124 // MemberAccess (MemberAccess (SimpleName ("System"), "Console"), "WriteLine")
3126 // The first SimpleName wont produce a match on its own, so it will
3128 // MemberAccess (SimpleName ("System.Console"), "WriteLine").
3130 // System.Console will produce a TypeExpr match.
3132 // The downside of this is that we might be hitting `LookupType' too many
3133 // times with this scheme.
3135 public class SimpleName : Expression {
3136 public readonly string Name;
3137 public readonly Location Location;
3139 public SimpleName (string name, Location l)
3145 public static void Error120 (Location l, string name)
3149 "An object reference is required " +
3150 "for the non-static field `"+name+"'");
3154 // Checks whether we are trying to access an instance
3155 // property, method or field from a static body.
3157 Expression MemberStaticCheck (Expression e)
3159 if (e is FieldExpr){
3160 FieldInfo fi = ((FieldExpr) e).FieldInfo;
3163 Error120 (Location, Name);
3166 } else if (e is MethodGroupExpr){
3167 MethodGroupExpr mg = (MethodGroupExpr) e;
3169 if (!mg.RemoveInstanceMethods ()){
3170 Error120 (Location, mg.Methods [0].Name);
3174 } else if (e is PropertyExpr){
3175 if (!((PropertyExpr) e).IsStatic){
3176 Error120 (Location, Name);
3185 // 7.5.2: Simple Names.
3187 // Local Variables and Parameters are handled at
3188 // parse time, so they never occur as SimpleNames.
3190 public override Expression DoResolve (EmitContext ec)
3195 // Stage 1: Performed by the parser (binding to local or parameters).
3199 // Stage 2: Lookup members
3201 e = MemberLookup (ec, ec.TypeContainer.TypeBuilder, Name, true, Location);
3204 // Stage 3: Lookup symbol in the various namespaces.
3208 if ((t = ec.TypeContainer.LookupType (Name, true)) != null)
3209 return new TypeExpr (t);
3212 // Stage 3 part b: Lookup up if we are an alias to a type
3215 // Since we are cheating: we only do the Alias lookup for
3216 // namespaces if the name does not include any dots in it
3219 // IMPLEMENT ME. Read mcs/mcs/TODO for ideas, or rewrite
3220 // using NamespaceExprs (dunno how that fixes the alias
3221 // per-file though).
3223 // No match, maybe our parent can compose us
3224 // into something meaningful.
3229 // Step 2, continues here.
3233 if (e is FieldExpr){
3234 FieldExpr fe = (FieldExpr) e;
3236 if (!fe.FieldInfo.IsStatic)
3237 fe.InstanceExpression = new This (Location.Null);
3241 return MemberStaticCheck (e);
3246 public override void Emit (EmitContext ec)
3249 // If this is ever reached, then we failed to
3250 // find the name as a namespace
3253 Error (103, Location, "The name `" + Name +
3254 "' does not exist in the class `" +
3255 ec.TypeContainer.Name + "'");
3260 // A simple interface that should be implemeneted by LValues
3262 public interface LValue {
3265 // The Store method should store the contents of the top
3266 // of the stack into the storage that is implemented by
3267 // the particular implementation of LValue
3269 void Store (EmitContext ec);
3272 // Allows an LValue to perform any necessary semantic
3273 // analysis in an lvalue-context.
3276 Expression LValueResolve (EmitContext ec);
3280 // This interface is implemented by variables
3282 public interface MemoryLocation {
3284 // The AddressOf method should generate code that loads
3285 // the address of the LValue and leaves it on the stack
3287 void AddressOf (EmitContext ec);
3290 public class LocalTemporary : Expression, LValue, MemoryLocation {
3291 LocalBuilder builder;
3293 public LocalTemporary (EmitContext ec, Type t)
3296 eclass = ExprClass.Value;
3297 builder = ec.GetTemporaryStorage (t);
3300 public override Expression DoResolve (EmitContext ec)
3305 public Expression LValueResolve (EmitContext ec)
3310 public override void Emit (EmitContext ec)
3312 ec.ig.Emit (OpCodes.Ldloc, builder);
3315 public void Store (EmitContext ec)
3317 ec.ig.Emit (OpCodes.Stloc, builder);
3320 public void AddressOf (EmitContext ec)
3322 ec.ig.Emit (OpCodes.Ldloca, builder);
3326 public class LocalVariableReference : Expression, LValue, MemoryLocation {
3327 public readonly string Name;
3328 public readonly Block Block;
3330 VariableInfo variable_info;
3332 public LocalVariableReference (Block block, string name)
3336 eclass = ExprClass.Variable;
3339 public VariableInfo VariableInfo {
3341 if (variable_info == null)
3342 variable_info = Block.GetVariableInfo (Name);
3343 return variable_info;
3347 public override Expression DoResolve (EmitContext ec)
3349 VariableInfo vi = VariableInfo;
3351 type = vi.VariableType;
3355 public Expression LValueResolve (EmitContext ec)
3360 public override void Emit (EmitContext ec)
3362 VariableInfo vi = VariableInfo;
3363 ILGenerator ig = ec.ig;
3370 ig.Emit (OpCodes.Ldloc_0);
3374 ig.Emit (OpCodes.Ldloc_1);
3378 ig.Emit (OpCodes.Ldloc_2);
3382 ig.Emit (OpCodes.Ldloc_3);
3387 ig.Emit (OpCodes.Ldloc_S, (byte) idx);
3389 ig.Emit (OpCodes.Ldloc, idx);
3394 public static void Store (ILGenerator ig, int idx)
3398 ig.Emit (OpCodes.Stloc_0);
3402 ig.Emit (OpCodes.Stloc_1);
3406 ig.Emit (OpCodes.Stloc_2);
3410 ig.Emit (OpCodes.Stloc_3);
3415 ig.Emit (OpCodes.Stloc_S, (byte) idx);
3417 ig.Emit (OpCodes.Stloc, idx);
3422 public void Store (EmitContext ec)
3424 ILGenerator ig = ec.ig;
3425 VariableInfo vi = VariableInfo;
3429 // Funny seems the above generates optimal code for us, but
3430 // seems to take too long to generate what we need.
3431 // ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
3436 public void AddressOf (EmitContext ec)
3438 VariableInfo vi = VariableInfo;
3445 ec.ig.Emit (OpCodes.Ldloca_S, (byte) idx);
3447 ec.ig.Emit (OpCodes.Ldloca, idx);
3451 public class ParameterReference : Expression, LValue, MemoryLocation {
3452 public readonly Parameters Pars;
3453 public readonly String Name;
3454 public readonly int Idx;
3457 public ParameterReference (Parameters pars, int idx, string name)
3462 eclass = ExprClass.Variable;
3465 public override Expression DoResolve (EmitContext ec)
3467 Type [] types = Pars.GetParameterInfo (ec.TypeContainer);
3478 public override void Emit (EmitContext ec)
3481 ec.ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
3483 ec.ig.Emit (OpCodes.Ldarg, arg_idx);
3486 public void Store (EmitContext ec)
3489 ec.ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
3491 ec.ig.Emit (OpCodes.Starg, arg_idx);
3495 public void AddressOf (EmitContext ec)
3498 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
3500 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
3503 public Expression LValueResolve (EmitContext ec)
3510 // Used for arguments to New(), Invocation()
3512 public class Argument {
3519 public readonly AType Type;
3520 public Expression expr;
3522 public Argument (Expression expr, AType type)
3528 public Expression Expr {
3538 public bool Resolve (EmitContext ec)
3540 expr = expr.Resolve (ec);
3542 return expr != null;
3545 public void Emit (EmitContext ec)
3552 // Invocation of methods or delegates.
3554 public class Invocation : ExpressionStatement {
3555 public readonly ArrayList Arguments;
3556 public readonly Location Location;
3559 MethodBase method = null;
3561 static Hashtable method_parameter_cache;
3563 static Invocation ()
3565 method_parameter_cache = new Hashtable ();
3569 // arguments is an ArrayList, but we do not want to typecast,
3570 // as it might be null.
3572 // FIXME: only allow expr to be a method invocation or a
3573 // delegate invocation (7.5.5)
3575 public Invocation (Expression expr, ArrayList arguments, Location l)
3578 Arguments = arguments;
3582 public Expression Expr {
3589 // Returns the Parameters (a ParameterData interface) for the
3592 public static ParameterData GetParameterData (MethodBase mb)
3594 object pd = method_parameter_cache [mb];
3597 return (ParameterData) pd;
3599 if (mb is MethodBuilder || mb is ConstructorBuilder){
3600 MethodCore mc = TypeContainer.LookupMethodByBuilder (mb);
3602 InternalParameters ip = mc.ParameterInfo;
3603 method_parameter_cache [mb] = ip;
3605 return (ParameterData) ip;
3607 ParameterInfo [] pi = mb.GetParameters ();
3608 ReflectionParameters rp = new ReflectionParameters (pi);
3609 method_parameter_cache [mb] = rp;
3611 return (ParameterData) rp;
3616 // Tells whether a user defined conversion from Type `from' to
3617 // Type `to' exists.
3619 // FIXME: we could implement a cache here.
3621 static bool ConversionExists (EmitContext ec, Type from, Type to, Location loc)
3623 // Locate user-defined implicit operators
3627 mg = MemberLookup (ec, to, "op_Implicit", false, loc);
3630 MethodGroupExpr me = (MethodGroupExpr) mg;
3632 for (int i = me.Methods.Length; i > 0;) {
3634 MethodBase mb = me.Methods [i];
3635 ParameterData pd = GetParameterData (mb);
3637 if (from == pd.ParameterType (0))
3642 mg = MemberLookup (ec, from, "op_Implicit", false, loc);
3645 MethodGroupExpr me = (MethodGroupExpr) mg;
3647 for (int i = me.Methods.Length; i > 0;) {
3649 MethodBase mb = me.Methods [i];
3650 MethodInfo mi = (MethodInfo) mb;
3652 if (mi.ReturnType == to)
3661 // Determines "better conversion" as specified in 7.4.2.3
3662 // Returns : 1 if a->p is better
3663 // 0 if a->q or neither is better
3665 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, bool use_standard,
3668 Type argument_type = a.Expr.Type;
3669 Expression argument_expr = a.Expr;
3671 if (argument_type == null)
3672 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
3677 if (argument_type == p)
3680 if (argument_type == q)
3684 // Now probe whether an implicit constant expression conversion
3687 // An implicit constant expression conversion permits the following
3690 // * A constant-expression of type `int' can be converted to type
3691 // sbyte, byute, short, ushort, uint, ulong provided the value of
3692 // of the expression is withing the range of the destination type.
3694 // * A constant-expression of type long can be converted to type
3695 // ulong, provided the value of the constant expression is not negative
3697 // FIXME: Note that this assumes that constant folding has
3698 // taken place. We dont do constant folding yet.
3701 if (argument_expr is IntLiteral){
3702 IntLiteral ei = (IntLiteral) argument_expr;
3703 int value = ei.Value;
3705 if (p == TypeManager.sbyte_type){
3706 if (value >= SByte.MinValue && value <= SByte.MaxValue)
3708 } else if (p == TypeManager.byte_type){
3709 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3711 } else if (p == TypeManager.short_type){
3712 if (value >= Int16.MinValue && value <= Int16.MaxValue)
3714 } else if (p == TypeManager.ushort_type){
3715 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3717 } else if (p == TypeManager.uint32_type){
3719 // we can optimize this case: a positive int32
3720 // always fits on a uint32
3724 } else if (p == TypeManager.uint64_type){
3726 // we can optimize this case: a positive int32
3727 // always fits on a uint64
3732 } else if (argument_type == TypeManager.int64_type && argument_expr is LongLiteral){
3733 LongLiteral ll = (LongLiteral) argument_expr;
3735 if (p == TypeManager.uint64_type){
3746 tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
3748 tmp = ConvertImplicit (ec, argument_expr, p, loc);
3757 if (ConversionExists (ec, p, q, loc) == true &&
3758 ConversionExists (ec, q, p, loc) == false)
3761 if (p == TypeManager.sbyte_type)
3762 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3763 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3766 if (p == TypeManager.short_type)
3767 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3768 q == TypeManager.uint64_type)
3771 if (p == TypeManager.int32_type)
3772 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3775 if (p == TypeManager.int64_type)
3776 if (q == TypeManager.uint64_type)
3783 // Determines "Better function" and returns an integer indicating :
3784 // 0 if candidate ain't better
3785 // 1 if candidate is better than the current best match
3787 static int BetterFunction (EmitContext ec, ArrayList args,
3788 MethodBase candidate, MethodBase best,
3789 bool use_standard, Location loc)
3791 ParameterData candidate_pd = GetParameterData (candidate);
3792 ParameterData best_pd;
3798 argument_count = args.Count;
3800 if (candidate_pd.Count == 0 && argument_count == 0)
3804 if (candidate_pd.Count == argument_count) {
3806 for (int j = argument_count; j > 0;) {
3809 Argument a = (Argument) args [j];
3811 x = BetterConversion (
3812 ec, a, candidate_pd.ParameterType (j), null,
3828 best_pd = GetParameterData (best);
3830 if (candidate_pd.Count == argument_count && best_pd.Count == argument_count) {
3831 int rating1 = 0, rating2 = 0;
3833 for (int j = argument_count; j > 0;) {
3837 Argument a = (Argument) args [j];
3839 x = BetterConversion (ec, a, candidate_pd.ParameterType (j),
3840 best_pd.ParameterType (j), use_standard, loc);
3841 y = BetterConversion (ec, a, best_pd.ParameterType (j),
3842 candidate_pd.ParameterType (j), use_standard,
3849 if (rating1 > rating2)
3858 public static string FullMethodDesc (MethodBase mb)
3860 StringBuilder sb = new StringBuilder (mb.Name);
3861 ParameterData pd = GetParameterData (mb);
3864 for (int i = pd.Count; i > 0;) {
3866 sb.Append (TypeManager.CSharpName (pd.ParameterType (i)));
3872 return sb.ToString ();
3875 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2)
3877 MemberInfo [] miset;
3878 MethodGroupExpr union;
3880 if (mg1 != null && mg2 != null) {
3882 MethodGroupExpr left_set = null, right_set = null;
3883 int length1 = 0, length2 = 0;
3885 left_set = (MethodGroupExpr) mg1;
3886 length1 = left_set.Methods.Length;
3888 right_set = (MethodGroupExpr) mg2;
3889 length2 = right_set.Methods.Length;
3891 ArrayList common = new ArrayList ();
3893 for (int i = 0; i < left_set.Methods.Length; i++) {
3894 for (int j = 0; j < right_set.Methods.Length; j++) {
3895 if (left_set.Methods [i] == right_set.Methods [j])
3896 common.Add (left_set.Methods [i]);
3900 miset = new MemberInfo [length1 + length2 - common.Count];
3902 left_set.Methods.CopyTo (miset, 0);
3906 for (int j = 0; j < right_set.Methods.Length; j++)
3907 if (!common.Contains (right_set.Methods [j]))
3908 miset [length1 + k++] = right_set.Methods [j];
3910 union = new MethodGroupExpr (miset);
3914 } else if (mg1 == null && mg2 != null) {
3916 MethodGroupExpr me = (MethodGroupExpr) mg2;
3918 miset = new MemberInfo [me.Methods.Length];
3919 me.Methods.CopyTo (miset, 0);
3921 union = new MethodGroupExpr (miset);
3925 } else if (mg2 == null && mg1 != null) {
3927 MethodGroupExpr me = (MethodGroupExpr) mg1;
3929 miset = new MemberInfo [me.Methods.Length];
3930 me.Methods.CopyTo (miset, 0);
3932 union = new MethodGroupExpr (miset);
3941 // Find the Applicable Function Members (7.4.2.1)
3943 // me: Method Group expression with the members to select.
3944 // it might contain constructors or methods (or anything
3945 // that maps to a method).
3947 // Arguments: ArrayList containing resolved Argument objects.
3949 // loc: The location if we want an error to be reported, or a Null
3950 // location for "probing" purposes.
3952 // inside_user_defined: controls whether OverloadResolve should use the
3953 // ConvertImplicit or ConvertImplicitStandard during overload resolution.
3955 // Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3956 // that is the best match of me on Arguments.
3959 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3960 ArrayList Arguments, Location loc,
3963 ArrayList afm = new ArrayList ();
3964 int best_match_idx = -1;
3965 MethodBase method = null;
3968 for (int i = me.Methods.Length; i > 0; ){
3970 MethodBase candidate = me.Methods [i];
3973 x = BetterFunction (ec, Arguments, candidate, method, use_standard, loc);
3979 method = me.Methods [best_match_idx];
3983 if (Arguments == null)
3986 argument_count = Arguments.Count;
3990 // Now we see if we can at least find a method with the same number of arguments
3991 // and then try doing implicit conversion on the arguments
3992 if (best_match_idx == -1) {
3994 for (int i = me.Methods.Length; i > 0;) {
3996 MethodBase mb = me.Methods [i];
3997 pd = GetParameterData (mb);
3999 if (pd.Count == argument_count) {
4001 method = me.Methods [best_match_idx];
4012 // And now convert implicitly, each argument to the required type
4014 pd = GetParameterData (method);
4016 for (int j = argument_count; j > 0;) {
4018 Argument a = (Argument) Arguments [j];
4019 Expression a_expr = a.Expr;
4020 Type parameter_type = pd.ParameterType (j);
4022 if (a_expr.Type != parameter_type){
4026 conv = ConvertImplicitStandard (ec, a_expr, parameter_type,
4029 conv = ConvertImplicit (ec, a_expr, parameter_type,
4033 if (!Location.IsNull (loc)) {
4035 "The best overloaded match for method '" + FullMethodDesc (method) +
4036 "' has some invalid arguments");
4038 "Argument " + (j+1) +
4039 ": Cannot convert from '" + TypeManager.CSharpName (a_expr.Type)
4040 + "' to '" + TypeManager.CSharpName (pd.ParameterType (j)) + "'");
4045 // Update the argument with the implicit conversion
4055 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
4056 ArrayList Arguments, Location loc)
4058 return OverloadResolve (ec, me, Arguments, loc, false);
4061 public override Expression DoResolve (EmitContext ec)
4064 // First, resolve the expression that is used to
4065 // trigger the invocation
4067 this.expr = expr.Resolve (ec);
4068 if (this.expr == null)
4071 if (!(this.expr is MethodGroupExpr)){
4072 report118 (Location, this.expr, "method group");
4077 // Next, evaluate all the expressions in the argument list
4079 if (Arguments != null){
4080 for (int i = Arguments.Count; i > 0;){
4082 Argument a = (Argument) Arguments [i];
4084 if (!a.Resolve (ec))
4089 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments,
4092 if (method == null){
4093 Error (-6, Location,
4094 "Could not find any applicable function for this argument list");
4098 if (method is MethodInfo)
4099 type = ((MethodInfo)method).ReturnType;
4101 eclass = ExprClass.Value;
4105 public static void EmitArguments (EmitContext ec, MethodBase method, ArrayList Arguments)
4109 if (Arguments != null)
4110 top = Arguments.Count;
4114 for (int i = 0; i < top; i++){
4115 Argument a = (Argument) Arguments [i];
4121 public static void EmitCall (EmitContext ec,
4122 bool is_static, Expression instance_expr,
4123 MethodBase method, ArrayList Arguments)
4125 ILGenerator ig = ec.ig;
4126 bool struct_call = false;
4130 // If this is ourselves, push "this"
4132 if (instance_expr == null){
4133 ig.Emit (OpCodes.Ldarg_0);
4136 // Push the instance expression
4138 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
4143 // If the expression is an LValue, then
4144 // we can optimize and use AddressOf on the
4147 // If not we have to use some temporary storage for
4149 if (instance_expr is MemoryLocation)
4150 ((MemoryLocation) instance_expr).AddressOf (ec);
4152 Type t = instance_expr.Type;
4154 instance_expr.Emit (ec);
4155 LocalBuilder temp = ec.GetTemporaryStorage (t);
4156 ig.Emit (OpCodes.Stloc, temp);
4157 ig.Emit (OpCodes.Ldloca, temp);
4160 instance_expr.Emit (ec);
4164 if (Arguments != null)
4165 EmitArguments (ec, method, Arguments);
4167 if (is_static || struct_call){
4168 if (method is MethodInfo)
4169 ig.Emit (OpCodes.Call, (MethodInfo) method);
4171 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
4173 if (method is MethodInfo)
4174 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
4176 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
4180 public override void Emit (EmitContext ec)
4182 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
4184 EmitCall (ec, method.IsStatic, mg.InstanceExpression, method, Arguments);
4187 public override void EmitStatement (EmitContext ec)
4192 // Pop the return value if there is one
4194 if (method is MethodInfo){
4195 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
4196 ec.ig.Emit (OpCodes.Pop);
4201 public class New : ExpressionStatement {
4208 public readonly NType NewType;
4209 public readonly ArrayList Arguments;
4210 public readonly string RequestedType;
4212 // These are for the case when we have an array
4213 public readonly string Rank;
4214 public readonly ArrayList Initializers;
4217 MethodBase method = null;
4221 // If set, the new expression is for a value_target, and
4222 // we will not leave anything on the stack.
4224 Expression value_target;
4226 public New (string requested_type, ArrayList arguments, Location loc)
4228 RequestedType = requested_type;
4229 Arguments = arguments;
4230 NewType = NType.Object;
4234 public New (string requested_type, ArrayList exprs, string rank, ArrayList initializers, Location loc)
4236 RequestedType = requested_type;
4238 Initializers = initializers;
4239 NewType = NType.Array;
4242 Arguments = new ArrayList ();
4244 foreach (Expression e in exprs)
4245 Arguments.Add (new Argument (e, Argument.AType.Expression));
4249 public static string FormLookupType (string base_type, int idx_count, string rank)
4251 StringBuilder sb = new StringBuilder (base_type);
4256 for (int i = 1; i < idx_count; i++)
4260 return sb.ToString ();
4263 public Expression ValueTypeVariable {
4265 return value_target;
4269 value_target = value;
4273 public override Expression DoResolve (EmitContext ec)
4275 if (NewType == NType.Object) {
4276 type = ec.TypeContainer.LookupType (RequestedType, false);
4281 if (TypeManager.IsDelegateType (type)) {
4282 Report.Error (-100, "No support for delegate instantiation yet !");
4288 ml = MemberLookup (ec, type, ".ctor", false,
4289 MemberTypes.Constructor, AllBindingsFlags, Location);
4292 is_struct = type.IsSubclassOf (TypeManager.value_type);
4294 if (! (ml is MethodGroupExpr)){
4296 report118 (Location, ml, "method group");
4302 if (Arguments != null){
4303 for (int i = Arguments.Count; i > 0;){
4305 Argument a = (Argument) Arguments [i];
4307 if (!a.Resolve (ec))
4312 method = Invocation.OverloadResolve (
4313 ec, (MethodGroupExpr) ml,
4314 Arguments, Location);
4316 if (method == null && !is_struct) {
4317 Error (-6, Location,
4318 "New invocation: Can not find a constructor for " +
4319 "this argument list");
4324 eclass = ExprClass.Value;
4328 if (NewType == NType.Array) {
4329 throw new Exception ("Finish array creation");
4336 // This DoEmit can be invoked in two contexts:
4337 // * As a mechanism that will leave a value on the stack (new object)
4338 // * As one that wont (init struct)
4340 // You can control whether a value is required on the stack by passing
4341 // need_value_on_stack. The code *might* leave a value on the stack
4342 // so it must be popped manually
4344 // Returns whether a value is left on the stack
4346 bool DoEmit (EmitContext ec, bool need_value_on_stack)
4348 if (method == null){
4349 MemoryLocation ml = (MemoryLocation) value_target;
4353 Invocation.EmitArguments (ec, method, Arguments);
4354 ec.ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4359 // It must be a value type, sanity check
4361 if (value_target != null){
4362 ec.ig.Emit (OpCodes.Initobj, type);
4364 if (need_value_on_stack){
4365 value_target.Emit (ec);
4371 throw new Exception ("No method and no value type");
4374 public override void Emit (EmitContext ec)
4379 public override void EmitStatement (EmitContext ec)
4381 if (DoEmit (ec, false))
4382 ec.ig.Emit (OpCodes.Pop);
4387 // Represents the `this' construct
4389 public class This : Expression, LValue, MemoryLocation {
4392 public This (Location loc)
4397 public override Expression DoResolve (EmitContext ec)
4399 eclass = ExprClass.Variable;
4400 type = ec.TypeContainer.TypeBuilder;
4403 Report.Error (26, loc,
4404 "Keyword this not valid in static code");
4411 public override void Emit (EmitContext ec)
4413 ec.ig.Emit (OpCodes.Ldarg_0);
4416 public void Store (EmitContext ec)
4418 ec.ig.Emit (OpCodes.Starg, 0);
4421 public void AddressOf (EmitContext ec)
4423 ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4426 public Expression LValueResolve (EmitContext ec)
4428 if (ec.TypeContainer is Class){
4429 Report.Error (1604, loc, "Cannot assign to `this'");
4438 // Implements the typeof operator
4440 public class TypeOf : Expression {
4441 public readonly string QueriedType;
4444 public TypeOf (string queried_type)
4446 QueriedType = queried_type;
4449 public override Expression DoResolve (EmitContext ec)
4451 typearg = ec.TypeContainer.LookupType (QueriedType, false);
4453 if (typearg == null)
4456 type = TypeManager.type_type;
4457 eclass = ExprClass.Type;
4461 public override void Emit (EmitContext ec)
4463 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4464 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4468 public class SizeOf : Expression {
4469 public readonly string QueriedType;
4471 public SizeOf (string queried_type)
4473 this.QueriedType = queried_type;
4476 public override Expression DoResolve (EmitContext ec)
4478 // FIXME: Implement;
4479 throw new Exception ("Unimplemented");
4483 public override void Emit (EmitContext ec)
4485 throw new Exception ("Implement me");
4489 public class MemberAccess : Expression {
4490 public readonly string Identifier;
4492 Expression member_lookup;
4495 public MemberAccess (Expression expr, string id, Location l)
4502 public Expression Expr {
4508 void error176 (Location loc, string name)
4510 Report.Error (176, loc, "Static member `" +
4511 name + "' cannot be accessed " +
4512 "with an instance reference, qualify with a " +
4513 "type name instead");
4516 public override Expression DoResolve (EmitContext ec)
4518 expr = expr.Resolve (ec);
4523 if (expr is SimpleName){
4524 SimpleName child_expr = (SimpleName) expr;
4526 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
4528 return expr.Resolve (ec);
4531 member_lookup = MemberLookup (ec, expr.Type, Identifier, false, loc);
4536 if (member_lookup is MethodGroupExpr){
4537 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4542 if (expr is TypeExpr){
4543 if (!mg.RemoveInstanceMethods ()){
4544 SimpleName.Error120 (loc, mg.Methods [0].Name);
4548 return member_lookup;
4552 // Instance.MethodGroup
4554 if (!mg.RemoveStaticMethods ()){
4555 error176 (loc, mg.Methods [0].Name);
4559 mg.InstanceExpression = expr;
4561 return member_lookup;
4564 if (member_lookup is FieldExpr){
4565 FieldExpr fe = (FieldExpr) member_lookup;
4567 if (expr is TypeExpr){
4568 if (!fe.FieldInfo.IsStatic){
4569 error176 (loc, fe.FieldInfo.Name);
4572 return member_lookup;
4574 if (fe.FieldInfo.IsStatic){
4575 error176 (loc, fe.FieldInfo.Name);
4578 fe.InstanceExpression = expr;
4584 if (member_lookup is PropertyExpr){
4585 PropertyExpr pe = (PropertyExpr) member_lookup;
4587 if (expr is TypeExpr){
4589 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4595 error176 (loc, pe.PropertyInfo.Name);
4598 pe.InstanceExpression = expr;
4604 Console.WriteLine ("Support for " + member_lookup + " is not present yet");
4605 Environment.Exit (0);
4609 public override void Emit (EmitContext ec)
4611 throw new Exception ("Should not happen I think");
4617 // Fully resolved expression that evaluates to a type
4619 public class TypeExpr : Expression {
4620 public TypeExpr (Type t)
4623 eclass = ExprClass.Type;
4626 override public Expression DoResolve (EmitContext ec)
4631 override public void Emit (EmitContext ec)
4633 throw new Exception ("Implement me");
4638 // MethodGroup Expression.
4640 // This is a fully resolved expression that evaluates to a type
4642 public class MethodGroupExpr : Expression {
4643 public MethodBase [] Methods;
4644 Expression instance_expression = null;
4646 public MethodGroupExpr (MemberInfo [] mi)
4648 Methods = new MethodBase [mi.Length];
4649 mi.CopyTo (Methods, 0);
4650 eclass = ExprClass.MethodGroup;
4654 // `A method group may have associated an instance expression'
4656 public Expression InstanceExpression {
4658 return instance_expression;
4662 instance_expression = value;
4666 override public Expression DoResolve (EmitContext ec)
4671 override public void Emit (EmitContext ec)
4673 throw new Exception ("This should never be reached");
4676 bool RemoveMethods (bool keep_static)
4678 ArrayList smethods = new ArrayList ();
4679 int top = Methods.Length;
4682 for (i = 0; i < top; i++){
4683 MethodBase mb = Methods [i];
4685 if (mb.IsStatic == keep_static)
4689 if (smethods.Count == 0)
4692 Methods = new MethodBase [smethods.Count];
4693 smethods.CopyTo (Methods, 0);
4699 // Removes any instance methods from the MethodGroup, returns
4700 // false if the resulting set is empty.
4702 public bool RemoveInstanceMethods ()
4704 return RemoveMethods (true);
4708 // Removes any static methods from the MethodGroup, returns
4709 // false if the resulting set is empty.
4711 public bool RemoveStaticMethods ()
4713 return RemoveMethods (false);
4718 // Fully resolved expression that evaluates to a Field
4720 public class FieldExpr : Expression, LValue, MemoryLocation {
4721 public readonly FieldInfo FieldInfo;
4722 public Expression InstanceExpression;
4724 public FieldExpr (FieldInfo fi)
4727 eclass = ExprClass.Variable;
4728 type = fi.FieldType;
4731 override public Expression DoResolve (EmitContext ec)
4733 if (!FieldInfo.IsStatic){
4734 if (InstanceExpression == null){
4735 throw new Exception ("non-static FieldExpr without instance var\n" +
4736 "You have to assign the Instance variable\n" +
4737 "Of the FieldExpr to set this\n");
4740 InstanceExpression = InstanceExpression.Resolve (ec);
4741 if (InstanceExpression == null)
4748 override public void Emit (EmitContext ec)
4750 ILGenerator ig = ec.ig;
4752 if (FieldInfo.IsStatic)
4753 ig.Emit (OpCodes.Ldsfld, FieldInfo);
4755 InstanceExpression.Emit (ec);
4757 ig.Emit (OpCodes.Ldfld, FieldInfo);
4761 public void Store (EmitContext ec)
4763 if (FieldInfo.IsStatic)
4764 ec.ig.Emit (OpCodes.Stsfld, FieldInfo);
4766 ec.ig.Emit (OpCodes.Stfld, FieldInfo);
4769 public void AddressOf (EmitContext ec)
4771 if (FieldInfo.IsStatic)
4772 ec.ig.Emit (OpCodes.Ldsflda, FieldInfo);
4774 InstanceExpression.Emit (ec);
4775 ec.ig.Emit (OpCodes.Ldflda, FieldInfo);
4779 public Expression LValueResolve (EmitContext ec)
4781 if (!FieldInfo.IsInitOnly)
4785 // InitOnly fields can only be assigned in constructors
4788 if (ec.IsConstructor)
4796 // Expression that evaluates to a Property. The Assign class
4797 // might set the `Value' expression if we are in an assignment.
4799 public class PropertyExpr : ExpressionStatement {
4800 public readonly PropertyInfo PropertyInfo;
4801 public readonly bool IsStatic;
4802 MethodInfo [] Accessors;
4805 Expression instance_expr;
4808 public PropertyExpr (PropertyInfo pi, Location l)
4811 eclass = ExprClass.PropertyAccess;
4814 Accessors = TypeManager.GetAccessors (pi);
4816 if (Accessors != null)
4817 for (int i = 0; i < Accessors.Length; i++){
4818 if (Accessors [i] != null)
4819 if (Accessors [i].IsStatic)
4823 Accessors = new MethodInfo [2];
4825 type = pi.PropertyType;
4829 // Controls the Value of the PropertyExpr. If the value
4830 // is null, then the property is being used in a `read' mode.
4831 // otherwise the property is used in assignment mode.
4833 // The value is set to a fully resolved type by assign.
4835 public Expression Value {
4846 // The instance expression associated with this expression
4848 public Expression InstanceExpression {
4850 instance_expr = value;
4854 return instance_expr;
4858 public bool VerifyAssignable ()
4860 if (!PropertyInfo.CanWrite){
4861 Report.Error (200, loc,
4862 "The property `" + PropertyInfo.Name +
4863 "' can not be assigned to, as it has not set accessor");
4870 override public Expression DoResolve (EmitContext ec)
4873 // Not really sure who should call perform the test below
4874 // given that `assignable' has special code for this.
4876 if (!PropertyInfo.CanRead){
4877 Report.Error (154, loc,
4878 "The property `" + PropertyInfo.Name +
4879 "' can not be used in " +
4880 "this context because it lacks a get accessor");
4887 override public void Emit (EmitContext ec)
4890 Invocation.EmitCall (ec, IsStatic, instance_expr, Accessors [0], null);
4892 Argument arg = new Argument (value, Argument.AType.Expression);
4893 ArrayList args = new ArrayList ();
4896 Invocation.EmitCall (ec, IsStatic, instance_expr, Accessors [1], args);
4900 override public void EmitStatement (EmitContext ec)
4904 ec.ig.Emit (OpCodes.Pop);
4910 // Fully resolved expression that evaluates to a Expression
4912 public class EventExpr : Expression {
4913 public readonly EventInfo EventInfo;
4916 public EventExpr (EventInfo ei, Location loc)
4920 eclass = ExprClass.EventAccess;
4923 override public Expression DoResolve (EmitContext ec)
4925 // We are born in resolved state.
4929 override public void Emit (EmitContext ec)
4931 throw new Exception ("Implement me");
4932 // FIXME: Implement.
4936 public class CheckedExpr : Expression {
4938 public Expression Expr;
4940 public CheckedExpr (Expression e)
4945 public override Expression DoResolve (EmitContext ec)
4947 Expr = Expr.Resolve (ec);
4952 eclass = Expr.ExprClass;
4957 public override void Emit (EmitContext ec)
4959 bool last_check = ec.CheckState;
4961 ec.CheckState = true;
4963 ec.CheckState = last_check;
4968 public class UnCheckedExpr : Expression {
4970 public Expression Expr;
4972 public UnCheckedExpr (Expression e)
4977 public override Expression DoResolve (EmitContext ec)
4979 Expr = Expr.Resolve (ec);
4984 eclass = Expr.ExprClass;
4989 public override void Emit (EmitContext ec)
4991 bool last_check = ec.CheckState;
4993 ec.CheckState = false;
4995 ec.CheckState = last_check;
5000 public class ElementAccess : Expression, LValue {
5002 public ArrayList Arguments;
5003 public Expression Expr;
5007 public ElementAccess (Expression e, ArrayList e_list, Location loc)
5011 Arguments = new ArrayList ();
5012 foreach (Expression tmp in e_list)
5013 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5018 public override Expression DoResolve (EmitContext ec)
5020 Expr = Expr.Resolve (ec);
5022 //Console.WriteLine (Expr.ToString ());
5027 if (Arguments == null)
5030 if (Expr.ExprClass != ExprClass.Variable) {
5031 report118 (location, Expr, "variable");
5035 if (Arguments != null){
5036 for (int i = Arguments.Count; i > 0;){
5038 Argument a = (Argument) Arguments [i];
5040 if (!a.Resolve (ec))
5043 Type a_type = a.expr.Type;
5044 if (!(StandardConversionExists (a_type, TypeManager.int32_type) ||
5045 StandardConversionExists (a_type, TypeManager.uint32_type) ||
5046 StandardConversionExists (a_type, TypeManager.int64_type) ||
5047 StandardConversionExists (a_type, TypeManager.uint64_type)))
5053 // FIXME : Implement the actual storage here.
5055 throw new Exception ("Finish element access");
5059 public void Store (EmitContext ec)
5061 throw new Exception ("Implement me !");
5064 public override void Emit (EmitContext ec)
5066 throw new Exception ("Implement me !");
5069 public Expression LValueResolve (EmitContext ec)
5075 public class BaseAccess : Expression {
5077 public enum BaseAccessType {
5082 public readonly BaseAccessType BAType;
5083 public readonly string Member;
5084 public readonly ArrayList Arguments;
5086 public BaseAccess (BaseAccessType t, string member, ArrayList args)
5094 public override Expression DoResolve (EmitContext ec)
5096 // FIXME: Implement;
5097 throw new Exception ("Unimplemented");
5101 public override void Emit (EmitContext ec)
5103 throw new Exception ("Unimplemented");
5108 // This class exists solely to pass the Type around and to be a dummy
5109 // that can be passed to the conversion functions (this is used by
5110 // foreach implementation to typecast the object return value from
5111 // get_Current into the proper type. All code has been generated and
5112 // we only care about the side effect conversions to be performed
5115 public class EmptyExpression : Expression {
5116 public EmptyExpression ()
5118 type = TypeManager.object_type;
5119 eclass = ExprClass.Value;
5122 public override Expression DoResolve (EmitContext ec)
5127 public override void Emit (EmitContext ec)
5129 // nothing, as we only exist to not do anything.
5133 public class UserCast : Expression {
5137 public UserCast (MethodInfo method, Expression source)
5139 this.method = method;
5140 this.source = source;
5141 type = method.ReturnType;
5142 eclass = ExprClass.Value;
5145 public override Expression DoResolve (EmitContext ec)
5148 // We are born fully resolved
5153 public override void Emit (EmitContext ec)
5155 ILGenerator ig = ec.ig;
5159 if (method is MethodInfo)
5160 ig.Emit (OpCodes.Call, (MethodInfo) method);
5162 ig.Emit (OpCodes.Call, (ConstructorInfo) method);