2 // expression.cs: Expression representation for the IL tree.
5 // Miguel de Icaza (miguel@ximian.com)
7 // (C) 2001 Ximian, Inc.
12 namespace Mono.CSharp {
14 using System.Collections;
15 using System.Diagnostics;
16 using System.Reflection;
17 using System.Reflection.Emit;
21 /// This is just a helper class, it is generated by Unary, UnaryMutator
22 /// when an overloaded method has been found. It just emits the code for a
25 public class StaticCallExpr : ExpressionStatement {
29 StaticCallExpr (MethodInfo m, ArrayList a)
35 eclass = ExprClass.Value;
38 public override Expression DoResolve (EmitContext ec)
41 // We are born fully resolved
46 public override void Emit (EmitContext ec)
49 Invocation.EmitArguments (ec, mi, args);
51 ec.ig.Emit (OpCodes.Call, mi);
55 static public Expression MakeSimpleCall (EmitContext ec, MethodGroupExpr mg,
56 Expression e, Location loc)
61 args = new ArrayList (1);
62 args.Add (new Argument (e, Argument.AType.Expression));
63 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) mg, args, loc);
68 return new StaticCallExpr ((MethodInfo) method, args);
71 public override void EmitStatement (EmitContext ec)
74 if (type != TypeManager.void_type)
75 ec.ig.Emit (OpCodes.Pop);
80 /// Unary expressions.
84 /// Unary implements unary expressions. It derives from
85 /// ExpressionStatement becuase the pre/post increment/decrement
86 /// operators can be used in a statement context.
88 public class Unary : Expression {
89 public enum Operator : byte {
90 UnaryPlus, UnaryNegation, LogicalNot, OnesComplement,
91 Indirection, AddressOf, TOP
95 public Expression Expr;
98 public Unary (Operator op, Expression expr, Location loc)
106 /// Returns a stringified representation of the Operator
108 static public string OperName (Operator oper)
111 case Operator.UnaryPlus:
113 case Operator.UnaryNegation:
115 case Operator.LogicalNot:
117 case Operator.OnesComplement:
119 case Operator.AddressOf:
121 case Operator.Indirection:
125 return oper.ToString ();
128 static string [] oper_names;
132 oper_names = new string [(int)Operator.TOP];
134 oper_names [(int) Operator.UnaryPlus] = "op_UnaryPlus";
135 oper_names [(int) Operator.UnaryNegation] = "op_UnaryNegation";
136 oper_names [(int) Operator.LogicalNot] = "op_LogicalNot";
137 oper_names [(int) Operator.OnesComplement] = "op_OnesComplement";
138 oper_names [(int) Operator.Indirection] = "op_Indirection";
139 oper_names [(int) Operator.AddressOf] = "op_AddressOf";
142 void Error23 (Type t)
145 23, loc, "Operator " + OperName (Oper) +
146 " cannot be applied to operand of type `" +
147 TypeManager.CSharpName (t) + "'");
151 /// The result has been already resolved:
153 /// FIXME: a minus constant -128 sbyte cant be turned into a
156 static Expression TryReduceNegative (Expression expr)
160 if (expr is IntConstant)
161 e = new IntConstant (-((IntConstant) expr).Value);
162 else if (expr is UIntConstant){
163 uint value = ((UIntConstant) expr).Value;
165 if (value < 2147483649)
166 return new IntConstant (-(int)value);
168 e = new LongConstant (value);
170 else if (expr is LongConstant)
171 e = new LongConstant (-((LongConstant) expr).Value);
172 else if (expr is FloatConstant)
173 e = new FloatConstant (-((FloatConstant) expr).Value);
174 else if (expr is DoubleConstant)
175 e = new DoubleConstant (-((DoubleConstant) expr).Value);
176 else if (expr is DecimalConstant)
177 e = new DecimalConstant (-((DecimalConstant) expr).Value);
178 else if (expr is ShortConstant)
179 e = new IntConstant (-((ShortConstant) expr).Value);
180 else if (expr is UShortConstant)
181 e = new IntConstant (-((UShortConstant) expr).Value);
185 Expression Reduce (EmitContext ec, Expression e)
187 Type expr_type = e.Type;
190 case Operator.UnaryPlus:
193 case Operator.UnaryNegation:
194 return TryReduceNegative (e);
196 case Operator.LogicalNot:
197 if (expr_type != TypeManager.bool_type) {
202 BoolConstant b = (BoolConstant) e;
203 return new BoolConstant (!(b.Value));
205 case Operator.OnesComplement:
206 if (!((expr_type == TypeManager.int32_type) ||
207 (expr_type == TypeManager.uint32_type) ||
208 (expr_type == TypeManager.int64_type) ||
209 (expr_type == TypeManager.uint64_type) ||
210 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
215 if (e is EnumConstant){
216 EnumConstant enum_constant = (EnumConstant) e;
218 Expression reduced = Reduce (ec, enum_constant.Child);
220 return new EnumConstant ((Constant) reduced, enum_constant.Type);
223 if (expr_type == TypeManager.int32_type)
224 return new IntConstant (~ ((IntConstant) e).Value);
225 if (expr_type == TypeManager.uint32_type)
226 return new UIntConstant (~ ((UIntConstant) e).Value);
227 if (expr_type == TypeManager.int64_type)
228 return new LongConstant (~ ((LongConstant) e).Value);
229 if (expr_type == TypeManager.uint64_type)
230 return new ULongConstant (~ ((ULongConstant) e).Value);
235 throw new Exception ("Can not constant fold");
238 Expression ResolveOperator (EmitContext ec)
240 Type expr_type = Expr.Type;
243 // Step 1: Perform Operator Overload location
248 op_name = oper_names [(int) Oper];
250 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
253 Expression e = StaticCallExpr.MakeSimpleCall (
254 ec, (MethodGroupExpr) mg, Expr, loc);
264 // Only perform numeric promotions on:
267 if (expr_type == null)
271 // Step 2: Default operations on CLI native types.
273 if (Expr is Constant)
274 return Reduce (ec, Expr);
276 if (Oper == Operator.LogicalNot){
277 if (expr_type != TypeManager.bool_type) {
282 type = TypeManager.bool_type;
286 if (Oper == Operator.OnesComplement) {
287 if (!((expr_type == TypeManager.int32_type) ||
288 (expr_type == TypeManager.uint32_type) ||
289 (expr_type == TypeManager.int64_type) ||
290 (expr_type == TypeManager.uint64_type) ||
291 (expr_type.IsSubclassOf (TypeManager.enum_type)))){
294 e = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
296 type = TypeManager.int32_type;
299 e = ConvertImplicit (ec, Expr, TypeManager.uint32_type, loc);
301 type = TypeManager.uint32_type;
304 e = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
306 type = TypeManager.int64_type;
309 e = ConvertImplicit (ec, Expr, TypeManager.uint64_type, loc);
311 type = TypeManager.uint64_type;
321 if (Oper == Operator.UnaryPlus) {
323 // A plus in front of something is just a no-op, so return the child.
329 // Deals with -literals
330 // int operator- (int x)
331 // long operator- (long x)
332 // float operator- (float f)
333 // double operator- (double d)
334 // decimal operator- (decimal d)
336 if (Oper == Operator.UnaryNegation){
340 // transform - - expr into expr
343 Unary unary = (Unary) Expr;
345 if (unary.Oper == Operator.UnaryNegation)
350 // perform numeric promotions to int,
354 // The following is inneficient, because we call
355 // ConvertImplicit too many times.
357 // It is also not clear if we should convert to Float
358 // or Double initially.
360 if (expr_type == TypeManager.uint32_type){
362 // FIXME: handle exception to this rule that
363 // permits the int value -2147483648 (-2^31) to
364 // bt wrote as a decimal interger literal
366 type = TypeManager.int64_type;
367 Expr = ConvertImplicit (ec, Expr, type, loc);
371 if (expr_type == TypeManager.uint64_type){
373 // FIXME: Handle exception of `long value'
374 // -92233720368547758087 (-2^63) to be wrote as
375 // decimal integer literal.
381 if (expr_type == TypeManager.float_type){
386 e = ConvertImplicit (ec, Expr, TypeManager.int32_type, loc);
393 e = ConvertImplicit (ec, Expr, TypeManager.int64_type, loc);
400 e = ConvertImplicit (ec, Expr, TypeManager.double_type, loc);
411 if (Oper == Operator.AddressOf){
412 if (Expr.eclass != ExprClass.Variable){
413 Error (211, loc, "Cannot take the address of non-variables");
422 if (!TypeManager.VerifyUnManaged (Expr.Type, loc)){
427 // This construct is needed because dynamic types
428 // are not known by Type.GetType, so we have to try then to use
429 // ModuleBuilder.GetType.
431 string ptr_type_name = Expr.Type.FullName + "*";
432 type = Type.GetType (ptr_type_name);
434 type = CodeGen.ModuleBuilder.GetType (ptr_type_name);
439 if (Oper == Operator.Indirection){
445 if (!expr_type.IsPointer){
448 "The * or -> operator can only be applied to pointers");
453 // We create an Indirection expression, because
454 // it can implement the IMemoryLocation.
456 return new Indirection (Expr);
459 Error (187, loc, "No such operator '" + OperName (Oper) + "' defined for type '" +
460 TypeManager.CSharpName (expr_type) + "'");
464 public override Expression DoResolve (EmitContext ec)
466 Expr = Expr.Resolve (ec);
471 eclass = ExprClass.Value;
472 return ResolveOperator (ec);
475 public override void Emit (EmitContext ec)
477 ILGenerator ig = ec.ig;
478 Type expr_type = Expr.Type;
481 case Operator.UnaryPlus:
482 throw new Exception ("This should be caught by Resolve");
484 case Operator.UnaryNegation:
486 ig.Emit (OpCodes.Neg);
489 case Operator.LogicalNot:
491 ig.Emit (OpCodes.Ldc_I4_0);
492 ig.Emit (OpCodes.Ceq);
495 case Operator.OnesComplement:
497 ig.Emit (OpCodes.Not);
500 case Operator.AddressOf:
501 ((IMemoryLocation)Expr).AddressOf (ec, AddressOp.LoadStore);
505 throw new Exception ("This should not happen: Operator = "
511 /// This will emit the child expression for `ec' avoiding the logical
512 /// not. The parent will take care of changing brfalse/brtrue
514 public void EmitLogicalNot (EmitContext ec)
516 if (Oper != Operator.LogicalNot)
517 throw new Exception ("EmitLogicalNot can only be called with !expr");
522 public override string ToString ()
524 return "Unary (" + Oper + ", " + Expr + ")";
530 // Unary operators are turned into Indirection expressions
531 // after semantic analysis (this is so we can take the address
532 // of an indirection).
534 public class Indirection : Expression, IMemoryLocation, IAssignMethod {
537 public Indirection (Expression expr)
540 this.type = expr.Type.GetElementType ();
541 eclass = ExprClass.Variable;
544 public override void Emit (EmitContext ec)
547 LoadFromPtr (ec.ig, Type, false);
550 public void EmitAssign (EmitContext ec, Expression source)
554 StoreFromPtr (ec.ig, type);
557 public void AddressOf (EmitContext ec, AddressOp Mode)
562 public override Expression DoResolve (EmitContext ec)
565 // Born fully resolved
572 /// Unary Mutator expressions (pre and post ++ and --)
576 /// UnaryMutator implements ++ and -- expressions. It derives from
577 /// ExpressionStatement becuase the pre/post increment/decrement
578 /// operators can be used in a statement context.
580 /// FIXME: Idea, we could split this up in two classes, one simpler
581 /// for the common case, and one with the extra fields for more complex
582 /// classes (indexers require temporary access; overloaded require method)
584 /// Maybe we should have classes PreIncrement, PostIncrement, PreDecrement,
585 /// PostDecrement, that way we could save the `Mode' byte as well.
587 public class UnaryMutator : ExpressionStatement {
588 public enum Mode : byte {
589 PreIncrement, PreDecrement, PostIncrement, PostDecrement
595 LocalTemporary temp_storage;
598 // This is expensive for the simplest case.
602 public UnaryMutator (Mode m, Expression e, Location l)
609 static string OperName (Mode mode)
611 return (mode == Mode.PreIncrement || mode == Mode.PostIncrement) ?
615 void Error23 (Type t)
618 23, loc, "Operator " + OperName (mode) +
619 " cannot be applied to operand of type `" +
620 TypeManager.CSharpName (t) + "'");
624 /// Returns whether an object of type `t' can be incremented
625 /// or decremented with add/sub (ie, basically whether we can
626 /// use pre-post incr-decr operations on it, but it is not a
627 /// System.Decimal, which we require operator overloading to catch)
629 static bool IsIncrementableNumber (Type t)
631 return (t == TypeManager.sbyte_type) ||
632 (t == TypeManager.byte_type) ||
633 (t == TypeManager.short_type) ||
634 (t == TypeManager.ushort_type) ||
635 (t == TypeManager.int32_type) ||
636 (t == TypeManager.uint32_type) ||
637 (t == TypeManager.int64_type) ||
638 (t == TypeManager.uint64_type) ||
639 (t == TypeManager.char_type) ||
640 (t.IsSubclassOf (TypeManager.enum_type)) ||
641 (t == TypeManager.float_type) ||
642 (t == TypeManager.double_type) ||
643 (t.IsPointer && t != TypeManager.void_ptr_type);
646 Expression ResolveOperator (EmitContext ec)
648 Type expr_type = expr.Type;
651 // Step 1: Perform Operator Overload location
656 if (mode == Mode.PreIncrement || mode == Mode.PostIncrement)
657 op_name = "op_Increment";
659 op_name = "op_Decrement";
661 mg = MemberLookup (ec, expr_type, op_name, MemberTypes.Method, AllBindingFlags, loc);
663 if (mg == null && expr_type.BaseType != null)
664 mg = MemberLookup (ec, expr_type.BaseType, op_name,
665 MemberTypes.Method, AllBindingFlags, loc);
668 method = StaticCallExpr.MakeSimpleCall (
669 ec, (MethodGroupExpr) mg, expr, loc);
676 // The operand of the prefix/postfix increment decrement operators
677 // should be an expression that is classified as a variable,
678 // a property access or an indexer access
681 if (expr.eclass == ExprClass.Variable){
682 if (IsIncrementableNumber (expr_type) ||
683 expr_type == TypeManager.decimal_type){
686 } else if (expr.eclass == ExprClass.IndexerAccess){
687 IndexerAccess ia = (IndexerAccess) expr;
689 temp_storage = new LocalTemporary (ec, expr.Type);
691 expr = ia.ResolveLValue (ec, temp_storage);
696 } else if (expr.eclass == ExprClass.PropertyAccess){
697 PropertyExpr pe = (PropertyExpr) expr;
699 if (pe.VerifyAssignable ())
704 report118 (loc, expr, "variable, indexer or property access");
708 Error (187, loc, "No such operator '" + OperName (mode) + "' defined for type '" +
709 TypeManager.CSharpName (expr_type) + "'");
713 public override Expression DoResolve (EmitContext ec)
715 expr = expr.Resolve (ec);
720 eclass = ExprClass.Value;
721 return ResolveOperator (ec);
724 static int PtrTypeSize (Type t)
726 return GetTypeSize (t.GetElementType ());
730 // FIXME: We need some way of avoiding the use of temp_storage
731 // for some types of storage (parameters, local variables,
732 // static fields) and single-dimension array access.
734 void EmitCode (EmitContext ec, bool is_expr)
736 ILGenerator ig = ec.ig;
737 IAssignMethod ia = (IAssignMethod) expr;
738 Type expr_type = expr.Type;
740 if (temp_storage == null)
741 temp_storage = new LocalTemporary (ec, expr_type);
744 case Mode.PreIncrement:
745 case Mode.PreDecrement:
749 if (expr_type == TypeManager.uint64_type ||
750 expr_type == TypeManager.int64_type)
751 ig.Emit (OpCodes.Ldc_I8, 1L);
752 else if (expr_type == TypeManager.double_type)
753 ig.Emit (OpCodes.Ldc_R8, 1.0);
754 else if (expr_type == TypeManager.float_type)
755 ig.Emit (OpCodes.Ldc_R4, 1.0F);
756 else if (expr_type.IsPointer){
757 int n = PtrTypeSize (expr_type);
760 ig.Emit (OpCodes.Sizeof, expr_type);
762 IntConstant.EmitInt (ig, n);
764 ig.Emit (OpCodes.Ldc_I4_1);
767 // Select the opcode based on the check state (then the type)
768 // and the actual operation
771 if (expr_type == TypeManager.int32_type ||
772 expr_type == TypeManager.int64_type){
773 if (mode == Mode.PreDecrement)
774 ig.Emit (OpCodes.Sub_Ovf);
776 ig.Emit (OpCodes.Add_Ovf);
777 } else if (expr_type == TypeManager.uint32_type ||
778 expr_type == TypeManager.uint64_type){
779 if (mode == Mode.PreDecrement)
780 ig.Emit (OpCodes.Sub_Ovf_Un);
782 ig.Emit (OpCodes.Add_Ovf_Un);
784 if (mode == Mode.PreDecrement)
785 ig.Emit (OpCodes.Sub_Ovf);
787 ig.Emit (OpCodes.Add_Ovf);
790 if (mode == Mode.PreDecrement)
791 ig.Emit (OpCodes.Sub);
793 ig.Emit (OpCodes.Add);
798 temp_storage.Store (ec);
799 ia.EmitAssign (ec, temp_storage);
801 temp_storage.Emit (ec);
804 case Mode.PostIncrement:
805 case Mode.PostDecrement:
813 ig.Emit (OpCodes.Dup);
815 if (expr_type == TypeManager.uint64_type ||
816 expr_type == TypeManager.int64_type)
817 ig.Emit (OpCodes.Ldc_I8, 1L);
818 else if (expr_type == TypeManager.double_type)
819 ig.Emit (OpCodes.Ldc_R8, 1.0);
820 else if (expr_type == TypeManager.float_type)
821 ig.Emit (OpCodes.Ldc_R4, 1.0F);
822 else if (expr_type.IsPointer){
823 int n = PtrTypeSize (expr_type);
826 ig.Emit (OpCodes.Sizeof, expr_type);
828 IntConstant.EmitInt (ig, n);
830 ig.Emit (OpCodes.Ldc_I4_1);
833 if (expr_type == TypeManager.int32_type ||
834 expr_type == TypeManager.int64_type){
835 if (mode == Mode.PostDecrement)
836 ig.Emit (OpCodes.Sub_Ovf);
838 ig.Emit (OpCodes.Add_Ovf);
839 } else if (expr_type == TypeManager.uint32_type ||
840 expr_type == TypeManager.uint64_type){
841 if (mode == Mode.PostDecrement)
842 ig.Emit (OpCodes.Sub_Ovf_Un);
844 ig.Emit (OpCodes.Add_Ovf_Un);
846 if (mode == Mode.PostDecrement)
847 ig.Emit (OpCodes.Sub_Ovf);
849 ig.Emit (OpCodes.Add_Ovf);
852 if (mode == Mode.PostDecrement)
853 ig.Emit (OpCodes.Sub);
855 ig.Emit (OpCodes.Add);
861 temp_storage.Store (ec);
862 ia.EmitAssign (ec, temp_storage);
867 public override void Emit (EmitContext ec)
873 public override void EmitStatement (EmitContext ec)
875 EmitCode (ec, false);
881 /// Base class for the `Is' and `As' classes.
885 /// FIXME: Split this in two, and we get to save the `Operator' Oper
888 public abstract class Probe : Expression {
889 public readonly string ProbeType;
890 protected Expression expr;
891 protected Type probe_type;
892 protected Location loc;
894 public Probe (Expression expr, string probe_type, Location l)
896 ProbeType = probe_type;
901 public Expression Expr {
907 public override Expression DoResolve (EmitContext ec)
909 probe_type = RootContext.LookupType (ec.DeclSpace, ProbeType, false, loc);
911 if (probe_type == null)
914 expr = expr.Resolve (ec);
921 /// Implementation of the `is' operator.
923 public class Is : Probe {
924 public Is (Expression expr, string probe_type, Location l)
925 : base (expr, probe_type, l)
929 public override void Emit (EmitContext ec)
931 ILGenerator ig = ec.ig;
935 ig.Emit (OpCodes.Isinst, probe_type);
936 ig.Emit (OpCodes.Ldnull);
937 ig.Emit (OpCodes.Cgt_Un);
940 public override Expression DoResolve (EmitContext ec)
942 Expression e = base.DoResolve (ec);
947 if (RootContext.WarningLevel >= 1){
948 Type etype = expr.Type;
950 if (etype == probe_type || etype.IsSubclassOf (probe_type)){
953 "The expression is always of type `" +
954 TypeManager.CSharpName (probe_type) + "'");
955 } else if (etype != probe_type && !probe_type.IsSubclassOf (etype)){
956 if (!(probe_type.IsInterface || expr.Type.IsInterface))
959 "The expression is never of type `" +
960 TypeManager.CSharpName (probe_type) + "'");
964 type = TypeManager.bool_type;
965 eclass = ExprClass.Value;
972 /// Implementation of the `as' operator.
974 public class As : Probe {
975 public As (Expression expr, string probe_type, Location l)
976 : base (expr, probe_type, l)
980 public override void Emit (EmitContext ec)
982 ILGenerator ig = ec.ig;
984 Type etype = expr.Type;
987 if (etype == probe_type || etype.IsSubclassOf (probe_type))
990 ig.Emit (OpCodes.Isinst, probe_type);
993 public override Expression DoResolve (EmitContext ec)
995 Expression e = base.DoResolve (ec);
1001 eclass = ExprClass.Value;
1008 /// This represents a typecast in the source language.
1010 /// FIXME: Cast expressions have an unusual set of parsing
1011 /// rules, we need to figure those out.
1013 public class Cast : Expression {
1014 Expression target_type;
1018 public Cast (Expression cast_type, Expression expr, Location loc)
1020 this.target_type = cast_type;
1025 public Expression TargetType {
1031 public Expression Expr {
1041 /// Attempts to do a compile-time folding of a constant cast.
1043 Expression TryReduce (EmitContext ec, Type target_type)
1045 if (expr is ByteConstant){
1046 byte v = ((ByteConstant) expr).Value;
1048 if (target_type == TypeManager.sbyte_type)
1049 return new SByteConstant ((sbyte) v);
1050 if (target_type == TypeManager.short_type)
1051 return new ShortConstant ((short) v);
1052 if (target_type == TypeManager.ushort_type)
1053 return new UShortConstant ((ushort) v);
1054 if (target_type == TypeManager.int32_type)
1055 return new IntConstant ((int) v);
1056 if (target_type == TypeManager.uint32_type)
1057 return new UIntConstant ((uint) v);
1058 if (target_type == TypeManager.int64_type)
1059 return new LongConstant ((long) v);
1060 if (target_type == TypeManager.uint64_type)
1061 return new ULongConstant ((ulong) v);
1062 if (target_type == TypeManager.float_type)
1063 return new FloatConstant ((float) v);
1064 if (target_type == TypeManager.double_type)
1065 return new DoubleConstant ((double) v);
1067 if (expr is SByteConstant){
1068 sbyte v = ((SByteConstant) expr).Value;
1070 if (target_type == TypeManager.byte_type)
1071 return new ByteConstant ((byte) v);
1072 if (target_type == TypeManager.short_type)
1073 return new ShortConstant ((short) v);
1074 if (target_type == TypeManager.ushort_type)
1075 return new UShortConstant ((ushort) v);
1076 if (target_type == TypeManager.int32_type)
1077 return new IntConstant ((int) v);
1078 if (target_type == TypeManager.uint32_type)
1079 return new UIntConstant ((uint) v);
1080 if (target_type == TypeManager.int64_type)
1081 return new LongConstant ((long) v);
1082 if (target_type == TypeManager.uint64_type)
1083 return new ULongConstant ((ulong) v);
1084 if (target_type == TypeManager.float_type)
1085 return new FloatConstant ((float) v);
1086 if (target_type == TypeManager.double_type)
1087 return new DoubleConstant ((double) v);
1089 if (expr is ShortConstant){
1090 short v = ((ShortConstant) expr).Value;
1092 if (target_type == TypeManager.byte_type)
1093 return new ByteConstant ((byte) v);
1094 if (target_type == TypeManager.sbyte_type)
1095 return new SByteConstant ((sbyte) v);
1096 if (target_type == TypeManager.ushort_type)
1097 return new UShortConstant ((ushort) v);
1098 if (target_type == TypeManager.int32_type)
1099 return new IntConstant ((int) v);
1100 if (target_type == TypeManager.uint32_type)
1101 return new UIntConstant ((uint) v);
1102 if (target_type == TypeManager.int64_type)
1103 return new LongConstant ((long) v);
1104 if (target_type == TypeManager.uint64_type)
1105 return new ULongConstant ((ulong) v);
1106 if (target_type == TypeManager.float_type)
1107 return new FloatConstant ((float) v);
1108 if (target_type == TypeManager.double_type)
1109 return new DoubleConstant ((double) v);
1111 if (expr is UShortConstant){
1112 ushort v = ((UShortConstant) expr).Value;
1114 if (target_type == TypeManager.byte_type)
1115 return new ByteConstant ((byte) v);
1116 if (target_type == TypeManager.sbyte_type)
1117 return new SByteConstant ((sbyte) v);
1118 if (target_type == TypeManager.short_type)
1119 return new ShortConstant ((short) v);
1120 if (target_type == TypeManager.int32_type)
1121 return new IntConstant ((int) v);
1122 if (target_type == TypeManager.uint32_type)
1123 return new UIntConstant ((uint) v);
1124 if (target_type == TypeManager.int64_type)
1125 return new LongConstant ((long) v);
1126 if (target_type == TypeManager.uint64_type)
1127 return new ULongConstant ((ulong) v);
1128 if (target_type == TypeManager.float_type)
1129 return new FloatConstant ((float) v);
1130 if (target_type == TypeManager.double_type)
1131 return new DoubleConstant ((double) v);
1133 if (expr is IntConstant){
1134 int v = ((IntConstant) expr).Value;
1136 if (target_type == TypeManager.byte_type)
1137 return new ByteConstant ((byte) v);
1138 if (target_type == TypeManager.sbyte_type)
1139 return new SByteConstant ((sbyte) v);
1140 if (target_type == TypeManager.short_type)
1141 return new ShortConstant ((short) v);
1142 if (target_type == TypeManager.ushort_type)
1143 return new UShortConstant ((ushort) v);
1144 if (target_type == TypeManager.uint32_type)
1145 return new UIntConstant ((uint) v);
1146 if (target_type == TypeManager.int64_type)
1147 return new LongConstant ((long) v);
1148 if (target_type == TypeManager.uint64_type)
1149 return new ULongConstant ((ulong) v);
1150 if (target_type == TypeManager.float_type)
1151 return new FloatConstant ((float) v);
1152 if (target_type == TypeManager.double_type)
1153 return new DoubleConstant ((double) v);
1155 if (expr is UIntConstant){
1156 uint v = ((UIntConstant) expr).Value;
1158 if (target_type == TypeManager.byte_type)
1159 return new ByteConstant ((byte) v);
1160 if (target_type == TypeManager.sbyte_type)
1161 return new SByteConstant ((sbyte) v);
1162 if (target_type == TypeManager.short_type)
1163 return new ShortConstant ((short) v);
1164 if (target_type == TypeManager.ushort_type)
1165 return new UShortConstant ((ushort) v);
1166 if (target_type == TypeManager.int32_type)
1167 return new IntConstant ((int) v);
1168 if (target_type == TypeManager.int64_type)
1169 return new LongConstant ((long) v);
1170 if (target_type == TypeManager.uint64_type)
1171 return new ULongConstant ((ulong) v);
1172 if (target_type == TypeManager.float_type)
1173 return new FloatConstant ((float) v);
1174 if (target_type == TypeManager.double_type)
1175 return new DoubleConstant ((double) v);
1177 if (expr is LongConstant){
1178 long v = ((LongConstant) expr).Value;
1180 if (target_type == TypeManager.byte_type)
1181 return new ByteConstant ((byte) v);
1182 if (target_type == TypeManager.sbyte_type)
1183 return new SByteConstant ((sbyte) v);
1184 if (target_type == TypeManager.short_type)
1185 return new ShortConstant ((short) v);
1186 if (target_type == TypeManager.ushort_type)
1187 return new UShortConstant ((ushort) v);
1188 if (target_type == TypeManager.int32_type)
1189 return new IntConstant ((int) v);
1190 if (target_type == TypeManager.uint32_type)
1191 return new UIntConstant ((uint) v);
1192 if (target_type == TypeManager.uint64_type)
1193 return new ULongConstant ((ulong) v);
1194 if (target_type == TypeManager.float_type)
1195 return new FloatConstant ((float) v);
1196 if (target_type == TypeManager.double_type)
1197 return new DoubleConstant ((double) v);
1199 if (expr is ULongConstant){
1200 ulong v = ((ULongConstant) expr).Value;
1202 if (target_type == TypeManager.byte_type)
1203 return new ByteConstant ((byte) v);
1204 if (target_type == TypeManager.sbyte_type)
1205 return new SByteConstant ((sbyte) v);
1206 if (target_type == TypeManager.short_type)
1207 return new ShortConstant ((short) v);
1208 if (target_type == TypeManager.ushort_type)
1209 return new UShortConstant ((ushort) v);
1210 if (target_type == TypeManager.int32_type)
1211 return new IntConstant ((int) v);
1212 if (target_type == TypeManager.uint32_type)
1213 return new UIntConstant ((uint) v);
1214 if (target_type == TypeManager.int64_type)
1215 return new LongConstant ((long) v);
1216 if (target_type == TypeManager.float_type)
1217 return new FloatConstant ((float) v);
1218 if (target_type == TypeManager.double_type)
1219 return new DoubleConstant ((double) v);
1221 if (expr is FloatConstant){
1222 float v = ((FloatConstant) expr).Value;
1224 if (target_type == TypeManager.byte_type)
1225 return new ByteConstant ((byte) v);
1226 if (target_type == TypeManager.sbyte_type)
1227 return new SByteConstant ((sbyte) v);
1228 if (target_type == TypeManager.short_type)
1229 return new ShortConstant ((short) v);
1230 if (target_type == TypeManager.ushort_type)
1231 return new UShortConstant ((ushort) v);
1232 if (target_type == TypeManager.int32_type)
1233 return new IntConstant ((int) v);
1234 if (target_type == TypeManager.uint32_type)
1235 return new UIntConstant ((uint) v);
1236 if (target_type == TypeManager.int64_type)
1237 return new LongConstant ((long) v);
1238 if (target_type == TypeManager.uint64_type)
1239 return new ULongConstant ((ulong) v);
1240 if (target_type == TypeManager.double_type)
1241 return new DoubleConstant ((double) v);
1243 if (expr is DoubleConstant){
1244 double v = ((DoubleConstant) expr).Value;
1246 if (target_type == TypeManager.byte_type)
1247 return new ByteConstant ((byte) v);
1248 if (target_type == TypeManager.sbyte_type)
1249 return new SByteConstant ((sbyte) v);
1250 if (target_type == TypeManager.short_type)
1251 return new ShortConstant ((short) v);
1252 if (target_type == TypeManager.ushort_type)
1253 return new UShortConstant ((ushort) v);
1254 if (target_type == TypeManager.int32_type)
1255 return new IntConstant ((int) v);
1256 if (target_type == TypeManager.uint32_type)
1257 return new UIntConstant ((uint) v);
1258 if (target_type == TypeManager.int64_type)
1259 return new LongConstant ((long) v);
1260 if (target_type == TypeManager.uint64_type)
1261 return new ULongConstant ((ulong) v);
1262 if (target_type == TypeManager.float_type)
1263 return new FloatConstant ((float) v);
1269 public override Expression DoResolve (EmitContext ec)
1271 expr = expr.Resolve (ec);
1275 bool old_state = ec.OnlyLookupTypes;
1276 ec.OnlyLookupTypes = true;
1277 target_type = target_type.Resolve (ec);
1278 ec.OnlyLookupTypes = old_state;
1280 if (target_type == null){
1281 Report.Error (-10, loc, "Can not resolve type");
1285 if (target_type.eclass != ExprClass.Type){
1286 report118 (loc, target_type, "class");
1290 type = target_type.Type;
1291 eclass = ExprClass.Value;
1296 if (expr is Constant){
1297 Expression e = TryReduce (ec, type);
1303 expr = ConvertExplicit (ec, expr, type, loc);
1307 public override void Emit (EmitContext ec)
1310 // This one will never happen
1312 throw new Exception ("Should not happen");
1317 /// Binary operators
1319 public class Binary : Expression {
1320 public enum Operator : byte {
1321 Multiply, Division, Modulus,
1322 Addition, Subtraction,
1323 LeftShift, RightShift,
1324 LessThan, GreaterThan, LessThanOrEqual, GreaterThanOrEqual,
1325 Equality, Inequality,
1335 Expression left, right;
1338 // After resolution, method might contain the operator overload
1341 protected MethodBase method;
1342 ArrayList Arguments;
1346 bool DelegateOperation;
1348 // This must be kept in sync with Operator!!!
1349 static string [] oper_names;
1353 oper_names = new string [(int) Operator.TOP];
1355 oper_names [(int) Operator.Multiply] = "op_Multiply";
1356 oper_names [(int) Operator.Division] = "op_Division";
1357 oper_names [(int) Operator.Modulus] = "op_Modulus";
1358 oper_names [(int) Operator.Addition] = "op_Addition";
1359 oper_names [(int) Operator.Subtraction] = "op_Subtraction";
1360 oper_names [(int) Operator.LeftShift] = "op_LeftShift";
1361 oper_names [(int) Operator.RightShift] = "op_RightShift";
1362 oper_names [(int) Operator.LessThan] = "op_LessThan";
1363 oper_names [(int) Operator.GreaterThan] = "op_GreaterThan";
1364 oper_names [(int) Operator.LessThanOrEqual] = "op_LessThanOrEqual";
1365 oper_names [(int) Operator.GreaterThanOrEqual] = "op_GreaterThanOrEqual";
1366 oper_names [(int) Operator.Equality] = "op_Equality";
1367 oper_names [(int) Operator.Inequality] = "op_Inequality";
1368 oper_names [(int) Operator.BitwiseAnd] = "op_BitwiseAnd";
1369 oper_names [(int) Operator.BitwiseOr] = "op_BitwiseOr";
1370 oper_names [(int) Operator.ExclusiveOr] = "op_ExclusiveOr";
1371 oper_names [(int) Operator.LogicalOr] = "op_LogicalOr";
1372 oper_names [(int) Operator.LogicalAnd] = "op_LogicalAnd";
1375 public Binary (Operator oper, Expression left, Expression right, Location loc)
1383 public Operator Oper {
1392 public Expression Left {
1401 public Expression Right {
1412 /// Returns a stringified representation of the Operator
1414 static string OperName (Operator oper)
1417 case Operator.Multiply:
1419 case Operator.Division:
1421 case Operator.Modulus:
1423 case Operator.Addition:
1425 case Operator.Subtraction:
1427 case Operator.LeftShift:
1429 case Operator.RightShift:
1431 case Operator.LessThan:
1433 case Operator.GreaterThan:
1435 case Operator.LessThanOrEqual:
1437 case Operator.GreaterThanOrEqual:
1439 case Operator.Equality:
1441 case Operator.Inequality:
1443 case Operator.BitwiseAnd:
1445 case Operator.BitwiseOr:
1447 case Operator.ExclusiveOr:
1449 case Operator.LogicalOr:
1451 case Operator.LogicalAnd:
1455 return oper.ToString ();
1458 public override string ToString ()
1460 return "operator " + OperName (oper) + "(" + left.ToString () + ", " +
1461 right.ToString () + ")";
1464 Expression ForceConversion (EmitContext ec, Expression expr, Type target_type)
1466 if (expr.Type == target_type)
1469 return ConvertImplicit (ec, expr, target_type, new Location (-1));
1472 public static void Error_OperatorAmbiguous (Location loc, Operator oper, Type l, Type r)
1475 34, loc, "Operator `" + OperName (oper)
1476 + "' is ambiguous on operands of type `"
1477 + TypeManager.CSharpName (l) + "' "
1478 + "and `" + TypeManager.CSharpName (r)
1483 // Note that handling the case l == Decimal || r == Decimal
1484 // is taken care of by the Step 1 Operator Overload resolution.
1486 bool DoNumericPromotions (EmitContext ec, Type l, Type r)
1488 if (l == TypeManager.double_type || r == TypeManager.double_type){
1490 // If either operand is of type double, the other operand is
1491 // conveted to type double.
1493 if (r != TypeManager.double_type)
1494 right = ConvertImplicit (ec, right, TypeManager.double_type, loc);
1495 if (l != TypeManager.double_type)
1496 left = ConvertImplicit (ec, left, TypeManager.double_type, loc);
1498 type = TypeManager.double_type;
1499 } else if (l == TypeManager.float_type || r == TypeManager.float_type){
1501 // if either operand is of type float, the other operand is
1502 // converted to type float.
1504 if (r != TypeManager.double_type)
1505 right = ConvertImplicit (ec, right, TypeManager.float_type, loc);
1506 if (l != TypeManager.double_type)
1507 left = ConvertImplicit (ec, left, TypeManager.float_type, loc);
1508 type = TypeManager.float_type;
1509 } else if (l == TypeManager.uint64_type || r == TypeManager.uint64_type){
1513 // If either operand is of type ulong, the other operand is
1514 // converted to type ulong. or an error ocurrs if the other
1515 // operand is of type sbyte, short, int or long
1517 if (l == TypeManager.uint64_type){
1518 if (r != TypeManager.uint64_type){
1519 if (right is IntConstant){
1520 IntConstant ic = (IntConstant) right;
1522 e = TryImplicitIntConversion (l, ic);
1525 } else if (right is LongConstant){
1526 long ll = ((LongConstant) right).Value;
1529 right = new ULongConstant ((ulong) ll);
1531 e = ImplicitNumericConversion (ec, right, l, loc);
1538 if (left is IntConstant){
1539 e = TryImplicitIntConversion (r, (IntConstant) left);
1542 } else if (left is LongConstant){
1543 long ll = ((LongConstant) left).Value;
1546 left = new ULongConstant ((ulong) ll);
1548 e = ImplicitNumericConversion (ec, left, r, loc);
1555 if ((other == TypeManager.sbyte_type) ||
1556 (other == TypeManager.short_type) ||
1557 (other == TypeManager.int32_type) ||
1558 (other == TypeManager.int64_type))
1559 Error_OperatorAmbiguous (loc, oper, l, r);
1560 type = TypeManager.uint64_type;
1561 } else if (l == TypeManager.int64_type || r == TypeManager.int64_type){
1563 // If either operand is of type long, the other operand is converted
1566 if (l != TypeManager.int64_type)
1567 left = ConvertImplicit (ec, left, TypeManager.int64_type, loc);
1568 if (r != TypeManager.int64_type)
1569 right = ConvertImplicit (ec, right, TypeManager.int64_type, loc);
1571 type = TypeManager.int64_type;
1572 } else if (l == TypeManager.uint32_type || r == TypeManager.uint32_type){
1574 // If either operand is of type uint, and the other
1575 // operand is of type sbyte, short or int, othe operands are
1576 // converted to type long.
1580 if (l == TypeManager.uint32_type){
1581 if (right is IntConstant){
1582 IntConstant ic = (IntConstant) right;
1586 right = new UIntConstant ((uint) val);
1593 else if (r == TypeManager.uint32_type){
1594 if (left is IntConstant){
1595 IntConstant ic = (IntConstant) left;
1599 left = new UIntConstant ((uint) val);
1608 if ((other == TypeManager.sbyte_type) ||
1609 (other == TypeManager.short_type) ||
1610 (other == TypeManager.int32_type)){
1611 left = ForceConversion (ec, left, TypeManager.int64_type);
1612 right = ForceConversion (ec, right, TypeManager.int64_type);
1613 type = TypeManager.int64_type;
1616 // if either operand is of type uint, the other
1617 // operand is converd to type uint
1619 left = ForceConversion (ec, left, TypeManager.uint32_type);
1620 right = ForceConversion (ec, right, TypeManager.uint32_type);
1621 type = TypeManager.uint32_type;
1623 } else if (l == TypeManager.decimal_type || r == TypeManager.decimal_type){
1624 if (l != TypeManager.decimal_type)
1625 left = ConvertImplicit (ec, left, TypeManager.decimal_type, loc);
1626 if (r != TypeManager.decimal_type)
1627 right = ConvertImplicit (ec, right, TypeManager.decimal_type, loc);
1629 type = TypeManager.decimal_type;
1631 Expression l_tmp, r_tmp;
1633 l_tmp = ForceConversion (ec, left, TypeManager.int32_type);
1637 r_tmp = ForceConversion (ec, right, TypeManager.int32_type);
1644 type = TypeManager.int32_type;
1650 static public void Error_OperatorCannotBeApplied (Location loc, string name, Type l, Type r)
1653 "Operator " + name + " cannot be applied to operands of type `" +
1654 TypeManager.CSharpName (l) + "' and `" +
1655 TypeManager.CSharpName (r) + "'");
1658 void Error_OperatorCannotBeApplied ()
1660 Error_OperatorCannotBeApplied (loc, OperName (oper), left.Type, right.Type);
1663 static bool is_32_or_64 (Type t)
1665 return (t == TypeManager.int32_type || t == TypeManager.uint32_type ||
1666 t == TypeManager.int64_type || t == TypeManager.uint64_type);
1669 Expression CheckShiftArguments (EmitContext ec)
1673 Type r = right.Type;
1675 e = ForceConversion (ec, right, TypeManager.int32_type);
1677 Error_OperatorCannotBeApplied ();
1682 if (((e = ConvertImplicit (ec, left, TypeManager.int32_type, loc)) != null) ||
1683 ((e = ConvertImplicit (ec, left, TypeManager.uint32_type, loc)) != null) ||
1684 ((e = ConvertImplicit (ec, left, TypeManager.int64_type, loc)) != null) ||
1685 ((e = ConvertImplicit (ec, left, TypeManager.uint64_type, loc)) != null)){
1691 Error_OperatorCannotBeApplied ();
1695 Expression ResolveOperator (EmitContext ec)
1698 Type r = right.Type;
1700 bool overload_failed = false;
1703 // Step 1: Perform Operator Overload location
1705 Expression left_expr, right_expr;
1707 string op = oper_names [(int) oper];
1709 MethodGroupExpr union;
1710 left_expr = MemberLookup (ec, l, op, MemberTypes.Method, AllBindingFlags, loc);
1712 right_expr = MemberLookup (
1713 ec, r, op, MemberTypes.Method, AllBindingFlags, loc);
1714 union = Invocation.MakeUnionSet (left_expr, right_expr, loc);
1716 union = (MethodGroupExpr) left_expr;
1718 if (union != null) {
1719 Arguments = new ArrayList ();
1720 Arguments.Add (new Argument (left, Argument.AType.Expression));
1721 Arguments.Add (new Argument (right, Argument.AType.Expression));
1723 method = Invocation.OverloadResolve (ec, union, Arguments, Location.Null);
1724 if (method != null) {
1725 MethodInfo mi = (MethodInfo) method;
1727 type = mi.ReturnType;
1730 overload_failed = true;
1735 // Step 2: Default operations on CLI native types.
1739 // Step 0: String concatenation (because overloading will get this wrong)
1741 if (oper == Operator.Addition){
1743 // If any of the arguments is a string, cast to string
1746 if (l == TypeManager.string_type){
1748 if (r == TypeManager.void_type) {
1749 Error_OperatorCannotBeApplied ();
1753 if (r == TypeManager.string_type){
1754 if (left is Constant && right is Constant){
1755 StringConstant ls = (StringConstant) left;
1756 StringConstant rs = (StringConstant) right;
1758 return new StringConstant (
1759 ls.Value + rs.Value);
1763 method = TypeManager.string_concat_string_string;
1766 method = TypeManager.string_concat_object_object;
1767 right = ConvertImplicit (ec, right,
1768 TypeManager.object_type, loc);
1770 type = TypeManager.string_type;
1772 Arguments = new ArrayList ();
1773 Arguments.Add (new Argument (left, Argument.AType.Expression));
1774 Arguments.Add (new Argument (right, Argument.AType.Expression));
1778 } else if (r == TypeManager.string_type){
1781 if (l == TypeManager.void_type) {
1782 Error_OperatorCannotBeApplied ();
1786 method = TypeManager.string_concat_object_object;
1787 left = ConvertImplicit (ec, left, TypeManager.object_type, loc);
1788 Arguments = new ArrayList ();
1789 Arguments.Add (new Argument (left, Argument.AType.Expression));
1790 Arguments.Add (new Argument (right, Argument.AType.Expression));
1792 type = TypeManager.string_type;
1798 // Transform a + ( - b) into a - b
1800 if (right is Unary){
1801 Unary right_unary = (Unary) right;
1803 if (right_unary.Oper == Unary.Operator.UnaryNegation){
1804 oper = Operator.Subtraction;
1805 right = right_unary.Expr;
1811 if (oper == Operator.Equality || oper == Operator.Inequality){
1812 if (l == TypeManager.bool_type || r == TypeManager.bool_type){
1813 if (r != TypeManager.bool_type || l != TypeManager.bool_type){
1814 Error_OperatorCannotBeApplied ();
1818 type = TypeManager.bool_type;
1823 // operator != (object a, object b)
1824 // operator == (object a, object b)
1826 // For this to be used, both arguments have to be reference-types.
1827 // Read the rationale on the spec (14.9.6)
1829 // Also, if at compile time we know that the classes do not inherit
1830 // one from the other, then we catch the error there.
1832 if (!(l.IsValueType || r.IsValueType)){
1833 type = TypeManager.bool_type;
1838 if (l.IsSubclassOf (r) || r.IsSubclassOf (l))
1842 // Also, a standard conversion must exist from either one
1844 if (!(StandardConversionExists (left, r) ||
1845 StandardConversionExists (right, l))){
1846 Error_OperatorCannotBeApplied ();
1850 // We are going to have to convert to an object to compare
1852 if (l != TypeManager.object_type)
1853 left = new EmptyCast (left, TypeManager.object_type);
1854 if (r != TypeManager.object_type)
1855 right = new EmptyCast (right, TypeManager.object_type);
1858 // FIXME: CSC here catches errors cs254 and cs252
1864 // Only perform numeric promotions on:
1865 // +, -, *, /, %, &, |, ^, ==, !=, <, >, <=, >=
1867 if (oper == Operator.Addition || oper == Operator.Subtraction) {
1868 if (l.IsSubclassOf (TypeManager.delegate_type) &&
1869 r.IsSubclassOf (TypeManager.delegate_type)) {
1871 Arguments = new ArrayList ();
1872 Arguments.Add (new Argument (left, Argument.AType.Expression));
1873 Arguments.Add (new Argument (right, Argument.AType.Expression));
1875 if (oper == Operator.Addition)
1876 method = TypeManager.delegate_combine_delegate_delegate;
1878 method = TypeManager.delegate_remove_delegate_delegate;
1880 DelegateOperation = true;
1886 // Pointer arithmetic:
1888 // T* operator + (T* x, int y);
1889 // T* operator + (T* x, uint y);
1890 // T* operator + (T* x, long y);
1891 // T* operator + (T* x, ulong y);
1893 // T* operator + (int y, T* x);
1894 // T* operator + (uint y, T *x);
1895 // T* operator + (long y, T *x);
1896 // T* operator + (ulong y, T *x);
1898 // T* operator - (T* x, int y);
1899 // T* operator - (T* x, uint y);
1900 // T* operator - (T* x, long y);
1901 // T* operator - (T* x, ulong y);
1903 // long operator - (T* x, T *y)
1906 if (r.IsPointer && oper == Operator.Subtraction){
1908 return new PointerArithmetic (
1909 false, left, right, TypeManager.int64_type);
1910 } else if (is_32_or_64 (r))
1911 return new PointerArithmetic (
1912 oper == Operator.Addition, left, right, l);
1913 } else if (r.IsPointer && is_32_or_64 (l) && oper == Operator.Addition)
1914 return new PointerArithmetic (
1915 true, right, left, r);
1919 // Enumeration operators
1921 bool lie = TypeManager.IsEnumType (l);
1922 bool rie = TypeManager.IsEnumType (r);
1927 // operator + (E e, U x)
1929 if (oper == Operator.Addition){
1931 Error_OperatorCannotBeApplied ();
1935 Type enum_type = lie ? l : r;
1936 Type other_type = lie ? r : l;
1937 Type underlying_type = TypeManager.EnumToUnderlying (enum_type);
1940 if (underlying_type != other_type){
1941 Error_OperatorCannotBeApplied ();
1950 temp = ConvertImplicit (ec, right, l, loc);
1954 temp = ConvertImplicit (ec, left, r, loc);
1961 if (oper == Operator.Equality || oper == Operator.Inequality ||
1962 oper == Operator.LessThanOrEqual || oper == Operator.LessThan ||
1963 oper == Operator.GreaterThanOrEqual || oper == Operator.GreaterThan){
1964 type = TypeManager.bool_type;
1968 if (oper == Operator.BitwiseAnd ||
1969 oper == Operator.BitwiseOr ||
1970 oper == Operator.ExclusiveOr){
1977 if (oper == Operator.LeftShift || oper == Operator.RightShift)
1978 return CheckShiftArguments (ec);
1980 if (oper == Operator.LogicalOr || oper == Operator.LogicalAnd){
1981 if (l != TypeManager.bool_type || r != TypeManager.bool_type){
1982 Error_OperatorCannotBeApplied ();
1986 type = TypeManager.bool_type;
1991 // operator & (bool x, bool y)
1992 // operator | (bool x, bool y)
1993 // operator ^ (bool x, bool y)
1995 if (l == TypeManager.bool_type && r == TypeManager.bool_type){
1996 if (oper == Operator.BitwiseAnd ||
1997 oper == Operator.BitwiseOr ||
1998 oper == Operator.ExclusiveOr){
2005 // Pointer comparison
2007 if (l.IsPointer && r.IsPointer){
2008 if (oper == Operator.Equality || oper == Operator.Inequality ||
2009 oper == Operator.LessThan || oper == Operator.LessThanOrEqual ||
2010 oper == Operator.GreaterThan || oper == Operator.GreaterThanOrEqual){
2011 type = TypeManager.bool_type;
2017 // We are dealing with numbers
2019 if (overload_failed){
2020 Error_OperatorCannotBeApplied ();
2024 if (!DoNumericPromotions (ec, l, r)){
2025 Error_OperatorCannotBeApplied ();
2029 if (left == null || right == null)
2033 // reload our cached types if required
2038 if (oper == Operator.BitwiseAnd ||
2039 oper == Operator.BitwiseOr ||
2040 oper == Operator.ExclusiveOr){
2042 if (!((l == TypeManager.int32_type) ||
2043 (l == TypeManager.uint32_type) ||
2044 (l == TypeManager.int64_type) ||
2045 (l == TypeManager.uint64_type)))
2048 Error_OperatorCannotBeApplied ();
2053 if (oper == Operator.Equality ||
2054 oper == Operator.Inequality ||
2055 oper == Operator.LessThanOrEqual ||
2056 oper == Operator.LessThan ||
2057 oper == Operator.GreaterThanOrEqual ||
2058 oper == Operator.GreaterThan){
2059 type = TypeManager.bool_type;
2065 public override Expression DoResolve (EmitContext ec)
2067 left = left.Resolve (ec);
2068 right = right.Resolve (ec);
2070 if (left == null || right == null)
2073 if (left.Type == null)
2074 throw new Exception (
2075 "Resolve returned non null, but did not set the type! (" +
2076 left + ") at Line: " + loc.Row);
2077 if (right.Type == null)
2078 throw new Exception (
2079 "Resolve returned non null, but did not set the type! (" +
2080 right + ") at Line: "+ loc.Row);
2082 eclass = ExprClass.Value;
2084 if (left is Constant && right is Constant){
2085 Expression e = ConstantFold.BinaryFold (
2086 ec, oper, (Constant) left, (Constant) right, loc);
2091 return ResolveOperator (ec);
2094 public bool IsBranchable ()
2096 if (oper == Operator.Equality ||
2097 oper == Operator.Inequality ||
2098 oper == Operator.LessThan ||
2099 oper == Operator.GreaterThan ||
2100 oper == Operator.LessThanOrEqual ||
2101 oper == Operator.GreaterThanOrEqual){
2108 /// This entry point is used by routines that might want
2109 /// to emit a brfalse/brtrue after an expression, and instead
2110 /// they could use a more compact notation.
2112 /// Typically the code would generate l.emit/r.emit, followed
2113 /// by the comparission and then a brtrue/brfalse. The comparissions
2114 /// are sometimes inneficient (there are not as complete as the branches
2115 /// look for the hacks in Emit using double ceqs).
2117 /// So for those cases we provide EmitBranchable that can emit the
2118 /// branch with the test
2120 public void EmitBranchable (EmitContext ec, int target)
2123 bool close_target = false;
2124 ILGenerator ig = ec.ig;
2127 // short-circuit operators
2129 if (oper == Operator.LogicalAnd){
2131 ig.Emit (OpCodes.Brfalse, target);
2133 ig.Emit (OpCodes.Brfalse, target);
2134 } else if (oper == Operator.LogicalOr){
2136 ig.Emit (OpCodes.Brtrue, target);
2138 ig.Emit (OpCodes.Brfalse, target);
2145 case Operator.Equality:
2147 opcode = OpCodes.Beq_S;
2149 opcode = OpCodes.Beq;
2152 case Operator.Inequality:
2154 opcode = OpCodes.Bne_Un_S;
2156 opcode = OpCodes.Bne_Un;
2159 case Operator.LessThan:
2161 opcode = OpCodes.Blt_S;
2163 opcode = OpCodes.Blt;
2166 case Operator.GreaterThan:
2168 opcode = OpCodes.Bgt_S;
2170 opcode = OpCodes.Bgt;
2173 case Operator.LessThanOrEqual:
2175 opcode = OpCodes.Ble_S;
2177 opcode = OpCodes.Ble;
2180 case Operator.GreaterThanOrEqual:
2182 opcode = OpCodes.Bge_S;
2184 opcode = OpCodes.Ble;
2188 throw new Exception ("EmitBranchable called on non-EmitBranchable operator: "
2189 + oper.ToString ());
2192 ig.Emit (opcode, target);
2195 public override void Emit (EmitContext ec)
2197 ILGenerator ig = ec.ig;
2199 Type r = right.Type;
2202 if (method != null) {
2204 // Note that operators are static anyway
2206 if (Arguments != null)
2207 Invocation.EmitArguments (ec, method, Arguments);
2209 if (method is MethodInfo)
2210 ig.Emit (OpCodes.Call, (MethodInfo) method);
2212 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
2214 if (DelegateOperation)
2215 ig.Emit (OpCodes.Castclass, type);
2221 // Handle short-circuit operators differently
2224 if (oper == Operator.LogicalAnd){
2225 Label load_zero = ig.DefineLabel ();
2226 Label end = ig.DefineLabel ();
2229 ig.Emit (OpCodes.Brfalse, load_zero);
2231 ig.Emit (OpCodes.Br, end);
2232 ig.MarkLabel (load_zero);
2233 ig.Emit (OpCodes.Ldc_I4_0);
2236 } else if (oper == Operator.LogicalOr){
2237 Label load_one = ig.DefineLabel ();
2238 Label end = ig.DefineLabel ();
2241 ig.Emit (OpCodes.Brtrue, load_one);
2243 ig.Emit (OpCodes.Br, end);
2244 ig.MarkLabel (load_one);
2245 ig.Emit (OpCodes.Ldc_I4_1);
2254 case Operator.Multiply:
2256 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2257 opcode = OpCodes.Mul_Ovf;
2258 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2259 opcode = OpCodes.Mul_Ovf_Un;
2261 opcode = OpCodes.Mul;
2263 opcode = OpCodes.Mul;
2267 case Operator.Division:
2268 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2269 opcode = OpCodes.Div_Un;
2271 opcode = OpCodes.Div;
2274 case Operator.Modulus:
2275 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2276 opcode = OpCodes.Rem_Un;
2278 opcode = OpCodes.Rem;
2281 case Operator.Addition:
2283 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2284 opcode = OpCodes.Add_Ovf;
2285 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2286 opcode = OpCodes.Add_Ovf_Un;
2288 opcode = OpCodes.Add;
2290 opcode = OpCodes.Add;
2293 case Operator.Subtraction:
2295 if (l == TypeManager.int32_type || l == TypeManager.int64_type)
2296 opcode = OpCodes.Sub_Ovf;
2297 else if (l==TypeManager.uint32_type || l==TypeManager.uint64_type)
2298 opcode = OpCodes.Sub_Ovf_Un;
2300 opcode = OpCodes.Sub;
2302 opcode = OpCodes.Sub;
2305 case Operator.RightShift:
2306 if (l == TypeManager.uint32_type || l == TypeManager.uint64_type)
2307 opcode = OpCodes.Shr_Un;
2309 opcode = OpCodes.Shr;
2312 case Operator.LeftShift:
2313 opcode = OpCodes.Shl;
2316 case Operator.Equality:
2317 opcode = OpCodes.Ceq;
2320 case Operator.Inequality:
2321 ec.ig.Emit (OpCodes.Ceq);
2322 ec.ig.Emit (OpCodes.Ldc_I4_0);
2324 opcode = OpCodes.Ceq;
2327 case Operator.LessThan:
2328 opcode = OpCodes.Clt;
2331 case Operator.GreaterThan:
2332 opcode = OpCodes.Cgt;
2335 case Operator.LessThanOrEqual:
2336 ec.ig.Emit (OpCodes.Cgt);
2337 ec.ig.Emit (OpCodes.Ldc_I4_0);
2339 opcode = OpCodes.Ceq;
2342 case Operator.GreaterThanOrEqual:
2343 ec.ig.Emit (OpCodes.Clt);
2344 ec.ig.Emit (OpCodes.Ldc_I4_1);
2346 opcode = OpCodes.Sub;
2349 case Operator.BitwiseOr:
2350 opcode = OpCodes.Or;
2353 case Operator.BitwiseAnd:
2354 opcode = OpCodes.And;
2357 case Operator.ExclusiveOr:
2358 opcode = OpCodes.Xor;
2362 throw new Exception ("This should not happen: Operator = "
2363 + oper.ToString ());
2369 public bool IsBuiltinOperator {
2371 return method == null;
2376 public class PointerArithmetic : Expression {
2377 Expression left, right;
2381 // We assume that `l' is always a pointer
2383 public PointerArithmetic (bool is_addition, Expression l, Expression r, Type t)
2386 eclass = ExprClass.Variable;
2389 is_add = is_addition;
2392 public override Expression DoResolve (EmitContext ec)
2395 // We are born fully resolved
2400 public override void Emit (EmitContext ec)
2402 Type op_type = left.Type;
2403 ILGenerator ig = ec.ig;
2404 int size = GetTypeSize (op_type.GetElementType ());
2406 if (right.Type.IsPointer){
2408 // handle (pointer - pointer)
2412 ig.Emit (OpCodes.Sub);
2416 ig.Emit (OpCodes.Sizeof, op_type);
2418 IntLiteral.EmitInt (ig, size);
2419 ig.Emit (OpCodes.Div);
2421 ig.Emit (OpCodes.Conv_I8);
2424 // handle + and - on (pointer op int)
2427 ig.Emit (OpCodes.Conv_I);
2431 ig.Emit (OpCodes.Sizeof, op_type);
2433 IntLiteral.EmitInt (ig, size);
2434 ig.Emit (OpCodes.Mul);
2437 ig.Emit (OpCodes.Add);
2439 ig.Emit (OpCodes.Sub);
2445 /// Implements the ternary conditiona operator (?:)
2447 public class Conditional : Expression {
2448 Expression expr, trueExpr, falseExpr;
2451 public Conditional (Expression expr, Expression trueExpr, Expression falseExpr, Location l)
2454 this.trueExpr = trueExpr;
2455 this.falseExpr = falseExpr;
2459 public Expression Expr {
2465 public Expression TrueExpr {
2471 public Expression FalseExpr {
2477 public override Expression DoResolve (EmitContext ec)
2479 expr = expr.Resolve (ec);
2481 if (expr.Type != TypeManager.bool_type)
2482 expr = Expression.ConvertImplicitRequired (
2483 ec, expr, TypeManager.bool_type, loc);
2485 trueExpr = trueExpr.Resolve (ec);
2486 falseExpr = falseExpr.Resolve (ec);
2488 if (expr == null || trueExpr == null || falseExpr == null)
2491 eclass = ExprClass.Value;
2492 if (trueExpr.Type == falseExpr.Type)
2493 type = trueExpr.Type;
2496 Type true_type = trueExpr.Type;
2497 Type false_type = falseExpr.Type;
2499 if (trueExpr is NullLiteral){
2502 } else if (falseExpr is NullLiteral){
2508 // First, if an implicit conversion exists from trueExpr
2509 // to falseExpr, then the result type is of type falseExpr.Type
2511 conv = ConvertImplicit (ec, trueExpr, false_type, loc);
2514 // Check if both can convert implicitl to each other's type
2516 if (ConvertImplicit (ec, falseExpr, true_type, loc) != null){
2519 "Can not compute type of conditional expression " +
2520 "as `" + TypeManager.CSharpName (trueExpr.Type) +
2521 "' and `" + TypeManager.CSharpName (falseExpr.Type) +
2522 "' convert implicitly to each other");
2527 } else if ((conv = ConvertImplicit(ec, falseExpr, true_type,loc))!= null){
2531 Error (173, loc, "The type of the conditional expression can " +
2532 "not be computed because there is no implicit conversion" +
2533 " from `" + TypeManager.CSharpName (trueExpr.Type) + "'" +
2534 " and `" + TypeManager.CSharpName (falseExpr.Type) + "'");
2539 if (expr is BoolConstant){
2540 BoolConstant bc = (BoolConstant) expr;
2551 public override void Emit (EmitContext ec)
2553 ILGenerator ig = ec.ig;
2554 Label false_target = ig.DefineLabel ();
2555 Label end_target = ig.DefineLabel ();
2558 ig.Emit (OpCodes.Brfalse, false_target);
2560 ig.Emit (OpCodes.Br, end_target);
2561 ig.MarkLabel (false_target);
2562 falseExpr.Emit (ec);
2563 ig.MarkLabel (end_target);
2571 public class LocalVariableReference : Expression, IAssignMethod, IMemoryLocation {
2572 public readonly string Name;
2573 public readonly Block Block;
2575 VariableInfo variable_info;
2577 public LocalVariableReference (Block block, string name, Location l)
2582 eclass = ExprClass.Variable;
2585 public VariableInfo VariableInfo {
2587 if (variable_info == null)
2588 variable_info = Block.GetVariableInfo (Name);
2589 return variable_info;
2593 public override Expression DoResolve (EmitContext ec)
2595 VariableInfo vi = VariableInfo;
2597 if (Block.IsConstant (Name)) {
2598 Expression e = Block.GetConstantExpression (Name);
2604 type = vi.VariableType;
2608 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
2610 Expression e = DoResolve (ec);
2615 VariableInfo vi = VariableInfo;
2619 // Sigh: this breaks `using' and `fixed'. Need to review that
2624 "cannot assign to `" + Name + "' because it is readonly");
2632 public override void Emit (EmitContext ec)
2634 VariableInfo vi = VariableInfo;
2635 ILGenerator ig = ec.ig;
2637 ig.Emit (OpCodes.Ldloc, vi.LocalBuilder);
2641 public void EmitAssign (EmitContext ec, Expression source)
2643 ILGenerator ig = ec.ig;
2644 VariableInfo vi = VariableInfo;
2650 ig.Emit (OpCodes.Stloc, vi.LocalBuilder);
2653 public void AddressOf (EmitContext ec, AddressOp mode)
2655 VariableInfo vi = VariableInfo;
2657 if ((mode & AddressOp.Load) != 0)
2659 if ((mode & AddressOp.Store) != 0)
2662 ec.ig.Emit (OpCodes.Ldloca, vi.LocalBuilder);
2667 /// This represents a reference to a parameter in the intermediate
2670 public class ParameterReference : Expression, IAssignMethod, IMemoryLocation {
2676 public ParameterReference (Parameters pars, int idx, string name)
2681 eclass = ExprClass.Variable;
2685 // Notice that for ref/out parameters, the type exposed is not the
2686 // same type exposed externally.
2689 // externally we expose "int&"
2690 // here we expose "int".
2692 // We record this in "is_ref". This means that the type system can treat
2693 // the type as it is expected, but when we generate the code, we generate
2694 // the alternate kind of code.
2696 public override Expression DoResolve (EmitContext ec)
2698 type = pars.GetParameterInfo (ec.DeclSpace, idx, out is_ref);
2699 eclass = ExprClass.Variable;
2705 // This method is used by parameters that are references, that are
2706 // being passed as references: we only want to pass the pointer (that
2707 // is already stored in the parameter, not the address of the pointer,
2708 // and not the value of the variable).
2710 public void EmitLoad (EmitContext ec)
2712 ILGenerator ig = ec.ig;
2719 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2721 ig.Emit (OpCodes.Ldarg, arg_idx);
2724 public override void Emit (EmitContext ec)
2726 ILGenerator ig = ec.ig;
2733 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2735 ig.Emit (OpCodes.Ldarg, arg_idx);
2741 // If we are a reference, we loaded on the stack a pointer
2742 // Now lets load the real value
2744 LoadFromPtr (ig, type, true);
2747 public void EmitAssign (EmitContext ec, Expression source)
2749 ILGenerator ig = ec.ig;
2758 ig.Emit (OpCodes.Ldarg_S, (byte) arg_idx);
2760 ig.Emit (OpCodes.Ldarg, arg_idx);
2766 StoreFromPtr (ig, type);
2769 ig.Emit (OpCodes.Starg_S, (byte) arg_idx);
2771 ig.Emit (OpCodes.Starg, arg_idx);
2776 public void AddressOf (EmitContext ec, AddressOp mode)
2784 ec.ig.Emit (OpCodes.Ldarga_S, (byte) arg_idx);
2786 ec.ig.Emit (OpCodes.Ldarga, arg_idx);
2791 /// Used for arguments to New(), Invocation()
2793 public class Argument {
2794 public enum AType : byte {
2800 public readonly AType ArgType;
2801 public Expression expr;
2803 public Argument (Expression expr, AType type)
2806 this.ArgType = type;
2809 public Expression Expr {
2821 if (ArgType == AType.Ref || ArgType == AType.Out)
2822 return TypeManager.LookupType (expr.Type.ToString () + "&");
2828 public Parameter.Modifier GetParameterModifier ()
2830 if (ArgType == AType.Ref || ArgType == AType.Out)
2831 return Parameter.Modifier.OUT;
2833 return Parameter.Modifier.NONE;
2836 public static string FullDesc (Argument a)
2838 return (a.ArgType == AType.Ref ? "ref " :
2839 (a.ArgType == AType.Out ? "out " : "")) +
2840 TypeManager.CSharpName (a.Expr.Type);
2843 public bool Resolve (EmitContext ec, Location loc)
2845 expr = expr.Resolve (ec);
2847 if (ArgType == AType.Expression)
2848 return expr != null;
2850 if (expr.eclass != ExprClass.Variable){
2852 // We just probe to match the CSC output
2854 if (expr.eclass == ExprClass.PropertyAccess ||
2855 expr.eclass == ExprClass.IndexerAccess){
2858 "A property or indexer can not be passed as an out or ref " +
2863 "An lvalue is required as an argument to out or ref");
2868 return expr != null;
2871 public void Emit (EmitContext ec)
2874 // Ref and Out parameters need to have their addresses taken.
2876 // ParameterReferences might already be references, so we want
2877 // to pass just the value
2879 if (ArgType == AType.Ref || ArgType == AType.Out){
2880 AddressOp mode = AddressOp.Store;
2882 if (ArgType == AType.Ref)
2883 mode |= AddressOp.Load;
2885 if (expr is ParameterReference){
2886 ParameterReference pr = (ParameterReference) expr;
2892 pr.AddressOf (ec, mode);
2895 ((IMemoryLocation)expr).AddressOf (ec, mode);
2902 /// Invocation of methods or delegates.
2904 public class Invocation : ExpressionStatement {
2905 public readonly ArrayList Arguments;
2909 MethodBase method = null;
2912 static Hashtable method_parameter_cache;
2914 static Invocation ()
2916 method_parameter_cache = new PtrHashtable ();
2920 // arguments is an ArrayList, but we do not want to typecast,
2921 // as it might be null.
2923 // FIXME: only allow expr to be a method invocation or a
2924 // delegate invocation (7.5.5)
2926 public Invocation (Expression expr, ArrayList arguments, Location l)
2929 Arguments = arguments;
2933 public Expression Expr {
2940 /// Returns the Parameters (a ParameterData interface) for the
2943 public static ParameterData GetParameterData (MethodBase mb)
2945 object pd = method_parameter_cache [mb];
2949 return (ParameterData) pd;
2952 ip = TypeManager.LookupParametersByBuilder (mb);
2954 method_parameter_cache [mb] = ip;
2956 return (ParameterData) ip;
2958 ParameterInfo [] pi = mb.GetParameters ();
2959 ReflectionParameters rp = new ReflectionParameters (pi);
2960 method_parameter_cache [mb] = rp;
2962 return (ParameterData) rp;
2967 /// Determines "better conversion" as specified in 7.4.2.3
2968 /// Returns : 1 if a->p is better
2969 /// 0 if a->q or neither is better
2971 static int BetterConversion (EmitContext ec, Argument a, Type p, Type q, Location loc)
2973 Type argument_type = a.Type;
2974 Expression argument_expr = a.Expr;
2976 if (argument_type == null)
2977 throw new Exception ("Expression of type " + a.Expr + " does not resolve its type");
2982 if (argument_type == p)
2985 if (argument_type == q)
2989 // Now probe whether an implicit constant expression conversion
2992 // An implicit constant expression conversion permits the following
2995 // * A constant-expression of type `int' can be converted to type
2996 // sbyte, byute, short, ushort, uint, ulong provided the value of
2997 // of the expression is withing the range of the destination type.
2999 // * A constant-expression of type long can be converted to type
3000 // ulong, provided the value of the constant expression is not negative
3002 // FIXME: Note that this assumes that constant folding has
3003 // taken place. We dont do constant folding yet.
3006 if (argument_expr is IntConstant){
3007 IntConstant ei = (IntConstant) argument_expr;
3008 int value = ei.Value;
3010 if (p == TypeManager.sbyte_type){
3011 if (value >= SByte.MinValue && value <= SByte.MaxValue)
3013 } else if (p == TypeManager.byte_type){
3014 if (Byte.MinValue >= 0 && value <= Byte.MaxValue)
3016 } else if (p == TypeManager.short_type){
3017 if (value >= Int16.MinValue && value <= Int16.MaxValue)
3019 } else if (p == TypeManager.ushort_type){
3020 if (value >= UInt16.MinValue && value <= UInt16.MaxValue)
3022 } else if (p == TypeManager.uint32_type){
3024 // we can optimize this case: a positive int32
3025 // always fits on a uint32
3029 } else if (p == TypeManager.uint64_type){
3031 // we can optimize this case: a positive int32
3032 // always fits on a uint64
3037 } else if (argument_type == TypeManager.int64_type && argument_expr is LongConstant){
3038 LongConstant lc = (LongConstant) argument_expr;
3040 if (p == TypeManager.uint64_type){
3047 Expression tmp = ConvertImplicitStandard (ec, argument_expr, p, loc);
3055 Expression p_tmp = new EmptyExpression (p);
3056 Expression q_tmp = new EmptyExpression (q);
3058 if (StandardConversionExists (p_tmp, q) == true &&
3059 StandardConversionExists (q_tmp, p) == false)
3062 if (p == TypeManager.sbyte_type)
3063 if (q == TypeManager.byte_type || q == TypeManager.ushort_type ||
3064 q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3067 if (p == TypeManager.short_type)
3068 if (q == TypeManager.ushort_type || q == TypeManager.uint32_type ||
3069 q == TypeManager.uint64_type)
3072 if (p == TypeManager.int32_type)
3073 if (q == TypeManager.uint32_type || q == TypeManager.uint64_type)
3076 if (p == TypeManager.int64_type)
3077 if (q == TypeManager.uint64_type)
3084 /// Determines "Better function"
3087 /// and returns an integer indicating :
3088 /// 0 if candidate ain't better
3089 /// 1 if candidate is better than the current best match
3091 static int BetterFunction (EmitContext ec, ArrayList args,
3092 MethodBase candidate, MethodBase best,
3093 bool expanded_form, Location loc)
3095 ParameterData candidate_pd = GetParameterData (candidate);
3096 ParameterData best_pd;
3102 argument_count = args.Count;
3104 int cand_count = candidate_pd.Count;
3106 if (cand_count == 0 && argument_count == 0)
3109 if (candidate_pd.ParameterModifier (cand_count - 1) != Parameter.Modifier.PARAMS)
3110 if (cand_count != argument_count)
3116 if (argument_count == 0 && cand_count == 1 &&
3117 candidate_pd.ParameterModifier (cand_count - 1) == Parameter.Modifier.PARAMS)
3120 for (int j = argument_count; j > 0;) {
3123 Argument a = (Argument) args [j];
3124 Type t = candidate_pd.ParameterType (j);
3126 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3128 t = t.GetElementType ();
3130 x = BetterConversion (ec, a, t, null, loc);
3142 best_pd = GetParameterData (best);
3144 int rating1 = 0, rating2 = 0;
3146 for (int j = 0; j < argument_count; ++j) {
3149 Argument a = (Argument) args [j];
3151 Type ct = candidate_pd.ParameterType (j);
3152 Type bt = best_pd.ParameterType (j);
3154 if (candidate_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3156 ct = ct.GetElementType ();
3158 if (best_pd.ParameterModifier (j) == Parameter.Modifier.PARAMS)
3160 bt = bt.GetElementType ();
3162 x = BetterConversion (ec, a, ct, bt, loc);
3163 y = BetterConversion (ec, a, bt, ct, loc);
3172 if (rating1 > rating2)
3178 public static string FullMethodDesc (MethodBase mb)
3180 string ret_type = "";
3182 if (mb is MethodInfo)
3183 ret_type = TypeManager.CSharpName (((MethodInfo) mb).ReturnType);
3185 StringBuilder sb = new StringBuilder (ret_type + " " + mb.Name);
3186 ParameterData pd = GetParameterData (mb);
3188 int count = pd.Count;
3191 for (int i = count; i > 0; ) {
3194 sb.Append (pd.ParameterDesc (count - i - 1));
3200 return sb.ToString ();
3203 public static MethodGroupExpr MakeUnionSet (Expression mg1, Expression mg2, Location loc)
3205 MemberInfo [] miset;
3206 MethodGroupExpr union;
3211 return (MethodGroupExpr) mg2;
3214 return (MethodGroupExpr) mg1;
3217 MethodGroupExpr left_set = null, right_set = null;
3218 int length1 = 0, length2 = 0;
3220 left_set = (MethodGroupExpr) mg1;
3221 length1 = left_set.Methods.Length;
3223 right_set = (MethodGroupExpr) mg2;
3224 length2 = right_set.Methods.Length;
3226 ArrayList common = new ArrayList ();
3228 foreach (MethodBase l in left_set.Methods){
3229 foreach (MethodBase r in right_set.Methods){
3237 miset = new MemberInfo [length1 + length2 - common.Count];
3238 left_set.Methods.CopyTo (miset, 0);
3242 foreach (MemberInfo mi in right_set.Methods){
3243 if (!common.Contains (mi))
3247 union = new MethodGroupExpr (miset, loc);
3253 /// Determines is the candidate method, if a params method, is applicable
3254 /// in its expanded form to the given set of arguments
3256 static bool IsParamsMethodApplicable (ArrayList arguments, MethodBase candidate)
3260 if (arguments == null)
3263 arg_count = arguments.Count;
3265 ParameterData pd = GetParameterData (candidate);
3267 int pd_count = pd.Count;
3272 if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
3275 if (pd_count - 1 > arg_count)
3278 if (pd_count == 1 && arg_count == 0)
3282 // If we have come this far, the case which remains is when the number of parameters
3283 // is less than or equal to the argument count.
3285 for (int i = 0; i < pd_count - 1; ++i) {
3287 Argument a = (Argument) arguments [i];
3289 Parameter.Modifier a_mod = a.GetParameterModifier ();
3290 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3292 if (a_mod == p_mod) {
3294 if (a_mod == Parameter.Modifier.NONE)
3295 if (!StandardConversionExists (a.Expr, pd.ParameterType (i)))
3298 if (a_mod == Parameter.Modifier.REF ||
3299 a_mod == Parameter.Modifier.OUT) {
3300 Type pt = pd.ParameterType (i);
3303 pt = TypeManager.LookupType (pt.FullName + "&");
3313 Type element_type = pd.ParameterType (pd_count - 1).GetElementType ();
3315 foreach (Argument a in arguments){
3316 if (!StandardConversionExists (a.Expr, element_type))
3324 /// Determines if the candidate method is applicable (section 14.4.2.1)
3325 /// to the given set of arguments
3327 static bool IsApplicable (ArrayList arguments, MethodBase candidate)
3331 if (arguments == null)
3334 arg_count = arguments.Count;
3336 ParameterData pd = GetParameterData (candidate);
3338 int pd_count = pd.Count;
3340 if (arg_count != pd.Count)
3343 for (int i = arg_count; i > 0; ) {
3346 Argument a = (Argument) arguments [i];
3348 Parameter.Modifier a_mod = a.GetParameterModifier ();
3349 Parameter.Modifier p_mod = pd.ParameterModifier (i);
3351 if (a_mod == p_mod ||
3352 (a_mod == Parameter.Modifier.NONE && p_mod == Parameter.Modifier.PARAMS)) {
3353 if (a_mod == Parameter.Modifier.NONE)
3354 if (!StandardConversionExists (a.Expr, pd.ParameterType (i)))
3357 if (a_mod == Parameter.Modifier.REF ||
3358 a_mod == Parameter.Modifier.OUT) {
3359 Type pt = pd.ParameterType (i);
3362 pt = TypeManager.LookupType (pt.FullName + "&");
3377 /// Find the Applicable Function Members (7.4.2.1)
3379 /// me: Method Group expression with the members to select.
3380 /// it might contain constructors or methods (or anything
3381 /// that maps to a method).
3383 /// Arguments: ArrayList containing resolved Argument objects.
3385 /// loc: The location if we want an error to be reported, or a Null
3386 /// location for "probing" purposes.
3388 /// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
3389 /// that is the best match of me on Arguments.
3392 public static MethodBase OverloadResolve (EmitContext ec, MethodGroupExpr me,
3393 ArrayList Arguments, Location loc)
3395 ArrayList afm = new ArrayList ();
3396 MethodBase method = null;
3398 ArrayList candidates = new ArrayList ();
3401 foreach (MethodBase candidate in me.Methods){
3404 // Check if candidate is applicable (section 14.4.2.1)
3405 if (!IsApplicable (Arguments, candidate))
3408 candidates.Add (candidate);
3409 x = BetterFunction (ec, Arguments, candidate, method, false, loc);
3416 if (Arguments == null)
3419 argument_count = Arguments.Count;
3422 // Now we see if we can find params functions, applicable in their expanded form
3423 // since if they were applicable in their normal form, they would have been selected
3426 bool chose_params_expanded = false;
3428 if (method == null) {
3429 candidates = new ArrayList ();
3430 foreach (MethodBase candidate in me.Methods){
3431 if (!IsParamsMethodApplicable (Arguments, candidate))
3434 candidates.Add (candidate);
3436 int x = BetterFunction (ec, Arguments, candidate, method, true, loc);
3441 chose_params_expanded = true;
3449 // Now check that there are no ambiguities i.e the selected method
3450 // should be better than all the others
3453 foreach (MethodBase candidate in candidates){
3454 if (candidate == method)
3458 // If a normal method is applicable in the sense that it has the same
3459 // number of arguments, then the expanded params method is never applicable
3460 // so we debar the params method.
3462 if (IsParamsMethodApplicable (Arguments, candidate) &&
3463 IsApplicable (Arguments, method))
3466 int x = BetterFunction (ec, Arguments, method, candidate,
3467 chose_params_expanded, loc);
3472 "Ambiguous call when selecting function due to implicit casts");
3478 // And now check if the arguments are all compatible, perform conversions
3479 // if necessary etc. and return if everything is all right
3482 if (VerifyArgumentsCompat (ec, Arguments, argument_count, method,
3483 chose_params_expanded, null, loc))
3489 public static bool VerifyArgumentsCompat (EmitContext ec, ArrayList Arguments,
3492 bool chose_params_expanded,
3496 ParameterData pd = GetParameterData (method);
3497 int pd_count = pd.Count;
3499 for (int j = 0; j < argument_count; j++) {
3500 Argument a = (Argument) Arguments [j];
3501 Expression a_expr = a.Expr;
3502 Type parameter_type = pd.ParameterType (j);
3504 if (pd.ParameterModifier (j) == Parameter.Modifier.PARAMS &&
3505 chose_params_expanded)
3506 parameter_type = parameter_type.GetElementType ();
3508 if (a.Type != parameter_type){
3511 conv = ConvertImplicitStandard (ec, a_expr, parameter_type, loc);
3514 if (!Location.IsNull (loc)) {
3515 if (delegate_type == null)
3517 "The best overloaded match for method '" +
3518 FullMethodDesc (method) +
3519 "' has some invalid arguments");
3521 Report.Error (1594, loc,
3522 "Delegate '" + delegate_type.ToString () +
3523 "' has some invalid arguments.");
3525 "Argument " + (j+1) +
3526 ": Cannot convert from '" + Argument.FullDesc (a)
3527 + "' to '" + pd.ParameterDesc (j) + "'");
3534 // Update the argument with the implicit conversion
3540 if (a.GetParameterModifier () != pd.ParameterModifier (j) &&
3541 pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS) {
3542 if (!Location.IsNull (loc)) {
3543 Console.WriteLine ("A:P: " + a.GetParameterModifier ());
3544 Console.WriteLine ("PP:: " + pd.ParameterModifier (j));
3545 Console.WriteLine ("PT: " + parameter_type.IsByRef);
3547 "The best overloaded match for method '" + FullMethodDesc (method)+
3548 "' has some invalid arguments");
3550 "Argument " + (j+1) +
3551 ": Cannot convert from '" + Argument.FullDesc (a)
3552 + "' to '" + pd.ParameterDesc (j) + "'");
3562 public override Expression DoResolve (EmitContext ec)
3565 // First, resolve the expression that is used to
3566 // trigger the invocation
3568 if (expr is BaseAccess)
3571 expr = expr.Resolve (ec);
3575 if (!(expr is MethodGroupExpr)) {
3576 Type expr_type = expr.Type;
3578 if (expr_type != null){
3579 bool IsDelegate = TypeManager.IsDelegateType (expr_type);
3581 return (new DelegateInvocation (
3582 this.expr, Arguments, loc)).Resolve (ec);
3586 if (!(expr is MethodGroupExpr)){
3587 report118 (loc, this.expr, "method group");
3592 // Next, evaluate all the expressions in the argument list
3594 if (Arguments != null){
3595 foreach (Argument a in Arguments){
3596 if (!a.Resolve (ec, loc))
3601 method = OverloadResolve (ec, (MethodGroupExpr) this.expr, Arguments, loc);
3603 if (method == null){
3605 "Could not find any applicable function for this argument list");
3609 if (method is MethodInfo)
3610 type = ((MethodInfo)method).ReturnType;
3612 if (type.IsPointer){
3619 eclass = ExprClass.Value;
3624 // Emits the list of arguments as an array
3626 static void EmitParams (EmitContext ec, int idx, ArrayList arguments)
3628 ILGenerator ig = ec.ig;
3629 int count = arguments.Count - idx;
3630 Argument a = (Argument) arguments [idx];
3631 Type t = a.expr.Type;
3632 string array_type = t.FullName + "[]";
3635 array = ig.DeclareLocal (Type.GetType (array_type));
3636 IntConstant.EmitInt (ig, count);
3637 ig.Emit (OpCodes.Newarr, t);
3638 ig.Emit (OpCodes.Stloc, array);
3640 int top = arguments.Count;
3641 for (int j = idx; j < top; j++){
3642 a = (Argument) arguments [j];
3644 ig.Emit (OpCodes.Ldloc, array);
3645 IntConstant.EmitInt (ig, j - idx);
3648 ArrayAccess.EmitStoreOpcode (ig, t);
3650 ig.Emit (OpCodes.Ldloc, array);
3654 /// Emits a list of resolved Arguments that are in the arguments
3657 /// The MethodBase argument might be null if the
3658 /// emission of the arguments is known not to contain
3659 /// a `params' field (for example in constructors or other routines
3660 /// that keep their arguments in this structure
3662 public static void EmitArguments (EmitContext ec, MethodBase mb, ArrayList arguments)
3666 pd = GetParameterData (mb);
3671 // If we are calling a params method with no arguments, special case it
3673 if (arguments == null){
3674 if (pd != null && pd.Count > 0 &&
3675 pd.ParameterModifier (0) == Parameter.Modifier.PARAMS){
3676 ILGenerator ig = ec.ig;
3678 IntConstant.EmitInt (ig, 0);
3679 ig.Emit (OpCodes.Newarr, pd.ParameterType (0).GetElementType ());
3685 int top = arguments.Count;
3687 for (int i = 0; i < top; i++){
3688 Argument a = (Argument) arguments [i];
3691 if (pd.ParameterModifier (i) == Parameter.Modifier.PARAMS){
3693 // Special case if we are passing the same data as the
3694 // params argument, do not put it in an array.
3696 if (pd.ParameterType (i) == a.Type)
3699 EmitParams (ec, i, arguments);
3709 /// is_base tells whether we want to force the use of the `call'
3710 /// opcode instead of using callvirt. Call is required to call
3711 /// a specific method, while callvirt will always use the most
3712 /// recent method in the vtable.
3714 /// is_static tells whether this is an invocation on a static method
3716 /// instance_expr is an expression that represents the instance
3717 /// it must be non-null if is_static is false.
3719 /// method is the method to invoke.
3721 /// Arguments is the list of arguments to pass to the method or constructor.
3723 public static void EmitCall (EmitContext ec, bool is_base,
3724 bool is_static, Expression instance_expr,
3725 MethodBase method, ArrayList Arguments)
3727 ILGenerator ig = ec.ig;
3728 bool struct_call = false;
3732 if (method.DeclaringType.IsValueType)
3735 // If this is ourselves, push "this"
3737 if (instance_expr == null){
3738 ig.Emit (OpCodes.Ldarg_0);
3741 // Push the instance expression
3743 if (instance_expr.Type.IsSubclassOf (TypeManager.value_type)){
3745 // Special case: calls to a function declared in a
3746 // reference-type with a value-type argument need
3747 // to have their value boxed.
3750 if (method.DeclaringType.IsValueType){
3752 // If the expression implements IMemoryLocation, then
3753 // we can optimize and use AddressOf on the
3756 // If not we have to use some temporary storage for
3758 if (instance_expr is IMemoryLocation){
3759 ((IMemoryLocation)instance_expr).
3760 AddressOf (ec, AddressOp.LoadStore);
3763 Type t = instance_expr.Type;
3765 instance_expr.Emit (ec);
3766 LocalBuilder temp = ig.DeclareLocal (t);
3767 ig.Emit (OpCodes.Stloc, temp);
3768 ig.Emit (OpCodes.Ldloca, temp);
3771 instance_expr.Emit (ec);
3772 ig.Emit (OpCodes.Box, instance_expr.Type);
3775 instance_expr.Emit (ec);
3779 EmitArguments (ec, method, Arguments);
3781 if (is_static || struct_call || is_base){
3782 if (method is MethodInfo)
3783 ig.Emit (OpCodes.Call, (MethodInfo) method);
3785 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3787 if (method is MethodInfo)
3788 ig.Emit (OpCodes.Callvirt, (MethodInfo) method);
3790 ig.Emit (OpCodes.Callvirt, (ConstructorInfo) method);
3794 public override void Emit (EmitContext ec)
3796 MethodGroupExpr mg = (MethodGroupExpr) this.expr;
3798 EmitCall (ec, is_base, method.IsStatic, mg.InstanceExpression, method, Arguments);
3801 public override void EmitStatement (EmitContext ec)
3806 // Pop the return value if there is one
3808 if (method is MethodInfo){
3809 if (((MethodInfo)method).ReturnType != TypeManager.void_type)
3810 ec.ig.Emit (OpCodes.Pop);
3816 // This class is used to "disable" the code generation for the
3817 // temporary variable when initializing value types.
3819 class EmptyAddressOf : EmptyExpression, IMemoryLocation {
3820 public void AddressOf (EmitContext ec, AddressOp Mode)
3827 /// Implements the new expression
3829 public class New : ExpressionStatement {
3830 public readonly ArrayList Arguments;
3831 public readonly string RequestedType;
3834 MethodBase method = null;
3837 // If set, the new expression is for a value_target, and
3838 // we will not leave anything on the stack.
3840 Expression value_target;
3842 public New (string requested_type, ArrayList arguments, Location l)
3844 RequestedType = requested_type;
3845 Arguments = arguments;
3849 public Expression ValueTypeVariable {
3851 return value_target;
3855 value_target = value;
3860 // This function is used to disable the following code sequence for
3861 // value type initialization:
3863 // AddressOf (temporary)
3867 // Instead the provide will have provided us with the address on the
3868 // stack to store the results.
3870 static Expression MyEmptyExpression;
3872 public void DisableTemporaryValueType ()
3874 if (MyEmptyExpression == null)
3875 MyEmptyExpression = new EmptyAddressOf ();
3878 // To enable this, look into:
3879 // test-34 and test-89 and self bootstrapping.
3881 // For instance, we can avoid a copy by using `newobj'
3882 // instead of Call + Push-temp on value types.
3883 // value_target = MyEmptyExpression;
3886 public override Expression DoResolve (EmitContext ec)
3888 type = RootContext.LookupType (ec.DeclSpace, RequestedType, false, loc);
3893 bool IsDelegate = TypeManager.IsDelegateType (type);
3896 return (new NewDelegate (type, Arguments, loc)).Resolve (ec);
3898 bool is_struct = false;
3899 is_struct = type.IsSubclassOf (TypeManager.value_type);
3900 eclass = ExprClass.Value;
3903 // SRE returns a match for .ctor () on structs (the object constructor),
3904 // so we have to manually ignore it.
3906 if (is_struct && Arguments == null)
3910 ml = MemberLookup (ec, type, ".ctor",
3911 MemberTypes.Constructor,
3912 AllBindingFlags | BindingFlags.DeclaredOnly, loc);
3914 if (! (ml is MethodGroupExpr)){
3916 report118 (loc, ml, "method group");
3922 if (Arguments != null){
3923 foreach (Argument a in Arguments){
3924 if (!a.Resolve (ec, loc))
3929 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml,
3934 if (method == null && !is_struct) {
3936 "New invocation: Can not find a constructor for " +
3937 "this argument list");
3944 // This DoEmit can be invoked in two contexts:
3945 // * As a mechanism that will leave a value on the stack (new object)
3946 // * As one that wont (init struct)
3948 // You can control whether a value is required on the stack by passing
3949 // need_value_on_stack. The code *might* leave a value on the stack
3950 // so it must be popped manually
3952 // If we are dealing with a ValueType, we have a few
3953 // situations to deal with:
3955 // * The target is a ValueType, and we have been provided
3956 // the instance (this is easy, we are being assigned).
3958 // * The target of New is being passed as an argument,
3959 // to a boxing operation or a function that takes a
3962 // In this case, we need to create a temporary variable
3963 // that is the argument of New.
3965 // Returns whether a value is left on the stack
3967 bool DoEmit (EmitContext ec, bool need_value_on_stack)
3969 bool is_value_type = type.IsSubclassOf (TypeManager.value_type);
3970 ILGenerator ig = ec.ig;
3975 if (value_target == null)
3976 value_target = new LocalTemporary (ec, type);
3978 ml = (IMemoryLocation) value_target;
3979 ml.AddressOf (ec, AddressOp.Store);
3983 Invocation.EmitArguments (ec, method, Arguments);
3987 ig.Emit (OpCodes.Initobj, type);
3989 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
3990 if (need_value_on_stack){
3991 value_target.Emit (ec);
3996 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4001 public override void Emit (EmitContext ec)
4006 public override void EmitStatement (EmitContext ec)
4008 if (DoEmit (ec, false))
4009 ec.ig.Emit (OpCodes.Pop);
4014 /// Represents an array creation expression.
4018 /// There are two possible scenarios here: one is an array creation
4019 /// expression that specifies the dimensions and optionally the
4020 /// initialization data and the other which does not need dimensions
4021 /// specified but where initialization data is mandatory.
4023 public class ArrayCreation : ExpressionStatement {
4024 string RequestedType;
4026 ArrayList Initializers;
4030 // The list of Argument types.
4031 // This is used to constrcut the `newarray' or constructor signature
4033 ArrayList Arguments;
4035 MethodBase method = null;
4036 Type array_element_type;
4037 bool IsOneDimensional = false;
4038 bool IsBuiltinType = false;
4039 bool ExpectInitializers = false;
4042 Type underlying_type;
4044 ArrayList ArrayData;
4049 // The number of array initializers that we can handle
4050 // via the InitializeArray method - through EmitStaticInitializers
4052 int num_automatic_initializers;
4054 public ArrayCreation (string requested_type, ArrayList exprs,
4055 string rank, ArrayList initializers, Location l)
4057 RequestedType = requested_type;
4059 Initializers = initializers;
4062 Arguments = new ArrayList ();
4064 foreach (Expression e in exprs)
4065 Arguments.Add (new Argument (e, Argument.AType.Expression));
4068 public ArrayCreation (string requested_type, string rank, ArrayList initializers, Location l)
4070 RequestedType = requested_type;
4071 Initializers = initializers;
4074 Rank = rank.Substring (0, rank.LastIndexOf ("["));
4076 string tmp = rank.Substring (rank.LastIndexOf ("["));
4078 dimensions = tmp.Length - 1;
4079 ExpectInitializers = true;
4082 public static string FormArrayType (string base_type, int idx_count, string rank)
4084 StringBuilder sb = new StringBuilder (base_type);
4089 for (int i = 1; i < idx_count; i++)
4094 return sb.ToString ();
4097 public static string FormElementType (string base_type, int idx_count, string rank)
4099 StringBuilder sb = new StringBuilder (base_type);
4102 for (int i = 1; i < idx_count; i++)
4109 string val = sb.ToString ();
4111 return val.Substring (0, val.LastIndexOf ("["));
4116 Report.Error (178, loc, "Incorrectly structured array initializer");
4119 public bool CheckIndices (EmitContext ec, ArrayList probe, int idx, bool specified_dims)
4121 if (specified_dims) {
4122 Argument a = (Argument) Arguments [idx];
4124 if (!a.Resolve (ec, loc))
4127 if (!(a.Expr is Constant)) {
4128 Report.Error (150, loc, "A constant value is expected");
4132 int value = (int) ((Constant) a.Expr).GetValue ();
4134 if (value != probe.Count) {
4139 Bounds [idx] = value;
4142 foreach (object o in probe) {
4143 if (o is ArrayList) {
4144 bool ret = CheckIndices (ec, (ArrayList) o, idx + 1, specified_dims);
4148 Expression tmp = (Expression) o;
4149 tmp = tmp.Resolve (ec);
4153 // Handle initialization from vars, fields etc.
4155 Expression conv = ConvertImplicitRequired (
4156 ec, tmp, underlying_type, loc);
4161 if (conv is StringConstant)
4162 ArrayData.Add (conv);
4163 else if (conv is Constant) {
4164 ArrayData.Add (conv);
4165 num_automatic_initializers++;
4167 ArrayData.Add (conv);
4174 public void UpdateIndices (EmitContext ec)
4177 for (ArrayList probe = Initializers; probe != null;) {
4178 if (probe.Count > 0 && probe [0] is ArrayList) {
4179 Expression e = new IntConstant (probe.Count);
4180 Arguments.Add (new Argument (e, Argument.AType.Expression));
4182 Bounds [i++] = probe.Count;
4184 probe = (ArrayList) probe [0];
4187 Expression e = new IntConstant (probe.Count);
4188 Arguments.Add (new Argument (e, Argument.AType.Expression));
4190 Bounds [i++] = probe.Count;
4197 public bool ValidateInitializers (EmitContext ec)
4199 if (Initializers == null) {
4200 if (ExpectInitializers)
4206 underlying_type = RootContext.LookupType (
4207 ec.DeclSpace, RequestedType, false, loc);
4210 // We use this to store all the date values in the order in which we
4211 // will need to store them in the byte blob later
4213 ArrayData = new ArrayList ();
4214 Bounds = new Hashtable ();
4218 if (Arguments != null) {
4219 ret = CheckIndices (ec, Initializers, 0, true);
4223 Arguments = new ArrayList ();
4225 ret = CheckIndices (ec, Initializers, 0, false);
4232 if (Arguments.Count != dimensions) {
4241 public override Expression DoResolve (EmitContext ec)
4246 // First step is to validate the initializers and fill
4247 // in any missing bits
4249 if (!ValidateInitializers (ec))
4252 if (Arguments == null)
4255 arg_count = Arguments.Count;
4256 foreach (Argument a in Arguments){
4257 if (!a.Resolve (ec, loc))
4261 // Now, convert that to an integer
4263 Expression real_arg;
4264 bool old_checked = ec.CheckState;
4265 ec.CheckState = true;
4267 real_arg = ConvertExplicit (
4268 ec, a.expr, TypeManager.uint32_type, loc);
4269 ec.CheckState = old_checked;
4270 if (real_arg == null)
4277 string array_type = FormArrayType (RequestedType, arg_count, Rank);
4278 string element_type = FormElementType (RequestedType, arg_count, Rank);
4280 type = RootContext.LookupType (ec.DeclSpace, array_type, false, loc);
4282 array_element_type = RootContext.LookupType (
4283 ec.DeclSpace, element_type, false, loc);
4288 if (arg_count == 1) {
4289 IsOneDimensional = true;
4290 eclass = ExprClass.Value;
4294 IsBuiltinType = TypeManager.IsBuiltinType (type);
4296 if (IsBuiltinType) {
4300 ml = MemberLookup (ec, type, ".ctor", MemberTypes.Constructor,
4301 AllBindingFlags, loc);
4303 if (!(ml is MethodGroupExpr)){
4304 report118 (loc, ml, "method group");
4309 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4310 "this argument list");
4314 method = Invocation.OverloadResolve (ec, (MethodGroupExpr) ml, Arguments, loc);
4316 if (method == null) {
4317 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4318 "this argument list");
4322 eclass = ExprClass.Value;
4327 ModuleBuilder mb = CodeGen.ModuleBuilder;
4329 ArrayList args = new ArrayList ();
4330 if (Arguments != null){
4331 for (int i = 0; i < arg_count; i++)
4332 args.Add (TypeManager.int32_type);
4335 Type [] arg_types = null;
4338 arg_types = new Type [args.Count];
4340 args.CopyTo (arg_types, 0);
4342 method = mb.GetArrayMethod (type, ".ctor", CallingConventions.HasThis, null,
4345 if (method == null) {
4346 Report.Error (-6, loc, "New invocation: Can not find a constructor for " +
4347 "this argument list");
4351 eclass = ExprClass.Value;
4357 public static byte [] MakeByteBlob (ArrayList ArrayData, Type underlying_type, Location loc)
4362 int count = ArrayData.Count;
4364 factor = GetTypeSize (underlying_type);
4368 data = new byte [(count * factor + 4) & ~3];
4371 for (int i = 0; i < count; ++i) {
4372 object v = ArrayData [i];
4374 if (v is EnumConstant)
4375 v = ((EnumConstant) v).Child;
4377 if (v is Constant && !(v is StringConstant))
4378 v = ((Constant) v).GetValue ();
4384 if (underlying_type == TypeManager.int64_type){
4385 if (!(v is Expression)){
4386 long val = (long) v;
4388 for (int j = 0; j < factor; ++j) {
4389 data [idx + j] = (byte) (val & 0xFF);
4393 } else if (underlying_type == TypeManager.uint64_type){
4394 if (!(v is Expression)){
4395 ulong val = (ulong) v;
4397 for (int j = 0; j < factor; ++j) {
4398 data [idx + j] = (byte) (val & 0xFF);
4402 } else if (underlying_type == TypeManager.float_type) {
4403 if (!(v is Expression)){
4404 element = BitConverter.GetBytes ((float) v);
4406 for (int j = 0; j < factor; ++j)
4407 data [idx + j] = element [j];
4409 } else if (underlying_type == TypeManager.double_type) {
4410 if (!(v is Expression)){
4411 element = BitConverter.GetBytes ((double) v);
4413 for (int j = 0; j < factor; ++j)
4414 data [idx + j] = element [j];
4416 } else if (underlying_type == TypeManager.char_type){
4417 if (!(v is Expression)){
4418 int val = (int) ((char) v);
4420 data [idx] = (byte) (val & 0xff);
4421 data [idx+1] = (byte) (val >> 8);
4423 } else if (underlying_type == TypeManager.short_type){
4424 if (!(v is Expression)){
4425 int val = (int) ((short) v);
4427 data [idx] = (byte) (val & 0xff);
4428 data [idx+1] = (byte) (val >> 8);
4430 } else if (underlying_type == TypeManager.ushort_type){
4431 if (!(v is Expression)){
4432 int val = (int) ((ushort) v);
4434 data [idx] = (byte) (val & 0xff);
4435 data [idx+1] = (byte) (val >> 8);
4437 } else if (underlying_type == TypeManager.int32_type) {
4438 if (!(v is Expression)){
4441 data [idx] = (byte) (val & 0xff);
4442 data [idx+1] = (byte) ((val >> 8) & 0xff);
4443 data [idx+2] = (byte) ((val >> 16) & 0xff);
4444 data [idx+3] = (byte) (val >> 24);
4446 } else if (underlying_type == TypeManager.uint32_type) {
4447 if (!(v is Expression)){
4448 uint val = (uint) v;
4450 data [idx] = (byte) (val & 0xff);
4451 data [idx+1] = (byte) ((val >> 8) & 0xff);
4452 data [idx+2] = (byte) ((val >> 16) & 0xff);
4453 data [idx+3] = (byte) (val >> 24);
4455 } else if (underlying_type == TypeManager.sbyte_type) {
4456 if (!(v is Expression)){
4457 sbyte val = (sbyte) v;
4458 data [idx] = (byte) val;
4460 } else if (underlying_type == TypeManager.byte_type) {
4461 if (!(v is Expression)){
4462 byte val = (byte) v;
4463 data [idx] = (byte) val;
4465 } else if (underlying_type == TypeManager.bool_type) {
4466 if (!(v is Expression)){
4467 bool val = (bool) v;
4468 data [idx] = (byte) (val ? 1 : 0);
4471 throw new Exception ("Unrecognized type in MakeByteBlob");
4480 // Emits the initializers for the array
4482 void EmitStaticInitializers (EmitContext ec, bool is_expression)
4485 // First, the static data
4488 ILGenerator ig = ec.ig;
4490 byte [] data = MakeByteBlob (ArrayData, underlying_type, loc);
4493 fb = RootContext.MakeStaticData (data);
4496 ig.Emit (OpCodes.Dup);
4497 ig.Emit (OpCodes.Ldtoken, fb);
4498 ig.Emit (OpCodes.Call,
4499 TypeManager.void_initializearray_array_fieldhandle);
4504 // Emits pieces of the array that can not be computed at compile
4505 // time (variables and string locations).
4507 // This always expect the top value on the stack to be the array
4509 void EmitDynamicInitializers (EmitContext ec, bool is_expression)
4511 ILGenerator ig = ec.ig;
4512 int dims = Bounds.Count;
4513 int [] current_pos = new int [dims];
4514 int top = ArrayData.Count;
4515 LocalBuilder temp = ig.DeclareLocal (type);
4517 ig.Emit (OpCodes.Stloc, temp);
4519 MethodInfo set = null;
4523 ModuleBuilder mb = null;
4524 mb = CodeGen.ModuleBuilder;
4525 args = new Type [dims + 1];
4528 for (j = 0; j < dims; j++)
4529 args [j] = TypeManager.int32_type;
4531 args [j] = array_element_type;
4533 set = mb.GetArrayMethod (
4535 CallingConventions.HasThis | CallingConventions.Standard,
4536 TypeManager.void_type, args);
4539 for (int i = 0; i < top; i++){
4541 Expression e = null;
4543 if (ArrayData [i] is Expression)
4544 e = (Expression) ArrayData [i];
4548 // Basically we do this for string literals and
4549 // other non-literal expressions
4551 if (e is StringConstant || !(e is Constant) ||
4552 num_automatic_initializers <= 2) {
4553 Type etype = e.Type;
4555 ig.Emit (OpCodes.Ldloc, temp);
4557 for (int idx = dims; idx > 0; ) {
4559 IntConstant.EmitInt (ig, current_pos [idx]);
4563 // If we are dealing with a struct, get the
4564 // address of it, so we can store it.
4566 if (etype.IsSubclassOf (TypeManager.value_type) &&
4567 !TypeManager.IsBuiltinType (etype)){
4572 // Let new know that we are providing
4573 // the address where to store the results
4575 n.DisableTemporaryValueType ();
4578 ig.Emit (OpCodes.Ldelema, etype);
4584 ArrayAccess.EmitStoreOpcode (ig, array_element_type);
4586 ig.Emit (OpCodes.Call, set);
4593 for (int j = 0; j < dims; j++){
4595 if (current_pos [j] < (int) Bounds [j])
4597 current_pos [j] = 0;
4602 ig.Emit (OpCodes.Ldloc, temp);
4605 void EmitArrayArguments (EmitContext ec)
4607 foreach (Argument a in Arguments)
4611 void DoEmit (EmitContext ec, bool is_statement)
4613 ILGenerator ig = ec.ig;
4615 EmitArrayArguments (ec);
4616 if (IsOneDimensional)
4617 ig.Emit (OpCodes.Newarr, array_element_type);
4620 ig.Emit (OpCodes.Newobj, (ConstructorInfo) method);
4622 ig.Emit (OpCodes.Newobj, (MethodInfo) method);
4625 if (Initializers != null){
4627 // FIXME: Set this variable correctly.
4629 bool dynamic_initializers = true;
4631 if (underlying_type != TypeManager.string_type &&
4632 underlying_type != TypeManager.object_type) {
4633 if (num_automatic_initializers > 2)
4634 EmitStaticInitializers (ec, dynamic_initializers || !is_statement);
4637 if (dynamic_initializers)
4638 EmitDynamicInitializers (ec, !is_statement);
4642 public override void Emit (EmitContext ec)
4647 public override void EmitStatement (EmitContext ec)
4655 /// Represents the `this' construct
4657 public class This : Expression, IAssignMethod, IMemoryLocation {
4660 public This (Location loc)
4665 public override Expression DoResolve (EmitContext ec)
4667 eclass = ExprClass.Variable;
4668 type = ec.ContainerType;
4671 Report.Error (26, loc,
4672 "Keyword this not valid in static code");
4679 override public Expression DoResolveLValue (EmitContext ec, Expression right_side)
4683 if (ec.TypeContainer is Class){
4684 Report.Error (1604, loc, "Cannot assign to `this'");
4691 public override void Emit (EmitContext ec)
4693 ec.ig.Emit (OpCodes.Ldarg_0);
4696 public void EmitAssign (EmitContext ec, Expression source)
4699 ec.ig.Emit (OpCodes.Starg, 0);
4702 public void AddressOf (EmitContext ec, AddressOp mode)
4704 ec.ig.Emit (OpCodes.Ldarg_0);
4707 // FIGURE OUT WHY LDARG_S does not work
4709 // consider: struct X { int val; int P { set { val = value; }}}
4711 // Yes, this looks very bad. Look at `NOTAS' for
4713 // ec.ig.Emit (OpCodes.Ldarga_S, (byte) 0);
4718 /// Implements the typeof operator
4720 public class TypeOf : Expression {
4721 public readonly string QueriedType;
4725 public TypeOf (string queried_type, Location l)
4727 QueriedType = queried_type;
4731 public override Expression DoResolve (EmitContext ec)
4733 typearg = RootContext.LookupType (
4734 ec.DeclSpace, QueriedType, false, loc);
4736 if (typearg == null)
4739 type = TypeManager.type_type;
4740 eclass = ExprClass.Type;
4744 public override void Emit (EmitContext ec)
4746 ec.ig.Emit (OpCodes.Ldtoken, typearg);
4747 ec.ig.Emit (OpCodes.Call, TypeManager.system_type_get_type_from_handle);
4750 public Type TypeArg {
4751 get { return typearg; }
4756 /// Implements the sizeof expression
4758 public class SizeOf : Expression {
4759 public readonly string QueriedType;
4763 public SizeOf (string queried_type, Location l)
4765 this.QueriedType = queried_type;
4769 public override Expression DoResolve (EmitContext ec)
4771 type_queried = RootContext.LookupType (
4772 ec.DeclSpace, QueriedType, false, loc);
4773 if (type_queried == null)
4776 type = TypeManager.int32_type;
4777 eclass = ExprClass.Value;
4781 public override void Emit (EmitContext ec)
4783 int size = GetTypeSize (type_queried);
4786 ec.ig.Emit (OpCodes.Sizeof, type_queried);
4788 IntConstant.EmitInt (ec.ig, size);
4793 /// Implements the member access expression
4795 public class MemberAccess : Expression {
4796 public readonly string Identifier;
4798 Expression member_lookup;
4801 public MemberAccess (Expression expr, string id, Location l)
4808 public Expression Expr {
4814 static void error176 (Location loc, string name)
4816 Report.Error (176, loc, "Static member `" +
4817 name + "' cannot be accessed " +
4818 "with an instance reference, qualify with a " +
4819 "type name instead");
4822 static bool IdenticalNameAndTypeName (EmitContext ec, Expression left_original, Location loc)
4824 if (left_original == null)
4827 if (!(left_original is SimpleName))
4830 SimpleName sn = (SimpleName) left_original;
4832 Type t = RootContext.LookupType (ec.DeclSpace, sn.Name, true, loc);
4839 public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
4840 Expression left, Location loc,
4841 Expression left_original)
4846 if (member_lookup is MethodGroupExpr){
4847 MethodGroupExpr mg = (MethodGroupExpr) member_lookup;
4852 if (left is TypeExpr){
4853 if (!mg.RemoveInstanceMethods ()){
4854 SimpleName.Error120 (loc, mg.Methods [0].Name);
4858 return member_lookup;
4862 // Instance.MethodGroup
4864 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4865 if (mg.RemoveInstanceMethods ())
4866 return member_lookup;
4869 if (!mg.RemoveStaticMethods ()){
4870 error176 (loc, mg.Methods [0].Name);
4874 mg.InstanceExpression = left;
4875 return member_lookup;
4877 if (!mg.RemoveStaticMethods ()){
4878 if (IdenticalNameAndTypeName (ec, left_original, loc)){
4879 if (!mg.RemoveInstanceMethods ()){
4880 SimpleName.Error120 (loc, mg.Methods [0].Name);
4883 return member_lookup;
4886 error176 (loc, mg.Methods [0].Name);
4890 mg.InstanceExpression = left;
4892 return member_lookup;
4896 if (member_lookup is FieldExpr){
4897 FieldExpr fe = (FieldExpr) member_lookup;
4898 FieldInfo fi = fe.FieldInfo;
4899 Type decl_type = fi.DeclaringType;
4901 if (fi is FieldBuilder) {
4902 Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
4905 object o = c.LookupConstantValue (ec);
4906 object real_value = ((Constant) c.Expr).GetValue ();
4908 return Constantify (real_value, fi.FieldType);
4913 Type t = fi.FieldType;
4917 if (fi is FieldBuilder)
4918 o = TypeManager.GetValue ((FieldBuilder) fi);
4920 o = fi.GetValue (fi);
4922 if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
4923 Expression enum_member = MemberLookup (
4924 ec, decl_type, "value__", MemberTypes.Field,
4925 AllBindingFlags, loc);
4927 Enum en = TypeManager.LookupEnum (decl_type);
4931 c = Constantify (o, en.UnderlyingType);
4933 c = Constantify (o, enum_member.Type);
4935 return new EnumConstant (c, decl_type);
4938 Expression exp = Constantify (o, t);
4940 if (!(left is TypeExpr)) {
4941 error176 (loc, fe.FieldInfo.Name);
4948 if (fi.FieldType.IsPointer && !ec.InUnsafe){
4953 if (left is TypeExpr){
4954 // and refers to a type name or an
4955 if (!fe.FieldInfo.IsStatic){
4956 error176 (loc, fe.FieldInfo.Name);
4959 return member_lookup;
4961 if (fe.FieldInfo.IsStatic){
4962 if (IdenticalNameAndTypeName (ec, left_original, loc))
4963 return member_lookup;
4965 error176 (loc, fe.FieldInfo.Name);
4968 fe.InstanceExpression = left;
4974 if (member_lookup is PropertyExpr){
4975 PropertyExpr pe = (PropertyExpr) member_lookup;
4977 if (left is TypeExpr){
4979 SimpleName.Error120 (loc, pe.PropertyInfo.Name);
4985 if (IdenticalNameAndTypeName (ec, left_original, loc))
4986 return member_lookup;
4987 error176 (loc, pe.PropertyInfo.Name);
4990 pe.InstanceExpression = left;
4996 if (member_lookup is EventExpr) {
4998 EventExpr ee = (EventExpr) member_lookup;
5001 // If the event is local to this class, we transform ourselves into
5005 Expression ml = MemberLookup (
5006 ec, ec.ContainerType,
5007 ee.EventInfo.Name, MemberTypes.Event, AllBindingFlags, loc);
5010 MemberInfo mi = ec.TypeContainer.GetFieldFromEvent ((EventExpr) ml);
5014 // If this happens, then we have an event with its own
5015 // accessors and private field etc so there's no need
5016 // to transform ourselves : we should instead flag an error
5018 Assign.error70 (ee.EventInfo, loc);
5022 ml = ExprClassFromMemberInfo (ec, mi, loc);
5025 Report.Error (-200, loc, "Internal error!!");
5028 return ResolveMemberAccess (ec, ml, left, loc, left_original);
5031 if (left is TypeExpr) {
5033 SimpleName.Error120 (loc, ee.EventInfo.Name);
5041 if (IdenticalNameAndTypeName (ec, left_original, loc))
5044 error176 (loc, ee.EventInfo.Name);
5048 ee.InstanceExpression = left;
5054 if (member_lookup is TypeExpr){
5055 member_lookup.Resolve (ec);
5056 return member_lookup;
5059 Console.WriteLine ("Left is: " + left);
5060 Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
5061 Environment.Exit (0);
5065 public override Expression DoResolve (EmitContext ec)
5068 // We are the sole users of ResolveWithSimpleName (ie, the only
5069 // ones that can cope with it
5071 Expression original = expr;
5072 expr = expr.ResolveWithSimpleName (ec);
5077 if (expr is SimpleName){
5078 SimpleName child_expr = (SimpleName) expr;
5080 expr = new SimpleName (child_expr.Name + "." + Identifier, loc);
5082 return expr.ResolveWithSimpleName (ec);
5086 // TODO: I mailed Ravi about this, and apparently we can get rid
5087 // of this and put it in the right place.
5089 // Handle enums here when they are in transit.
5090 // Note that we cannot afford to hit MemberLookup in this case because
5091 // it will fail to find any members at all
5094 Type expr_type = expr.Type;
5095 if ((expr is TypeExpr) && (expr_type.IsSubclassOf (TypeManager.enum_type))){
5097 Enum en = TypeManager.LookupEnum (expr_type);
5100 object value = en.LookupEnumValue (ec, Identifier, loc);
5103 Constant c = Constantify (value, en.UnderlyingType);
5104 return new EnumConstant (c, expr_type);
5109 if (expr_type.IsPointer){
5110 Report.Error (23, loc,
5111 "The `.' operator can not be applied to pointer operands (" +
5112 TypeManager.CSharpName (expr_type) + ")");
5116 member_lookup = MemberLookup (ec, expr_type, Identifier, loc);
5118 if (member_lookup == null){
5119 Report.Error (117, loc, "`" + expr_type + "' does not contain a " +
5120 "definition for `" + Identifier + "'");
5125 return ResolveMemberAccess (ec, member_lookup, expr, loc, original);
5128 public override void Emit (EmitContext ec)
5130 throw new Exception ("Should not happen");
5135 /// Implements checked expressions
5137 public class CheckedExpr : Expression {
5139 public Expression Expr;
5141 public CheckedExpr (Expression e)
5146 public override Expression DoResolve (EmitContext ec)
5148 bool last_const_check = ec.ConstantCheckState;
5150 ec.ConstantCheckState = true;
5151 Expr = Expr.Resolve (ec);
5152 ec.ConstantCheckState = last_const_check;
5157 eclass = Expr.eclass;
5162 public override void Emit (EmitContext ec)
5164 bool last_check = ec.CheckState;
5165 bool last_const_check = ec.ConstantCheckState;
5167 ec.CheckState = true;
5168 ec.ConstantCheckState = true;
5170 ec.CheckState = last_check;
5171 ec.ConstantCheckState = last_const_check;
5177 /// Implements the unchecked expression
5179 public class UnCheckedExpr : Expression {
5181 public Expression Expr;
5183 public UnCheckedExpr (Expression e)
5188 public override Expression DoResolve (EmitContext ec)
5190 bool last_const_check = ec.ConstantCheckState;
5192 ec.ConstantCheckState = false;
5193 Expr = Expr.Resolve (ec);
5194 ec.ConstantCheckState = last_const_check;
5199 eclass = Expr.eclass;
5204 public override void Emit (EmitContext ec)
5206 bool last_check = ec.CheckState;
5207 bool last_const_check = ec.ConstantCheckState;
5209 ec.CheckState = false;
5210 ec.ConstantCheckState = false;
5212 ec.CheckState = last_check;
5213 ec.ConstantCheckState = last_const_check;
5219 /// An Element Access expression.
5221 /// During semantic analysis these are transformed into
5222 /// IndexerAccess or ArrayAccess
5224 public class ElementAccess : Expression {
5225 public ArrayList Arguments;
5226 public Expression Expr;
5227 public Location loc;
5229 public ElementAccess (Expression e, ArrayList e_list, Location l)
5238 Arguments = new ArrayList ();
5239 foreach (Expression tmp in e_list)
5240 Arguments.Add (new Argument (tmp, Argument.AType.Expression));
5244 bool CommonResolve (EmitContext ec)
5246 Expr = Expr.Resolve (ec);
5251 if (Arguments == null)
5254 foreach (Argument a in Arguments){
5255 if (!a.Resolve (ec, loc))
5262 Expression MakePointerAccess ()
5266 if (t == TypeManager.void_ptr_type){
5269 "The array index operation is not valid for void pointers");
5272 if (Arguments.Count != 1){
5275 "A pointer must be indexed by a single value");
5278 Expression p = new PointerArithmetic (true, Expr, ((Argument)Arguments [0]).Expr, t);
5279 return new Indirection (p);
5282 public override Expression DoResolve (EmitContext ec)
5284 if (!CommonResolve (ec))
5288 // We perform some simple tests, and then to "split" the emit and store
5289 // code we create an instance of a different class, and return that.
5291 // I am experimenting with this pattern.
5295 if (t.IsSubclassOf (TypeManager.array_type))
5296 return (new ArrayAccess (this)).Resolve (ec);
5297 else if (t.IsPointer)
5298 return MakePointerAccess ();
5300 return (new IndexerAccess (this)).Resolve (ec);
5303 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5305 if (!CommonResolve (ec))
5309 if (t.IsSubclassOf (TypeManager.array_type))
5310 return (new ArrayAccess (this)).ResolveLValue (ec, right_side);
5311 else if (t.IsPointer)
5312 return MakePointerAccess ();
5314 return (new IndexerAccess (this)).ResolveLValue (ec, right_side);
5317 public override void Emit (EmitContext ec)
5319 throw new Exception ("Should never be reached");
5324 /// Implements array access
5326 public class ArrayAccess : Expression, IAssignMethod, IMemoryLocation {
5328 // Points to our "data" repository
5332 public ArrayAccess (ElementAccess ea_data)
5335 eclass = ExprClass.Variable;
5338 public override Expression DoResolve (EmitContext ec)
5340 ExprClass eclass = ea.Expr.eclass;
5343 // As long as the type is valid
5344 if (!(eclass == ExprClass.Variable || eclass == ExprClass.PropertyAccess ||
5345 eclass == ExprClass.Value)) {
5346 report118 (ea.loc, ea.Expr, "variable or value");
5351 Type t = ea.Expr.Type;
5352 if (t.GetArrayRank () != ea.Arguments.Count){
5353 Report.Error (22, ea.loc,
5354 "Incorrect number of indexes for array " +
5355 " expected: " + t.GetArrayRank () + " got: " +
5356 ea.Arguments.Count);
5359 type = t.GetElementType ();
5360 if (type.IsPointer && !ec.InUnsafe){
5361 UnsafeError (ea.loc);
5365 eclass = ExprClass.Variable;
5371 /// Emits the right opcode to load an object of Type `t'
5372 /// from an array of T
5374 static public void EmitLoadOpcode (ILGenerator ig, Type type)
5376 if (type == TypeManager.byte_type || type == TypeManager.bool_type)
5377 ig.Emit (OpCodes.Ldelem_I1);
5378 else if (type == TypeManager.sbyte_type)
5379 ig.Emit (OpCodes.Ldelem_U1);
5380 else if (type == TypeManager.short_type)
5381 ig.Emit (OpCodes.Ldelem_I2);
5382 else if (type == TypeManager.ushort_type)
5383 ig.Emit (OpCodes.Ldelem_U2);
5384 else if (type == TypeManager.int32_type)
5385 ig.Emit (OpCodes.Ldelem_I4);
5386 else if (type == TypeManager.uint32_type)
5387 ig.Emit (OpCodes.Ldelem_U4);
5388 else if (type == TypeManager.uint64_type)
5389 ig.Emit (OpCodes.Ldelem_I8);
5390 else if (type == TypeManager.int64_type)
5391 ig.Emit (OpCodes.Ldelem_I8);
5392 else if (type == TypeManager.float_type)
5393 ig.Emit (OpCodes.Ldelem_R4);
5394 else if (type == TypeManager.double_type)
5395 ig.Emit (OpCodes.Ldelem_R8);
5396 else if (type == TypeManager.intptr_type)
5397 ig.Emit (OpCodes.Ldelem_I);
5398 else if (type.IsValueType){
5399 ig.Emit (OpCodes.Ldelema, type);
5400 ig.Emit (OpCodes.Ldobj, type);
5402 ig.Emit (OpCodes.Ldelem_Ref);
5406 /// Emits the right opcode to store an object of Type `t'
5407 /// from an array of T.
5409 static public void EmitStoreOpcode (ILGenerator ig, Type t)
5411 if (t == TypeManager.byte_type || t == TypeManager.sbyte_type ||
5412 t == TypeManager.bool_type)
5413 ig.Emit (OpCodes.Stelem_I1);
5414 else if (t == TypeManager.short_type || t == TypeManager.ushort_type || t == TypeManager.char_type)
5415 ig.Emit (OpCodes.Stelem_I2);
5416 else if (t == TypeManager.int32_type || t == TypeManager.uint32_type)
5417 ig.Emit (OpCodes.Stelem_I4);
5418 else if (t == TypeManager.int64_type || t == TypeManager.uint64_type)
5419 ig.Emit (OpCodes.Stelem_I8);
5420 else if (t == TypeManager.float_type)
5421 ig.Emit (OpCodes.Stelem_R4);
5422 else if (t == TypeManager.double_type)
5423 ig.Emit (OpCodes.Stelem_R8);
5424 else if (t == TypeManager.intptr_type)
5425 ig.Emit (OpCodes.Stelem_I);
5426 else if (t.IsValueType)
5427 ig.Emit (OpCodes.Stobj, t);
5429 ig.Emit (OpCodes.Stelem_Ref);
5432 MethodInfo FetchGetMethod ()
5434 ModuleBuilder mb = CodeGen.ModuleBuilder;
5435 int arg_count = ea.Arguments.Count;
5436 Type [] args = new Type [arg_count];
5439 for (int i = 0; i < arg_count; i++){
5440 //args [i++] = a.Type;
5441 args [i] = TypeManager.int32_type;
5444 get = mb.GetArrayMethod (
5445 ea.Expr.Type, "Get",
5446 CallingConventions.HasThis |
5447 CallingConventions.Standard,
5453 MethodInfo FetchAddressMethod ()
5455 ModuleBuilder mb = CodeGen.ModuleBuilder;
5456 int arg_count = ea.Arguments.Count;
5457 Type [] args = new Type [arg_count];
5459 string ptr_type_name;
5462 ptr_type_name = type.FullName + "&";
5463 ret_type = Type.GetType (ptr_type_name);
5466 // It is a type defined by the source code we are compiling
5468 if (ret_type == null){
5469 ret_type = mb.GetType (ptr_type_name);
5472 for (int i = 0; i < arg_count; i++){
5473 //args [i++] = a.Type;
5474 args [i] = TypeManager.int32_type;
5477 address = mb.GetArrayMethod (
5478 ea.Expr.Type, "Address",
5479 CallingConventions.HasThis |
5480 CallingConventions.Standard,
5486 public override void Emit (EmitContext ec)
5488 int rank = ea.Expr.Type.GetArrayRank ();
5489 ILGenerator ig = ec.ig;
5493 foreach (Argument a in ea.Arguments)
5497 EmitLoadOpcode (ig, type);
5501 method = FetchGetMethod ();
5502 ig.Emit (OpCodes.Call, method);
5506 public void EmitAssign (EmitContext ec, Expression source)
5508 int rank = ea.Expr.Type.GetArrayRank ();
5509 ILGenerator ig = ec.ig;
5513 foreach (Argument a in ea.Arguments)
5516 Type t = source.Type;
5519 // The stobj opcode used by value types will need
5520 // an address on the stack, not really an array/array
5524 if (t.IsValueType && !TypeManager.IsBuiltinType (t))
5525 ig.Emit (OpCodes.Ldelema, t);
5531 EmitStoreOpcode (ig, t);
5533 ModuleBuilder mb = CodeGen.ModuleBuilder;
5534 int arg_count = ea.Arguments.Count;
5535 Type [] args = new Type [arg_count + 1];
5538 for (int i = 0; i < arg_count; i++){
5539 //args [i++] = a.Type;
5540 args [i] = TypeManager.int32_type;
5543 args [arg_count] = type;
5545 set = mb.GetArrayMethod (
5546 ea.Expr.Type, "Set",
5547 CallingConventions.HasThis |
5548 CallingConventions.Standard,
5549 TypeManager.void_type, args);
5551 ig.Emit (OpCodes.Call, set);
5555 public void AddressOf (EmitContext ec, AddressOp mode)
5557 int rank = ea.Expr.Type.GetArrayRank ();
5558 ILGenerator ig = ec.ig;
5562 foreach (Argument a in ea.Arguments)
5566 ig.Emit (OpCodes.Ldelema, type);
5568 MethodInfo address = FetchAddressMethod ();
5569 ig.Emit (OpCodes.Call, address);
5576 public ArrayList getters, setters;
5577 static Hashtable map;
5581 map = new Hashtable ();
5584 Indexers (MemberInfo [] mi)
5586 foreach (PropertyInfo property in mi){
5587 MethodInfo get, set;
5589 get = property.GetGetMethod (true);
5591 if (getters == null)
5592 getters = new ArrayList ();
5597 set = property.GetSetMethod (true);
5599 if (setters == null)
5600 setters = new ArrayList ();
5606 static public Indexers GetIndexersForType (Type caller_type, Type lookup_type, Location loc)
5608 Indexers ix = (Indexers) map [lookup_type];
5609 string p_name = TypeManager.IndexerPropertyName (lookup_type);
5614 MemberInfo [] mi = TypeManager.MemberLookup (
5615 caller_type, lookup_type, MemberTypes.Property,
5616 BindingFlags.Public | BindingFlags.Instance, p_name);
5618 if (mi == null || mi.Length == 0){
5619 Report.Error (21, loc,
5620 "Type `" + TypeManager.CSharpName (lookup_type) +
5621 "' does not have any indexers defined");
5625 ix = new Indexers (mi);
5626 map [lookup_type] = ix;
5633 /// Expressions that represent an indexer call.
5635 public class IndexerAccess : Expression, IAssignMethod {
5637 // Points to our "data" repository
5640 MethodInfo get, set;
5642 ArrayList set_arguments;
5644 public IndexerAccess (ElementAccess ea_data)
5647 eclass = ExprClass.Value;
5650 public override Expression DoResolve (EmitContext ec)
5652 Type indexer_type = ea.Expr.Type;
5655 // Step 1: Query for all `Item' *properties*. Notice
5656 // that the actual methods are pointed from here.
5658 // This is a group of properties, piles of them.
5661 ilist = Indexers.GetIndexersForType (
5662 ec.ContainerType, indexer_type, ea.loc);
5666 // Step 2: find the proper match
5668 if (ilist != null && ilist.getters != null && ilist.getters.Count > 0){
5669 Location loc = ea.loc;
5671 get = (MethodInfo) Invocation.OverloadResolve (
5672 ec, new MethodGroupExpr (ilist.getters, loc), ea.Arguments, loc);
5676 Report.Error (154, ea.loc,
5677 "indexer can not be used in this context, because " +
5678 "it lacks a `get' accessor");
5682 type = get.ReturnType;
5683 if (type.IsPointer && !ec.InUnsafe){
5684 UnsafeError (ea.loc);
5688 eclass = ExprClass.IndexerAccess;
5692 public override Expression DoResolveLValue (EmitContext ec, Expression right_side)
5694 Type indexer_type = ea.Expr.Type;
5695 Type right_type = right_side.Type;
5698 ilist = Indexers.GetIndexersForType (
5699 ec.ContainerType, indexer_type, ea.loc);
5701 if (ilist != null && ilist.setters != null && ilist.setters.Count > 0){
5702 Location loc = ea.loc;
5704 set_arguments = (ArrayList) ea.Arguments.Clone ();
5705 set_arguments.Add (new Argument (right_side, Argument.AType.Expression));
5707 set = (MethodInfo) Invocation.OverloadResolve (
5708 ec, new MethodGroupExpr (ilist.setters, loc), set_arguments, loc);
5712 Report.Error (200, ea.loc,
5713 "indexer X.this [" + TypeManager.CSharpName (right_type) +
5714 "] lacks a `set' accessor");
5718 type = TypeManager.void_type;
5719 eclass = ExprClass.IndexerAccess;
5723 public override void Emit (EmitContext ec)
5725 Invocation.EmitCall (ec, false, false, ea.Expr, get, ea.Arguments);
5729 // source is ignored, because we already have a copy of it from the
5730 // LValue resolution and we have already constructed a pre-cached
5731 // version of the arguments (ea.set_arguments);
5733 public void EmitAssign (EmitContext ec, Expression source)
5735 Invocation.EmitCall (ec, false, false, ea.Expr, set, set_arguments);
5740 /// The base operator for method names
5742 public class BaseAccess : Expression {
5746 public BaseAccess (string member, Location l)
5748 this.member = member;
5752 public override Expression DoResolve (EmitContext ec)
5754 Expression member_lookup;
5755 Type current_type = ec.ContainerType;
5756 Type base_type = current_type.BaseType;
5760 Report.Error (1511, loc,
5761 "Keyword base is not allowed in static method");
5765 member_lookup = MemberLookup (ec, base_type, member, loc);
5766 if (member_lookup == null)
5772 left = new TypeExpr (base_type);
5776 e = MemberAccess.ResolveMemberAccess (ec, member_lookup, left, loc, null);
5777 if (e is PropertyExpr){
5778 PropertyExpr pe = (PropertyExpr) e;
5786 public override void Emit (EmitContext ec)
5788 throw new Exception ("Should never be called");
5793 /// The base indexer operator
5795 public class BaseIndexerAccess : Expression {
5796 ArrayList Arguments;
5799 public BaseIndexerAccess (ArrayList args, Location l)
5805 public override Expression DoResolve (EmitContext ec)
5807 Type current_type = ec.ContainerType;
5808 Type base_type = current_type.BaseType;
5809 Expression member_lookup;
5812 Report.Error (1511, loc,
5813 "Keyword base is not allowed in static method");
5817 member_lookup = MemberLookup (ec, base_type, "get_Item", MemberTypes.Method, AllBindingFlags, loc);
5818 if (member_lookup == null)
5821 return MemberAccess.ResolveMemberAccess (ec, member_lookup, ec.This, loc, null);
5824 public override void Emit (EmitContext ec)
5826 throw new Exception ("Should never be called");
5831 /// This class exists solely to pass the Type around and to be a dummy
5832 /// that can be passed to the conversion functions (this is used by
5833 /// foreach implementation to typecast the object return value from
5834 /// get_Current into the proper type. All code has been generated and
5835 /// we only care about the side effect conversions to be performed
5837 /// This is also now used as a placeholder where a no-action expression
5838 /// is needed (the `New' class).
5840 public class EmptyExpression : Expression {
5841 public EmptyExpression ()
5843 type = TypeManager.object_type;
5844 eclass = ExprClass.Value;
5847 public EmptyExpression (Type t)
5850 eclass = ExprClass.Value;
5853 public override Expression DoResolve (EmitContext ec)
5858 public override void Emit (EmitContext ec)
5860 // nothing, as we only exist to not do anything.
5864 // This is just because we might want to reuse this bad boy
5865 // instead of creating gazillions of EmptyExpressions.
5866 // (CanConvertImplicit uses it)
5868 public void SetType (Type t)
5874 public class UserCast : Expression {
5878 public UserCast (MethodInfo method, Expression source)
5880 this.method = method;
5881 this.source = source;
5882 type = method.ReturnType;
5883 eclass = ExprClass.Value;
5886 public override Expression DoResolve (EmitContext ec)
5889 // We are born fully resolved
5894 public override void Emit (EmitContext ec)
5896 ILGenerator ig = ec.ig;
5900 if (method is MethodInfo)
5901 ig.Emit (OpCodes.Call, (MethodInfo) method);
5903 ig.Emit (OpCodes.Call, (ConstructorInfo) method);
5909 // This class is used to "construct" the type during a typecast
5910 // operation. Since the Type.GetType class in .NET can parse
5911 // the type specification, we just use this to construct the type
5912 // one bit at a time.
5914 public class ComposedCast : Expression {
5919 public ComposedCast (Expression left, string dim, Location l)
5926 public override Expression DoResolve (EmitContext ec)
5928 left = left.Resolve (ec);
5932 if (left.eclass != ExprClass.Type){
5933 report118 (loc, left, "type");
5937 type = RootContext.LookupType (
5938 ec.DeclSpace, left.Type.FullName + dim, false, loc);
5942 if (!ec.InUnsafe && type.IsPointer){
5947 eclass = ExprClass.Type;
5951 public override void Emit (EmitContext ec)
5953 throw new Exception ("This should never be called");
5958 // This class is used to represent the address of an array, used
5959 // only by the Fixed statement, this is like the C "&a [0]" construct.
5961 public class ArrayPtr : Expression {
5964 public ArrayPtr (Expression array)
5966 Type array_type = array.Type.GetElementType ();
5970 string array_ptr_type_name = array_type.FullName + "*";
5972 type = Type.GetType (array_ptr_type_name);
5974 ModuleBuilder mb = CodeGen.ModuleBuilder;
5976 type = mb.GetType (array_ptr_type_name);
5979 eclass = ExprClass.Value;
5982 public override void Emit (EmitContext ec)
5984 ILGenerator ig = ec.ig;
5987 IntLiteral.EmitInt (ig, 0);
5988 ig.Emit (OpCodes.Ldelema, array.Type.GetElementType ());
5991 public override Expression DoResolve (EmitContext ec)
5994 // We are born fully resolved
6001 // Used by the fixed statement
6003 public class StringPtr : Expression {
6006 public StringPtr (LocalBuilder b)
6009 eclass = ExprClass.Value;
6010 type = TypeManager.char_ptr_type;
6013 public override Expression DoResolve (EmitContext ec)
6015 // This should never be invoked, we are born in fully
6016 // initialized state.
6021 public override void Emit (EmitContext ec)
6023 ILGenerator ig = ec.ig;
6025 ig.Emit (OpCodes.Ldloc, b);
6026 ig.Emit (OpCodes.Conv_I);
6027 ig.Emit (OpCodes.Call, TypeManager.int_get_offset_to_string_data);
6028 ig.Emit (OpCodes.Add);
6033 // Implements the `stackalloc' keyword
6035 public class StackAlloc : Expression {
6041 public StackAlloc (string type, Expression count, Location l)
6048 public override Expression DoResolve (EmitContext ec)
6050 count = count.Resolve (ec);
6054 if (count.Type != TypeManager.int32_type){
6055 count = ConvertImplicitRequired (ec, count, TypeManager.int32_type, loc);
6060 if (ec.InCatch || ec.InFinally){
6061 Report.Error (255, loc,
6062 "stackalloc can not be used in a catch or finally block");
6066 otype = RootContext.LookupType (ec.DeclSpace, t, false, loc);
6071 if (!TypeManager.VerifyUnManaged (otype, loc))
6074 string ptr_name = otype.FullName + "*";
6075 type = Type.GetType (ptr_name);
6077 ModuleBuilder mb = CodeGen.ModuleBuilder;
6079 type = mb.GetType (ptr_name);
6081 eclass = ExprClass.Value;
6086 public override void Emit (EmitContext ec)
6088 int size = GetTypeSize (otype);
6089 ILGenerator ig = ec.ig;
6092 ig.Emit (OpCodes.Sizeof, otype);
6094 IntConstant.EmitInt (ig, size);
6096 ig.Emit (OpCodes.Mul);
6097 ig.Emit (OpCodes.Localloc);